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
namespace DataCollection.Migrations { using System; using System.Data.Entity.Migrations; public partial class addedelementsupport : DbMigration { public override void Up() { CreateTable( "dbo.Elements", c => new { ElementId = c.Int(nullable: false, identity: true), ElementType = c.String(), NameAttribute = c.String(), IdAttribute = c.String(), ClassAttribute = c.String(), }) .PrimaryKey(t => t.ElementId); AddColumn("dbo.UserInputDatas", "Element_ElementId", c => c.Int()); CreateIndex("dbo.UserInputDatas", "Element_ElementId"); AddForeignKey("dbo.UserInputDatas", "Element_ElementId", "dbo.Elements", "ElementId"); } public override void Down() { DropForeignKey("dbo.UserInputDatas", "Element_ElementId", "dbo.Elements"); DropIndex("dbo.UserInputDatas", new[] { "Element_ElementId" }); DropColumn("dbo.UserInputDatas", "Element_ElementId"); DropTable("dbo.Elements"); } } }
35.5
98
0.513302
[ "MIT" ]
rohansen/Code-Examples
Security/Security - XSS SQL Injection Examples/DataCollection/DataCollection/Migrations/201603301036583_added element support.cs
1,278
C#
using FirstSample.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstSample.Services { public class MyBooksController : IMyBooksController { private readonly BooksContext _booksContext; private readonly ILogger<MyBooksController> _logger; public MyBooksController(BooksContext booksContext, ILogger<MyBooksController> logger) { _booksContext = booksContext ?? throw new ArgumentNullException(nameof(booksContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task CreateDatabaseAsync() { _logger.LogTrace("Create database"); await _booksContext.Database.EnsureCreatedAsync(); } public async Task AddBooksAsync(IEnumerable<Book> books) { await _booksContext.Books.AddRangeAsync(books); await _booksContext.SaveChangesAsync(); } public void ReadBooks() { var q = from b in _booksContext.Books where b.Publisher == "AWL" select b; var q1 = _booksContext.Books.Where(b => b.Publisher == "AWL").Select(b => b); var books = _booksContext.Books.Where(b => b.Publisher == "Wrox Press"); foreach (var book in books) { Console.WriteLine($"{book.Title}"); } } public void InMemoryBooks() { var books = new[] { new Book { BookId=1, Title = "Professional C# 7", Publisher = "Wrox Press" }, new Book { BookId=2, Title = "Enterprise Services", Publisher = "AWL" }, }; var q1 = books.Where(b => b.Publisher == "AWL").Select(b => b); foreach (var b in q1) { Console.WriteLine(b); } } public void QueryDemo() { var tx = _booksContext.Database.BeginTransaction(); var b3 = new Book { Title = "Programming UWP Apps", Publisher = "Self" }; _booksContext.Books.Add(b3); _booksContext.SaveChanges(); // _booksContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var b1 = _booksContext.Books.FirstOrDefault(b => b.Publisher.StartsWith("Wrox")); var b2 = _booksContext.Books.FirstOrDefault(b => b.Title.StartsWith("Pro")); if (b1 == b2) { Console.WriteLine("the same"); } else { Console.WriteLine("not the same"); } b1.Title = "Professional C# 8"; var entries = _booksContext.ChangeTracker.Entries<Book>(); foreach (var entry in entries) { Console.WriteLine(entry.State); } _booksContext.SaveChanges(); _booksContext.Database.CommitTransaction(); } } }
30.605769
100
0.562048
[ "MIT" ]
CNinnovation/efcorejan2019
Day2/ChangeTracking/FirstSample/Services/MyBooksController.cs
3,185
C#
#pragma checksum "..\..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "DFD51DB48B919928877099F765344937" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using TFOIBeta; namespace TFOIBeta { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { TFOIBeta.App app = new TFOIBeta.App(); app.InitializeComponent(); app.Run(); } } }
31.521127
113
0.610813
[ "MIT" ]
espilioto/TFOI
TFOI/obj/x64/Debug/App.g.cs
2,240
C#
using System.Collections.ObjectModel; namespace AUapi.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
27.071429
80
0.701847
[ "MIT" ]
merchansky-alevel/module-task-mvc-and-api
AUapi/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
379
C#
using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Threading.Tasks; namespace Xuey.NET.Framework.Service { public interface ISysRoleService { Task AddRole(AddRoleInput input); Task DeleteRole(DeleteRoleInput input); Task<string> GetNameByRoleId(long roleId); Task<dynamic> GetRoleDropDown(); Task<SysRole> GetRoleInfo([FromQuery] QueryRoleInput input); Task<dynamic> GetRoleList([FromQuery] RoleInput input); Task<List<long>> GetUserDataScopeIdList(List<long> roleIdList, long orgId); Task<List<RoleOutput>> GetUserRoleList(long userId); Task GrantData(GrantRoleDataInput input); Task GrantMenu(GrantRoleMenuInput input); Task<List<long>> OwnData([FromQuery] QueryRoleInput input); Task<List<long>> OwnMenu([FromQuery] QueryRoleInput input); Task<dynamic> QueryRolePageList([FromQuery] RolePageInput input); Task UpdateRole(UpdateRoleInput input); } }
27.513514
83
0.707269
[ "MIT" ]
xueynet/XYP
src/backend/Xuey.NET.Framework/Service/Role/ISysRoleService.cs
1,020
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace FluidDbClient { public class DataRecord : IDataRecord { private class DataField { public DataField(int index, string name, object value) { Index = index; Name = name; Value = value; } public int Index { get; } public string Name { get; } public object Value { get; } } private readonly List<DataField> _dataFields = new List<DataField>(); public DataRecord(IDataRecord record) { for (var i = 0; i != record.FieldCount; i++) { _dataFields.Add(new DataField(i, record.GetName(i), record[i])); } } public string GetName(int i) => _dataFields.First(df => df.Index == i).Name; public int GetOrdinal(string name) { return _dataFields.First(df => df.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Index; } public Type GetFieldType(int i) => Get(i).GetType(); public string GetDataTypeName(int i) => GetFieldType(i).Name; public bool IsDBNull(int i) => Get(i) is DBNull; public int FieldCount => _dataFields.Count; public object this[int i] => Get(i); public object this[string name] { get { return _dataFields.First(df => df.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Value; } } public int GetValues(object[] values) { for (var i = 0; i != _dataFields.Count; i++) { values[i] = Get(i); } return _dataFields.Count; } public object GetValue(int i) => Get(i); public bool GetBoolean(int i) => (bool)Get(i); public byte GetByte(int i) => (byte)Get(i); public char GetChar(int i) => (char)Get(i); public DateTime GetDateTime(int i) => (DateTime)Get(i); public decimal GetDecimal(int i) => (decimal)Get(i); public double GetDouble(int i) => (double)Get(i); public float GetFloat(int i) => (float)Get(i); public Guid GetGuid(int i) => (Guid)Get(i); public short GetInt16(int i) => (short) Get(i); public int GetInt32(int i) => (int) Get(i); public long GetInt64(int i) => (long) Get(i); public string GetString(int i) => (string) Get(i); public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { var buf = (byte[])Get(i); var bytes = Math.Min(length, buf.Length - (int)fieldOffset); Buffer.BlockCopy(buf, (int)fieldOffset, buffer, bufferoffset, bytes); return bytes; } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { var s = (string)Get(i); var chars = Math.Min(length, s.Length - (int)fieldoffset); s.CopyTo((int)fieldoffset, buffer ?? throw new ArgumentNullException(nameof(buffer)), bufferoffset, chars); return chars; } public IDataReader GetData(int i) { throw new NotSupportedException("Cannot get IDataReader for buffered records"); } private object Get(int i) { return _dataFields[i].Value; } } }
32.626168
119
0.556574
[ "MIT" ]
davidwest/FluidDbClient
FluidDbClient/DefaultImplementations/DataRecord.cs
3,493
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 organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Organizations.Model { /// <summary> /// Container for the parameters to the DisableAWSServiceAccess operation. /// Disables the integration of an AWS service (the service that is specified by <code>ServicePrincipal</code>) /// with AWS Organizations. When you disable integration, the specified service no longer /// can create a <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html">service-linked /// role</a> in <i>new</i> accounts in your organization. This means the service can't /// perform operations on your behalf on any new accounts in your organization. The service /// can still perform operations in older accounts until the service completes its clean-up /// from AWS Organizations. /// /// <important> /// <para> /// We recommend that you disable integration between AWS Organizations and the specified /// AWS service by using the console or commands that are provided by the specified service. /// Doing so ensures that the other service is aware that it can clean up any resources /// that are required only for the integration. How the service cleans up its resources /// in the organization's accounts depends on that service. For more information, see /// the documentation for the other AWS service. /// </para> /// </important> /// <para> /// After you perform the <code>DisableAWSServiceAccess</code> operation, the specified /// service can no longer perform operations in your organization's accounts unless the /// operations are explicitly permitted by the IAM policies that are attached to your /// roles. /// </para> /// /// <para> /// For more information about integrating other services with AWS Organizations, including /// the list of services that work with Organizations, see <a href="http://docs.aws.amazon.com/organizations/latest/userguide/orgs_integrate_services.html">Integrating /// AWS Organizations with Other AWS Services</a> in the <i>AWS Organizations User Guide</i>. /// </para> /// /// <para> /// This operation can be called only from the organization's master account. /// </para> /// </summary> public partial class DisableAWSServiceAccessRequest : AmazonOrganizationsRequest { private string _servicePrincipal; /// <summary> /// Gets and sets the property ServicePrincipal. /// <para> /// The service principal name of the AWS service for which you want to disable integration /// with your organization. This is typically in the form of a URL, such as <code> <i>service-abbreviation</i>.amazonaws.com</code>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string ServicePrincipal { get { return this._servicePrincipal; } set { this._servicePrincipal = value; } } // Check to see if ServicePrincipal property is set internal bool IsSetServicePrincipal() { return this._servicePrincipal != null; } } }
44.108696
171
0.689749
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/DisableAWSServiceAccessRequest.cs
4,058
C#
using System.Windows; using System.Windows.Media.Animation; using MaterialDesignThemes.Wpf.Transitions; namespace MaterialDesignThemes.Wpf.Transitions { public abstract class TransitionEffectBase : FrameworkElement, ITransitionEffect { public abstract Timeline Build<TSubject>(TSubject effectSubject) where TSubject : FrameworkElement, ITransitionEffectSubject; } }
35.818182
141
0.794416
[ "MIT" ]
AlexP11223/YAPA-2
packages/MaterialDesignThemes.2.1.0.657/src/net45/Transitions/TransitionEffectBase.cs
394
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.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms.VisualStyles; using Microsoft.Win32; using Directory = System.IO.Directory; using static Interop; namespace System.Windows.Forms { /// <summary> /// Provides <see langword='static'/> methods and properties to manage an application, such as methods to run and quit an application, /// to process Windows messages, and properties to get information about an application. /// This class cannot be inherited. /// </summary> public sealed partial class Application { /// <summary> /// Hash table for our event list /// </summary> private static EventHandlerList s_eventHandlers; private static string s_startupPath; private static string s_executablePath; private static object s_appFileVersion; private static Type s_mainType; private static string s_companyName; private static string s_productName; private static string s_productVersion; private static string s_safeTopLevelCaptionSuffix; private static bool s_comCtlSupportsVisualStylesInitialized = false; private static bool s_comCtlSupportsVisualStyles = false; private static FormCollection s_forms = null; private static readonly object s_internalSyncObject = new object(); private static bool s_useWaitCursor = false; private static bool s_useEverettThreadAffinity = false; private static bool s_checkedThreadAffinity = false; private const string EverettThreadAffinityValue = "EnableSystemEventsThreadAffinityCompatibility"; /// <summary> /// In case Application.exit gets called recursively /// </summary> private static bool s_exiting; /// <summary> /// Events the user can hook into /// </summary> private static readonly object EVENT_APPLICATIONEXIT = new object(); private static readonly object EVENT_THREADEXIT = new object(); // Constant string used in Application.Restart() private const string IEEXEC = "ieexec.exe"; // Defines a new callback delegate type [EditorBrowsable(EditorBrowsableState.Advanced)] public delegate bool MessageLoopCallback(); /// <summary> /// This class is static, there is no need to ever create it. /// </summary> private Application() { } /// <summary> /// Determines if the caller should be allowed to quit the application. This will return false, /// for example, if being called from a windows forms control being hosted within a web browser. The /// windows forms control should not attempt to quit the application. /// </summary> public static bool AllowQuit => ThreadContext.FromCurrent().GetAllowQuit(); /// <summary> /// Returns True if it is OK to continue idle processing. Typically called in an Application.Idle event handler. /// </summary> internal static bool CanContinueIdle => ThreadContext.FromCurrent().ComponentManager.FContinueIdle().IsTrue(); /// <summary> /// Typically, you shouldn't need to use this directly - use RenderWithVisualStyles instead. /// </summary> internal static bool ComCtlSupportsVisualStyles { get { if (!s_comCtlSupportsVisualStylesInitialized) { s_comCtlSupportsVisualStyles = InitializeComCtlSupportsVisualStyles(); s_comCtlSupportsVisualStylesInitialized = true; } return s_comCtlSupportsVisualStyles; } } private static bool InitializeComCtlSupportsVisualStyles() { if (UseVisualStyles) { // At this point, we may not have loaded ComCtl6 yet, but it will eventually be loaded, // so we return true here. This works because UseVisualStyles, once set, cannot be // turned off. return true; } // To see if we are comctl6, we look for a function that is exposed only from comctl6 // we do not call DllGetVersion or any direct p/invoke, because the binding will be // cached. // // GetModuleHandle returns a handle to a mapped module without incrementing its // reference count. IntPtr hModule = Kernel32.GetModuleHandleW(Libraries.Comctl32); if (hModule != IntPtr.Zero) { return Kernel32.GetProcAddress(hModule, "ImageList_WriteEx") != IntPtr.Zero; } // Load comctl since GetModuleHandle failed to find it hModule = Kernel32.LoadLibraryFromSystemPathIfAvailable(Libraries.Comctl32); if (hModule == IntPtr.Zero) { return false; } return Kernel32.GetProcAddress(hModule, "ImageList_WriteEx") != IntPtr.Zero; } /// <summary> /// Gets the registry key for the application data that is shared among all users. /// </summary> public static RegistryKey CommonAppDataRegistry => Registry.LocalMachine.CreateSubKey(CommonAppDataRegistryKeyName); internal static string CommonAppDataRegistryKeyName => $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}"; internal static bool UseEverettThreadAffinity { get { if (!s_checkedThreadAffinity) { s_checkedThreadAffinity = true; try { // We need access to be able to read from the registry here. We're not creating a // registry key, nor are we returning information from the registry to the user. RegistryKey key = Registry.LocalMachine.OpenSubKey(CommonAppDataRegistryKeyName); if (key != null) { object value = key.GetValue(EverettThreadAffinityValue); key.Close(); if (value != null && (int)value != 0) { s_useEverettThreadAffinity = true; } } } catch (Security.SecurityException) { // Can't read the key: use default value (false) } catch (InvalidCastException) { // Key is of wrong type: use default value (false) } } return s_useEverettThreadAffinity; } } /// <summary> /// Gets the path for the application data that is shared among all users. /// </summary> /// <remarks> /// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides /// the Windows logo required adornments to the directory (Company\Product\Version) /// </remarks> public static string CommonAppDataPath => GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); /// <summary> /// Gets the company name associated with the application. /// </summary> public static string CompanyName { get { lock (s_internalSyncObject) { if (s_companyName == null) { // Custom attribute Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attrs != null && attrs.Length > 0) { s_companyName = ((AssemblyCompanyAttribute)attrs[0]).Company; } } // Win32 version if (s_companyName == null || s_companyName.Length == 0) { s_companyName = GetAppFileVersionInfo().CompanyName; if (s_companyName != null) { s_companyName = s_companyName.Trim(); } } // fake it with a namespace // won't work with MC++ see GetAppMainType. if (s_companyName == null || s_companyName.Length == 0) { Type t = GetAppMainType(); if (t != null) { string ns = t.Namespace; if (!string.IsNullOrEmpty(ns)) { int firstDot = ns.IndexOf('.'); if (firstDot != -1) { s_companyName = ns.Substring(0, firstDot); } else { s_companyName = ns; } } else { // last ditch... no namespace, use product name... s_companyName = ProductName; } } } } } return s_companyName; } } /// <summary> /// Gets or sets the locale information for the current thread. /// </summary> public static CultureInfo CurrentCulture { get => Thread.CurrentThread.CurrentCulture; set => Thread.CurrentThread.CurrentCulture = value; } /// <summary> /// Gets or sets the current input language for the current thread. /// </summary> public static InputLanguage CurrentInputLanguage { get => InputLanguage.CurrentInputLanguage; set => InputLanguage.CurrentInputLanguage = value; } internal static bool CustomThreadExceptionHandlerAttached => ThreadContext.FromCurrent().CustomThreadExceptionHandlerAttached; /// <summary> /// Gets the path for the executable file that started the application. /// </summary> public static string ExecutablePath { get { if (s_executablePath == null) { Assembly asm = Assembly.GetEntryAssembly(); if (asm == null) { StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef); s_executablePath = Path.GetFullPath(sb.ToString()); } else { string cb = asm.CodeBase; Uri codeBase = new Uri(cb); if (codeBase.IsFile) { s_executablePath = codeBase.LocalPath + Uri.UnescapeDataString(codeBase.Fragment); ; } else { s_executablePath = codeBase.ToString(); } } } return s_executablePath; } } /// <summary> /// Gets the current <see cref="HighDpiMode"/> mode for the process. /// </summary> /// <value>One of the enumeration values that indicates the high DPI mode.</value> public static HighDpiMode HighDpiMode => DpiHelper.GetWinformsApplicationDpiAwareness(); /// <summary> /// Sets the <see cref="HighDpiMode"/> mode for process. /// </summary> /// <param name="highDpiMode">One of the enumeration values that specifies the high DPI mode to set.</param> /// <returns><see langword="true" /> if the high DPI mode was set; otherwise, <see langword="false" />.</returns> public static bool SetHighDpiMode(HighDpiMode highDpiMode) => !DpiHelper.FirstParkingWindowCreated && DpiHelper.SetWinformsApplicationDpiAwareness(highDpiMode); /// <summary> /// Gets the path for the application data specific to a local, non-roaming user. /// </summary> /// <remarks> /// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides /// the Windows logo required adornments to the directory (Company\Product\Version) /// </remarks> public static string LocalUserAppDataPath => GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); /// <summary> /// Determines if a message loop exists on this thread. /// </summary> public static bool MessageLoop => ThreadContext.FromCurrent().GetMessageLoop(); /// <summary> /// Gets the forms collection associated with this application. /// </summary> public static FormCollection OpenForms => s_forms ?? (s_forms = new FormCollection()); /// <summary> /// Gets /// the product name associated with this application. /// </summary> public static string ProductName { get { lock (s_internalSyncObject) { if (s_productName == null) { // Custom attribute Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attrs != null && attrs.Length > 0) { s_productName = ((AssemblyProductAttribute)attrs[0]).Product; } } // Win32 version info if (s_productName == null || s_productName.Length == 0) { s_productName = GetAppFileVersionInfo().ProductName; if (s_productName != null) { s_productName = s_productName.Trim(); } } // fake it with namespace // won't work with MC++ see GetAppMainType. if (s_productName == null || s_productName.Length == 0) { Type t = GetAppMainType(); if (t != null) { string ns = t.Namespace; if (!string.IsNullOrEmpty(ns)) { int lastDot = ns.LastIndexOf('.'); if (lastDot != -1 && lastDot < ns.Length - 1) { s_productName = ns.Substring(lastDot + 1); } else { s_productName = ns; } } else { // last ditch... use the main type s_productName = t.Name; } } } } } return s_productName; } } /// <summary> /// Gets the product version associated with this application. /// </summary> public static string ProductVersion { get { lock (s_internalSyncObject) { if (s_productVersion == null) { // Custom attribute Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) { object[] attrs = entryAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if (attrs != null && attrs.Length > 0) { s_productVersion = ((AssemblyInformationalVersionAttribute)attrs[0]).InformationalVersion; } } // Win32 version info if (s_productVersion == null || s_productVersion.Length == 0) { s_productVersion = GetAppFileVersionInfo().ProductVersion; if (s_productVersion != null) { s_productVersion = s_productVersion.Trim(); } } // fake it if (s_productVersion == null || s_productVersion.Length == 0) { s_productVersion = "1.0.0.0"; } } } return s_productVersion; } } // Allows the hosting environment to register a callback [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RegisterMessageLoop(MessageLoopCallback callback) => ThreadContext.FromCurrent().RegisterMessageLoop(callback); /// <summary> /// Magic property that answers a simple question - are my controls currently going to render with /// visual styles? If you are doing visual styles rendering, use this to be consistent with the rest /// of the controls in your app. /// </summary> public static bool RenderWithVisualStyles => ComCtlSupportsVisualStyles && VisualStyleRenderer.IsSupported; /// <summary> /// Gets or sets the format string to apply to top level window captions /// when they are displayed with a warning banner. /// </summary> public static string SafeTopLevelCaptionFormat { get { if (s_safeTopLevelCaptionSuffix == null) { s_safeTopLevelCaptionSuffix = SR.SafeTopLevelCaptionFormat; // 0 - original, 1 - zone, 2 - site } return s_safeTopLevelCaptionSuffix; } set { if (value == null) { value = string.Empty; } s_safeTopLevelCaptionSuffix = value; } } /// <summary> /// Gets the path for the executable file that started the application. /// </summary> public static string StartupPath { get { if (s_startupPath == null) { // StringBuilder sb = UnsafeNativeMethods.GetModuleFileNameLongPath(NativeMethods.NullHandleRef); // startupPath = Path.GetDirectoryName(sb.ToString()); s_startupPath = AppContext.BaseDirectory; } return s_startupPath; } } // Allows the hosting environment to unregister a callback [EditorBrowsable(EditorBrowsableState.Advanced)] public static void UnregisterMessageLoop() => ThreadContext.FromCurrent().RegisterMessageLoop(null); /// <summary> /// Gets or sets whether the wait cursor is used for all open forms of the application. /// </summary> public static bool UseWaitCursor { get => s_useWaitCursor; set { lock (FormCollection.CollectionSyncRoot) { s_useWaitCursor = value; // Set the WaitCursor of all forms. foreach (Form f in OpenForms) { f.UseWaitCursor = s_useWaitCursor; } } } } /// <summary> /// Gets the path for the application data specific to the roaming user. /// </summary> /// <remarks> /// Don't obsolete these. GetDataPath isn't on SystemInformation, and it provides /// the Windows logo required adornments to the directory (Company\Product\Version) /// </remarks> public static string UserAppDataPath => GetDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); /// <summary> /// Gets the registry key of /// the application data specific to the roaming user. /// </summary> public static RegistryKey UserAppDataRegistry => Registry.CurrentUser.CreateSubKey($"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}"); /// <summary> /// Gets a value that indicates whether visual styles are enabled for the application. /// </summary> /// <value><see langword="true" /> if visual styles are enabled; otherwise, <see langword="false" />.</value> /// <remarks> /// The visual styles can be enabled by calling <see cref="EnableVisualStyles"/>. /// The visual styles will not be enabled if the OS does not support them, or theming is disabled at the OS level. /// </remarks> public static bool UseVisualStyles { get; private set; } = false; /// <remarks> /// Don't never ever change this name, since the window class and partner teams /// dependent on this. Changing this will introduce breaking changes. /// If there is some reason need to change this, notify any partner teams affected. /// </remarks> internal static string WindowsFormsVersion => "WindowsForms10"; internal static string WindowMessagesVersion => "WindowsForms12"; /// <summary> /// Use this property to determine how visual styles will be applied to this application. /// This property is meaningful only if visual styles are supported on the current /// platform (VisualStyleInformation.SupportedByOS is true). /// /// This property can be set only to one of the S.W.F.VisualStyles.VisualStyleState enum values. /// </summary> public static VisualStyleState VisualStyleState { get { if (!VisualStyleInformation.IsSupportedByOS) { return VisualStyleState.NoneEnabled; } VisualStyleState vState = (VisualStyleState)SafeNativeMethods.GetThemeAppProperties(); return vState; } set { if (VisualStyleInformation.IsSupportedByOS) { SafeNativeMethods.SetThemeAppProperties((int)value); // 248887 we need to send a WM_THEMECHANGED to the top level windows of this application. // We do it this way to ensure that we get all top level windows -- whether we created them or not. SafeNativeMethods.EnumThreadWindowsCallback callback = new SafeNativeMethods.EnumThreadWindowsCallback(Application.SendThemeChanged); SafeNativeMethods.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); } } } /// <summary> /// This helper broadcasts out a WM_THEMECHANGED to appropriate top level windows of this app. /// </summary> private unsafe static bool SendThemeChanged(IntPtr handle, IntPtr extraParameter) { uint thisPID = Kernel32.GetCurrentProcessId(); User32.GetWindowThreadProcessId(handle, out uint processId); if (processId == thisPID && SafeNativeMethods.IsWindowVisible(new HandleRef(null, handle))) { SendThemeChangedRecursive(handle, IntPtr.Zero); User32.RedrawWindow( handle, null, IntPtr.Zero, User32.RDW.INVALIDATE | User32.RDW.FRAME | User32.RDW.ERASE | User32.RDW.ALLCHILDREN); } return true; } /// <summary> /// This helper broadcasts out a WM_THEMECHANGED this window and all children. /// It is assumed at this point that the handle belongs to the current process /// and has a visible top level window. /// </summary> private static bool SendThemeChangedRecursive(IntPtr handle, IntPtr lparam) { // First send to all children... UnsafeNativeMethods.EnumChildWindows(new HandleRef(null, handle), new NativeMethods.EnumChildrenCallback(Application.SendThemeChangedRecursive), NativeMethods.NullHandleRef); // Then do myself. UnsafeNativeMethods.SendMessage(new HandleRef(null, handle), Interop.WindowMessages.WM_THEMECHANGED, 0, 0); return true; } /// <summary> /// Occurs when the application is about to shut down. /// </summary> public static event EventHandler ApplicationExit { add => AddEventHandler(EVENT_APPLICATIONEXIT, value); remove => RemoveEventHandler(EVENT_APPLICATIONEXIT, value); } private static void AddEventHandler(object key, Delegate value) { lock (s_internalSyncObject) { if (null == s_eventHandlers) { s_eventHandlers = new EventHandlerList(); } s_eventHandlers.AddHandler(key, value); } } private static void RemoveEventHandler(object key, Delegate value) { lock (s_internalSyncObject) { if (null == s_eventHandlers) { return; } s_eventHandlers.RemoveHandler(key, value); } } /// <summary> /// Adds a message filter to monitor Windows messages as they are routed to their /// destinations. /// </summary> public static void AddMessageFilter(IMessageFilter value) => ThreadContext.FromCurrent().AddMessageFilter(value); /// <summary> /// Processes all message filters for given message /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static bool FilterMessage(ref Message message) { // Create copy of MSG structure User32.MSG msg = message; bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out bool modified); if (modified) { message.HWnd = msg.hwnd; message.Msg = (int)msg.message; message.WParam = msg.wParam; message.LParam = msg.lParam; } return processed; } /// <summary> /// Occurs when the application has finished processing and is about to enter the /// idle state. /// </summary> public static event EventHandler Idle { add { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._idleHandler += value; // This just ensures that the component manager is hooked up. We // need it for idle time processing. object o = current.ComponentManager; } } remove { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._idleHandler -= value; } } } /// <summary> /// Occurs when the application is about to enter a modal state /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static event EventHandler EnterThreadModal { add { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._enterModalHandler += value; } } remove { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._enterModalHandler -= value; } } } /// <summary> /// Occurs when the application is about to leave a modal state /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static event EventHandler LeaveThreadModal { add { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._leaveModalHandler += value; } } remove { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._leaveModalHandler -= value; } } } /// <summary> /// Occurs when an untrapped thread exception is thrown. /// </summary> public static event ThreadExceptionEventHandler ThreadException { add { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._threadExceptionHandler = value; } } remove { ThreadContext current = ThreadContext.FromCurrent(); lock (current) { current._threadExceptionHandler -= value; } } } /// <summary> /// Occurs when a thread is about to shut down. When the main thread for an /// application is about to be shut down, this event will be raised first, /// followed by an <see cref="ApplicationExit"/> event. /// </summary> public static event EventHandler ThreadExit { add => AddEventHandler(EVENT_THREADEXIT, value); remove => RemoveEventHandler(EVENT_THREADEXIT, value); } /// <summary> /// Called immediately before we begin pumping messages for a modal message loop. /// Does not actually start a message pump; that's the caller's responsibility. /// </summary> internal static void BeginModalMessageLoop() => ThreadContext.FromCurrent().BeginModalMessageLoop(null); /// <summary> /// Processes all Windows messages currently in the message queue. /// </summary> public static void DoEvents() => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.DoEvents, null); internal static void DoEventsModal() => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.DoEventsModal, null); /// <summary> /// Enables visual styles for all subsequent <see cref="Application.Run"/> and <see cref="CreateHandle"/> calls. /// Uses the default theming manifest file shipped with the redist. /// </summary> public static void EnableVisualStyles() { // Pull manifest from our resources string assemblyLoc = typeof(Application).Assembly.Location; if (assemblyLoc != null) { // CSC embeds DLL manifests as resource ID 2 UseVisualStyles = UnsafeNativeMethods.ThemingScope.CreateActivationContext(assemblyLoc, nativeResourceManifestID: 2); Debug.Assert(UseVisualStyles, "Enable Visual Styles failed"); } } /// <summary> /// Called immediately after we stop pumping messages for a modal message loop. /// Does not actually end the message pump itself. /// </summary> internal static void EndModalMessageLoop() => ThreadContext.FromCurrent().EndModalMessageLoop(null); /// <summary> /// Overload of Exit that does not care about e.Cancel. /// </summary> public static void Exit() => Exit(null); /// <summary> /// Informs all message pumps that they are to terminate and /// then closes all application windows after the messages have been processed. /// e.Cancel indicates whether any of the open forms cancelled the exit call. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static void Exit(CancelEventArgs e) { bool cancelExit = ExitInternal(); if (e != null) { e.Cancel = cancelExit; } } /// <summary> /// Private version of Exit which does not do any security checks. /// </summary> private static bool ExitInternal() { bool cancelExit = false; lock (s_internalSyncObject) { if (s_exiting) { return false; } s_exiting = true; try { // Raise the FormClosing and FormClosed events for each open form if (s_forms != null) { foreach (Form f in OpenForms) { if (f.RaiseFormClosingOnAppExit()) { cancelExit = true; break; // quit the loop as soon as one form refuses to close } } } if (!cancelExit) { if (s_forms != null) { while (OpenForms.Count > 0) { OpenForms[0].RaiseFormClosedOnAppExit(); // OnFormClosed removes the form from the FormCollection } } ThreadContext.ExitApplication(); } } finally { s_exiting = false; } } return cancelExit; } /// <summary> /// Exits the message loop on the /// current thread and closes all windows on the thread. /// </summary> public static void ExitThread() { ThreadContext context = ThreadContext.FromCurrent(); if (context.ApplicationContext != null) { context.ApplicationContext.ExitThread(); } else { context.Dispose(true); } } // When a Form receives a WM_ACTIVATE message, it calls this method so we can do the // appropriate MsoComponentManager activation magic internal static void FormActivated(bool modal, bool activated) { if (modal) { return; } ThreadContext.FromCurrent().FormActivated(activated); } /// <summary> /// Retrieves the FileVersionInfo associated with the main module for /// the application. /// </summary> private static FileVersionInfo GetAppFileVersionInfo() { lock (s_internalSyncObject) { if (s_appFileVersion == null) { Type t = GetAppMainType(); if (t != null) { s_appFileVersion = FileVersionInfo.GetVersionInfo(t.Module.FullyQualifiedName); } else { s_appFileVersion = FileVersionInfo.GetVersionInfo(ExecutablePath); } } } return (FileVersionInfo)s_appFileVersion; } /// <summary> /// Retrieves the Type that contains the "Main" method. /// </summary> private static Type GetAppMainType() { lock (s_internalSyncObject) { if (s_mainType == null) { Assembly exe = Assembly.GetEntryAssembly(); // Get Main type...This doesn't work in MC++ because Main is a global function and not // a class static method (it doesn't belong to a Type). if (exe != null) { s_mainType = exe.EntryPoint.ReflectedType; } } } return s_mainType; } /// <summary> /// Locates a thread context given a window handle. /// </summary> private static ThreadContext GetContextForHandle(HandleRef handle) { ThreadContext cxt = ThreadContext.FromId(User32.GetWindowThreadProcessId(handle.Handle, out _)); Debug.Assert( cxt != null, "No thread context for handle. This is expected if you saw a previous assert about the handle being invalid."); GC.KeepAlive(handle.Wrapper); return cxt; } /// <summary> /// Returns a string that is the combination of the basePath + CompanyName + ProducName + ProductVersion. This /// will also create the directory if it doesn't exist. /// </summary> private static string GetDataPath(string basePath) { string path = Path.Join(basePath, CompanyName, ProductName, ProductVersion); lock (s_internalSyncObject) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } return path; } /// <summary> /// Called by the last thread context before it shuts down. /// </summary> private static void RaiseExit() { if (s_eventHandlers != null) { Delegate exit = s_eventHandlers[EVENT_APPLICATIONEXIT]; if (exit != null) { ((EventHandler)exit)(null, EventArgs.Empty); } } } /// <summary> /// Called by the each thread context before it shuts down. /// </summary> private static void RaiseThreadExit() { if (s_eventHandlers != null) { Delegate exit = s_eventHandlers[EVENT_THREADEXIT]; if (exit != null) { ((EventHandler)exit)(null, EventArgs.Empty); } } } /// <summary> /// "Parks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// </summary> internal static void ParkHandle(HandleRef handle, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) { Debug.Assert(UnsafeNativeMethods.IsWindow(handle), "Handle being parked is not a valid window handle"); Debug.Assert(((int)UnsafeNativeMethods.GetWindowLong(handle, NativeMethods.GWL_STYLE) & NativeMethods.WS_CHILD) != 0, "Only WS_CHILD windows should be parked."); ThreadContext cxt = GetContextForHandle(handle); if (cxt != null) { cxt.GetParkingWindow(dpiAwarenessContext).ParkHandle(handle); } } /// <summary> /// Park control handle on a parkingwindow that has matching DpiAwareness. /// </summary> /// <param name="cp"> create params for control handle</param> /// <param name="dpiContext"> dpi awareness</param> internal static void ParkHandle(CreateParams cp, DpiAwarenessContext dpiAwarenessContext = DpiAwarenessContext.DPI_AWARENESS_CONTEXT_UNSPECIFIED) { ThreadContext cxt = ThreadContext.FromCurrent(); if (cxt != null) { cp.Parent = cxt.GetParkingWindow(dpiAwarenessContext).Handle; } } /// <summary> /// Initializes OLE on the current thread. /// </summary> public static ApartmentState OleRequired() => ThreadContext.FromCurrent().OleRequired(); /// <summary> /// Raises the <see cref='ThreadException'/> event. /// </summary> public static void OnThreadException(Exception t) => ThreadContext.FromCurrent().OnThreadException(t); /// <summary> /// "Unparks" the given HWND to a temporary HWND. This allows WS_CHILD windows to /// be parked. /// </summary> internal static void UnparkHandle(HandleRef handle, DpiAwarenessContext context) { ThreadContext cxt = GetContextForHandle(handle); if (cxt != null) { cxt.GetParkingWindow(context).UnparkHandle(handle); } } /// <summary> /// Raises the Idle event. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public static void RaiseIdle(EventArgs e) => ThreadContext.FromCurrent()._idleHandler?.Invoke(Thread.CurrentThread, e); /// <summary> /// Removes a message filter from the application's message pump. /// </summary> public static void RemoveMessageFilter(IMessageFilter value) => ThreadContext.FromCurrent().RemoveMessageFilter(value); /// <summary> /// Restarts the application. /// </summary> public static void Restart() { if (Assembly.GetEntryAssembly() == null) { throw new NotSupportedException(SR.RestartNotSupported); } bool hrefExeCase = false; Process process = Process.GetCurrentProcess(); Debug.Assert(process != null); if (string.Equals(process.MainModule.ModuleName, IEEXEC, StringComparison.OrdinalIgnoreCase)) { string clrPath = Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName); if (string.Equals(clrPath + "\\" + IEEXEC, process.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) { // HRef exe case hrefExeCase = true; ExitInternal(); if (AppDomain.CurrentDomain.GetData("APP_LAUNCH_URL") is string launchUrl) { Process.Start(process.MainModule.FileName, launchUrl); } } } if (!hrefExeCase) { // Regular app case string[] arguments = Environment.GetCommandLineArgs(); Debug.Assert(arguments != null && arguments.Length > 0); StringBuilder sb = new StringBuilder((arguments.Length - 1) * 16); for (int argumentIndex = 1; argumentIndex < arguments.Length - 1; argumentIndex++) { sb.Append('"'); sb.Append(arguments[argumentIndex]); sb.Append("\" "); } if (arguments.Length > 1) { sb.Append('"'); sb.Append(arguments[arguments.Length - 1]); sb.Append('"'); } ProcessStartInfo currentStartInfo = Process.GetCurrentProcess().StartInfo; currentStartInfo.FileName = ExecutablePath; if (sb.Length > 0) { currentStartInfo.Arguments = sb.ToString(); } ExitInternal(); Process.Start(currentStartInfo); } } /// <summary> /// Begins running a standard application message loop on the current thread, /// without a form. /// </summary> public static void Run() => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.Main, new ApplicationContext()); /// <summary> /// Begins running a standard application message loop on the current /// thread, and makes the specified form visible. /// </summary> public static void Run(Form mainForm) => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.Main, new ApplicationContext(mainForm)); /// <summary> /// Begins running a standard application message loop on the current thread, /// without a form. /// </summary> public static void Run(ApplicationContext context) => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.Main, context); /// <summary> /// Runs a modal dialog. This starts a special type of message loop that runs until /// the dialog has a valid DialogResult. This is called internally by a form /// when an application calls System.Windows.Forms.Form.ShowDialog(). /// </summary> internal static void RunDialog(Form form) => ThreadContext.FromCurrent().RunMessageLoop(Interop.Mso.msoloop.ModalForm, new ModalApplicationContext(form)); /// <summary> /// Sets the static UseCompatibleTextRenderingDefault field on Control to the value passed in. /// This switch determines the default text rendering engine to use by some controls that support /// switching rendering engine. /// </summary> public static void SetCompatibleTextRenderingDefault(bool defaultValue) { if (NativeWindow.AnyHandleCreated) { throw new InvalidOperationException(SR.Win32WindowAlreadyCreated); } Control.UseCompatibleTextRenderingDefault = defaultValue; } /// <summary> /// Sets the suspend/hibernate state of the machine. /// Returns true if the call succeeded, else false. /// </summary> public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent) => Powrprof.SetSuspendState((state == PowerState.Hibernate).ToBOOLEAN(), force.ToBOOLEAN(), disableWakeEvent.ToBOOLEAN()).IsTrue(); /// <summary> /// Overload version of SetUnhandledExceptionMode that sets the UnhandledExceptionMode /// mode at the current thread level. /// </summary> public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode) => SetUnhandledExceptionMode(mode, true /*threadScope*/); /// <summary> /// This method can be used to modify the exception handling behavior of /// NativeWindow. By default, NativeWindow will detect if an application /// is running under a debugger, or is running on a machine with a debugger /// installed. In this case, an unhandled exception in the NativeWindow's /// WndProc method will remain unhandled so the debugger can trap it. If /// there is no debugger installed NativeWindow will trap the exception /// and route it to the Application class's unhandled exception filter. /// /// You can control this behavior via a config file, or directly through /// code using this method. Setting the unhandled exception mode does /// not change the behavior of any NativeWindow objects that are currently /// connected to window handles; it only affects new handle connections. /// /// The parameter threadScope defines the scope of the setting: either /// the current thread or the application. /// When a thread exception mode isn't UnhandledExceptionMode.Automatic, it takes /// precedence over the application exception mode. /// </summary> public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope) => NativeWindow.SetUnhandledExceptionModeInternal(mode, threadScope); } }
39.820533
173
0.522525
[ "MIT" ]
ESgarbi/winforms
src/System.Windows.Forms/src/System/Windows/Forms/Application.cs
50,813
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Microsoft.Extensions.Logging; using Requestrr.WebApi.RequestrrBot.ChatClients.Discord; using Requestrr.WebApi.RequestrrBot.TvShows; namespace Requestrr.WebApi.RequestrrBot.Notifications.TvShows { public class ChannelTvShowNotifier : ITvShowNotifier { private readonly DiscordSocketClient _discordClient; private readonly string[] _channelNames; private readonly ILogger<ChatBot> _logger; public ChannelTvShowNotifier( DiscordSocketClient discordClient, string[] channelNames, ILogger<ChatBot> logger) { _discordClient = discordClient; _channelNames = channelNames; _logger = logger; } public async Task<HashSet<string>> NotifyAsync(IReadOnlyCollection<string> userIds, TvShow tvShow, int seasonNumber, CancellationToken token) { var discordUserIds = new HashSet<ulong>(userIds.Select(x => ulong.Parse(x))); var userNotified = new HashSet<string>(); var channels = GetNotificationChannels(); HandleRemovedUsers(discordUserIds, userNotified, token); foreach (var channel in channels) { if (token.IsCancellationRequested) return userNotified; try { await NotifyUsersInChannel(tvShow, seasonNumber, discordUserIds, userNotified, channel); } catch (System.Exception ex) { _logger.LogError(ex, $"An error occurred while sending a tv show notification to channel \"{channel?.Name}\" in server \"{channel?.Guild?.Name}\": " + ex.Message); } } return userNotified; } private SocketTextChannel[] GetNotificationChannels() { return _discordClient.Guilds .SelectMany(x => x.Channels) .Where(x => _channelNames.Any(n => n.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase))) .OfType<SocketTextChannel>() .ToArray(); } private void HandleRemovedUsers(HashSet<ulong> discordUserIds, HashSet<string> userNotified, CancellationToken token) { foreach (var userId in discordUserIds.Where(x => _discordClient.GetUser(x) == null)) { if (token.IsCancellationRequested) return; if (_discordClient.ConnectionState == ConnectionState.Connected) { userNotified.Add(userId.ToString()); } } } private static async Task NotifyUsersInChannel(TvShow tvShow, int seasonNumber, HashSet<ulong> discordUserIds, HashSet<string> userNotified, SocketTextChannel channel) { var usersToMention = channel.Users .Where(x => discordUserIds.Contains(x.Id)) .Where(x => !userNotified.Contains(x.Id.ToString())); if (usersToMention.Any()) { var messageBuilder = new StringBuilder(); messageBuilder.AppendLine($"The first episode of **season {seasonNumber}** of **{tvShow.Title}** has finished downloading!"); foreach (var user in usersToMention) { var userMentionText = $"{user.Mention} "; if (messageBuilder.Length + userMentionText.Length < DiscordConstants.MaxMessageLength) messageBuilder.Append(userMentionText); } await channel.SendMessageAsync(messageBuilder.ToString(), false, DiscordTvShowsRequestingWorkFlow.GenerateTvShowDetailsAsync(tvShow)); foreach (var user in usersToMention) { userNotified.Add(user.Id.ToString()); } } } } }
38.212963
183
0.598982
[ "MIT" ]
hthighwaymonk/requestrr
Requestrr.WebApi/RequestrrBot/Notifications/TvShows/ChannelTvShowNotifier.cs
4,129
C#
using System.Collections.Generic; namespace Randomizer.SMZ3.Generation { public class SeedData { public string Guid { get; set; } public string Seed { get; set; } public string Game { get; set; } public string Logic { get; set; } public string Mode { get; set; } public List<(World World, Dictionary<int, byte[]> Patches)> Worlds { get; set; } public List<Dictionary<string, string>> Playthrough { get; set; } } }
27
88
0.611111
[ "MIT" ]
MattEqualsCoder/SMZ3Randomizer
src/Randomizer.SMZ3/Generation/SeedData.cs
488
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 City.Chain.Identity.Website { 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>(); }); } }
26.259259
70
0.648801
[ "MIT" ]
CityChainFoundation/website-identity
src/City.Chain.Identity.Website/Program.cs
709
C#
namespace TAO3.Internal.Types; internal static class NumberHelper { private readonly static Dictionary<Type, string> _prefixes = new Dictionary<Type, string>() { [typeof(long)] = "L", [typeof(double)] = "d", [typeof(float)] = "f", [typeof(decimal)] = "m", [typeof(uint)] = "u", [typeof(ulong)] = "UL" }; public static string? GetNumberSuffix(Type numberType) { if (_prefixes.ContainsKey(numberType)) { return _prefixes[numberType]; } return null; } }
23.75
95
0.557895
[ "MIT" ]
Lawlzee/TAO3
TAO3/Internal/Types/NumberHelper.cs
572
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.470) // Version 5.470.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Windows.Forms; using System.Diagnostics; namespace ComponentFactory.Krypton.Docking { /// <summary> /// Set of common helper routines for Docking functionality /// </summary> public static class DockingHelper { #region Public /// <summary> /// Convert from DockEdge to DockStyle enumeration value. /// </summary> /// <param name="edge">DockEdge value to convert.</param> /// <param name="opposite">Should the separator be docked against the opposite edge.</param> /// <returns>DockStyle value.</returns> public static DockStyle DockStyleFromDockEdge(DockingEdge edge, bool opposite) { switch (edge) { case DockingEdge.Top: return (opposite ? DockStyle.Bottom : DockStyle.Top); case DockingEdge.Bottom: return (opposite ? DockStyle.Top : DockStyle.Bottom); case DockingEdge.Left: return (opposite ? DockStyle.Right : DockStyle.Left); case DockingEdge.Right: return (opposite ? DockStyle.Left : DockStyle.Right); default: // Should never happen! Debug.Assert(false); return DockStyle.Top; } } /// <summary> /// Convert the DockEdge to Orientation enumeration value. /// </summary> /// <param name="edge">DockEdge value to convert.</param> /// <returns>Orientation value.</returns> public static Orientation OrientationFromDockEdge(DockingEdge edge) { switch (edge) { case DockingEdge.Left: case DockingEdge.Right: return Orientation.Vertical; default: return Orientation.Horizontal; } } /// <summary> /// Find the inner space that occupied by the edge docking controls. /// </summary> /// <param name="c">Reference to control.</param> /// <returns>Rectangle in control coordinates.</returns> public static Rectangle InnerRectangle(Control c) { // Start with entire client area Rectangle inner = c.ClientRectangle; // Adjust for edge docked controls foreach (Control child in c.Controls) { if (child.Visible) { switch (child.Dock) { case DockStyle.Left: inner.Width -= child.Width; inner.X += child.Width; break; case DockStyle.Right: inner.Width -= child.Width; break; case DockStyle.Top: inner.Height -= child.Height; inner.Y += child.Height; break; case DockStyle.Bottom: inner.Height -= child.Height; break; } } } return inner; } #endregion } }
39.018868
157
0.505319
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-NET-5.470
Source/Krypton Components/ComponentFactory.Krypton.Docking/General/DockingHelper.cs
4,139
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("CSImpersonator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CSImpersonator")] [assembly: AssemblyCopyright("")] [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("50ee85a3-4c58-4f97-9278-bce55dc11c8f")] // 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.378378
85
0.726761
[ "MIT" ]
Defilan/CSImpersonator
Properties/AssemblyInfo.cs
1,422
C#
using System.Threading.Tasks; using ApiGateway.Client; using ApiGateway.Common.Constants; using ApiGateway.Common.Extensions; using ApiGateway.Common.Models; using ApiGateway.Core; using Microsoft.AspNetCore.Mvc; namespace ApiGateway.WebApi.Controllers { [Produces("application/json")] [Route("api/IsValid")] public class IsValidController : ApiControllerBase { private readonly IApiKeyValidator _keyValidator; public IsValidController(IApiKeyValidator keyValidator, IApiRequestHelper apiRequestHelper) : base(apiRequestHelper) { _keyValidator = keyValidator; } [HttpGet("{id}")] [ProducesResponseType(200, Type = typeof(KeyValidationResult))] [ProducesResponseType(404)] public async Task<IActionResult> Get(string id,string api, string httpMethod) { if (string.IsNullOrWhiteSpace(api)) { api = ""; } if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(httpMethod)) { return BadRequest(); } var serviceName = id.ToLower(); var challenge = new KeyChallenge { Type = ApiKeyType, Properties = {[ApiKeyPropertyNames.ClientSecret1] = ApiSecret, [ApiKeyPropertyNames.PublicKey] = ApiKey} }; var result = await _keyValidator.IsValid(challenge, httpMethod, serviceName, api); return Ok(result.ToLite()); } } }
31.27451
124
0.605643
[ "MIT" ]
shahedk/ApiGateway
src/ApiGateway.WebApi/Controllers/IsValidController.cs
1,597
C#
using System; using System.Threading.Tasks; using Autofac; using Autofac.Extensions.DependencyInjection; using AzureStorage.Tables; using Common.Log; using Lykke.Common.ApiLibrary.Middleware; using Lykke.Common.ApiLibrary.Swagger; using Lykke.Common.Api.Contract.Responses; using Lykke.Job.AzureTableCheck.Core.Services; using Lykke.Job.AzureTableCheck.Settings; using Lykke.Job.AzureTableCheck.Modules; using Lykke.Logs; using Lykke.SettingsReader; using Lykke.MonitoringServiceApiCaller; using Lykke.SlackNotification.AzureQueue; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Lykke.Job.AzureTableCheck { public class Startup { private string _monitoringServiceUrl; public IHostingEnvironment Environment { get; } public IContainer ApplicationContainer { get; private set; } public IConfigurationRoot Configuration { get; } public ILog Log { get; private set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddEnvironmentVariables(); Configuration = builder.Build(); Environment = env; } public IServiceProvider ConfigureServices(IServiceCollection services) { try { services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); }); services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration("v1", "AzureTableCheck API"); }); var builder = new ContainerBuilder(); var appSettings = Configuration.LoadSettings<AppSettings>(); if (appSettings.CurrentValue.MonitoringServiceClient != null) _monitoringServiceUrl = appSettings.CurrentValue.MonitoringServiceClient.MonitoringServiceUrl; Log = CreateLogWithSlack(services, appSettings); builder.RegisterModule(new JobModule(appSettings.CurrentValue.AzureTableCheckJob, appSettings.Nested(x => x.AzureTableCheckJob), Log)); builder.Populate(services); ApplicationContainer = builder.Build(); return new AutofacServiceProvider(ApplicationContainer); } catch (Exception ex) { Log?.WriteFatalError(nameof(Startup), nameof(ConfigureServices), ex); throw; } } public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime) { try { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseLykkeForwardedHeaders(); app.UseLykkeMiddleware("AzureTableCheck", ex => new ErrorResponse {ErrorMessage = "Technical problem"}); app.UseMvc(); app.UseSwagger(c => { c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value); }); app.UseSwaggerUI(x => { x.RoutePrefix = "swagger/ui"; x.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); }); app.UseStaticFiles(); appLifetime.ApplicationStarted.Register(() => StartApplication().GetAwaiter().GetResult()); appLifetime.ApplicationStopping.Register(() => StopApplication().GetAwaiter().GetResult()); appLifetime.ApplicationStopped.Register(() => CleanUp().GetAwaiter().GetResult()); } catch (Exception ex) { Log?.WriteFatalError(nameof(Startup), nameof(Configure), ex); throw; } } private async Task StartApplication() { try { // NOTE: Job not yet recieve and process IsAlive requests here await ApplicationContainer.Resolve<IStartupManager>().StartAsync(); await Log.WriteMonitorAsync("", Program.EnvInfo, "Started"); //await AutoRegistrationInMonitoring.RegisterAsync(Configuration, _monitoringServiceUrl, Log); } catch (Exception ex) { await Log.WriteFatalErrorAsync(nameof(Startup), nameof(StartApplication), "", ex); throw; } } private async Task StopApplication() { try { // NOTE: Job still can recieve and process IsAlive requests here, so take care about it if you add logic here. await ApplicationContainer.Resolve<IShutdownManager>().StopAsync(); } catch (Exception ex) { if (Log != null) { await Log.WriteFatalErrorAsync(nameof(Startup), nameof(StopApplication), "", ex); } throw; } } private async Task CleanUp() { try { // NOTE: Job can't recieve and process IsAlive requests here, so you can destroy all resources if (Log != null) { await Log.WriteMonitorAsync("", Program.EnvInfo, "Terminating"); } ApplicationContainer.Dispose(); } catch (Exception ex) { if (Log != null) { await Log.WriteFatalErrorAsync(nameof(Startup), nameof(CleanUp), "", ex); (Log as IDisposable)?.Dispose(); } throw; } } private static ILog CreateLogWithSlack(IServiceCollection services, IReloadingManager<AppSettings> settings) { var consoleLogger = new LogToConsole(); var aggregateLogger = new AggregateLogger(); aggregateLogger.AddLog(consoleLogger); var dbLogConnectionStringManager = settings.Nested(x => x.AzureTableCheckJob.Db.LogsConnString); var dbLogConnectionString = dbLogConnectionStringManager.CurrentValue; if (string.IsNullOrEmpty(dbLogConnectionString)) { consoleLogger.WriteWarningAsync(nameof(Startup), nameof(CreateLogWithSlack), "Table loggger is not inited").Wait(); return aggregateLogger; } if (dbLogConnectionString.StartsWith("${") && dbLogConnectionString.EndsWith("}")) throw new InvalidOperationException($"LogsConnString {dbLogConnectionString} is not filled in settings"); var persistenceManager = new LykkeLogToAzureStoragePersistenceManager( AzureTableStorage<LogEntity>.Create(dbLogConnectionStringManager, "AzureTableCheckLog", consoleLogger), consoleLogger); // Creating slack notification service, which logs own azure queue processing messages to aggregate log var slackService = services.UseSlackNotificationsSenderViaAzureQueue(new AzureQueueIntegration.AzureQueueSettings { ConnectionString = settings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString, QueueName = settings.CurrentValue.SlackNotifications.AzureQueue.QueueName }, aggregateLogger); var slackNotificationsManager = new LykkeLogToAzureSlackNotificationsManager(slackService, consoleLogger); // Creating azure storage logger, which logs own messages to concole log var azureStorageLogger = new LykkeLogToAzureStorage( persistenceManager, slackNotificationsManager, consoleLogger); azureStorageLogger.Start(); aggregateLogger.AddLog(azureStorageLogger); return aggregateLogger; } } }
37.927928
151
0.589311
[ "MIT" ]
LykkeCity/Lykke.Job.AzureTableCheck
src/Lykke.Job.AzureTableCheck/Startup.cs
8,422
C#
using Microsoft.AspNetCore.Mvc; namespace CPTech.Payment.WeChatPay { /// <summary> /// WeChatPay 通知应答。 /// </summary> public static class WeChatPayNotifyResult { private static readonly ContentResult _success = new ContentResult { Content = "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>", ContentType = "text/xml", StatusCode = 200 }; private static readonly ContentResult _failure = new ContentResult { Content = "<xml><return_code><![CDATA[FAIL]]></return_code></xml>", ContentType = "text/xml", StatusCode = 200 }; /// <summary> /// 成功 /// </summary> public static IActionResult Success => _success; /// <summary> /// 失败 /// </summary> public static IActionResult Failure => _failure; } }
33.875
193
0.619926
[ "MIT" ]
huamouse/Bank
src/CPTech.Core.Jwt/Payment/WeChatPay/WeChatPayNotifyResult.cs
833
C#
namespace Cawotte.Toolbox.Audio { using UnityEngine; /* * Class used to define a sound, any playable sound clips. * The audio manager contains an Array of 'Sound' which will all contain a sound. * */ /// <summary> /// Class encapsulating a playable sound, /// that must be registered in the AudioManager or a SoundList from the AudioManager. /// </summary> [System.Serializable] [CreateAssetMenu(fileName ="New Sound", menuName = "Audio/Sound")] public class Sound : ScriptableObject { [Header("Sound Info")] public string name; //sound name public AudioClip clip; //sound asset public bool isMusic = false; [Header("Sound parameters")] [SerializeField] [Range(0f, 1f)] private float volume = 0.5f; [SerializeField] [Range(.1f, 3f)] private float pitch = 1f; [SerializeField] private bool loop = false; //No volume spatialisation private float minDistance = 0f; private float maxDistance = 500f; //component which will play the sound [HideInInspector] public AudioSource source; public float Volume { get => volume; } public float Pitch { get => pitch; } public float MinDistance { get => minDistance; } public float MaxDistance { get => maxDistance; } public bool Loop { get => loop; set => loop = value; } /// <summary> /// Load the Sound in the given source. /// </summary> /// <param name="source"></param> /// <param name="sound"></param> public void LoadIn(AudioSource source) { source.clip = this.clip; source.volume = this.Volume; source.pitch = this.Pitch; source.loop = this.Loop; //No spatialization source.minDistance = this.MinDistance; source.maxDistance = this.MaxDistance; source.spatialBlend = 1f; source.rolloffMode = AudioRolloffMode.Linear; } } }
28.346667
89
0.575259
[ "MIT" ]
Cawotte/SmallWorld_WeeklyJam40
Assets/Scripts/Toolbox/Audio/Sound.cs
2,128
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using FakeItEasy; using FluentAssertions; using Machine.Specifications; using SolutionInspector.Api.Configuration.MsBuildParsing; using SolutionInspector.Api.Extensions; using SolutionInspector.Api.ObjectModel; #region R# preamble for Machine.Specifications files // ReSharper disable ArrangeTypeMemberModifiers // ReSharper disable ClassNeverInstantiated.Local // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Local // ReSharper disable NotAccessedField.Local // ReSharper disable StaticMemberInGenericType // ReSharper disable UnassignedField.Global // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable UnassignedGetOnlyAutoProperty #endregion namespace SolutionInspector.Api.Tests.ObjectModel { [Subject (typeof(ProjectItem))] class ProjectItemSpec { static string SolutionPath; static IMsBuildParsingConfiguration MsBuildParsingConfiguration; Establish ctx = () => { SolutionPath = Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath).AssertNotNull(), @"ObjectModel\TestData\ProjectItem\TestSolution.sln"); MsBuildParsingConfiguration = A.Fake<IMsBuildParsingConfiguration>(); A.CallTo(() => MsBuildParsingConfiguration.IsValidProjectItemType(A<string>._)).Returns(true); }; class when_loading { Establish ctx = () => { ProjectItemName = "Direct.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).Single(); It parses_project_item = () => { var projectItemPath = GetProjectItemPath(ProjectItemName); Result.Name.Should().Be(ProjectItemName); Result.Include.Should().Be(new ProjectItemInclude(ProjectItemName, ProjectItemName)); Result.BuildAction.Should().Be(ProjectItemBuildAction.Compile); Result.File.FullName.Should().Be(projectItemPath); Result.Metadata["CustomMetadata"].Should().Be("SomeCustomMetadata"); Result.CustomTool.Should().Be("SomeCustomTool"); Result.CustomToolNamespace.Should().Be("SomeCustomToolNamespace"); Result.Parent.Should().BeNull(); Result.Children.Should().BeEmpty(); Result.Identifier.Should().Be($"Project.csproj/{ProjectItemName}"); Result.Location.Should().Be(new ProjectLocation(54, 5)); Result.FullPath.Should().Be(projectItemPath); }; static string ProjectItemName; static IProjectItem Result; } class when_loading_nested_project_item { Establish ctx = () => { ProjectItemName = "Nested.Designer.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).Single(); It parses_project_item = () => { var include = $"Folder\\{ProjectItemName}"; var projectItemPath = GetProjectItemPath(include); Result.Name.Should().Be(ProjectItemName); Result.Include.Should().Be(new ProjectItemInclude(include, include)); Result.BuildAction.Should().Be(ProjectItemBuildAction.Compile); Result.File.FullName.Should().Be(projectItemPath); Result.Parent.Name.Should().Be("Nested.resx"); Result.Children.Should().BeEmpty(); Result.Identifier.Should().Be($"Project.csproj/Folder/Nested.resx/{ProjectItemName}"); Result.Location.Should().Be(new ProjectLocation(59, 5)); Result.FullPath.Should().Be(projectItemPath); }; static string ProjectItemName; static IProjectItem Result; } class when_loading_parent_project_item { Establish ctx = () => { ProjectItemName = "Nested.resx"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).Single(); It parses_project_item = () => { var include = $"Folder\\{ProjectItemName}"; var projectItemPath = GetProjectItemPath(include); Result.Name.Should().Be(ProjectItemName); Result.Include.Should().Be(new ProjectItemInclude(include, include)); Result.BuildAction.Should().Be(ProjectItemBuildAction.EmbeddedResource); Result.File.FullName.Should().Be(projectItemPath); Result.Parent.Should().BeNull(); Result.Children.Single().Name.Should().Be("Nested.Designer.cs"); Result.Identifier.Should().Be($"Project.csproj/Folder/{ProjectItemName}"); Result.Location.Should().Be(new ProjectLocation(45, 5)); Result.FullPath.Should().Be(projectItemPath); }; static string ProjectItemName; static IProjectItem Result; } class when_loading_linked_project_item { Establish ctx = () => { ProjectItemName = "Link.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).Single(); It parses_project_item = () => { var projectItemPath = Path.Combine(Path.GetDirectoryName(SolutionPath).AssertNotNull(), ProjectItemName); Result.Name.Should().Be(ProjectItemName); Result.Include.Should().Be(new ProjectItemInclude("..\\Link.cs", "..\\Link.cs")); Result.BuildAction.Should().Be(ProjectItemBuildAction.Compile); Result.File.FullName.Should().Be(projectItemPath); Result.Parent.Should().BeNull(); Result.Children.Should().BeEmpty(); Result.Identifier.Should().Be($"Project.csproj/{ProjectItemName}"); Result.Location.Should().Be(new ProjectLocation(51, 5)); Result.FullPath.Should().Be(projectItemPath); }; static string ProjectItemName; static IProjectItem Result; } class when_loading_a_duplicate_project_item { Establish ctx = () => { ProjectItemName = "Duplicate.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).ToArray(); It returns_both = () => Result.Should().HaveCount(2); static string ProjectItemName; static IProjectItem[] Result; } class when_loading_a_project_item_with_duplicate_name_but_differing_somehow { Establish ctx = () => { ProjectItemName = "AlmostDuplicate.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).ToArray(); It parses_both_items = () => { Result[0].Include.Evaluated.Should().Be("AlmostDuplicate.cs"); Result[0].Metadata["Metadata"].Should().Be("3"); Result[1].Include.Evaluated.Should().Be("AlmostDuplicate.cs"); Result[1].Metadata["Metadata"].Should().Be("5"); }; static string ProjectItemName; static IProjectItem[] Result; } class when_loading_a_project_item_included_by_wildcard { Establish ctx = () => { ProjectItemName = "IncludedByWildcard.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).Single(); It parses_project_item = () => { Result.Include.Evaluated.Should().Be("Wildcard\\IncludedByWildcard.cs"); Result.Include.Unevaluated.Should().Be("Wildcard\\*.cs;Wildcard2\\*.cs"); Result.IsIncludedByWildcard.Should().BeTrue(); Result.WildcardInclude.Should().Be("Wildcard\\*.cs;Wildcard2\\*.cs"); Result.WildcardExclude.Should().Be("Wildcard\\Excluded.cs;Wildcard2\\Excluded2.cs"); Result.Metadata["Metadata"].Should().Be("SomeMetadata"); }; It does_not_load_excluded_items = () => { LoadProjectItems("Exclude.cs").Should().BeEmpty(); LoadProjectItems("Exclude2.cs").Should().BeEmpty(); }; static string ProjectItemName; static IProjectItem Result; } class when_loading_a_project_item_included_by_wildcard_and_normally { Establish ctx = () => { ProjectItemName = "IncludedByWildcardAndNormally.cs"; }; Because of = () => Result = LoadProjectItems(ProjectItemName).ToArray(); It parses_both_items = () => { Result[0].Include.Evaluated.Should().Be("Wildcard\\IncludedByWildcardAndNormally.cs"); Result[0].Include.Unevaluated.Should().Be("Wildcard\\*.cs;Wildcard2\\*.cs"); Result[0].IsIncludedByWildcard.Should().BeTrue(); Result[0].WildcardInclude.Should().Be("Wildcard\\*.cs;Wildcard2\\*.cs"); Result[0].WildcardExclude.Should().Be("Wildcard\\Excluded.cs;Wildcard2\\Excluded2.cs"); Result[0].Metadata["Metadata"].Should().Be("SomeMetadata"); Result[1].Include.Evaluated.Should().Be("Wildcard\\IncludedByWildcardAndNormally.cs"); Result[1].Include.Unevaluated.Should().Be("Wildcard\\IncludedByWildcardAndNormally.cs"); Result[1].IsIncludedByWildcard.Should().BeFalse(); Result[1].WildcardInclude.Should().BeNull(); Result[1].WildcardExclude.Should().BeNull(); Result[1].Metadata.GetValueOrDefault("Metadata").Should().BeNull(); }; static string ProjectItemName; static IProjectItem[] Result; } static IEnumerable<IProjectItem> LoadProjectItems (string itemName) { var solution = Solution.Load(SolutionPath, MsBuildParsingConfiguration); var project = solution.Projects.Single(); return project.ProjectItems.Where(i => i.Name == itemName); } static string GetProjectItemPath (string itemName) { return Path.Combine(Path.GetDirectoryName(SolutionPath).AssertNotNull(), $"Project\\{itemName}"); } } }
37.736
113
0.682213
[ "MIT" ]
chrischu/SolutionChecker
src/SolutionInspector.Api.Tests/ObjectModel/ProjectItemSpec.cs
9,436
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Lonsdale.API.Data; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; namespace Lonsdale.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); services.AddCors(); services.AddScoped<IAuthRepository, AuthRepository>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
36.15493
143
0.63732
[ "MIT" ]
AxelDevara/LonsdaleProject
Lonsdale.API/Startup.cs
2,567
C#
using Newtonsoft.Json; namespace GodSeekerPlus.Settings; public sealed class GlobalSettings { [JsonIgnore] public Dictionary<string, bool> modules = ModuleHelper.GetDefaultModuleStateDict(); [JsonIgnore] public float fastSuperDashSpeedMultiplier = 1.5f; [JsonIgnore] public int frameRateLimitMultiplier = 5; [JsonIgnore] public int lifebloodAmount = 5; [JsonProperty(PropertyName = "features")] public Dictionary<string, bool> Modules { get => modules; set { foreach (KeyValuePair<string, bool> pair in value) { if (modules.ContainsKey(pair.Key)) { modules[pair.Key] = pair.Value; } } } } [JsonProperty(PropertyName = "fastSuperDashSpeedMultiplier")] public float FastSuperDashSpeedMultiplier { get => fastSuperDashSpeedMultiplier; set => fastSuperDashSpeedMultiplier = MiscUtil.ForceInRange(value, 1f, 2f); } [JsonProperty(PropertyName = "frameRateLimitMultiplier")] public int FrameRateLimitMultiplier { get => frameRateLimitMultiplier; set => frameRateLimitMultiplier = MiscUtil.ForceInRange(value, 0, 10); } [JsonProperty(PropertyName = "lifebloodAmount")] public int LifebloodAmount { get => lifebloodAmount; set => lifebloodAmount = MiscUtil.ForceInRange(value, 0, 10); } }
24.98
77
0.745396
[ "MIT" ]
TheMulhima/HollowKnight.GodSeekerPlus
GodSeekerPlus/Settings/GlobalSettings.cs
1,249
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands { #region get-date /// <summary> /// Implementation for the get-date command. /// </summary> [Cmdlet(VerbsCommon.Get, "Date", DefaultParameterSetName = DateAndFormatParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096615")] [OutputType(typeof(string))] [OutputType(typeof(DateTime), ParameterSetName = new[] { DateAndFormatParameterSet, UnixTimeSecondsAndFormatParameterSet })] public sealed class GetDateCommand : Cmdlet { #region parameters /// <summary> /// Allows user to override the date/time object that will be processed. /// </summary> [Parameter(ParameterSetName = DateAndFormatParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = DateAndUFormatParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("LastWriteTime")] public DateTime Date { get { return _date; } set { _date = value; _dateSpecified = true; } } private DateTime _date; private bool _dateSpecified; // The const comes from DateTimeOffset.MinValue.ToUnixTimeSeconds() private const long MinimumUnixTimeSecond = -62135596800; // The const comes from DateTimeOffset.MaxValue.ToUnixTimeSeconds() private const long MaximumUnixTimeSecond = 253402300799; /// <summary> /// Gets or sets whether to treat a numeric input as ticks, or unix time. /// </summary> [Parameter(ParameterSetName = UnixTimeSecondsAndFormatParameterSet, Mandatory = true)] [Parameter(ParameterSetName = UnixTimeSecondsAndUFormatParameterSet, Mandatory = true)] [ValidateRange(MinimumUnixTimeSecond, MaximumUnixTimeSecond)] [Alias("UnixTime")] public long UnixTimeSeconds { get { return _unixTimeSeconds; } set { _unixTimeSeconds = value; _unixTimeSecondsSpecified = true; } } private long _unixTimeSeconds; private bool _unixTimeSecondsSpecified; /// <summary> /// Allows the user to override the year. /// </summary> [Parameter] [ValidateRangeAttribute(1, 9999)] public int Year { get { return _year; } set { _year = value; _yearSpecified = true; } } private int _year; private bool _yearSpecified; /// <summary> /// Allows the user to override the month. /// </summary> [Parameter] [ValidateRangeAttribute(1, 12)] public int Month { get { return _month; } set { _month = value; _monthSpecified = true; } } private int _month; private bool _monthSpecified; /// <summary> /// Allows the user to override the day. /// </summary> [Parameter] [ValidateRangeAttribute(1, 31)] public int Day { get { return _day; } set { _day = value; _daySpecified = true; } } private int _day; private bool _daySpecified; /// <summary> /// Allows the user to override the hour. /// </summary> [Parameter] [ValidateRangeAttribute(0, 23)] public int Hour { get { return _hour; } set { _hour = value; _hourSpecified = true; } } private int _hour; private bool _hourSpecified; /// <summary> /// Allows the user to override the minute. /// </summary> [Parameter] [ValidateRangeAttribute(0, 59)] public int Minute { get { return _minute; } set { _minute = value; _minuteSpecified = true; } } private int _minute; private bool _minuteSpecified; /// <summary> /// Allows the user to override the second. /// </summary> [Parameter] [ValidateRangeAttribute(0, 59)] public int Second { get { return _second; } set { _second = value; _secondSpecified = true; } } private int _second; private bool _secondSpecified; /// <summary> /// Allows the user to override the millisecond. /// </summary> [Parameter] [ValidateRangeAttribute(0, 999)] public int Millisecond { get { return _millisecond; } set { _millisecond = value; _millisecondSpecified = true; } } private int _millisecond; private bool _millisecondSpecified; /// <summary> /// This option determines the default output format used to display the object get-date emits. /// </summary> [Parameter] public DisplayHintType DisplayHint { get; set; } = DisplayHintType.DateTime; /// <summary> /// Unix format string. /// </summary> [Parameter(ParameterSetName = DateAndUFormatParameterSet, Mandatory = true)] [Parameter(ParameterSetName = UnixTimeSecondsAndUFormatParameterSet, Mandatory = true)] public string UFormat { get; set; } /// <summary> /// DotNet format string. /// </summary> [Parameter(ParameterSetName = DateAndFormatParameterSet)] [Parameter(ParameterSetName = UnixTimeSecondsAndFormatParameterSet)] [ArgumentCompletions("FileDate", "FileDateUniversal", "FileDateTime", "FileDateTimeUniversal")] public string Format { get; set; } /// <summary> /// Gets or sets a value that converts date to UTC before formatting. /// </summary> [Parameter] public SwitchParameter AsUTC { get; set; } #endregion #region methods /// <summary> /// Get the time. /// </summary> protected override void ProcessRecord() { DateTime dateToUse = DateTime.Now; int offset; // use passed date object if specified if (_dateSpecified) { dateToUse = Date; } else if (_unixTimeSecondsSpecified) { dateToUse = DateTimeOffset.FromUnixTimeSeconds(UnixTimeSeconds).LocalDateTime; } // use passed year if specified if (_yearSpecified) { offset = Year - dateToUse.Year; dateToUse = dateToUse.AddYears(offset); } // use passed month if specified if (_monthSpecified) { offset = Month - dateToUse.Month; dateToUse = dateToUse.AddMonths(offset); } // use passed day if specified if (_daySpecified) { offset = Day - dateToUse.Day; dateToUse = dateToUse.AddDays(offset); } // use passed hour if specified if (_hourSpecified) { offset = Hour - dateToUse.Hour; dateToUse = dateToUse.AddHours(offset); } // use passed minute if specified if (_minuteSpecified) { offset = Minute - dateToUse.Minute; dateToUse = dateToUse.AddMinutes(offset); } // use passed second if specified if (_secondSpecified) { offset = Second - dateToUse.Second; dateToUse = dateToUse.AddSeconds(offset); } // use passed millisecond if specified if (_millisecondSpecified) { offset = Millisecond - dateToUse.Millisecond; dateToUse = dateToUse.AddMilliseconds(offset); dateToUse = dateToUse.Subtract(TimeSpan.FromTicks(dateToUse.Ticks % 10000)); } if (AsUTC) { dateToUse = dateToUse.ToUniversalTime(); } if (UFormat != null) { // format according to UFormat string WriteObject(UFormatDateString(dateToUse)); } else if (Format != null) { // format according to Format string // Special case built-in primitives: FileDate, FileDateTime. // These are the ISO 8601 "basic" formats, dropping dashes and colons // so that they can be used in file names if (string.Equals("FileDate", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMdd"; } else if (string.Equals("FileDateUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddZ"; } else if (string.Equals("FileDateTime", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMddTHHmmssffff"; } else if (string.Equals("FileDateTimeUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddTHHmmssffffZ"; } WriteObject(dateToUse.ToString(Format, CultureInfo.CurrentCulture)); } else { // output DateTime object wrapped in an PSObject with DisplayHint attached PSObject outputObj = new(dateToUse); PSNoteProperty note = new("DisplayHint", DisplayHint); outputObj.Properties.Add(note); WriteObject(outputObj); } } private static readonly DateTime s_epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <summary> /// This is more an implementation of the UNIX strftime. /// </summary> private string UFormatDateString(DateTime dateTime) { int offset = 0; StringBuilder sb = new(); // folks may include the "+" as part of the format string if (UFormat[0] == '+') { offset++; } for (int i = offset; i < UFormat.Length; i++) { if (UFormat[i] == '%') { i++; switch (UFormat[i]) { case 'A': sb.Append("{0:dddd}"); break; case 'a': sb.Append("{0:ddd}"); break; case 'B': sb.Append("{0:MMMM}"); break; case 'b': sb.Append("{0:MMM}"); break; case 'C': sb.Append(dateTime.Year / 100); break; case 'c': sb.Append("{0:ddd} {0:dd} {0:MMM} {0:yyyy} {0:HH}:{0:mm}:{0:ss}"); break; case 'D': sb.Append("{0:MM/dd/yy}"); break; case 'd': sb.Append("{0:dd}"); break; case 'e': sb.Append(StringUtil.Format("{0,2}", dateTime.Day)); break; case 'F': sb.Append("{0:yyyy}-{0:MM}-{0:dd}"); break; case 'G': sb.Append(StringUtil.Format("{0:0000}", ISOWeek.GetYear(dateTime))); break; case 'g': int isoYearWithoutCentury = ISOWeek.GetYear(dateTime) % 100; sb.Append(StringUtil.Format("{0:00}", isoYearWithoutCentury)); break; case 'H': sb.Append("{0:HH}"); break; case 'h': sb.Append("{0:MMM}"); break; case 'I': sb.Append("{0:hh}"); break; case 'j': sb.Append(StringUtil.Format("{0:000}", dateTime.DayOfYear)); break; case 'k': sb.Append(StringUtil.Format("{0,2:0}", dateTime.Hour)); break; case 'l': sb.Append("{0,2:%h}"); break; case 'M': sb.Append("{0:mm}"); break; case 'm': sb.Append("{0:MM}"); break; case 'n': sb.Append('\n'); break; case 'p': sb.Append("{0:tt}"); break; case 'R': sb.Append("{0:HH:mm}"); break; case 'r': sb.Append("{0:hh:mm:ss tt}"); break; case 'S': sb.Append("{0:ss}"); break; case 's': sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(s_epoch).TotalSeconds)); break; case 'T': sb.Append("{0:HH:mm:ss}"); break; case 't': sb.Append('\t'); break; case 'U': sb.Append(dateTime.DayOfYear / 7); break; case 'u': int dayOfWeek = dateTime.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)dateTime.DayOfWeek; sb.Append(dayOfWeek); break; case 'V': sb.Append(StringUtil.Format("{0:00}", ISOWeek.GetWeekOfYear(dateTime))); break; case 'W': sb.Append(dateTime.DayOfYear / 7); break; case 'w': sb.Append((int)dateTime.DayOfWeek); break; case 'X': sb.Append("{0:HH:mm:ss}"); break; case 'x': sb.Append("{0:MM/dd/yy}"); break; case 'Y': sb.Append("{0:yyyy}"); break; case 'y': sb.Append("{0:yy}"); break; case 'Z': sb.Append("{0:zz}"); break; default: sb.Append(UFormat[i]); break; } } else { // It's not a known format specifier, so just append it sb.Append(UFormat[i]); } } return StringUtil.Format(sb.ToString(), dateTime); } #endregion private const string DateAndFormatParameterSet = "DateAndFormat"; private const string DateAndUFormatParameterSet = "DateAndUFormat"; private const string UnixTimeSecondsAndFormatParameterSet = "UnixTimeSecondsAndFormat"; private const string UnixTimeSecondsAndUFormatParameterSet = "UnixTimeSecondsAndUFormat"; } #endregion #region DisplayHintType enum /// <summary> /// Display Hint type. /// </summary> public enum DisplayHintType { /// <summary> /// Display preference Date-Only. /// </summary> Date, /// <summary> /// Display preference Time-Only. /// </summary> Time, /// <summary> /// Display preference Date and Time. /// </summary> DateTime } #endregion }
30.383585
151
0.432052
[ "MIT" ]
Hwangjonggyun/PowerShell
src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs
18,139
C#
using System; namespace JX.Application.DTOs { /// <summary> /// 数据库表:ProductPrice 的DTO类. /// </summary> public partial class ProductPriceDTO { #region Properties private System.Int32 _id = 0; /// <summary> /// ID (主键)(自增长) /// </summary> public System.Int32 ID { get {return _id;} set {_id = value;} } private System.Int32 _productID = 0; /// <summary> /// 商品ID /// </summary> public System.Int32 ProductID { get {return _productID;} set {_productID = value;} } private System.String _propertyValue = string.Empty; /// <summary> /// 属性值 /// </summary> public System.String PropertyValue { get {return _propertyValue;} set {_propertyValue = value;} } private System.String _tableName = string.Empty; /// <summary> /// 表名 /// </summary> public System.String TableName { get {return _tableName;} set {_tableName = value;} } private System.Int32 _groupID = 0; /// <summary> /// 会员组ID /// </summary> public System.Int32 GroupID { get {return _groupID;} set {_groupID = value;} } private System.Decimal _price = 0; /// <summary> /// 价格 /// </summary> public System.Decimal Price { get {return _price;} set {_price = value;} } #endregion } }
18.705882
54
0.613994
[ "Apache-2.0" ]
lixiong24/IPS2.1
CodeSmith/output/DTOs/ProductPriceDTO.cs
1,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("simulation game")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HP Inc.")] [assembly: AssemblyProduct("simulation game")] [assembly: AssemblyCopyright("Copyright © HP Inc. 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("09e7eca9-cbcc-4be0-818b-f7b3b757db98")] // 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.162162
84
0.747167
[ "MIT" ]
Tatheon/Task-1
simulation game/simulation game/Properties/AssemblyInfo.cs
1,415
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using MonoGame.Extended.ViewportAdapters; using System; namespace MonoGameCefSharp { public class SharedDataManager : BaseManager { private static SharedDataManager _instance; public static SharedDataManager Instance { get { if (_instance == null) { _instance = new SharedDataManager(); } return _instance; } } public const string Url = "https://html5test.com"; //public const string Url = "https://youtu.be/dR-4vgED8pQ?t=687"; public const int Width = 1920; public const int Height = 1080; //public const int Width = 3840; //public const int Height = 2160; public int ScreenWidth { get; set; } public int ScreenHeight { get; set; } public Version Version { get; set; } public GameComponentCollection Components { get; set; } public ContentManager Content { get; set; } public GraphicsDevice GraphicsDevice { get; set; } public GameServiceContainer Services { get; set; } public GameWindow Window { get; set; } public ScalingViewportAdapter ViewportAdapter { get; set; } public SpriteBatch SpriteBatch { get; set; } public override void Initialize() { ViewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, ScreenWidth, ScreenHeight); SpriteBatch = new SpriteBatch(GraphicsDevice); base.Initialize(); } public override void Update(GameTime gameTime) { base.Update(gameTime); } public override void Draw(GameTime gameTime) { base.Draw(gameTime); } public override void Dispose() { ViewportAdapter = null; SpriteBatch.Dispose(); base.Dispose(); } } }
26.935065
107
0.586307
[ "MIT" ]
Lysfith/MonoGameCefSharp
MonoGameCefSharp/SharedDataManager.cs
2,076
C#
// // Mono.Xml.SecurityParser.cs class implementation // // Author: // Sebastien Pouliot (spouliot@motus.com) // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Security; namespace Mono.Xml { // convert an XML document into SecurityElement objects #if INSIDE_CORLIB internal #else public #endif class SecurityParser : SmallXmlParser, SmallXmlParser.IContentHandler { private SecurityElement root; public SecurityParser () : base () { stack = new Stack (); } public void LoadXml (string xml) { root = null; stack.Clear (); Parse (new StringReader (xml), this); } public SecurityElement ToXml () { return root; } // IContentHandler private SecurityElement current; private Stack stack; public void OnStartParsing (SmallXmlParser parser) {} public void OnProcessingInstruction (string name, string text) {} public void OnIgnorableWhitespace (string s) {} public void OnStartElement (string name, SmallXmlParser.IAttrList attrs) { SecurityElement newel = new SecurityElement (name); if (root == null) { root = newel; current = newel; } else { SecurityElement parent = (SecurityElement) stack.Peek (); parent.AddChild (newel); } stack.Push (newel); current = newel; // attributes int n = attrs.Length; for (int i=0; i < n; i++) current.AddAttribute (attrs.GetName (i), SecurityElement.Escape (attrs.GetValue (i))); } public void OnEndElement (string name) { current = (SecurityElement) stack.Pop (); } public void OnChars (string ch) { current.Text = SecurityElement.Escape (ch); } public void OnEndParsing (SmallXmlParser parser) {} } }
26.481818
90
0.711637
[ "Apache-2.0" ]
121468615/mono
mcs/class/corlib/Mono.Xml/SecurityParser.cs
2,913
C#
using CommandLine; using GitFolks.Utils; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace GitFolks { class Program { static void Main(string[] args) { Initialize(args); DoWork(); } private static void DoWork() { bool result = GitFolks.Services.GitFolksService.ListAllUsersFromOrg(); Environment.Exit(result ? 1 : -1); } private static void Initialize(string[] args) { Console.WriteLine($"GitFolks - {Assembly.GetEntryAssembly().GetName().Version}"); CommandLine.Parser.Default.ParseArguments<Arguments.DefaultOptions>(args) .WithParsed(RunOptions) .WithNotParsed(HandleParseError); Console.WriteLine(); } static void RunOptions(Arguments.DefaultOptions opts) { //handle options //if (string.IsNullOrEmpty(opts.Org)) //{ // Console.WriteLine("Please provide organization to scan. to see all parameters use -h"); // Environment.Exit(-1); //} GlobalConfiguration.SetWorkingPath(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); GlobalConfiguration.SetGithubToken(opts.GithubToken); GlobalConfiguration.SetOrgName(opts.Org); if (!Directory.Exists(GlobalConfiguration.OutputPath)) Directory.CreateDirectory(GlobalConfiguration.OutputPath); Console.WriteLine($"OS: {OS.GetCurrent()} - Architecture: {RuntimeInformation.OSArchitecture.ToString()} architecture"); Console.WriteLine($"Working Path: {GlobalConfiguration.WorkingPath}"); } static void HandleParseError(IEnumerable<Error> errs) { foreach (var error in errs) { if (error.Tag != ErrorType.MissingRequiredOptionError) continue; Environment.Exit(-1); } } } }
29.30137
132
0.611968
[ "MIT" ]
rodrigoramosrs/gitfolks
src/Program.cs
2,141
C#
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Plethora.Xaml.Converters { /// <summary> /// A <see cref="IValueConverter"/> which acts to NOT a boolean values. /// </summary> /// <remarks> /// Requires a boolean value. /// Returns (!value) /// </remarks> [ValueConversion(typeof(bool), typeof(bool))] public class BooleanNotConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool) { return !(bool)value; } return DependencyProperty.UnsetValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool) { return !(bool)value; } return DependencyProperty.UnsetValue; } } }
25.564103
103
0.581745
[ "MIT", "BSD-3-Clause" ]
mikebarker/Plethora.NET
src/Plethora.Xaml/Converters/Logic/BooleanNotConverter.cs
999
C#
namespace Task4 { /// <summary> /// Move command class /// </summary> public sealed class MoveCommand : Command { private Line newLine; private Line oldLine; /// <summary> /// Initializes a new instance of the <see cref="MoveCommand"/> class /// </summary> public MoveCommand(Line newLine) => this.newLine = newLine; /// <summary> /// Execute move command /// </summary> public override void Execute(Model model) { this.oldLine = model.SelectedLine; model.RemoveSelectedLine(); model.AddLine(this.newLine); } /// <summary> /// Unexecute move command /// </summary> public override void Unexecute(Model model) { model.RemoveLine(this.newLine); model.AddLine(this.oldLine); } } }
25.277778
77
0.535165
[ "Unlicense" ]
RexTremendaeMajestatis/SACDP
course2/sem3/hw1/task4/task4/Controller/Command/MoveCommand.cs
912
C#
using System.Collections.Generic; using System.Threading.Tasks; using NClient.Annotations.Http; using NClient.Providers.Results.HttpResults; namespace NClient.Benchmark.Client.JsonHttpResponseClient { public interface INClientJsonHttpResponseClient { [PostMethod("/api")] Task<IHttpResponse<List<string>>> SendAsync([BodyParam] string[] ids); } public interface IRefitJsonHttpResponseClient { [Refit.Post("/api")] Task<Refit.IApiResponse<List<string>>> SendAsync([Refit.Body] string[] ids); } public interface IRestEaseJsonHttpResponseClient { [RestEase.Post("/api")] Task<RestEase.Response<List<string>>> SendAsync([RestEase.Body] string[] ids); } }
28.692308
86
0.69571
[ "Apache-2.0" ]
nclient/NClient
benchmark/NClient.Benchmark.Client/JsonHttpResponseClient/JsonHttpResponseClient.cs
746
C#
namespace Judge.Application.ViewModels.Admin.Submits { using System.Collections.Generic; using Judge.Model.SubmitSolution; public sealed class SubmitsQueue { public IEnumerable<SubmitQueueItem> Submits { get; set; } public IEnumerable<LanguageItem> Languages { get; set; } public IEnumerable<SubmitStatusItem> Statuses { get; set; } public int? SelectedLanguage { get; set; } public SubmitStatus? SelectedStatus { get; set; } } }
26.105263
67
0.683468
[ "MIT" ]
Backs/judge.net
Judge/Judge.Application/ViewModels/Admin/Submits/SubmitsQueue.cs
498
C#
using System; using System.Collections.Generic; using System.Globalization; using Orckestra.Composer.Providers.Dam; using Orckestra.Overture.ServiceModel.Orders; namespace Orckestra.Composer.Cart.Parameters { public class CreateLineItemDetailViewModelParam { public Action<LineItem> PreMapAction { get; set; } public LineItem LineItem { get; set; } public IDictionary<(string ProductId, string VariantId), ProductMainImage> ImageDictionary { get; set; } public CultureInfo CultureInfo { get; set; } public string BaseUrl { get; set; } } }
27.136364
112
0.723618
[ "MIT" ]
colinjacobsorckestra/BetterRetail
src/Orckestra.Composer.Cart/Parameters/CreateLineItemDetailViewModelParam.cs
599
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using qtools.qhierarchy.pcomponent.pbase; using qtools.qhierarchy.pdata; using System.Reflection; namespace qtools.qhierarchy.pcomponent { public class QTagLayerComponent: QBaseComponent { // PRIVATE private GUIStyle labelStyle; private QHierarchyTagAndLayerShowType showType; private Color layerColor; private Color tagColor; private bool showAlways; private bool sizeIsPixel; private int pixelSize; private float percentSize; private GameObject[] gameObjects; private float labelAlpha; private QHierarchyTagAndLayerLabelSize labelSize; private Rect tagRect = new Rect(); private Rect layerRect = new Rect(); private bool needDrawTag; private bool needDrawLayer; private int layer; private string tag; // CONSTRUCTOR public QTagLayerComponent() { labelStyle = new GUIStyle(); labelStyle.fontSize = 8; labelStyle.clipping = TextClipping.Clip; labelStyle.alignment = TextAnchor.MiddleLeft; QSettings.getInstance().addEventListener(QSetting.TagAndLayerSizeShowType , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerType , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerSizeValueType , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerSizeValuePixel , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerSizeValuePercent , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerLabelSize , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerShow , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerShowDuringPlayMode , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerTagLabelColor , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerLayerLabelColor , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerAligment , settingsChanged); QSettings.getInstance().addEventListener(QSetting.TagAndLayerLabelAlpha , settingsChanged); settingsChanged(); } // PRIVATE private void settingsChanged() { showAlways = QSettings.getInstance().get<int>(QSetting.TagAndLayerType) == (int)QHierarchyTagAndLayerType.Always; showType = (QHierarchyTagAndLayerShowType)QSettings.getInstance().get<int>(QSetting.TagAndLayerSizeShowType); sizeIsPixel = QSettings.getInstance().get<int>(QSetting.TagAndLayerSizeValueType) == (int)QHierarchyTagAndLayerSizeType.Pixel; pixelSize = QSettings.getInstance().get<int>(QSetting.TagAndLayerSizeValuePixel); percentSize = QSettings.getInstance().get<float>(QSetting.TagAndLayerSizeValuePercent); labelSize = (QHierarchyTagAndLayerLabelSize)QSettings.getInstance().get<int>(QSetting.TagAndLayerLabelSize); enabled = QSettings.getInstance().get<bool>(QSetting.TagAndLayerShow); tagColor = QSettings.getInstance().getColor(QSetting.TagAndLayerTagLabelColor); layerColor = QSettings.getInstance().getColor(QSetting.TagAndLayerLayerLabelColor); labelAlpha = QSettings.getInstance().get<float>(QSetting.TagAndLayerLabelAlpha); showComponentDuringPlayMode = QSettings.getInstance().get<bool>(QSetting.TagAndLayerShowDuringPlayMode); QHierarchyTagAndLayerAligment aligment = (QHierarchyTagAndLayerAligment)QSettings.getInstance().get<int>(QSetting.TagAndLayerAligment); switch (aligment) { case QHierarchyTagAndLayerAligment.Left : labelStyle.alignment = TextAnchor.MiddleLeft; break; case QHierarchyTagAndLayerAligment.Center: labelStyle.alignment = TextAnchor.MiddleCenter; break; case QHierarchyTagAndLayerAligment.Right : labelStyle.alignment = TextAnchor.MiddleRight; break; } } // DRAW public override QLayoutStatus layout(GameObject gameObject, QObjectList objectList, Rect selectionRect, ref Rect curRect, float maxWidth) { float textWidth = sizeIsPixel ? pixelSize : percentSize * rect.x; rect.width = textWidth + 4; if (maxWidth < rect.width) { return QLayoutStatus.Failed; } else { curRect.x -= rect.width + 2; rect.x = curRect.x; rect.y = curRect.y; layer = gameObject.layer; tag = getTagName(gameObject); needDrawTag = (showType != QHierarchyTagAndLayerShowType.Layer) && ((showAlways || tag != "Untagged")); needDrawLayer = (showType != QHierarchyTagAndLayerShowType.Tag ) && ((showAlways || layer != 0 )); if (labelSize == QHierarchyTagAndLayerLabelSize.Big || (labelSize == QHierarchyTagAndLayerLabelSize.BigIfSpecifiedOnlyTagOrLayer && needDrawTag != needDrawLayer)) labelStyle.fontSize = 9; else labelStyle.fontSize = 8; if (needDrawTag) tagRect.Set(rect.x, rect.y - (needDrawLayer ? 4 : 0), rect.width, 16); if (needDrawLayer) layerRect.Set(rect.x, rect.y + (needDrawTag ? 4 : 0), rect.width, 16); return QLayoutStatus.Success; } } public override void draw(GameObject gameObject, QObjectList objectList, Rect selectionRect) { if (needDrawTag ) { tagColor.a = (tag == "Untagged" ? labelAlpha : 1.0f); labelStyle.normal.textColor = tagColor; EditorGUI.LabelField(tagRect, tag, labelStyle); } if (needDrawLayer) { layerColor.a = (layer == 0 ? labelAlpha : 1.0f); labelStyle.normal.textColor = layerColor; EditorGUI.LabelField(layerRect, getLayerName(layer), labelStyle); } } public override void eventHandler(GameObject gameObject, QObjectList objectList, Event currentEvent) { if (Event.current.isMouse && currentEvent.type == EventType.MouseDown && Event.current.button == 0) { if (needDrawTag && needDrawLayer) { tagRect.height = 8; layerRect.height = 8; tagRect.y += 4; layerRect.y += 4; } if (needDrawTag && tagRect.Contains(Event.current.mousePosition)) { gameObjects = Selection.Contains(gameObject) ? Selection.gameObjects : new GameObject[] { gameObject }; showTagsContextMenu(tag); Event.current.Use(); } else if (needDrawLayer && layerRect.Contains(Event.current.mousePosition)) { gameObjects = Selection.Contains(gameObject) ? Selection.gameObjects : new GameObject[] { gameObject }; showLayersContextMenu(LayerMask.LayerToName(layer)); Event.current.Use(); } } } private string getTagName(GameObject gameObject) { string tag = "Undefined"; try { tag = gameObject.tag; } catch {} return tag; } public string getLayerName(int layer) { string layerName = LayerMask.LayerToName(layer); if (layerName.Equals("")) layerName = "Undefined"; return layerName; } // PRIVATE private void showTagsContextMenu(string tag) { List<string> tags = new List<string>(UnityEditorInternal.InternalEditorUtility.tags); GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Untagged" ), false, tagChangedHandler, "Untagged"); for (int i = 0, n = tags.Count; i < n; i++) { string curTag = tags[i]; menu.AddItem(new GUIContent(curTag), tag == curTag, tagChangedHandler, curTag); } menu.AddSeparator(""); menu.AddItem(new GUIContent("Add Tag..." ), false, addTagOrLayerHandler, "Tags"); menu.ShowAsContext(); } private void showLayersContextMenu(string layer) { List<string> layers = new List<string>(UnityEditorInternal.InternalEditorUtility.layers); GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Default" ), false, layerChangedHandler, "Default"); for (int i = 0, n = layers.Count; i < n; i++) { string curLayer = layers[i]; menu.AddItem(new GUIContent(curLayer), layer == curLayer, layerChangedHandler, curLayer); } menu.AddSeparator(""); menu.AddItem(new GUIContent("Add Layer..." ), false, addTagOrLayerHandler, "Layers"); menu.ShowAsContext(); } private void tagChangedHandler(object newTag) { for (int i = gameObjects.Length - 1; i >= 0; i--) { GameObject gameObject = gameObjects[i]; Undo.RecordObject(gameObject, "Change Tag"); gameObject.tag = (string)newTag; EditorUtility.SetDirty(gameObject); } } private void layerChangedHandler(object newLayer) { int newLayerId = LayerMask.NameToLayer((string)newLayer); for (int i = gameObjects.Length - 1; i >= 0; i--) { GameObject gameObject = gameObjects[i]; Undo.RecordObject(gameObject, "Change Layer"); gameObject.layer = newLayerId; EditorUtility.SetDirty(gameObject); } } private void addTagOrLayerHandler(object value) { PropertyInfo propertyInfo = typeof(EditorApplication).GetProperty("tagManager", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetProperty); UnityEngine.Object obj = (UnityEngine.Object)(propertyInfo.GetValue(null, null)); obj.GetType().GetField("m_DefaultExpandedFoldout").SetValue(obj, value); Selection.activeObject = obj; } } }
47.086777
180
0.581483
[ "Apache-2.0" ]
ChinarG/Tutorial--Texture-Packer
Assets/QHierarchy/Editor/Scripts/pcomponent/QTagLayerComponent.cs
11,395
C#
////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018 Audiokinetic Inc. / All Rights Reserved // ////////////////////////////////////////////////////////////////////// using System.IO; using UnityEditor; #if AK_WWISE_ADDRESSABLES && UNITY_ADDRESSABLES using AK.Wwise.Unity.WwiseAddressables; #endif /// @brief Represents Wwise banks as Unity assets. /// public class WwiseBankReference : WwiseObjectReference { #if AK_WWISE_ADDRESSABLES && UNITY_ADDRESSABLES [UnityEngine.SerializeField, AkShowOnly] private WwiseAddressableSoundBank bank; public WwiseAddressableSoundBank AddressableBank => bank; #if UNITY_EDITOR public void OnEnable() { AkAssetUtilities.AddressableBankUpdated += UpdateAddressableBankReference; } public override void CompleteData() { SetAddressableBank(AkAssetUtilities.GetAddressableBankAsset(DisplayName)); } public override bool IsComplete() { return bank != null; } public void SetAddressableBank(WwiseAddressableSoundBank asset) { bank = asset; EditorUtility.SetDirty(this); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } public bool UpdateAddressableBankReference(WwiseAddressableSoundBank asset, string name) { if (name == ObjectName) { SetAddressableBank(asset); return true; } return false; } public static bool FindBankReferenceAndSetAddressableBank(WwiseAddressableSoundBank addressableAsset, string name) { var guids = UnityEditor.AssetDatabase.FindAssets("t:" + typeof(WwiseBankReference).Name); WwiseBankReference asset; foreach (var assetGuid in guids) { var assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(assetGuid); asset = UnityEditor.AssetDatabase.LoadAssetAtPath<WwiseBankReference>(assetPath); if (asset && asset.ObjectName == name) { asset.SetAddressableBank(addressableAsset); return true; } } return false; } public void OnDestroy() { AkAssetUtilities.AddressableBankUpdated -= UpdateAddressableBankReference; } #endif #endif public override WwiseObjectType WwiseObjectType { get { return WwiseObjectType.Soundbank; } } }
24.494253
115
0.720319
[ "Apache-2.0" ]
PlotArmorStudios/GJL_Jam_2022
GJL Jam 2022/Assets/Wwise/API/Runtime/WwiseTypes/WwiseObjects/WwiseBankReference.cs
2,131
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace PiCandy.Renderer.RpiWs2812.Interop { [StructLayout(LayoutKind.Sequential)] internal struct Ws281x_channel_t { /// <summary> /// GPIO Pin with PWM alternate function, 0 if unused /// </summary> /// <remarks>int gpionum;</remarks> public int gpionum; /// <summary> /// Invert output signal /// </summary> /// <remarks>int invert;</remarks> public int invert; /// <summary> /// Number of LEDs, 0 if channel is unused /// </summary> /// <remarks>int count;</remarks> public int count; /// <summary> /// Brightness value between 0 and 255 /// </summary> /// <remarks>int brightness;</remarks> public int brightness; /// <summary> /// Pointer to LED buffers, allocated by driver based on count /// each is uint32_t (0x00RRGGBB) /// </summary> /// <remarks>ws2811_led_t *leds; /// Going to have to use explicit marshalling to get the value back /// See http://stackoverflow.com/questions/1197181/how-to-marshal-a-variable-sized-array-of-structs-c-sharp-and-c-interop-help /// </remarks> public System.IntPtr leds; } }
30
134
0.58913
[ "MIT" ]
piers7/PiCandy
src/PiCandy.Renderer.RpiWs2812/Interop/Ws281x_channel_t.cs
1,382
C#
namespace YouiToolkit.Design { internal static class StringUtils { public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value); } }
20.888889
59
0.659574
[ "Unlicense" ]
MaQaQu/Tool
YouiToolkit.Design/Helpers/StringUtils.cs
190
C#
namespace Sitecore.Foundation.Alerts.Exceptions { using System; using System.Runtime.Serialization; [Serializable] public class InvalidDataSourceItemException : Exception { public InvalidDataSourceItemException() : base("Data source isn't set or have wrong template") { } public InvalidDataSourceItemException(string message) : base(message) { } public InvalidDataSourceItemException(string message, Exception inner) : base(message, inner) { } protected InvalidDataSourceItemException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
25.16
116
0.73132
[ "Apache-2.0" ]
BIGANDYT/HabitatDemo
src/Foundation/Alerts/code/Exceptions/InvalidDataSourceItemException.cs
631
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Internal.TypeSystem; using Internal.ReadyToRunConstants; using Debug = System.Diagnostics.Debug; namespace ILCompiler { public class ReadyToRunSingleAssemblyCompilationModuleGroup : ReadyToRunCompilationModuleGroupBase { private ProfileDataManager _profileGuidedCompileRestriction; private bool _profileGuidedCompileRestrictionSet; public ReadyToRunSingleAssemblyCompilationModuleGroup( TypeSystemContext context, IEnumerable<ModuleDesc> compilationModuleSet, IEnumerable<ModuleDesc> versionBubbleModuleSet, bool compileGenericDependenciesFromVersionBubbleModuleSet) : base(context, compilationModuleSet, versionBubbleModuleSet, compileGenericDependenciesFromVersionBubbleModuleSet) { } public sealed override bool ContainsMethodBody(MethodDesc method, bool unboxingStub) { if (!_profileGuidedCompileRestrictionSet) throw new InternalCompilerErrorException("Called ContainsMethodBody without setting profile guided restriction"); if (_profileGuidedCompileRestriction != null) { if (!_profileGuidedCompileRestriction.IsMethodInProfileData(method)) return false; } if (method is ArrayMethod) { // TODO-PERF: for now, we never emit native code for array methods as Crossgen ignores // them too. At some point we might be able to "exceed Crossgen CQ" by adding this support. return false; } return (ContainsType(method.OwningType) && VersionsWithMethodBody(method)) || CompileVersionBubbleGenericsIntoCurrentModule(method); } public sealed override void ApplyProfilerGuidedCompilationRestriction(ProfileDataManager profileGuidedCompileRestriction) { if (_profileGuidedCompileRestrictionSet) throw new InternalCompilerErrorException("Called ApplyProfilerGuidedCompilationRestriction twice."); _profileGuidedCompileRestrictionSet = true; _profileGuidedCompileRestriction = profileGuidedCompileRestriction; } public override ReadyToRunFlags GetReadyToRunFlags() { Debug.Assert(_profileGuidedCompileRestrictionSet); ReadyToRunFlags flags = 0; if (_profileGuidedCompileRestriction != null) flags |= ReadyToRunFlags.READYTORUN_FLAG_Partial; return flags; } } }
39.875
144
0.681992
[ "MIT" ]
Drawaes/runtime
src/coreclr/src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/ReadyToRunSingleAssemblyCompilationModuleGroup.cs
2,871
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码已从模板生成。 // // 手动更改此文件可能导致应用程序出现意外的行为。 // 如果重新生成代码,将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ namespace Jade.Model { using System; using System.Collections.Generic; public partial class Product_Category { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Product_Category() { this.Product_Attribute = new HashSet<Product_Attribute>(); this.Product_CategoryChild = new HashSet<Product_Category>(); this.Product_Info = new HashSet<Product_Info>(); } public int id { get; set; } public string category_name { get; set; } public Nullable<int> parent_id { get; set; } public string img_url { get; set; } public int serial_no { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Product_Attribute> Product_Attribute { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Product_Category> Product_CategoryChild { get; set; } public virtual Product_Category Product_CategoryParent { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Product_Info> Product_Info { get; set; } } }
43.775
128
0.630497
[ "MIT" ]
colin08/Jade.Net
Jade.Model/Product_Category.cs
1,861
C#
using System; using swf = System.Windows.Forms; using sd = System.Drawing; using Eto.Forms; using System.Diagnostics; using System.Threading; using Microsoft.WindowsAPICodePack.Taskbar; using System.Collections.Generic; namespace Eto.WinForms.Forms { public class ApplicationHandler : WidgetHandler<object, Application, Application.ICallback>, Application.IHandler { string badgeLabel; bool attached; bool quitting; readonly Thread mainThread; SynchronizationContext context; public static bool EnableScrollingUnderMouse = true; public static bool BubbleMouseEvents = true; public static bool BubbleKeyEvents = true; public static ApplicationHandler Instance => Application.Instance?.Handler as ApplicationHandler; public ApplicationHandler() { mainThread = Thread.CurrentThread; swf.Application.EnableVisualStyles(); try { swf.Application.SetCompatibleTextRenderingDefault(false); } catch { // ignoring error, as it requires to be called before any IWin32Window is created // When integrating with other native apps, this may not be possible. } } void OnCurrentDomainUnhandledException(object sender, System.UnhandledExceptionEventArgs e) { var unhandledExceptionArgs = new UnhandledExceptionEventArgs(e.ExceptionObject, e.IsTerminating); Callback.OnUnhandledException(Widget, unhandledExceptionArgs); } void OnUnhandledThreadException(object sender, ThreadExceptionEventArgs e) { var unhandledExceptionArgs = new UnhandledExceptionEventArgs(e.Exception, true); Callback.OnUnhandledException(Widget, unhandledExceptionArgs); } public void RunIteration() { swf.Application.DoEvents(); } public void Restart() { swf.Application.Restart(); } public string BadgeLabel { get { return badgeLabel; } set { badgeLabel = value; if (TaskbarManager.IsPlatformSupported) { if (!string.IsNullOrEmpty(badgeLabel)) { var bmp = new sd.Bitmap(16, 16, sd.Imaging.PixelFormat.Format32bppArgb); using (var graphics = sd.Graphics.FromImage(bmp)) { DrawBadgeLabel(bmp, graphics); } var icon = sd.Icon.FromHandle(bmp.GetHicon()); TaskbarManager.Instance.SetOverlayIcon(icon, badgeLabel); } else TaskbarManager.Instance.SetOverlayIcon(null, null); } } } protected virtual void DrawBadgeLabel(sd.Bitmap bmp, sd.Graphics graphics) { var font = new sd.Font(sd.FontFamily.GenericSansSerif, 9, sd.FontStyle.Bold, sd.GraphicsUnit.Pixel); var size = graphics.MeasureString(badgeLabel, font, bmp.Size, sd.StringFormat.GenericTypographic); graphics.SmoothingMode = sd.Drawing2D.SmoothingMode.AntiAlias; graphics.FillEllipse(sd.Brushes.Red, new sd.Rectangle(0, 0, 16, 16)); graphics.DrawEllipse(new sd.Pen(sd.Brushes.White, 2), new sd.Rectangle(0, 0, 15, 15)); var pt = new sd.PointF((bmp.Width - size.Width - 0.5F) / 2, (bmp.Height - size.Height - 1) / 2); graphics.DrawString(badgeLabel, font, sd.Brushes.White, pt, sd.StringFormat.GenericTypographic); } public void Run() { if (!attached) { if (!EtoEnvironment.Platform.IsMono) swf.Application.DoEvents(); SetOptions(); Callback.OnInitialized(Widget, EventArgs.Empty); if (!quitting) { if (Widget.MainForm != null && Widget.MainForm.Loaded) swf.Application.Run((swf.Form)Widget.MainForm.ControlObject); else swf.Application.Run(); } } else { Callback.OnInitialized(Widget, EventArgs.Empty); } } static readonly object SuppressKeyPressKey = new object(); void SetOptions() { // creates sync context using (var ctl = new swf.Control()) { } context = SynchronizationContext.Current; if (EtoEnvironment.Platform.IsWindows && EnableScrollingUnderMouse) swf.Application.AddMessageFilter(new ScrollMessageFilter()); if (BubbleMouseEvents) { var bubble = new BubbleEventFilter(); bubble.AddBubbleMouseEvent((c, cb, e) => cb.OnMouseWheel(c, e), null, Win32.WM.MOUSEWHEEL); bubble.AddBubbleMouseEvent((c, cb, e) => cb.OnMouseMove(c, e), null, Win32.WM.MOUSEMOVE); bubble.AddBubbleMouseEvents((c, cb, e) => cb.OnMouseDown(c, e), true, Win32.WM.LBUTTONDOWN, Win32.WM.RBUTTONDOWN, Win32.WM.MBUTTONDOWN); bubble.AddBubbleMouseEvents((c, cb, e) => { cb.OnMouseDoubleClick(c, e); if (!e.Handled) cb.OnMouseDown(c, e); }, null, Win32.WM.LBUTTONDBLCLK, Win32.WM.RBUTTONDBLCLK, Win32.WM.MBUTTONDBLCLK); bubble.AddBubbleMouseEvent((c, cb, e) => cb.OnMouseUp(c, e), false, Win32.WM.LBUTTONUP, b => MouseButtons.Primary); bubble.AddBubbleMouseEvent((c, cb, e) => cb.OnMouseUp(c, e), false, Win32.WM.RBUTTONUP, b => MouseButtons.Alternate); bubble.AddBubbleMouseEvent((c, cb, e) => cb.OnMouseUp(c, e), false, Win32.WM.MBUTTONUP, b => MouseButtons.Middle); swf.Application.AddMessageFilter(bubble); } if (BubbleKeyEvents) { var bubble = new BubbleEventFilter(); Action<Control, Control.ICallback, KeyEventArgs> keyDown = (c, cb, e) => { cb.OnKeyDown(c, e); c.Properties[SuppressKeyPressKey] = e.Handled; }; Action<Control, Control.ICallback, KeyEventArgs> keyPress = (c, cb, e) => { if (!c.Properties.Get<bool>(SuppressKeyPressKey)) { if (!char.IsControl(e.KeyChar)) { var tia = new TextInputEventArgs(e.KeyChar.ToString()); cb.OnTextInput(c, tia); e.Handled = tia.Cancel; } if (!e.Handled) cb.OnKeyDown(c, e); } else { e.Handled = true; c.Properties.Remove(SuppressKeyPressKey); } }; bubble.AddBubbleKeyEvent(keyDown, Win32.WM.KEYDOWN, KeyEventType.KeyDown); bubble.AddBubbleKeyEvent(keyDown, Win32.WM.SYSKEYDOWN, KeyEventType.KeyDown); bubble.AddBubbleKeyCharEvent(keyPress, Win32.WM.CHAR, KeyEventType.KeyDown); bubble.AddBubbleKeyCharEvent(keyPress, Win32.WM.SYSCHAR, KeyEventType.KeyDown); bubble.AddBubbleKeyEvent((c, cb, e) => cb.OnKeyUp(c, e), Win32.WM.KEYUP, KeyEventType.KeyUp); bubble.AddBubbleKeyEvent((c, cb, e) => cb.OnKeyUp(c, e), Win32.WM.SYSKEYUP, KeyEventType.KeyUp); swf.Application.AddMessageFilter(bubble); } } public void Attach(object context) { attached = true; SetOptions(); } public void OnMainFormChanged() { } public void Quit() { quitting = true; swf.Application.Exit(); if (IsEventHandled(Application.UnhandledExceptionEvent)) { swf.Application.ThreadException -= OnUnhandledThreadException; AppDomain.CurrentDomain.UnhandledException -= OnCurrentDomainUnhandledException; } } public bool QuitIsSupported { get { return true; } } public void Open(string url) { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } public override void AttachEvent(string id) { switch (id) { case Application.TerminatingEvent: // handled by WindowHandler break; case Application.UnhandledExceptionEvent: swf.Application.ThreadException += OnUnhandledThreadException; AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException; break; case Application.NotificationActivatedEvent: // handled by NotificationHandler break; default: base.AttachEvent(id); break; } } public void Invoke(Action action) { if (Thread.CurrentThread == mainThread) action(); else if (context != null) context.Send(state => action(), null); } public void AsyncInvoke(Action action) { if (context != null) context.Post(state => action(), null); } public Keys CommonModifier { get { return Keys.Control; } } public Keys AlternateModifier { get { return Keys.Alt; } } } }
28.59707
140
0.694633
[ "BSD-3-Clause" ]
ManuelHu/Eto
src/Eto.WinForms/Forms/ApplicationHandler.cs
7,807
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TetraSlide.Api.Exceptions { public class GameNotFoundException : Exception { public string BadGameId { get; private set; } public GameNotFoundException(string badGameId) : base("Game not found:: " + badGameId) { this.BadGameId = BadGameId; } } }
23.722222
56
0.620609
[ "MIT" ]
petrsnd/tetrad
WebService/Api/Exceptions/GameNotFoundException.cs
429
C#
using System; using Eto.Forms; using Eto.Mac.Forms.Actions; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Eto.Mac.Drawing; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; using CoreImage; using System.Runtime.CompilerServices; #else using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; using MonoMac.CoreImage; #if Mac64 using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #if SDCOMPAT using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; #endif #endif namespace Eto.Mac.Forms { public class ApplicationHandler : WidgetHandler<NSApplication, Application, Application.ICallback>, Application.IHandler { bool attached; internal static bool QueueResizing { get; set; } public NSApplicationDelegate AppDelegate { get; set; } public bool AddFullScreenMenuItem { get; set; } public bool AllowClosingMainForm { get; set; } /// <summary> /// Gets or sets a value indicating whether native macOS crash reports are generated for uncaught .NET exceptions. /// </summary> /// <remarks> /// By default, this will be true when NOT debugging in Xamarin Studio. /// /// The crash report will also include the .NET exception details, which can be extremely useful to determine /// where crashes occurred. /// /// When attaching to existing applications, this is assumed to be dealt with by native code and will not be /// enabled regardless. /// </remarks> /// <value><c>true</c> to enable native crash reports; otherwise, <c>false</c>.</value> public bool EnableNativeCrashReport { get; set; } = !System.Diagnostics.Debugger.IsAttached; public ApplicationHandler() { Control = NSApplication.SharedApplication; } public static ApplicationHandler Instance { get { return Application.Instance == null ? null : Application.Instance.Handler as ApplicationHandler; } } /// <summary> /// Event to inject custom functionality during the event loop of a modal session for an eto dialog. /// </summary> public event EventHandler<ModalEventArgs> ProcessModalSession; /// <summary> /// Raises the <see cref="ProcessModalSession"/> event. /// </summary> /// <param name="e">Event arguments</param> protected virtual void OnProcessModalSession(ModalEventArgs e) { if (ProcessModalSession != null) ProcessModalSession(this, e); } internal void TriggerProcessModalSession(ModalEventArgs e) { OnProcessModalSession(e); } public string BadgeLabel { get { var badgeLabel = Control.DockTile.BadgeLabel; return string.IsNullOrEmpty(badgeLabel) ? null : badgeLabel; } set { Control.DockTile.BadgeLabel = value ?? string.Empty; } } public bool ShouldCloseForm(Window window, bool wasClosed) { if (ReferenceEquals(window, Widget.MainForm)) { if (AllowClosingMainForm && wasClosed) Widget.MainForm = null; return AllowClosingMainForm; } return true; } protected override NSApplication CreateControl() { return NSApplication.SharedApplication; } protected override bool DisposeControl { get { return false; } } static void restart_WillTerminate(object sender, EventArgs e) { // re-open after we terminate var args = new string[] { "-c", "open \"$1\"", string.Empty, NSBundle.MainBundle.BundlePath }; NSTask.LaunchFromPath("/bin/sh", args); } public void Invoke(Action action) { if (NSThread.IsMain) action(); else { #if XAMMAC1 Control.InvokeOnMainThread(new NSAction(action)); #else Control.InvokeOnMainThread(action); #endif } } public void AsyncInvoke(Action action) { #if XAMMAC1 Control.BeginInvokeOnMainThread(new NSAction(action)); #else Control.BeginInvokeOnMainThread(action); #endif } public void Restart() { NSApplication.SharedApplication.WillTerminate += restart_WillTerminate; NSApplication.SharedApplication.Terminate(AppDelegate); // only get here if cancelled, remove event to restart NSApplication.SharedApplication.WillTerminate -= restart_WillTerminate; } public void RunIteration() { #pragma warning disable 0618 // for some reason we get a warning (error in Release) here even though we aren't using an obsolete api. NSApplication.SharedApplication.NextEvent(NSEventMask.AnyEvent, NSDate.DistantFuture, NSRunLoop.NSDefaultRunLoopMode, true); #pragma warning restore 0618 } public void Attach(object context) { attached = true; } public void OnMainFormChanged() { } public void Run() { if (!attached) { if (EnableNativeCrashReport) CrashReporter.Attach(); EtoBundle.Init(); EtoFontManager.Install(); if (Control.Delegate == null) Control.Delegate = AppDelegate ?? new AppDelegate(); NSApplication.Main(new string[0]); } else Initialize(Control.Delegate as NSApplicationDelegate); } public void Initialize(NSApplicationDelegate appdelegate) { AppDelegate = appdelegate; Callback.OnInitialized(Widget, EventArgs.Empty); } public void Quit() { NSApplication.SharedApplication.Terminate((NSObject)AppDelegate ?? NSApplication.SharedApplication); } public bool QuitIsSupported { get { return true; } } public void Open(string url) { NSWorkspace.SharedWorkspace.OpenUrl(new NSUrl(url)); } public override void AttachEvent(string id) { switch (id) { case Application.UnhandledExceptionEvent: AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException; break; case Application.TerminatingEvent: // handled by app delegate break; case Application.NotificationActivatedEvent: if (MacVersion.IsAtLeast(10, 8)) { NSUserNotificationCenter.DefaultUserNotificationCenter.DidActivateNotification += (sender, e) => DidActivateNotification(e.Notification); NSApplication.Notifications.ObserveDidFinishLaunching(DidFinishLaunching); } break; default: base.AttachEvent(id); break; } } void OnCurrentDomainUnhandledException(object sender, System.UnhandledExceptionEventArgs e) { var unhandledExceptionArgs = new UnhandledExceptionEventArgs(e.ExceptionObject, e.IsTerminating); Callback.OnUnhandledException(Widget, unhandledExceptionArgs); } static readonly NSString s_NSApplicationLaunchUserNotificationKey = Dlfcn.GetStringConstant(Messaging.AppKitHandle, "NSApplicationLaunchUserNotificationKey"); static void DidFinishLaunching(object sender, NSApplicationDidFinishLaunchingEventArgs e) { NSObject userNotificationObject; if (e.Notification.UserInfo.TryGetValue(s_NSApplicationLaunchUserNotificationKey, out userNotificationObject)) { DidActivateNotification(userNotificationObject as NSUserNotification); } } internal static void DidActivateNotification(NSUserNotification notification) { NSObject idString, dataString; if (notification.UserInfo.TryGetValue(NotificationHandler.Info_Id, out idString)) { notification.UserInfo.TryGetValue(NotificationHandler.Info_Data, out dataString); var app = ApplicationHandler.Instance; app.Callback.OnNotificationActivated(app.Widget, new NotificationEventArgs((NSString)idString, dataString as NSString)); NSUserNotificationCenter.DefaultUserNotificationCenter.RemoveDeliveredNotification(notification); } } public void EnableFullScreen() { if (Control.RespondsToSelector(new Selector("setPresentationOptions:"))) { AddFullScreenMenuItem = true; } } public Keys CommonModifier { get { return Keys.Application; } } public Keys AlternateModifier { get { return Keys.Alt; } } } }
26.248366
160
0.73618
[ "BSD-3-Clause" ]
couven92/Eto
src/Eto.Mac/Forms/ApplicationHandler.cs
8,032
C#
using UnityEngine; public class coord { public int x, y, z; public coord(int setX, int setY, int setZ) { x = setX; y = setY; z = setZ; } } public class GridElement : MonoBehaviour { private coord coord; private Collider col; private Renderer rend; public CornerElement[] corners; bool isEnabled; private float elementHeight; public bool isGroundElement; public void Initialize(int setX, int setY, int setZ, float setElementHeight) { corners = new CornerElement[8]; coord = new coord(setX, setY, setZ); this.name = "GE_" + this.coord.x + "_" + this.coord.y + "_" + this.coord.z; this.col = this.GetComponent<Collider>(); this.rend = this.GetComponent<Renderer>(); this.elementHeight = setElementHeight; this.transform.localScale = new Vector3(1.001f, elementHeight + 0.001f, 1.001f); this.isGroundElement = setY == 0; //setting corners corners[0] = LevelGenerator.instance.GetCornerElement(coord.x, coord.y, coord.z); corners[1] = LevelGenerator.instance.GetCornerElement(coord.x + 1, coord.y, coord.z); corners[2] = LevelGenerator.instance.GetCornerElement(coord.x, coord.y, coord.z + 1); corners[3] = LevelGenerator.instance.GetCornerElement(coord.x + 1, coord.y, coord.z + 1); corners[4] = LevelGenerator.instance.GetCornerElement(coord.x, coord.y + 1, coord.z); corners[5] = LevelGenerator.instance.GetCornerElement(coord.x + 1, coord.y + 1, coord.z); corners[6] = LevelGenerator.instance.GetCornerElement(coord.x, coord.y + 1, coord.z + 1); corners[7] = LevelGenerator.instance.GetCornerElement(coord.x + 1, coord.y + 1, coord.z + 1); } public coord GetCoord() { return coord; } public void SetCornerPositions() { Vector3 position = this.transform.localPosition; float x = coord.x; float y = coord.y; float z = coord.z; float f = 0.5F; corners[0].SetPosition(x - f, y - f * elementHeight, z - f); corners[1].SetPosition(x + f, y - f * elementHeight, z - f); corners[2].SetPosition(x - f, y - f * elementHeight, z + f); corners[3].SetPosition(x + f, y - f * elementHeight, z + f); corners[4].SetPosition(x - f, y + f * elementHeight, z - f); corners[5].SetPosition(x + f, y + f * elementHeight, z - f); corners[6].SetPosition(x - f, y + f * elementHeight, z + f); corners[7].SetPosition(x + f, y + f * elementHeight, z + f); } public void SetEnabled() { this.col.enabled = true; this.rend.enabled = false; this.isEnabled = true; foreach (CornerElement ce in corners) { ce.SetCornerElement(); } } public void SetTapEnabled() { this.SetEnabled(); if (this.coord.x == LevelGenerator.currentWidthLow) { LevelGenerator.instance.AddShellInDirectionX(true); } else if (this.coord.x == LevelGenerator.currentWidthHigh - 1) { LevelGenerator.instance.AddShellInDirectionX(false); } else if (this.coord.z == LevelGenerator.currentLengthLow) { LevelGenerator.instance.AddShellInDirectionZ(true); } else if (this.coord.z == LevelGenerator.currentLengthHigh - 1) { LevelGenerator.instance.AddShellInDirectionZ(false); } else if (this.coord.y == LevelGenerator.currentHeightLow) { // Do nothing, as we don't build "down" into the floor } else if (this.coord.y == LevelGenerator.currentHeightHigh - 1) { LevelGenerator.instance.AddShellInDirectionY(); } } public void SetDisabled() { if (coord.y == 0) { return; } this.col.enabled = false; this.rend.enabled = false; this.isEnabled = false; foreach (CornerElement ce in corners) { ce.SetCornerElement(); } } public bool GetEnabled() { return isEnabled; } public float GetHeight() { return elementHeight; } }
32.106061
101
0.592025
[ "MIT" ]
Adrian-Hirt/BrickBlockHololens
Assets/Scripts/GridElement.cs
4,238
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Diagnostics; using Microsoft.Win32.SafeHandles; using NTSTATUS = Interop.BCrypt.NTSTATUS; using BCryptOpenAlgorithmProviderFlags = Interop.BCrypt.BCryptOpenAlgorithmProviderFlags; using BCryptCreateHashFlags = Interop.BCrypt.BCryptCreateHashFlags; namespace Internal.Cryptography { // // Provides hash services via the native provider (CNG). // internal sealed class HashProviderCng : HashProvider { // // - "hashAlgId" must be a name recognized by BCryptOpenAlgorithmProvider(). Examples: MD5, SHA1, SHA256. // // - "key" activates MAC hashing if present. If null, this HashProvider performs a regular old hash. // public HashProviderCng(string hashAlgId, byte[]? key) : this(hashAlgId, key, isHmac: key != null) { } internal HashProviderCng(string hashAlgId, ReadOnlySpan<byte> key, bool isHmac) { BCryptOpenAlgorithmProviderFlags dwFlags = BCryptOpenAlgorithmProviderFlags.None; if (isHmac) { _key = key.ToArray(); dwFlags |= BCryptOpenAlgorithmProviderFlags.BCRYPT_ALG_HANDLE_HMAC_FLAG; } _hAlgorithm = Interop.BCrypt.BCryptAlgorithmCache.GetCachedBCryptAlgorithmHandle(hashAlgId, dwFlags); // Win7 won't set hHash, Win8+ will; and both will set _hHash. // So keep hHash trapped in this scope to prevent (mis-)use of it. { SafeBCryptHashHandle? hHash = null; NTSTATUS ntStatus = Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out hHash, IntPtr.Zero, 0, key, key == null ? 0 : key.Length, BCryptCreateHashFlags.BCRYPT_HASH_REUSABLE_FLAG); if (ntStatus == NTSTATUS.STATUS_INVALID_PARAMETER) { // If we got here, we're running on a downlevel OS (pre-Win8) that doesn't support reusable CNG hash objects. Fall back to creating a // new HASH object each time. ResetHashObject(); } else if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(ntStatus); } else { _hHash = hHash; _reusable = true; } } unsafe { int cbSizeOfHashSize; int hashSize; Debug.Assert(_hHash != null); NTSTATUS ntStatus = Interop.BCrypt.BCryptGetProperty(_hHash, Interop.BCrypt.BCryptPropertyStrings.BCRYPT_HASH_LENGTH, &hashSize, sizeof(int), out cbSizeOfHashSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw Interop.BCrypt.CreateCryptographicException(ntStatus); _hashSize = hashSize; } } public sealed override unsafe void AppendHashData(ReadOnlySpan<byte> source) { Debug.Assert(_hHash != null); NTSTATUS ntStatus = Interop.BCrypt.BCryptHashData(_hHash, source, source.Length, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(ntStatus); } } public sealed override byte[] FinalizeHashAndReset() { var hash = new byte[_hashSize]; bool success = TryFinalizeHashAndReset(hash, out int bytesWritten); Debug.Assert(success); Debug.Assert(hash.Length == bytesWritten); return hash; } public override bool TryGetCurrentHash(Span<byte> destination, out int bytesWritten) { if (destination.Length < _hashSize) { bytesWritten = 0; return false; } Debug.Assert(_hHash != null); NTSTATUS ntStatus = Interop.BCrypt.BCryptDuplicateHash(_hHash, out SafeBCryptHashHandle copy, IntPtr.Zero, 0, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(ntStatus); } try { ntStatus = Interop.BCrypt.BCryptFinishHash(copy, destination, _hashSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(ntStatus); } bytesWritten = _hashSize; return true; } finally { copy.Dispose(); } } public override bool TryFinalizeHashAndReset(Span<byte> destination, out int bytesWritten) { if (destination.Length < _hashSize) { bytesWritten = 0; return false; } Debug.Assert(_hHash != null); NTSTATUS ntStatus = Interop.BCrypt.BCryptFinishHash(_hHash, destination, _hashSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(ntStatus); } bytesWritten = _hashSize; ResetHashObject(); return true; } public sealed override void Dispose(bool disposing) { if (disposing) { DestroyHash(); if (_key != null) { byte[] key = _key; _key = null; Array.Clear(key, 0, key.Length); } } } public sealed override int HashSizeInBytes => _hashSize; private void ResetHashObject() { if (_reusable) return; DestroyHash(); SafeBCryptHashHandle hHash; NTSTATUS ntStatus = Interop.BCrypt.BCryptCreateHash(_hAlgorithm, out hHash, IntPtr.Zero, 0, _key, _key == null ? 0 : _key.Length, BCryptCreateHashFlags.None); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw Interop.BCrypt.CreateCryptographicException(ntStatus); _hHash = hHash; } private void DestroyHash() { SafeBCryptHashHandle? hHash = _hHash; _hHash = null; if (hHash != null) { hHash.Dispose(); } // Not disposing of _hAlgorithm as we got this from a cache. So it's not ours to Dispose(). } private readonly SafeBCryptAlgorithmHandle _hAlgorithm; private SafeBCryptHashHandle? _hHash; private byte[]? _key; private readonly bool _reusable; private readonly int _hashSize; } }
36.312821
192
0.566304
[ "MIT" ]
Drawaes/runtime
src/libraries/Common/src/Internal/Cryptography/HashProviderCng.cs
7,081
C#
using System.Runtime.InteropServices; namespace DeviceIOControlLib.Objects.MountManager { [StructLayout(LayoutKind.Sequential)] public struct MOUNTMGR_MOUNT_POINTS { public uint Size; public uint NumberOfMountPoints; public MOUNTMGR_MOUNT_POINT[] MountPoints; } }
25.333333
50
0.736842
[ "MIT" ]
DamirAinullin/DeviceIOControlLib
DeviceIOControlLib/Objects/MountManager/MOUNTMGR_MOUNT_POINTS.cs
304
C#
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; // Internal C# wrapper for OVRPlugin. internal static class OVRPlugin { public static readonly System.Version wrapperVersion = OVRP_1_14_0.version; private static System.Version _version; public static System.Version version { get { if (_version == null) { try { string pluginVersion = OVRP_1_1_0.ovrp_GetVersion(); if (pluginVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. pluginVersion = pluginVersion.Split('-')[0]; _version = new System.Version(pluginVersion); } else { _version = _versionZero; } } catch { _version = _versionZero; } // Unity 5.1.1f3-p3 have OVRPlugin version "0.5.0", which isn't accurate. if (_version == OVRP_0_5_0.version) _version = OVRP_0_1_0.version; if (_version > _versionZero && _version < OVRP_1_3_0.version) throw new PlatformNotSupportedException("Oculus Utilities version " + wrapperVersion + " is too new for OVRPlugin version " + _version.ToString () + ". Update to the latest version of Unity."); } return _version; } } private static System.Version _nativeSDKVersion; public static System.Version nativeSDKVersion { get { if (_nativeSDKVersion == null) { try { string sdkVersion = string.Empty; if (version >= OVRP_1_1_0.version) sdkVersion = OVRP_1_1_0.ovrp_GetNativeSDKVersion(); else sdkVersion = _versionZero.ToString(); if (sdkVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. sdkVersion = sdkVersion.Split('-')[0]; _nativeSDKVersion = new System.Version(sdkVersion); } else { _nativeSDKVersion = _versionZero; } } catch { _nativeSDKVersion = _versionZero; } } return _nativeSDKVersion; } } [StructLayout(LayoutKind.Sequential)] private class GUID { public int a; public short b; public short c; public byte d0; public byte d1; public byte d2; public byte d3; public byte d4; public byte d5; public byte d6; public byte d7; } public enum Bool { False = 0, True } public enum Eye { None = -1, Left = 0, Right = 1, Count = 2 } public enum Tracker { None = -1, Zero = 0, One = 1, Two = 2, Three = 3, Count, } public enum Node { None = -1, EyeLeft = 0, EyeRight = 1, EyeCenter = 2, HandLeft = 3, HandRight = 4, TrackerZero = 5, TrackerOne = 6, TrackerTwo = 7, TrackerThree = 8, Head = 9, Count, } public enum Controller { None = 0, LTouch = 0x00000001, RTouch = 0x00000002, Touch = LTouch | RTouch, Remote = 0x00000004, Gamepad = 0x00000010, Touchpad = 0x08000000, LTrackedRemote = 0x01000000, RTrackedRemote = 0x02000000, Active = unchecked((int)0x80000000), All = ~None, } public enum TrackingOrigin { EyeLevel = 0, FloorLevel = 1, Count, } public enum RecenterFlags { Default = 0, Controllers = 0x40000000, IgnoreAll = unchecked((int)0x80000000), Count, } public enum BatteryStatus { Charging = 0, Discharging, Full, NotCharging, Unknown, } public enum EyeTextureFormat { Default = 0, R16G16B16A16_FP = 2, R11G11B10_FP = 3, } public enum PlatformUI { None = -1, GlobalMenu = 0, ConfirmQuit, GlobalMenuTutorial, } public enum SystemRegion { Unspecified = 0, Japan, China, } public enum SystemHeadset { None = 0, GearVR_R320, // Note4 Innovator GearVR_R321, // S6 Innovator GearVR_R322, // Commercial 1 GearVR_R323, // Commercial 2 (USB Type C) Rift_DK1 = 0x1000, Rift_DK2, Rift_CV1, } public enum OverlayShape { Quad = 0, Cylinder = 1, Cubemap = 2, OffcenterCubemap = 4, } public enum Step { Render = -1, Physics = 0, } private const int OverlayShapeFlagShift = 4; private enum OverlayFlag { None = unchecked((int)0x00000000), OnTop = unchecked((int)0x00000001), HeadLocked = unchecked((int)0x00000002), // Using the 5-8 bits for shapes, total 16 potential shapes can be supported 0x000000[0]0 -> 0x000000[F]0 ShapeFlag_Quad = unchecked((int)OverlayShape.Quad << OverlayShapeFlagShift), ShapeFlag_Cylinder = unchecked((int)OverlayShape.Cylinder << OverlayShapeFlagShift), ShapeFlag_Cubemap = unchecked((int)OverlayShape.Cubemap << OverlayShapeFlagShift), ShapeFlag_OffcenterCubemap = unchecked((int)OverlayShape.OffcenterCubemap << OverlayShapeFlagShift), ShapeFlagRangeMask = unchecked((int)0xF << OverlayShapeFlagShift), } [StructLayout(LayoutKind.Sequential)] public struct Vector2f { public float x; public float y; } [StructLayout(LayoutKind.Sequential)] public struct Vector3f { public float x; public float y; public float z; } [StructLayout(LayoutKind.Sequential)] public struct Quatf { public float x; public float y; public float z; public float w; } [StructLayout(LayoutKind.Sequential)] public struct Posef { public Quatf Orientation; public Vector3f Position; } [StructLayout(LayoutKind.Sequential)] public struct PoseStatef { public Posef Pose; public Vector3f Velocity; public Vector3f Acceleration; public Vector3f AngularVelocity; public Vector3f AngularAcceleration; double Time; } [StructLayout(LayoutKind.Sequential)] public struct ControllerState2 { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; public Vector2f LTouchpad; public Vector2f RTouchpad; public ControllerState2(ControllerState cs) { ConnectedControllers = cs.ConnectedControllers; Buttons = cs.Buttons; Touches = cs.Touches; NearTouches = cs.NearTouches; LIndexTrigger = cs.LIndexTrigger; RIndexTrigger = cs.RIndexTrigger; LHandTrigger = cs.LHandTrigger; RHandTrigger = cs.RHandTrigger; LThumbstick = cs.LThumbstick; RThumbstick = cs.RThumbstick; LTouchpad = new Vector2f() { x = 0.0f, y = 0.0f }; RTouchpad = new Vector2f() { x = 0.0f, y = 0.0f }; } } [StructLayout(LayoutKind.Sequential)] public struct ControllerState { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; } [StructLayout(LayoutKind.Sequential)] public struct HapticsBuffer { public IntPtr Samples; public int SamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct HapticsState { public int SamplesAvailable; public int SamplesQueued; } [StructLayout(LayoutKind.Sequential)] public struct HapticsDesc { public int SampleRateHz; public int SampleSizeInBytes; public int MinimumSafeSamplesQueued; public int MinimumBufferSamplesCount; public int OptimalBufferSamplesCount; public int MaximumBufferSamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct AppPerfFrameStats { public int HmdVsyncIndex; public int AppFrameIndex; public int AppDroppedFrameCount; public float AppMotionToPhotonLatency; public float AppQueueAheadTime; public float AppCpuElapsedTime; public float AppGpuElapsedTime; public int CompositorFrameIndex; public int CompositorDroppedFrameCount; public float CompositorLatency; public float CompositorCpuElapsedTime; public float CompositorGpuElapsedTime; public float CompositorCpuStartToGpuEndElapsedTime; public float CompositorGpuEndToVsyncElapsedTime; } public const int AppPerfFrameStatsMaxCount = 5; [StructLayout(LayoutKind.Sequential)] public struct AppPerfStats { [MarshalAs(UnmanagedType.ByValArray, SizeConst=AppPerfFrameStatsMaxCount)] public AppPerfFrameStats[] FrameStats; public int FrameStatsCount; public Bool AnyFrameStatsDropped; public float AdaptiveGpuPerformanceScale; } [StructLayout(LayoutKind.Sequential)] public struct Sizei { public int w; public int h; } [StructLayout(LayoutKind.Sequential)] public struct Frustumf { public float zNear; public float zFar; public float fovX; public float fovY; } public enum BoundaryType { OuterBoundary = 0x0001, PlayArea = 0x0100, } [StructLayout(LayoutKind.Sequential)] public struct BoundaryTestResult { public Bool IsTriggering; public float ClosestDistance; public Vector3f ClosestPoint; public Vector3f ClosestPointNormal; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryLookAndFeel { public Colorf Color; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryGeometry { public BoundaryType BoundaryType; [MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] public Vector3f[] Points; public int PointsCount; } [StructLayout(LayoutKind.Sequential)] public struct Colorf { public float r; public float g; public float b; public float a; } public static bool initialized { get { return OVRP_1_1_0.ovrp_GetInitialized() == OVRPlugin.Bool.True; } } public static bool chromatic { get { if (version >= OVRP_1_7_0.version) return OVRP_1_7_0.ovrp_GetAppChromaticCorrection() == OVRPlugin.Bool.True; #if UNITY_ANDROID && !UNITY_EDITOR return false; #else return true; #endif } set { if (version >= OVRP_1_7_0.version) OVRP_1_7_0.ovrp_SetAppChromaticCorrection(ToBool(value)); } } public static bool monoscopic { get { return OVRP_1_1_0.ovrp_GetAppMonoscopic() == OVRPlugin.Bool.True; } set { OVRP_1_1_0.ovrp_SetAppMonoscopic(ToBool(value)); } } public static bool rotation { get { return OVRP_1_1_0.ovrp_GetTrackingOrientationEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingOrientationEnabled(ToBool(value)); } } public static bool position { get { return OVRP_1_1_0.ovrp_GetTrackingPositionEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingPositionEnabled(ToBool(value)); } } public static bool useIPDInPositionTracking { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetTrackingIPDEnabled() == OVRPlugin.Bool.True; return true; } set { if (version >= OVRP_1_6_0.version) OVRP_1_6_0.ovrp_SetTrackingIPDEnabled(ToBool(value)); } } public static bool positionSupported { get { return OVRP_1_1_0.ovrp_GetTrackingPositionSupported() == Bool.True; } } public static bool positionTracked { get { return OVRP_1_1_0.ovrp_GetNodePositionTracked(Node.EyeCenter) == Bool.True; } } public static bool powerSaving { get { return OVRP_1_1_0.ovrp_GetSystemPowerSavingMode() == Bool.True; } } public static bool hmdPresent { get { return OVRP_1_1_0.ovrp_GetNodePresent(Node.EyeCenter) == Bool.True; } } public static bool userPresent { get { return OVRP_1_1_0.ovrp_GetUserPresent() == Bool.True; } } public static bool headphonesPresent { get { return OVRP_1_3_0.ovrp_GetSystemHeadphonesPresent() == OVRPlugin.Bool.True; } } public static int recommendedMSAALevel { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetSystemRecommendedMSAALevel (); else return 2; } } public static SystemRegion systemRegion { get { if (version >= OVRP_1_5_0.version) return OVRP_1_5_0.ovrp_GetSystemRegion(); else return SystemRegion.Unspecified; } } private static GUID _nativeAudioOutGuid = new OVRPlugin.GUID(); private static Guid _cachedAudioOutGuid; private static string _cachedAudioOutString; public static string audioOutId { get { try { if (_nativeAudioOutGuid == null) _nativeAudioOutGuid = new OVRPlugin.GUID(); IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioOutId(); if (ptr != IntPtr.Zero) { Marshal.PtrToStructure(ptr, _nativeAudioOutGuid); Guid managedGuid = new Guid( _nativeAudioOutGuid.a, _nativeAudioOutGuid.b, _nativeAudioOutGuid.c, _nativeAudioOutGuid.d0, _nativeAudioOutGuid.d1, _nativeAudioOutGuid.d2, _nativeAudioOutGuid.d3, _nativeAudioOutGuid.d4, _nativeAudioOutGuid.d5, _nativeAudioOutGuid.d6, _nativeAudioOutGuid.d7); if (managedGuid != _cachedAudioOutGuid) { _cachedAudioOutGuid = managedGuid; _cachedAudioOutString = _cachedAudioOutGuid.ToString(); } return _cachedAudioOutString; } } catch {} return string.Empty; } } private static GUID _nativeAudioInGuid = new OVRPlugin.GUID(); private static Guid _cachedAudioInGuid; private static string _cachedAudioInString; public static string audioInId { get { try { if (_nativeAudioInGuid == null) _nativeAudioInGuid = new OVRPlugin.GUID(); IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioInId(); if (ptr != IntPtr.Zero) { Marshal.PtrToStructure(ptr, _nativeAudioInGuid); Guid managedGuid = new Guid( _nativeAudioInGuid.a, _nativeAudioInGuid.b, _nativeAudioInGuid.c, _nativeAudioInGuid.d0, _nativeAudioInGuid.d1, _nativeAudioInGuid.d2, _nativeAudioInGuid.d3, _nativeAudioInGuid.d4, _nativeAudioInGuid.d5, _nativeAudioInGuid.d6, _nativeAudioInGuid.d7); if (managedGuid != _cachedAudioInGuid) { _cachedAudioInGuid = managedGuid; _cachedAudioInString = _cachedAudioInGuid.ToString(); } return _cachedAudioInString; } } catch {} return string.Empty; } } public static bool hasVrFocus { get { return OVRP_1_1_0.ovrp_GetAppHasVrFocus() == Bool.True; } } public static bool shouldQuit { get { return OVRP_1_1_0.ovrp_GetAppShouldQuit() == Bool.True; } } public static bool shouldRecenter { get { return OVRP_1_1_0.ovrp_GetAppShouldRecenter() == Bool.True; } } public static string productName { get { return OVRP_1_1_0.ovrp_GetSystemProductName(); } } public static string latency { get { return OVRP_1_1_0.ovrp_GetAppLatencyTimings(); } } public static float eyeDepth { get { return OVRP_1_1_0.ovrp_GetUserEyeDepth(); } set { OVRP_1_1_0.ovrp_SetUserEyeDepth(value); } } public static float eyeHeight { get { return OVRP_1_1_0.ovrp_GetUserEyeHeight(); } set { OVRP_1_1_0.ovrp_SetUserEyeHeight(value); } } public static float batteryLevel { get { return OVRP_1_1_0.ovrp_GetSystemBatteryLevel(); } } public static float batteryTemperature { get { return OVRP_1_1_0.ovrp_GetSystemBatteryTemperature(); } } public static int cpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemCpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemCpuLevel(value); } } public static int gpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemGpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemGpuLevel(value); } } public static int vsyncCount { get { return OVRP_1_1_0.ovrp_GetSystemVSyncCount(); } set { OVRP_1_2_0.ovrp_SetSystemVSyncCount(value); } } public static float systemVolume { get { return OVRP_1_1_0.ovrp_GetSystemVolume(); } } public static float ipd { get { return OVRP_1_1_0.ovrp_GetUserIPD(); } set { OVRP_1_1_0.ovrp_SetUserIPD(value); } } public static bool occlusionMesh { get { return OVRP_1_3_0.ovrp_GetEyeOcclusionMeshEnabled() == Bool.True; } set { OVRP_1_3_0.ovrp_SetEyeOcclusionMeshEnabled(ToBool(value)); } } public static BatteryStatus batteryStatus { get { return OVRP_1_1_0.ovrp_GetSystemBatteryStatus(); } } public static Frustumf GetEyeFrustum(Eye eyeId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)eyeId); } public static Sizei GetEyeTextureSize(Eye eyeId) { return OVRP_0_1_0.ovrp_GetEyeTextureSize(eyeId); } public static Posef GetTrackerPose(Tracker trackerId) { return GetNodePose((Node)((int)trackerId + (int)Node.TrackerZero), Step.Render); } public static Frustumf GetTrackerFrustum(Tracker trackerId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)((int)trackerId + (int)Node.TrackerZero)); } public static bool ShowUI(PlatformUI ui) { return OVRP_1_1_0.ovrp_ShowSystemUI(ui) == Bool.True; } public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr leftTexture, IntPtr rightTexture, IntPtr device, Posef pose, Vector3f scale, int layerIndex=0, OverlayShape shape=OverlayShape.Quad) { if (version >= OVRP_1_6_0.version) { uint flags = (uint)OverlayFlag.None; if (onTop) flags |= (uint)OverlayFlag.OnTop; if (headLocked) flags |= (uint)OverlayFlag.HeadLocked; if (shape == OverlayShape.Cylinder || shape == OverlayShape.Cubemap) { #if UNITY_ANDROID if (version >= OVRP_1_7_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #else if (shape == OverlayShape.Cubemap && version >= OVRP_1_10_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #endif return false; } if (shape == OverlayShape.OffcenterCubemap) { #if UNITY_ANDROID if (version >= OVRP_1_11_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #endif return false; } return OVRP_1_6_0.ovrp_SetOverlayQuad3(flags, leftTexture, rightTexture, device, pose, scale, layerIndex) == Bool.True; } if (layerIndex != 0) return false; return OVRP_0_1_1.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), leftTexture, device, pose, scale) == Bool.True; } public static bool UpdateNodePhysicsPoses(int frameIndex, double predictionSeconds) { if (version >= OVRP_1_8_0.version) return OVRP_1_8_0.ovrp_Update2((int)Step.Physics, frameIndex, predictionSeconds) == Bool.True; return false; } public static Posef GetNodePose(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Pose; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodePose2(0, nodeId); return OVRP_0_1_2.ovrp_GetNodePose(nodeId); } public static Vector3f GetNodeVelocity(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Velocity; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodeVelocity2(0, nodeId).Position; return OVRP_0_1_3.ovrp_GetNodeVelocity(nodeId).Position; } public static Vector3f GetNodeAngularVelocity(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularVelocity; return new Vector3f(); //TODO: Convert legacy quat to vec3? } public static Vector3f GetNodeAcceleration(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Acceleration; if (version >= OVRP_1_8_0.version && stepId == Step.Physics) return OVRP_1_8_0.ovrp_GetNodeAcceleration2(0, nodeId).Position; return OVRP_0_1_3.ovrp_GetNodeAcceleration(nodeId).Position; } public static Vector3f GetNodeAngularAcceleration(Node nodeId, Step stepId) { if (version >= OVRP_1_12_0.version) return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularAcceleration; return new Vector3f(); //TODO: Convert legacy quat to vec3? } public static bool GetNodePresent(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePresent(nodeId) == Bool.True; } public static bool GetNodeOrientationTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodeOrientationTracked(nodeId) == Bool.True; } public static bool GetNodePositionTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePositionTracked(nodeId) == Bool.True; } public static ControllerState GetControllerState(uint controllerMask) { return OVRP_1_1_0.ovrp_GetControllerState(controllerMask); } public static ControllerState2 GetControllerState2(uint controllerMask) { if (version >= OVRP_1_12_0.version) { return OVRP_1_12_0.ovrp_GetControllerState2(controllerMask); } return new ControllerState2(OVRP_1_1_0.ovrp_GetControllerState(controllerMask)); } public static bool SetControllerVibration(uint controllerMask, float frequency, float amplitude) { return OVRP_0_1_2.ovrp_SetControllerVibration(controllerMask, frequency, amplitude) == Bool.True; } public static HapticsDesc GetControllerHapticsDesc(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsDesc(controllerMask); } else { return new HapticsDesc(); } } public static HapticsState GetControllerHapticsState(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsState(controllerMask); } else { return new HapticsState(); } } public static bool SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_SetControllerHaptics(controllerMask, hapticsBuffer) == Bool.True; } else { return false; } } public static float GetEyeRecommendedResolutionScale() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetEyeRecommendedResolutionScale(); } else { return 1.0f; } } public static float GetAppCpuStartToGpuEndTime() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetAppCpuStartToGpuEndTime(); } else { return 0.0f; } } public static bool GetBoundaryConfigured() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryConfigured() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryTestResult TestBoundaryNode(Node nodeId, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryNode(nodeId, boundaryType); } else { return new BoundaryTestResult(); } } public static BoundaryTestResult TestBoundaryPoint(Vector3f point, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryPoint(point, boundaryType); } else { return new BoundaryTestResult(); } } public static bool SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryLookAndFeel(lookAndFeel) == OVRPlugin.Bool.True; } else { return false; } } public static bool ResetBoundaryLookAndFeel() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_ResetBoundaryLookAndFeel() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryGeometry GetBoundaryGeometry(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryGeometry(boundaryType); } else { return new BoundaryGeometry(); } } public static bool GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount) { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_GetBoundaryGeometry2(boundaryType, points, ref pointsCount) == OVRPlugin.Bool.True; } else { pointsCount = 0; return false; } } public static AppPerfStats GetAppPerfStats() { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_GetAppPerfStats(); } else { return new AppPerfStats(); } } public static bool ResetAppPerfStats() { if (version >= OVRP_1_9_0.version) { return OVRP_1_9_0.ovrp_ResetAppPerfStats() == OVRPlugin.Bool.True; } else { return false; } } public static float GetAppFramerate() { if (version >= OVRP_1_12_0.version) { return OVRP_1_12_0.ovrp_GetAppFramerate(); } else { return 0.0f; } } public static EyeTextureFormat GetDesiredEyeTextureFormat() { if (version >= OVRP_1_11_0.version ) { uint eyeTextureFormatValue = (uint) OVRP_1_11_0.ovrp_GetDesiredEyeTextureFormat(); // convert both R8G8B8A8 and R8G8B8A8_SRGB to R8G8B8A8 here for avoid confusing developers if (eyeTextureFormatValue == 1) eyeTextureFormatValue = 0; return (EyeTextureFormat)eyeTextureFormatValue; } else { return EyeTextureFormat.Default; } } public static bool SetDesiredEyeTextureFormat(EyeTextureFormat value) { if (version >= OVRP_1_11_0.version) { return OVRP_1_11_0.ovrp_SetDesiredEyeTextureFormat(value) == OVRPlugin.Bool.True; } else { return false; } } public static Vector3f GetBoundaryDimensions(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryDimensions(boundaryType); } else { return new Vector3f(); } } public static bool GetBoundaryVisible() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryVisible() == OVRPlugin.Bool.True; } else { return false; } } public static bool SetBoundaryVisible(bool value) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryVisible(ToBool(value)) == OVRPlugin.Bool.True; } else { return false; } } public static SystemHeadset GetSystemHeadsetType() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetSystemHeadsetType(); return SystemHeadset.None; } public static Controller GetActiveController() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetActiveController(); return Controller.None; } public static Controller GetConnectedControllers() { if (version >= OVRP_1_9_0.version) return OVRP_1_9_0.ovrp_GetConnectedControllers(); return Controller.None; } private static Bool ToBool(bool b) { return (b) ? OVRPlugin.Bool.True : OVRPlugin.Bool.False; } public static TrackingOrigin GetTrackingOriginType() { return OVRP_1_0_0.ovrp_GetTrackingOriginType(); } public static bool SetTrackingOriginType(TrackingOrigin originType) { return OVRP_1_0_0.ovrp_SetTrackingOriginType(originType) == Bool.True; } public static Posef GetTrackingCalibratedOrigin() { return OVRP_1_0_0.ovrp_GetTrackingCalibratedOrigin(); } public static bool SetTrackingCalibratedOrigin() { return OVRP_1_2_0.ovrpi_SetTrackingCalibratedOrigin() == Bool.True; } public static bool RecenterTrackingOrigin(RecenterFlags flags) { return OVRP_1_0_0.ovrp_RecenterTrackingOrigin((uint)flags) == Bool.True; } private const string pluginName = "OVRPlugin"; private static Version _versionZero = new System.Version(0, 0, 0); private static class OVRP_0_1_0 { public static readonly System.Version version = new System.Version(0, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Sizei ovrp_GetEyeTextureSize(Eye eyeId); } private static class OVRP_0_1_1 { public static readonly System.Version version = new System.Version(0, 1, 1); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad2(Bool onTop, Bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale); } private static class OVRP_0_1_2 { public static readonly System.Version version = new System.Version(0, 1, 2); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerVibration(uint controllerMask, float frequency, float amplitude); } private static class OVRP_0_1_3 { public static readonly System.Version version = new System.Version(0, 1, 3); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration(Node nodeId); } private static class OVRP_0_5_0 { public static readonly System.Version version = new System.Version(0, 5, 0); } private static class OVRP_1_0_0 { public static readonly System.Version version = new System.Version(1, 0, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern TrackingOrigin ovrp_GetTrackingOriginType(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOriginType(TrackingOrigin originType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetTrackingCalibratedOrigin(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_RecenterTrackingOrigin(uint flags); } private static class OVRP_1_1_0 { public static readonly System.Version version = new System.Version(1, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetInitialized(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetVersion")] private static extern IntPtr _ovrp_GetVersion(); public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativeSDKVersion")] private static extern IntPtr _ovrp_GetNativeSDKVersion(); public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioOutId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioInId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeTextureScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeTextureScale(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOrientationEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingPositionEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePresent(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodeOrientationTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePositionTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Frustumf ovrp_GetNodeFrustum(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern ControllerState ovrp_GetControllerState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemCpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemCpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemGpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemGpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemPowerSavingMode(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemDisplayFrequency(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemVSyncCount(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemVolume(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BatteryStatus ovrp_GetSystemBatteryStatus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryTemperature(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetSystemProductName")] private static extern IntPtr _ovrp_GetSystemProductName(); public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ShowSystemUI(PlatformUI ui); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppMonoscopic(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppMonoscopic(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppHasVrFocus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldQuit(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldRecenter(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetAppLatencyTimings")] private static extern IntPtr _ovrp_GetAppLatencyTimings(); public static string ovrp_GetAppLatencyTimings() { return Marshal.PtrToStringAnsi(_ovrp_GetAppLatencyTimings()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetUserPresent(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserIPD(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserIPD(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeDepth(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeDepth(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeHeight(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeHeight(float value); } private static class OVRP_1_2_0 { public static readonly System.Version version = new System.Version(1, 2, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemVSyncCount(int vsyncCount); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrpi_SetTrackingCalibratedOrigin(); } private static class OVRP_1_3_0 { public static readonly System.Version version = new System.Version(1, 3, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetEyeOcclusionMeshEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeOcclusionMeshEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemHeadphonesPresent(); } private static class OVRP_1_5_0 { public static readonly System.Version version = new System.Version(1, 5, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern SystemRegion ovrp_GetSystemRegion(); } private static class OVRP_1_6_0 { public static readonly System.Version version = new System.Version(1, 6, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingIPDEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingIPDEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsDesc ovrp_GetControllerHapticsDesc(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsState ovrp_GetControllerHapticsState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad3(uint flags, IntPtr textureLeft, IntPtr textureRight, IntPtr device, Posef pose, Vector3f scale, int layerIndex); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeRecommendedResolutionScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetAppCpuStartToGpuEndTime(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemRecommendedMSAALevel(); } private static class OVRP_1_7_0 { public static readonly System.Version version = new System.Version(1, 7, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppChromaticCorrection(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppChromaticCorrection(Bool value); } private static class OVRP_1_8_0 { public static readonly System.Version version = new System.Version(1, 8, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryConfigured(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryNode(Node nodeId, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryPoint(Vector3f point, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ResetBoundaryLookAndFeel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryGeometry ovrp_GetBoundaryGeometry(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Vector3f ovrp_GetBoundaryDimensions(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryVisible(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryVisible(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_Update2(int stateId, int frameIndex, double predictionSeconds); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration2(int stateId, Node nodeId); } private static class OVRP_1_9_0 { public static readonly System.Version version = new System.Version(1, 9, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern SystemHeadset ovrp_GetSystemHeadsetType(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Controller ovrp_GetActiveController(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Controller ovrp_GetConnectedControllers(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern AppPerfStats ovrp_GetAppPerfStats(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ResetAppPerfStats(); } private static class OVRP_1_10_0 { public static readonly System.Version version = new System.Version(1, 10, 0); } private static class OVRP_1_11_0 { public static readonly System.Version version = new System.Version(1, 11, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetDesiredEyeTextureFormat(EyeTextureFormat value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern EyeTextureFormat ovrp_GetDesiredEyeTextureFormat(); } private static class OVRP_1_12_0 { public static readonly System.Version version = new System.Version(1, 12, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetAppFramerate(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern PoseStatef ovrp_GetNodePoseState(Step stepId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern ControllerState2 ovrp_GetControllerState2(uint controllerMask); } private static class OVRP_1_13_0 { public static readonly System.Version version = new System.Version(1, 13, 0); } private static class OVRP_1_14_0 { public static readonly System.Version version = new System.Version(1, 14, 0); } }
29.695146
204
0.723098
[ "MIT" ]
SeijiEmery/BloodCellHero
Assets/OVR/Scripts/OVRPlugin.cs
45,879
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 kendra-2019-02-03.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.Kendra.Model { /// <summary> /// An attribute returned from an index query. /// </summary> public partial class AdditionalResultAttribute { private string _key; private AdditionalResultAttributeValue _value; private AdditionalResultAttributeValueType _valueType; /// <summary> /// Gets and sets the property Key. /// <para> /// The key that identifies the attribute. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=2048)] public string Key { get { return this._key; } set { this._key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this._key != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// An object that contains the attribute value. /// </para> /// </summary> [AWSProperty(Required=true)] public AdditionalResultAttributeValue Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } /// <summary> /// Gets and sets the property ValueType. /// <para> /// The data type of the <code>Value</code> property. /// </para> /// </summary> [AWSProperty(Required=true)] public AdditionalResultAttributeValueType ValueType { get { return this._valueType; } set { this._valueType = value; } } // Check to see if ValueType property is set internal bool IsSetValueType() { return this._valueType != null; } } }
28.510204
104
0.594488
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Kendra/Generated/Model/AdditionalResultAttribute.cs
2,794
C#
using AcmeChallengeResponder.Security.SimpleBearer; using Microsoft.AspNetCore.Authentication; using System; namespace Microsoft.Extensions.DependencyInjection { public static class SimpleBearerExtensions { public static AuthenticationBuilder AddSimpleBearer(this AuthenticationBuilder builder) { return AddSimpleBearer(builder, null); } public static AuthenticationBuilder AddSimpleBearer(this AuthenticationBuilder builder, Action<SimpleBearerOptions>? configureOptions) { return builder.AddScheme<SimpleBearerOptions, SimpleBearerHandler>(SimpleBearerDefaults.AuthenticationScheme, configureOptions); } } }
34.85
142
0.761836
[ "MIT" ]
marcoskirchner/AcmeChallengeResponder
src/Security/SimpleBearer/SimpleBearerExtensions.cs
699
C#
// Generated class v2.14.0.0, can be modified namespace NHtmlUnit.Activex.Javascript.Msxml { public partial class XMLDOMNode { } }
13.909091
46
0.660131
[ "Apache-2.0" ]
HtmlUnit/NHtmlUnit
app/NHtmlUnit/NonGenerated/Activex/Javascript/Msxml/XMLDOMNode.cs
153
C#
/* * FactSet Entity API * * Using an entity centric data model, FactSet's Entity API provides access to FactSet's complete security and entity level symbology, comprehensive entity reference data, and all of the necessary relationships and connections to create a foundation that tightly correlates disparate sources of information to a master entity identifier. Use this API to quickly understand the full entity structure and related securities. * * The version of the OpenAPI document: 1.2.0 * Contact: api@factset.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.Mime; using FactSet.SDK.FactSetEntity.Client; using FactSet.SDK.FactSetEntity.Model; using FactSet.SDK.Utils.Authentication; namespace FactSet.SDK.FactSetEntity.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IEntityStructureApiSync : IApiAccessor { #region Synchronous Operations /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>EntityStructureResponse</returns> EntityStructureResponse GetEntityStructure(List<string> ids, int? level = default(int?), int? active = default(int?)); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>ApiResponse of EntityStructureResponse</returns> ApiResponse<EntityStructureResponse> GetEntityStructureWithHttpInfo(List<string> ids, int? level = default(int?), int? active = default(int?)); /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. /// </summary> /// <remarks> /// Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>UltimateEntityStructureResponse</returns> UltimateEntityStructureResponse GetUltimateEntityStructure(List<string> ids, int? level = default(int?), int? active = default(int?)); /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. /// </summary> /// <remarks> /// Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>ApiResponse of UltimateEntityStructureResponse</returns> ApiResponse<UltimateEntityStructureResponse> GetUltimateEntityStructureWithHttpInfo(List<string> ids, int? level = default(int?), int? active = default(int?)); /// <summary> /// Returns all active or inactive entities below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <returns>EntityStructureResponse</returns> EntityStructureResponse PostEntityStructure(EntityStructureRequest entityStructureRequest); /// <summary> /// Returns all active or inactive entities below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <returns>ApiResponse of EntityStructureResponse</returns> ApiResponse<EntityStructureResponse> PostEntityStructureWithHttpInfo(EntityStructureRequest entityStructureRequest); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <returns>UltimateEntityStructureResponse</returns> UltimateEntityStructureResponse PostUltimateEntityStructure(UltimateEntityStructureRequest ultimateEntityStructureRequest); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <returns>ApiResponse of UltimateEntityStructureResponse</returns> ApiResponse<UltimateEntityStructureResponse> PostUltimateEntityStructureWithHttpInfo(UltimateEntityStructureRequest ultimateEntityStructureRequest); #endregion Synchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IEntityStructureApiAsync : IApiAccessor { #region Asynchronous Operations /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of EntityStructureResponse</returns> System.Threading.Tasks.Task<EntityStructureResponse> GetEntityStructureAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (EntityStructureResponse)</returns> System.Threading.Tasks.Task<ApiResponse<EntityStructureResponse>> GetEntityStructureWithHttpInfoAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. /// </summary> /// <remarks> /// Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of UltimateEntityStructureResponse</returns> System.Threading.Tasks.Task<UltimateEntityStructureResponse> GetUltimateEntityStructureAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. /// </summary> /// <remarks> /// Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (UltimateEntityStructureResponse)</returns> System.Threading.Tasks.Task<ApiResponse<UltimateEntityStructureResponse>> GetUltimateEntityStructureWithHttpInfoAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns all active or inactive entities below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of EntityStructureResponse</returns> System.Threading.Tasks.Task<EntityStructureResponse> PostEntityStructureAsync(EntityStructureRequest entityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns all active or inactive entities below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (EntityStructureResponse)</returns> System.Threading.Tasks.Task<ApiResponse<EntityStructureResponse>> PostEntityStructureWithHttpInfoAsync(EntityStructureRequest entityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of UltimateEntityStructureResponse</returns> System.Threading.Tasks.Task<UltimateEntityStructureResponse> PostUltimateEntityStructureAsync(UltimateEntityStructureRequest ultimateEntityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <remarks> /// Returns all active or inactive entities and respective levels below the requested entity id. /// </remarks> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (UltimateEntityStructureResponse)</returns> System.Threading.Tasks.Task<ApiResponse<UltimateEntityStructureResponse>> PostUltimateEntityStructureWithHttpInfoAsync(UltimateEntityStructureRequest ultimateEntityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IEntityStructureApi : IEntityStructureApiSync, IEntityStructureApiAsync { } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class EntityStructureApi : IEntityStructureApi { private FactSet.SDK.FactSetEntity.Client.ExceptionFactory _exceptionFactory = (name, response) => null; # region Response Type Disctionaries private static readonly Dictionary<HttpStatusCode, System.Type> GetEntityStructureResponseTypeDictionary = new Dictionary<HttpStatusCode, System.Type> { { (HttpStatusCode)200, typeof(EntityStructureResponse) }, { (HttpStatusCode)400, typeof(ErrorResponse) }, { (HttpStatusCode)401, typeof(ErrorResponse) }, { (HttpStatusCode)403, typeof(ErrorResponse) }, { (HttpStatusCode)415, typeof(ErrorResponse) }, { (HttpStatusCode)500, typeof(ErrorResponse) }, }; private static readonly Dictionary<HttpStatusCode, System.Type> GetUltimateEntityStructureResponseTypeDictionary = new Dictionary<HttpStatusCode, System.Type> { { (HttpStatusCode)200, typeof(UltimateEntityStructureResponse) }, { (HttpStatusCode)400, typeof(ErrorResponse) }, { (HttpStatusCode)401, typeof(ErrorResponse) }, { (HttpStatusCode)403, typeof(ErrorResponse) }, { (HttpStatusCode)415, typeof(ErrorResponse) }, { (HttpStatusCode)500, typeof(ErrorResponse) }, }; private static readonly Dictionary<HttpStatusCode, System.Type> PostEntityStructureResponseTypeDictionary = new Dictionary<HttpStatusCode, System.Type> { { (HttpStatusCode)200, typeof(EntityStructureResponse) }, { (HttpStatusCode)400, typeof(ErrorResponse) }, { (HttpStatusCode)401, typeof(ErrorResponse) }, { (HttpStatusCode)403, typeof(ErrorResponse) }, { (HttpStatusCode)415, typeof(ErrorResponse) }, { (HttpStatusCode)500, typeof(ErrorResponse) }, }; private static readonly Dictionary<HttpStatusCode, System.Type> PostUltimateEntityStructureResponseTypeDictionary = new Dictionary<HttpStatusCode, System.Type> { { (HttpStatusCode)200, typeof(UltimateEntityStructureResponse) }, { (HttpStatusCode)400, typeof(ErrorResponse) }, { (HttpStatusCode)401, typeof(ErrorResponse) }, { (HttpStatusCode)403, typeof(ErrorResponse) }, { (HttpStatusCode)415, typeof(ErrorResponse) }, { (HttpStatusCode)500, typeof(ErrorResponse) }, }; # endregion Response Type Disctionaries # region Api Response Objects # endregion Api Response Objects /// <summary> /// Initializes a new instance of the <see cref="EntityStructureApi"/> class. /// </summary> /// <returns></returns> public EntityStructureApi() : this((string)null) { } /// <summary> /// Initializes a new instance of the <see cref="EntityStructureApi"/> class. /// </summary> /// <returns></returns> public EntityStructureApi(string basePath) { this.Configuration = FactSet.SDK.FactSetEntity.Client.Configuration.MergeConfigurations( FactSet.SDK.FactSetEntity.Client.GlobalConfiguration.Instance, new FactSet.SDK.FactSetEntity.Client.Configuration { BasePath = basePath } ); this.Client = new FactSet.SDK.FactSetEntity.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new FactSet.SDK.FactSetEntity.Client.ApiClient(this.Configuration.BasePath); this.ExceptionFactory = FactSet.SDK.FactSetEntity.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="EntityStructureApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public EntityStructureApi(FactSet.SDK.FactSetEntity.Client.Configuration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.Configuration = FactSet.SDK.FactSetEntity.Client.Configuration.MergeConfigurations( FactSet.SDK.FactSetEntity.Client.GlobalConfiguration.Instance, configuration ); this.Client = new FactSet.SDK.FactSetEntity.Client.ApiClient(this.Configuration.BasePath); this.AsynchronousClient = new FactSet.SDK.FactSetEntity.Client.ApiClient(this.Configuration.BasePath); ExceptionFactory = FactSet.SDK.FactSetEntity.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// Initializes a new instance of the <see cref="EntityStructureApi"/> class /// using a Configuration object and client instance. /// </summary> /// <param name="client">The client interface for synchronous API access.</param> /// <param name="asyncClient">The client interface for asynchronous API access.</param> /// <param name="configuration">The configuration object.</param> public EntityStructureApi(FactSet.SDK.FactSetEntity.Client.ISynchronousClient client, FactSet.SDK.FactSetEntity.Client.IAsynchronousClient asyncClient, FactSet.SDK.FactSetEntity.Client.IReadableConfiguration configuration) { if (client == null) throw new ArgumentNullException("client"); if (asyncClient == null) throw new ArgumentNullException("asyncClient"); if (configuration == null) throw new ArgumentNullException("configuration"); this.Client = client; this.AsynchronousClient = asyncClient; this.Configuration = configuration; this.ExceptionFactory = FactSet.SDK.FactSetEntity.Client.Configuration.DefaultExceptionFactory; } /// <summary> /// The client for accessing this underlying API asynchronously. /// </summary> public FactSet.SDK.FactSetEntity.Client.IAsynchronousClient AsynchronousClient { get; set; } /// <summary> /// The client for accessing this underlying API synchronously. /// </summary> public FactSet.SDK.FactSetEntity.Client.ISynchronousClient Client { get; set; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public string GetBasePath() { return this.Configuration.BasePath; } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public FactSet.SDK.FactSetEntity.Client.IReadableConfiguration Configuration { get; set; } /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public FactSet.SDK.FactSetEntity.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>EntityStructureResponse</returns> public EntityStructureResponse GetEntityStructure(List<string> ids, int? level = default(int?), int? active = default(int?)) { var localVarResponse = GetEntityStructureWithHttpInfo(ids, level, active); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>ApiResponse of EntityStructureResponse</returns> public ApiResponse<EntityStructureResponse> GetEntityStructureWithHttpInfo(List<string> ids, int? level = default(int?), int? active = default(int?)) { // verify the required parameter 'ids' is set if (ids == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ids' when calling EntityStructureApi->GetEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("csv", "ids", ids)); if (level != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "level", level)); } if (active != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "active", active)); } // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = this.Configuration.OAuth2Client.GetAccessTokenAsync().Result; localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = GetEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = this.Client.Get< EntityStructureResponse>("/factset-entity/v1/entity-structures", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of EntityStructureResponse</returns> public async System.Threading.Tasks.Task<EntityStructureResponse>GetEntityStructureAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var localVarResponse = await GetEntityStructureWithHttpInfoAsync(ids, level, active, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (EntityStructureResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<EntityStructureResponse>> GetEntityStructureWithHttpInfoAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'ids' is set if (ids == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ids' when calling EntityStructureApi->GetEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("csv", "ids", ids)); if (level != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "level", level)); } if (active != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "active", active)); } // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = await this.Configuration.OAuth2Client.GetAccessTokenAsync(); localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = GetEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync<EntityStructureResponse>("/factset-entity/v1/entity-structures", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>UltimateEntityStructureResponse</returns> public UltimateEntityStructureResponse GetUltimateEntityStructure(List<string> ids, int? level = default(int?), int? active = default(int?)) { var localVarResponse = GetUltimateEntityStructureWithHttpInfo(ids, level, active); return localVarResponse.Data; } /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <returns>ApiResponse of UltimateEntityStructureResponse</returns> public ApiResponse<UltimateEntityStructureResponse> GetUltimateEntityStructureWithHttpInfo(List<string> ids, int? level = default(int?), int? active = default(int?)) { // verify the required parameter 'ids' is set if (ids == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ids' when calling EntityStructureApi->GetUltimateEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("csv", "ids", ids)); if (level != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "level", level)); } if (active != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "active", active)); } // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = this.Configuration.OAuth2Client.GetAccessTokenAsync().Result; localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = GetUltimateEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = this.Client.Get< UltimateEntityStructureResponse>("/factset-entity/v1/ultimate-entity-structures", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUltimateEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of UltimateEntityStructureResponse</returns> public async System.Threading.Tasks.Task<UltimateEntityStructureResponse>GetUltimateEntityStructureAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var localVarResponse = await GetUltimateEntityStructureWithHttpInfoAsync(ids, level, active, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// Returns the full ultimate parent entity hiearachy. Control levels and active status of underlying entities. Returns full ultimate entity structure including ultimate parent and all subordinates. Will accept entity from any level of entity structure or active vs. inactive status of entity. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ids">The requested Market Identifier. Accepted input identifiers include Ticker-Exchange, Ticker-Regions, CUSIPs, ISINs, SEDOLs, or FactSet Permanent Ids, such as -R, -L, or -E.&lt;p&gt;**Max Ids Limit set to 100 in a single request**&lt;/p&gt; *&lt;p&gt;Make note, GET Method URL request lines are also limited to a total length of 8192 bytes (8KB). In cases where the service allows for thousands of ids, which may lead to exceeding this request line limit of 8KB, its advised for any requests with large request lines to be requested through the respective \\\&quot;POST\\\&quot; method.&lt;/p&gt;* </param> /// <param name="level">Controls the levels returned in the hierarchy. Use -1 to return all levels, or 1-n for a specific level. (optional, default to -1)</param> /// <param name="active">Controls active or inactive securities returned in the hierarchy. Enter 1 to return only active entities, 0 for inactive entities, and -1 for all active and inactive. (optional, default to -1)</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (UltimateEntityStructureResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<UltimateEntityStructureResponse>> GetUltimateEntityStructureWithHttpInfoAsync(List<string> ids, int? level = default(int?), int? active = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'ids' is set if (ids == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ids' when calling EntityStructureApi->GetUltimateEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("csv", "ids", ids)); if (level != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "level", level)); } if (active != null) { localVarRequestOptions.QueryParameters.Add(FactSet.SDK.FactSetEntity.Client.ClientUtils.ParameterToMultiMap("", "active", active)); } // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = await this.Configuration.OAuth2Client.GetAccessTokenAsync(); localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = GetUltimateEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync<UltimateEntityStructureResponse>("/factset-entity/v1/ultimate-entity-structures", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUltimateEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns all active or inactive entities below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <returns>EntityStructureResponse</returns> public EntityStructureResponse PostEntityStructure(EntityStructureRequest entityStructureRequest) { var localVarResponse = PostEntityStructureWithHttpInfo(entityStructureRequest); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <returns>ApiResponse of EntityStructureResponse</returns> public ApiResponse<EntityStructureResponse> PostEntityStructureWithHttpInfo(EntityStructureRequest entityStructureRequest) { // verify the required parameter 'entityStructureRequest' is set if (entityStructureRequest == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'entityStructureRequest' when calling EntityStructureApi->PostEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.Data = entityStructureRequest; // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = this.Configuration.OAuth2Client.GetAccessTokenAsync().Result; localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = PostEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = this.Client.Post< EntityStructureResponse>("/factset-entity/v1/entity-structures", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PostEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns all active or inactive entities below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of EntityStructureResponse</returns> public async System.Threading.Tasks.Task<EntityStructureResponse>PostEntityStructureAsync(EntityStructureRequest entityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var localVarResponse = await PostEntityStructureWithHttpInfoAsync(entityStructureRequest, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="entityStructureRequest">Request Body to request a list of Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (EntityStructureResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<EntityStructureResponse>> PostEntityStructureWithHttpInfoAsync(EntityStructureRequest entityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'entityStructureRequest' is set if (entityStructureRequest == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'entityStructureRequest' when calling EntityStructureApi->PostEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.Data = entityStructureRequest; // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = await this.Configuration.OAuth2Client.GetAccessTokenAsync(); localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = PostEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = await this.AsynchronousClient.PostAsync<EntityStructureResponse>("/factset-entity/v1/entity-structures", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PostEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <returns>UltimateEntityStructureResponse</returns> public UltimateEntityStructureResponse PostUltimateEntityStructure(UltimateEntityStructureRequest ultimateEntityStructureRequest) { var localVarResponse = PostUltimateEntityStructureWithHttpInfo(ultimateEntityStructureRequest); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <returns>ApiResponse of UltimateEntityStructureResponse</returns> public ApiResponse<UltimateEntityStructureResponse> PostUltimateEntityStructureWithHttpInfo(UltimateEntityStructureRequest ultimateEntityStructureRequest) { // verify the required parameter 'ultimateEntityStructureRequest' is set if (ultimateEntityStructureRequest == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ultimateEntityStructureRequest' when calling EntityStructureApi->PostUltimateEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.Data = ultimateEntityStructureRequest; // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = this.Configuration.OAuth2Client.GetAccessTokenAsync().Result; localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = PostUltimateEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = this.Client.Post< UltimateEntityStructureResponse>("/factset-entity/v1/ultimate-entity-structures", localVarRequestOptions, this.Configuration); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PostUltimateEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of UltimateEntityStructureResponse</returns> public async System.Threading.Tasks.Task<UltimateEntityStructureResponse>PostUltimateEntityStructureAsync(UltimateEntityStructureRequest ultimateEntityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var localVarResponse = await PostUltimateEntityStructureWithHttpInfoAsync(ultimateEntityStructureRequest, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; } /// <summary> /// Returns all active or inactive entities and respective levels below the requested entity id. Returns all active or inactive entities and respective levels below the requested entity id. /// </summary> /// <exception cref="FactSet.SDK.FactSetEntity.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="ultimateEntityStructureRequest">Request Body to request a list of Ultimate Entity Structure objects.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (UltimateEntityStructureResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<UltimateEntityStructureResponse>> PostUltimateEntityStructureWithHttpInfoAsync(UltimateEntityStructureRequest ultimateEntityStructureRequest, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'ultimateEntityStructureRequest' is set if (ultimateEntityStructureRequest == null) { throw new FactSet.SDK.FactSetEntity.Client.ApiException(400, "Missing required parameter 'ultimateEntityStructureRequest' when calling EntityStructureApi->PostUltimateEntityStructure"); } FactSet.SDK.FactSetEntity.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.FactSetEntity.Client.RequestOptions(); string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = FactSet.SDK.FactSetEntity.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.Data = ultimateEntityStructureRequest; // authentication (FactSetApiKey) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.FactSetEntity.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // authentication (FactSetOAuth2) required // oauth required if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } // FactSet Authentication Client required if (this.Configuration.OAuth2Client != null) { var token = await this.Configuration.OAuth2Client.GetAccessTokenAsync(); localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token); } localVarRequestOptions.ResponseTypeDictionary = PostUltimateEntityStructureResponseTypeDictionary; // make the HTTP request var localVarResponse = await this.AsynchronousClient.PostAsync<UltimateEntityStructureResponse>("/factset-entity/v1/ultimate-entity-structures", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PostUltimateEntityStructure", localVarResponse); if (_exception != null) { throw _exception; } } return localVarResponse; } } }
70.261432
655
0.685349
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/FactSetEntity/v1/src/FactSet.SDK.FactSetEntity/Api/EntityStructureApi.cs
81,433
C#
namespace ImageProcessing.App.UILayer.Forms.Convolution { partial class ConvolutionForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) => Dispose(); #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ErrorToolTip = new System.Windows.Forms.ToolTip(this.components); this.ConvolutionFilterComboBox = new MetroFramework.Controls.MetroComboBox(); this.Apply = new MetroFramework.Controls.MetroButton(); this.ConvoltuionButtonPanel = new MetroFramework.Controls.MetroPanel(); this.ConvoltuionButtonPanel.SuspendLayout(); this.SuspendLayout(); // // ConvolutionFilterComboBox // this.ConvolutionFilterComboBox.FormattingEnabled = true; this.ConvolutionFilterComboBox.ItemHeight = 23; this.ConvolutionFilterComboBox.Location = new System.Drawing.Point(3, 10); this.ConvolutionFilterComboBox.MaxDropDownItems = 100; this.ConvolutionFilterComboBox.Name = "ConvolutionFilterComboBox"; this.ConvolutionFilterComboBox.Size = new System.Drawing.Size(254, 29); this.ConvolutionFilterComboBox.TabIndex = 0; this.ConvolutionFilterComboBox.UseSelectable = true; // // Apply // this.Apply.Location = new System.Drawing.Point(3, 45); this.Apply.Name = "Apply"; this.Apply.Size = new System.Drawing.Size(254, 23); this.Apply.TabIndex = 1; this.Apply.Text = "Apply"; this.Apply.UseSelectable = true; // // ConvoltuionButtonPanel // this.ConvoltuionButtonPanel.Controls.Add(this.ConvolutionFilterComboBox); this.ConvoltuionButtonPanel.Controls.Add(this.Apply); this.ConvoltuionButtonPanel.HorizontalScrollbarBarColor = true; this.ConvoltuionButtonPanel.HorizontalScrollbarHighlightOnWheel = false; this.ConvoltuionButtonPanel.HorizontalScrollbarSize = 10; this.ConvoltuionButtonPanel.Location = new System.Drawing.Point(23, 53); this.ConvoltuionButtonPanel.Name = "ConvoltuionButtonPanel"; this.ConvoltuionButtonPanel.Size = new System.Drawing.Size(263, 76); this.ConvoltuionButtonPanel.TabIndex = 2; this.ConvoltuionButtonPanel.VerticalScrollbarBarColor = true; this.ConvoltuionButtonPanel.VerticalScrollbarHighlightOnWheel = false; this.ConvoltuionButtonPanel.VerticalScrollbarSize = 10; // // ConvolutionForm // this.BorderStyle = MetroFramework.Forms.MetroFormBorderStyle.FixedSingle; this.ClientSize = new System.Drawing.Size(319, 130); this.Controls.Add(this.ConvoltuionButtonPanel); this.MaximizeBox = false; this.MinimizeBox = false; this.Movable = false; this.Name = "ConvolutionForm"; this.Resizable = false; this.ShadowType = MetroFramework.Forms.MetroFormShadowType.None; this.Text = "Convolution Kernel"; this.ConvoltuionButtonPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolTip ErrorToolTip; private MetroFramework.Controls.MetroComboBox ConvolutionFilterComboBox; private MetroFramework.Controls.MetroButton Apply; private MetroFramework.Controls.MetroPanel ConvoltuionButtonPanel; } }
45.741935
107
0.640339
[ "Apache-2.0" ]
Softenraged/Image-Processing
Source/ImageProcessing.App.UILayer/Forms/Convolution/ConvolutionForm.Designer.cs
4,254
C#
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; namespace APTCWEB.Models { public class ApplicationDbContext : DbContext { public ApplicationDbContext() : base("DefaultConnection") { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
21.692308
51
0.68617
[ "MIT" ]
DeePatrick/Ajman
V2.0/APTCWEB/Models/ApplicationDbContext.cs
566
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Bm.V20180423.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class SuccessTaskInfo : AbstractModel { /// <summary> /// 运行脚本的设备ID /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// 黑石异步任务ID /// </summary> [JsonProperty("TaskId")] public ulong? TaskId{ get; set; } /// <summary> /// 黑石自定义脚本运行任务ID /// </summary> [JsonProperty("CmdTaskId")] public string CmdTaskId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamSimple(map, prefix + "TaskId", this.TaskId); this.SetParamSimple(map, prefix + "CmdTaskId", this.CmdTaskId); } } }
29.931034
83
0.623848
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Bm/V20180423/Models/SuccessTaskInfo.cs
1,784
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using EbnfCompiler.AST; using EbnfCompiler.AST.Impl; namespace EbnfCompiler.CodeGenerator { internal class Context { public Context(AstNodeType nodeType) { NodeType = nodeType; Properties = new Dictionary<string, object>(); } public AstNodeType NodeType { get; } public Dictionary<string, object> Properties { get; } public override string ToString() { return NodeType.ToString(); } public bool GenerateSwitch { get; set; } } public class CSharpGenerator : ICodeGenerator { private readonly IAstTraverser _traverser; private readonly StreamWriter _streamWriter; private IReadOnlyCollection<ITokenDefinition> _tokens; private readonly Stack<Context> _stack; private int _indentLevel; public CSharpGenerator(IAstTraverser traverser, StreamWriter streamWriter) { _traverser = traverser; _streamWriter = streamWriter; _traverser.ProcessNode += ProcessNode; _traverser.PostProcessNode += PostProcessNode; _stack = new Stack<Context>(); } public void Run(IRootNode rootNode) { _tokens = rootNode.TokenDefs; _traverser.Traverse(rootNode.Syntax); } private void ProcessNode(IAstNode node) { Context context; switch (node.AstNodeType) { case AstNodeType.Syntax: context = new Context(node.AstNodeType); _stack.Push(context); PrintUsings(); PrintNamespaceHeader(); PrintClassHeader(); PrintClassProperties(); PrintConstructor(); PrintMatchMethod(); PrintMatchOneOfMethod(); PrintParseGoal(node.AsSyntax().Statements.First().ProdName, node.AsSyntax().PreActionNode?.ActionName, node.AsSyntax().PostActionNode?.ActionName); break; case AstNodeType.Statement: context = new Context(node.AstNodeType); _stack.Push(context); context.Properties.Add("PreActionName", node.AsStatement().PreActionNode?.ActionName); context.Properties.Add("PostActionName", node.AsStatement().PostActionNode?.ActionName); PrintMethodHeader(node.AsStatement().ProdName, context.Properties["PreActionName"]?.ToString()); if (node.FirstSet.AsEnumerable().Count() > 1) { PrintFirstSet(node.FirstSet, node.NodeId); PrintMatchOneOf(node.NodeId); } else { PrintMatchNonTerminal(node.FirstSet.AsEnumerable().First()); } break; case AstNodeType.Expression: _stack.Push(new Context(node.AstNodeType)); _stack.Peek().GenerateSwitch = node.AsExpression().TermCount > 1; if (node.AsExpression().PreActionNode != null) PrintAction(node.AsExpression().PreActionNode.ActionName); if (node.AsExpression().TermCount > 1) PrintTermSwitch(); break; case AstNodeType.Term: context = new Context(node.AstNodeType); context.GenerateSwitch = _stack.Peek().GenerateSwitch; _stack.Push(context); if (context.GenerateSwitch) { PrintTermCase(node.FirstSet); Indent(); } break; case AstNodeType.Factor: context = new Context(node.AstNodeType); context.Properties.Add("PostActionName", node.AsFactor().PostActionNode?.ActionName); _stack.Push(context); if (node.AsFactor().PreActionNode != null) PrintAction(node.AsFactor().PreActionNode.ActionName); break; case AstNodeType.ProdRef: _stack.Push(new Context(node.AstNodeType)); PrintProdRef(node.AsProdRef().ProdName); break; case AstNodeType.Terminal: _stack.Push(new Context(node.AstNodeType)); PrintMatchTerminal(node.AsTerminal().TermName); break; case AstNodeType.Action: _stack.Push(new Context(node.AstNodeType)); break; case AstNodeType.Paren: _stack.Push(new Context(node.AstNodeType)); break; case AstNodeType.Option: _stack.Push(new Context(node.AstNodeType)); PrintOption(node.FirstSet, node.NodeId); break; case AstNodeType.KleeneStar: _stack.Push(new Context(node.AstNodeType)); PrintKleene(node.FirstSet, node.NodeId); break; } } private void PostProcessNode() { var context = _stack.Pop(); switch (context.NodeType) { case AstNodeType.Syntax: PrintClassFooter(); PrintNamespaceFooter(); break; case AstNodeType.Statement: PrintMethodFooter(context.Properties["PostActionName"]?.ToString()); break; case AstNodeType.Expression: if (context.GenerateSwitch) { Outdent(); PrintLine("}"); } break; case AstNodeType.Term: if (context.GenerateSwitch) { PrintLine("break;"); Outdent(); } break; case AstNodeType.Factor: if (context.Properties["PostActionName"] != null) PrintAction(context.Properties["PostActionName"].ToString()); break; case AstNodeType.ProdRef: break; case AstNodeType.Terminal: break; case AstNodeType.Action: break; case AstNodeType.Paren: break; case AstNodeType.Option: Outdent(); PrintLine("}"); break; case AstNodeType.KleeneStar: Outdent(); PrintLine("}"); break; } } private void PrintUsings() { PrintLine("using System.Linq;"); // PrintLine("using EbnfCompiler.AST;"); // PrintLine("using EbnfCompiler.Compiler;"); // PrintLine("using EbnfCompiler.Scanner;"); PrintLine(); } private void PrintNamespaceHeader() { PrintLine("namespace EbnfCompiler.Sample.Impl"); PrintLine("{"); Indent(); } private void PrintNamespaceFooter() { Outdent(); PrintLine("}"); } private void PrintClassHeader() { PrintLine("public partial class Parser"); PrintLine("{"); Indent(); } private void PrintClassProperties() { PrintLine("private readonly IScanner _scanner;"); PrintLine("private readonly IAstBuilder _astBuilder;"); } private void PrintClassFooter() { Outdent(); PrintLine("}"); } private void PrintConstructor() { PrintLine(); PrintLine("public Parser(IScanner scanner, IAstBuilder astBuilder)"); PrintLine("{"); Indent(); PrintLine("_scanner = scanner;"); PrintLine("_astBuilder = astBuilder;"); Outdent(); PrintLine("}"); } private void PrintMatchMethod() { PrintLine(); PrintLine("private void Match(TokenKind tokenKind)"); PrintLine("{"); Indent(); PrintLine("if (_scanner.CurrentToken.TokenKind != tokenKind)"); Indent(); PrintLine("throw new SyntaxErrorException(tokenKind, _scanner.CurrentToken);"); Outdent(); Outdent(); PrintLine("}"); } private void PrintMatchOneOfMethod() { PrintLine(); PrintLine("private void MatchOneOf(TokenKind[] tokenSet)"); PrintLine("{"); Indent(); PrintLine("if (!tokenSet.Contains(_scanner.CurrentToken.TokenKind))"); Indent(); PrintLine("throw new SyntaxErrorException(tokenSet, _scanner.CurrentToken);"); Outdent(); Outdent(); PrintLine("}"); } private void PrintMatchOneOf(string nodeId) { PrintLine($"MatchOneOf(firstSetOf{nodeId});"); } private void PrintParseGoal(string prodName, string preActionName, string postActionName) { PrintLine(); PrintLine("public IRootNode ParseGoal()"); PrintLine("{"); Indent(); if (!string.IsNullOrEmpty(preActionName)) PrintAction(preActionName); PrintProdRef(prodName); PrintLine("Match(TokenKind.Eof);"); if (!string.IsNullOrEmpty(postActionName)) PrintAction(postActionName); PrintLine("return BuildRootNode();"); PrintMethodFooter(postActionName); } private void PrintMethodHeader(string name, string preActionName) { PrintLine(); PrintLine($"private void Parse{CamelCaseMethodName(name)}()"); PrintLine("{"); Indent(); if (!string.IsNullOrEmpty(preActionName)) PrintAction(preActionName); } private string CamelCaseMethodName(string name) { var result = String.Empty; var toUpperNexChar = true; foreach (var ch in name.Substring(1, name.Length - 2)) { if (ch == '-') { toUpperNexChar = true; continue; } var chStr = ch.ToString(); result += toUpperNexChar ? chStr.ToUpper() : chStr; toUpperNexChar = false; } return result; } private void PrintMethodFooter(string postActionName) { if (!string.IsNullOrEmpty(postActionName)) PrintAction(postActionName); Outdent(); PrintLine("}"); } private void PrintProdRef(string name) { PrintLine($"Parse{CamelCaseMethodName(name)}();"); } private void PrintMatchNonTerminal(string name) { var tokenDef = _tokens.FirstOrDefault(p => p.Image.Equals(name))?.Definition; if (tokenDef == null) throw new SemanticErrorException($"Token definition for \"{name}\" not found."); PrintLine($"Match(TokenKind.{tokenDef});"); PrintLine(); } private void PrintMatchTerminal(string name) { var tokenDef = _tokens.FirstOrDefault(p => p.Image.Equals(name))?.Definition; if (tokenDef == null) throw new SemanticErrorException($"Token definition for \"{name}\" not found."); PrintLine($"Match(TokenKind.{tokenDef});"); PrintLine("_scanner.Advance();"); } private void PrintAction(string actionName) { var action = CamelCaseMethodName(actionName); PrintLine($"_astBuilder.{action}(_scanner.CurrentToken);"); } private void PrintOption(ITerminalSet firstSet, string nodeId) { if (firstSet.AsEnumerable().Count(p => p != "$EPSILON$") > 1) { PrintFirstSet(firstSet, nodeId); PrintLine($"if (firstSetOf{nodeId}.Contains(_scanner.CurrentToken.TokenKind))"); } else { var defs = SetAsTokenDefinitions(firstSet); PrintLine($"if (_scanner.CurrentToken.TokenKind == TokenKind.{defs.First()})"); } PrintLine("{"); Indent(); } private void PrintKleene(ITerminalSet firstSet, string nodeId) { if (firstSet.AsEnumerable().Count() > 1) { PrintFirstSet(firstSet, nodeId); PrintLine($"while (firstSetOf{nodeId}.Contains(_scanner.CurrentToken.TokenKind))"); } else { var defs = SetAsTokenDefinitions(firstSet); PrintLine($"while (_scanner.CurrentToken.TokenKind == TokenKind.{defs.First()})"); } PrintLine("{"); Indent(); } private void PrintFirstSet(ITerminalSet firstSet, string nodeId) { var tokens = SetAsTokenDefinitions(firstSet); PrintLine($"var firstSetOf{nodeId} = new[]"); PrintLine("{"); Indent(); PrintLine(string.Join(", ", tokens.Select(s => "TokenKind." + s))); Outdent(); PrintLine("};"); } private List<string> SetAsTokenDefinitions(ITerminalSet firstSet) { var tokens = new List<string>(); foreach (var token in firstSet.AsEnumerable().Where(t => t != "$EPSILON$")) { var tokenDef = _tokens.FirstOrDefault(p => p.Image.Equals(token))?.Definition; if (tokenDef == null) throw new SemanticErrorException($"Token definition for \"{token}\" not found."); tokens.Add(tokenDef); } return tokens; } private void PrintTermSwitch() { PrintLine("switch (_scanner.CurrentToken.TokenKind)"); PrintLine("{"); Indent(); } private void PrintTermCase(ITerminalSet firstSet) { var tokens = SetAsTokenDefinitions(firstSet); foreach (var token in tokens) { PrintLine($"case TokenKind.{token}:"); } } private void Indent() { _indentLevel += 3; } private void Outdent() { _indentLevel -= 3; } private void PrintLine() { _streamWriter.WriteLine(); } private void PrintLine(string s) { var indent = new string(' ', _indentLevel); _streamWriter.WriteLine($"{indent}{s}"); } } }
29.034343
111
0.545018
[ "MIT" ]
ngdrascal/ebnfcompiler
EbnfCompiler.CodeGenerator/CSharpGenerator.cs
14,374
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\ksmedia.h(5330,9) namespace DirectN { public enum KSPROPERTY_TUNER { KSPROPERTY_TUNER_CAPS = 0, KSPROPERTY_TUNER_MODE_CAPS = 1, KSPROPERTY_TUNER_MODE = 2, KSPROPERTY_TUNER_STANDARD = 3, KSPROPERTY_TUNER_FREQUENCY = 4, KSPROPERTY_TUNER_INPUT = 5, KSPROPERTY_TUNER_STATUS = 6, KSPROPERTY_TUNER_IF_MEDIUM = 7, KSPROPERTY_TUNER_SCAN_CAPS = 8, KSPROPERTY_TUNER_SCAN_STATUS = 9, KSPROPERTY_TUNER_STANDARD_MODE = 10, KSPROPERTY_TUNER_NETWORKTYPE_SCAN_CAPS = 11, } }
32.85
89
0.657534
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/KSPROPERTY_TUNER.cs
659
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; #if !WINDOWS_PHONE && !PORTABLE using System.Threading; #endif using BrightstarDB.Profiling; using BrightstarDB.Storage.Persistence; namespace BrightstarDB.Storage.BPlusTreeStore.GraphIndex { internal class ConcurrentGraphIndex : IPageStoreGraphIndex { private readonly IPageStore _pageStore; private readonly Dictionary<string, int> _graphUriIndex; private readonly List<GraphIndexEntry> _allEntries; #if WINDOWS_PHONE || PORTABLE private readonly object _lock = new object(); #else private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); #endif public ConcurrentGraphIndex(IPageStore pageStore) { _pageStore = pageStore; _graphUriIndex = new Dictionary<string, int>(); _allEntries= new List<GraphIndexEntry>(); } public ConcurrentGraphIndex(IPageStore pageStore, ulong rootPage, BrightstarProfiler profiler) { using (profiler.Step("Load ConcurrentGraphIndex")) { _pageStore = pageStore; _graphUriIndex = new Dictionary<string, int>(); _allEntries = new List<GraphIndexEntry>(); Read(rootPage, profiler); } } #region Implementation of IGraphIndex /// <summary> /// Returns an enumeration over all graphs in the index /// </summary> /// <returns></returns> public IEnumerable<GraphIndexEntry> EnumerateEntries() { #if WINDOWS_PHONE || PORTABLE lock(_lock) { return _allEntries.Where(x => !x.IsDeleted).ToList(); } #else _lock.EnterReadLock(); try { return _allEntries.Where(x => !x.IsDeleted); } finally { _lock.ExitReadLock(); } #endif } /// <summary> /// Return the URI for the graph with the specified ID /// </summary> /// <param name="graphId">The ID of the graph to lookup</param> /// <returns></returns> /// <remarks>Returns null if no graph exists with the specified URI or if the graph is marked as deleted</remarks> public string GetGraphUri(int graphId) { #if WINDOWS_PHONE || PORTABLE lock(_lock) { if (graphId < _allEntries.Count && !_allEntries[graphId].IsDeleted) { return _allEntries[graphId].Uri; } return null; } #else _lock.EnterReadLock(); try { if (graphId < _allEntries.Count && !_allEntries[graphId].IsDeleted) { return _allEntries[graphId].Uri; } return null; } finally { _lock.ExitReadLock(); } #endif } /// <summary> /// Finds or creates a new ID for the graph with the specified graph URI /// </summary> /// <param name="graphUri">The graph URI to lookup</param> /// <param name="profiler"></param> /// <returns>The ID assigned to the graph</returns> public int AssertGraphId(string graphUri, BrightstarProfiler profiler = null) { if (String.IsNullOrEmpty(graphUri)) { throw new ArgumentException("Graph URI must not be null or an empty string", "graphUri"); } if (graphUri.Length > short.MaxValue) { throw new ArgumentException( String.Format("Graph URI string exceeds maximum allowed length of {0} bytes", short.MaxValue), "graphUri"); } #if WINDOWS_PHONE || PORTABLE lock(_lock) { int entryId; if (_graphUriIndex.TryGetValue(graphUri, out entryId) && !_allEntries[entryId].IsDeleted) { return entryId; } var newId = _allEntries.Count; var entry = new GraphIndexEntry(newId, graphUri, false); _allEntries.Add(entry); _graphUriIndex.Add(graphUri, newId); return newId; } #else using (profiler.Step("Assert Graph Id")) { _lock.EnterUpgradeableReadLock(); try { int entryId; if (_graphUriIndex.TryGetValue(graphUri, out entryId) && !_allEntries[entryId].IsDeleted) { return entryId; } _lock.EnterWriteLock(); try { var newId = _allEntries.Count; var entry = new GraphIndexEntry(newId, graphUri, false); _allEntries.Add(entry); _graphUriIndex.Add(graphUri, newId); return newId; } finally { _lock.ExitWriteLock(); } } finally { _lock.ExitUpgradeableReadLock(); } } #endif } /// <summary> /// Finds the ID assigned to the graph with the specified graph URI /// </summary> /// <param name="graphUri">The graph URI to lookup</param> /// <param name="graphId">Receives the ID of the graph</param> /// <returns>True if an ID was found, false otherwise</returns> public bool TryFindGraphId(string graphUri, out int graphId) { #if WINDOWS_PHONE || PORTABLE lock (_lock) { int entryId; if (_graphUriIndex.TryGetValue(graphUri, out entryId) && !_allEntries[entryId].IsDeleted) { graphId = entryId; return true; } graphId = -1; return false; } #else _lock.EnterReadLock(); try { int entryId; if (_graphUriIndex.TryGetValue(graphUri, out entryId) && !_allEntries[entryId].IsDeleted) { graphId = entryId; return true; } graphId = -1; return false; } finally { _lock.ExitReadLock(); } #endif } public void DeleteGraph(int graphId) { #if WINDOWS_PHONE || PORTABLE lock(_lock) { if (graphId < _allEntries.Count) { var toDelete = _allEntries[graphId]; if (!toDelete.IsDeleted) { _allEntries[graphId] = new GraphIndexEntry(toDelete.Id, toDelete.Uri, true); _graphUriIndex.Remove(toDelete.Uri); IsDirty = true; } } } #else _lock.EnterWriteLock(); try { if (graphId < _allEntries.Count) { var toDelete = _allEntries[graphId]; if (!toDelete.IsDeleted) { _allEntries[graphId] = new GraphIndexEntry(toDelete.Id, toDelete.Uri, true); _graphUriIndex.Remove(toDelete.Uri); IsDirty = true; } } } finally { _lock.ExitWriteLock(); } #endif } /// <summary> /// Get boolean flag indicating if the index contains changes that need to be saved /// </summary> public bool IsDirty { get; private set; } #endregion public ulong Save(ulong transactionId, BrightstarProfiler profiler) { return Write(_pageStore, transactionId, profiler); } public ulong Write(IPageStore pageStore, ulong transactionId, BrightstarProfiler profiler) { IPage rootPage = pageStore.Create(transactionId); IPage currentPage = rootPage; var buff = new byte[pageStore.PageSize]; int offset = 0; foreach (var graphIndexEntry in _allEntries) { int entrySize = String.IsNullOrEmpty(graphIndexEntry.Uri) ? 1 : 3 + Encoding.UTF8.GetByteCount(graphIndexEntry.Uri); if (offset + entrySize > pageStore.PageSize - 9) { IPage nextPage = pageStore.Create(transactionId); buff[offset] = 0xff; BitConverter.GetBytes(nextPage.Id).CopyTo(buff, pageStore.PageSize - 8); currentPage.SetData(buff); currentPage = nextPage; offset = 0; } else { if (String.IsNullOrEmpty(graphIndexEntry.Uri)) { // Record an empty entry buff[offset++] = 2; } else { if (graphIndexEntry.IsDeleted) { buff[offset++] = 1; } else { buff[offset++] = 0; } var uriBytes = Encoding.UTF8.GetBytes(graphIndexEntry.Uri); BitConverter.GetBytes(uriBytes.Length).CopyTo(buff, offset); offset += 4; uriBytes.CopyTo(buff, offset); offset += uriBytes.Length; } } } buff[offset] = 0xff; BitConverter.GetBytes(0ul).CopyTo(buff, pageStore.PageSize - 8); currentPage.SetData(buff); return rootPage.Id; } void Read(ulong rootPageId, BrightstarProfiler profiler) { IPage currentPage = _pageStore.Retrieve(rootPageId, profiler); int offset = 0; int entryIndex = 0; while(true) { var marker = currentPage.Data[offset++]; if (marker == 0xff) { ulong nextPageId = BitConverter.ToUInt64(currentPage.Data, _pageStore.PageSize - 8); if (nextPageId == 0) return; currentPage = _pageStore.Retrieve(nextPageId, profiler); offset = 0; } else if (marker == 2) { _allEntries.Add(new GraphIndexEntry(entryIndex++, null, true)); } else { int uriByteLength = BitConverter.ToInt32(currentPage.Data, offset); offset += 4; var uri = Encoding.UTF8.GetString(currentPage.Data, offset, uriByteLength); offset += uriByteLength; var newEntry = new GraphIndexEntry(entryIndex++, uri, marker == 1); _allEntries.Add(newEntry); if (!newEntry.IsDeleted) _graphUriIndex[newEntry.Uri] = newEntry.Id; } } } } }
34.803519
127
0.474975
[ "MIT" ]
BrightstarDB/BrightstarDB
src/core/BrightstarDB.Core/Storage/BPlusTreeStore/GraphIndex/ConcurrentGraphIndex.cs
11,870
C#
using System; using System.Collections.Generic; using TheGuild; namespace Client.UI.ViewModel { [UIWindow(Background = true,Enter = WindowAnimType.ScaleToNormal,Exit = WindowAnimType.ScaleToZero)] public class UI_JoinedGuild: UIBase<View_UnionMainPanel> { public enum MenuType { Info, //我的公会 Activity, //公会活动 Chat, //聊天 Help //好友帮助 } private Dictionary<int, InternalComponent> mSubPanel { get; }= new Dictionary<int, InternalComponent>(); private InternalComponent ActiveUI { get; set; } protected override void OnInit(IUIParams p) { base.OnInit(p); View.c2.onChanged.Add(Menu_OnChanged); Menu_OnChanged(); } private void Menu_OnChanged() { if (View.c2.selectedPage == "我的公会") { OpenPanel(MenuType.Info); } else if (View.c2.selectedPage == "公会活动") { OpenPanel(MenuType.Activity); } else if (View.c2.selectedPage == "聊天") { OpenPanel(MenuType.Chat); } else if (View.c2.selectedPage == "成员互助") { OpenPanel(MenuType.Help); } } protected override void OnRelease() { base.OnRelease(); GC.Collect(); } private void OpenPanel(MenuType menuType) { if (ActiveUI != null) { ActiveUI.OnDisable(); } InternalComponent ui; switch (menuType) { case MenuType.Info: if (!mSubPanel.TryGetValue((int) MenuType.Info, out ui)) { View.MyUnion.url = View_WoDeGongHuiZuJian.URL; ui = new UI_GuildHome(this, (View_WoDeGongHuiZuJian) View.MyUnion.component); mSubPanel.Add((int)MenuType.Info, ui); } ui.OnEnable(); ActiveUI = ui; break; case MenuType.Activity: break; case MenuType.Chat: if (!mSubPanel.TryGetValue((int) MenuType.Chat, out ui)) { View.Chat.url = View_LiaoTianZuJian.URL; ui = new UI_GuildChat(this, (View_LiaoTianZuJian) View.Chat.component); mSubPanel.Add((int)MenuType.Chat, ui); } ui.OnEnable(); ActiveUI = ui; break; case MenuType.Help: break; default: throw new ArgumentOutOfRangeException(nameof (menuType), menuType, null); } } } }
31.836957
112
0.470809
[ "MIT" ]
Noname-Studio/ET
Unity/Assets/Scripts/Client/UI/ViewModel/UI_JoinedGuild.cs
2,987
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Scf.V20180416.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class Filter : AbstractModel { /// <summary> /// 需要过滤的字段。 /// </summary> [JsonProperty("Name")] public string Name{ get; set; } /// <summary> /// 字段的过滤值。 /// </summary> [JsonProperty("Values")] public string[] Values{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Name", this.Name); this.SetParamArraySimple(map, prefix + "Values.", this.Values); } } }
29
81
0.626775
[ "Apache-2.0" ]
kimii/tencentcloud-sdk-dotnet
TencentCloud/Scf/V20180416/Models/Filter.cs
1,509
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.NetApp { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Microsoft NetApp Azure Resource Provider specification /// </summary> public partial interface IAzureNetAppFilesManagementClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// Subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every /// service call. /// </summary> string SubscriptionId { get; set; } /// <summary> /// Version of the API to be used with the client request. /// </summary> string ApiVersion { get; } /// <summary> /// The preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// The retry timeout in seconds for Long Running Operations. Default /// value is 30. /// </summary> int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Whether a unique x-ms-client-request-id should be generated. When /// set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IOperations. /// </summary> IOperations Operations { get; } /// <summary> /// Gets the IAccountsOperations. /// </summary> IAccountsOperations Accounts { get; } /// <summary> /// Gets the IPoolsOperations. /// </summary> IPoolsOperations Pools { get; } /// <summary> /// Gets the IVolumesOperations. /// </summary> IVolumesOperations Volumes { get; } /// <summary> /// Gets the IMountTargetsOperations. /// </summary> IMountTargetsOperations MountTargets { get; } /// <summary> /// Gets the ISnapshotsOperations. /// </summary> ISnapshotsOperations Snapshots { get; } /// <summary> /// Check resource name availability /// </summary> /// <remarks> /// Check if a resource name is available. /// </remarks> /// <param name='location'> /// The location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceNameAvailability>> CheckNameAvailabilityWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Check file path availability /// </summary> /// <remarks> /// Check if a file path is available. /// </remarks> /// <param name='location'> /// The location /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceNameAvailability>> CheckFilePathAvailabilityWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
33.270833
248
0.596118
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/NetApp/Management.NetApp/Generated/IAzureNetAppFilesManagementClient.cs
4,791
C#
//----------------------------------------------------------------------- // <copyright file="Saml2SubjectConfirmation.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace System.IdentityModel.Tokens { using System; using System.Collections.ObjectModel; /// <summary> /// A security token backed by a SAML2 assertion. /// </summary> public class Saml2SecurityToken : SecurityToken { private Saml2Assertion assertion; private ReadOnlyCollection<SecurityKey> keys; private SecurityToken issuerToken; /// <summary> /// Initializes an instance of <see cref="Saml2SecurityToken"/> from a <see cref="Saml2Assertion"/>. /// </summary> /// <param name="assertion">A <see cref="Saml2Assertion"/> to initialize from.</param> public Saml2SecurityToken(Saml2Assertion assertion) : this(assertion, EmptyReadOnlyCollection<SecurityKey>.Instance, null) { } /// <summary> /// Initializes an instance of <see cref="Saml2SecurityToken"/> from a <see cref="Saml2Assertion"/>. /// </summary> /// <param name="assertion">A <see cref="Saml2Assertion"/> to initialize from.</param> /// <param name="keys">A collection of <see cref="SecurityKey"/> to include in the token.</param> /// <param name="issuerToken">A <see cref="SecurityToken"/> representing the issuer.</param> public Saml2SecurityToken(Saml2Assertion assertion, ReadOnlyCollection<SecurityKey> keys, SecurityToken issuerToken) { if (null == assertion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } if (null == keys) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keys"); } this.assertion = assertion; this.keys = keys; this.issuerToken = issuerToken; } /// <summary> /// Gets the <see cref="Saml2Assertion"/> for this token. /// </summary> public Saml2Assertion Assertion { get { return this.assertion; } } /// <summary> /// Gets the SecurityToken id. /// </summary> public override string Id { get { return this.assertion.Id.Value; } } /// <summary> /// Gets the <see cref="SecurityToken"/> of the issuer. /// </summary> public SecurityToken IssuerToken { get { return this.issuerToken; } } /// <summary> /// Gets the collection of <see cref="SecurityKey"/> contained in this token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return this.keys; } } /// <summary> /// Gets the time the token is valid from. /// </summary> public override DateTime ValidFrom { get { if (null != this.assertion.Conditions && null != this.assertion.Conditions.NotBefore) { return this.assertion.Conditions.NotBefore.Value; } else { return DateTime.MinValue; } } } /// <summary> /// Gets the time the token is valid to. /// </summary> public override DateTime ValidTo { get { if (null != this.assertion.Conditions && null != this.assertion.Conditions.NotOnOrAfter) { return this.assertion.Conditions.NotOnOrAfter.Value; } else { return DateTime.MaxValue; } } } /// <summary> /// Determines if this token matches the keyIdentifierClause. /// </summary> /// <param name="keyIdentifierClause"><see cref="SecurityKeyIdentifierClause"/> to match.</param> /// <returns>True if the keyIdentifierClause is matched. False otherwise.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { return Saml2AssertionKeyIdentifierClause.Matches(this.Id, keyIdentifierClause) || base.MatchesKeyIdentifierClause(keyIdentifierClause); } /// <summary> /// Determines is this token can create a <see cref="SecurityKeyIdentifierClause"/>. /// </summary> /// <typeparam name="T">The type of <see cref="SecurityKeyIdentifierClause"/> to check if creation is possible.</typeparam> /// <returns>'True' if this token can create a <see cref="SecurityKeyIdentifierClause"/> of type T. 'False' otherwise.</returns> public override bool CanCreateKeyIdentifierClause<T>() { return (typeof(T) == typeof(Saml2AssertionKeyIdentifierClause)) || base.CanCreateKeyIdentifierClause<T>(); } /// <summary> /// Creates a <see cref="SecurityKeyIdentifierClause"/> that represents this token. /// </summary> /// <typeparam name="T">The type of the <see cref="SecurityKeyIdentifierClause"/> to create.</typeparam> /// <returns>A <see cref="SecurityKeyIdentifierClause"/> for this token.</returns> public override T CreateKeyIdentifierClause<T>() { if (typeof(T) == typeof(Saml2AssertionKeyIdentifierClause)) { return new Saml2AssertionKeyIdentifierClause(this.assertion.Id.Value) as T; } else if (typeof(T) == typeof(SamlAssertionKeyIdentifierClause)) { return new WrappedSaml2AssertionKeyIdentifierClause(new Saml2AssertionKeyIdentifierClause(this.assertion.Id.Value)) as T; } else { return base.CreateKeyIdentifierClause<T>(); } } } }
37.818182
137
0.559936
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WCF/IdentityModel/System/IdentityModel/Tokens/Saml2SecurityToken.cs
6,240
C#
namespace House.Basement { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class TheBasement { public TheBasement() { } } }
28.833333
146
0.638728
[ "MIT" ]
PhilipDaniels/dotnetversioning
Examples/Example2/House.Basement/TheBasement.cs
348
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Common { /// <summary> /// Defines values for ComposeDeploymentUpgradeState. /// </summary> public enum ComposeDeploymentUpgradeState { /// <summary> /// Indicates the upgrade state is invalid. All Service Fabric enumerations have the invalid type. The value is zero.. /// </summary> Invalid, /// <summary> /// The upgrade is in the progress of provisioning target application type version. The value is 1.. /// </summary> ProvisioningTarget, /// <summary> /// The upgrade is rolling forward to the target version but is not complete yet. The value is 2.. /// </summary> RollingForwardInProgress, /// <summary> /// The current upgrade domain has finished upgrading. The overall upgrade is waiting for an explicit move next request /// in UnmonitoredManual mode or performing health checks in Monitored mode. The value is 3. /// </summary> RollingForwardPending, /// <summary> /// The upgrade is in the progress of unprovisioning current application type version and rolling forward to the target /// version is completed. The value is 4.. /// </summary> UnprovisioningCurrent, /// <summary> /// The upgrade has finished rolling forward. The value is 5.. /// </summary> RollingForwardCompleted, /// <summary> /// The upgrade is rolling back to the previous version but is not complete yet. The value is 6.. /// </summary> RollingBackInProgress, /// <summary> /// The upgrade is in the progress of unprovisioning target application type version and rolling back to the current /// version is completed. The value is 7.. /// </summary> UnprovisioningTarget, /// <summary> /// The upgrade has finished rolling back. The value is 8.. /// </summary> RollingBackCompleted, /// <summary> /// The upgrade has failed and is unable to execute FailureAction. The value is 9.. /// </summary> Failed } }
37.179104
127
0.590124
[ "MIT" ]
aL3891/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Common/ComposeDeploymentUpgradeState.cs
2,491
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class effectTrackItemDecal : effectTrackItem { [Ordinal(0)] [RED("additionalRotation")] public CFloat AdditionalRotation { get; set; } [Ordinal(1)] [RED("atlasFrameEnd")] public CInt32 AtlasFrameEnd { get; set; } [Ordinal(2)] [RED("atlasFrameStart")] public CInt32 AtlasFrameStart { get; set; } [Ordinal(3)] [RED("decalRenderMode")] public CEnum<EDecalRenderMode> DecalRenderMode { get; set; } [Ordinal(4)] [RED("emissiveScale")] public CHandle<IEvaluatorVector> EmissiveScale { get; set; } [Ordinal(5)] [RED("fadeInTime")] public CFloat FadeInTime { get; set; } [Ordinal(6)] [RED("fadeOutTime")] public CFloat FadeOutTime { get; set; } [Ordinal(7)] [RED("horizontalFlip")] public CBool HorizontalFlip { get; set; } [Ordinal(8)] [RED("isAttached")] public CBool IsAttached { get; set; } [Ordinal(9)] [RED("isStretchEnabled")] public CBool IsStretchEnabled { get; set; } [Ordinal(10)] [RED("material")] public rRef<IMaterial> Material { get; set; } [Ordinal(11)] [RED("normalThreshold")] public CFloat NormalThreshold { get; set; } [Ordinal(12)] [RED("normalsBlendingMode")] public CEnum<RenderDecalNormalsBlendingMode> NormalsBlendingMode { get; set; } [Ordinal(13)] [RED("orderPriority")] public CEnum<RenderDecalOrderPriority> OrderPriority { get; set; } [Ordinal(14)] [RED("randomAtlasing")] public CBool RandomAtlasing { get; set; } [Ordinal(15)] [RED("randomRotation")] public CBool RandomRotation { get; set; } [Ordinal(16)] [RED("scale")] public CHandle<IEvaluatorVector> Scale { get; set; } [Ordinal(17)] [RED("surfaceType")] public CEnum<ERenderObjectType> SurfaceType { get; set; } [Ordinal(18)] [RED("verticalFlip")] public CBool VerticalFlip { get; set; } public effectTrackItemDecal(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
59.382353
125
0.696384
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/effectTrackItemDecal.cs
1,986
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectStockLibrary { public class Address { [Key] public Guid _id { get; private set; } public string _address_line_1 { get; set; } public string _address_line_2 { get; set; } public string _codePostal { get;set; } public string _city { get; set; } public string _country { get; set; } [JsonConstructorAttribute] public Address(string address_line_1, string address_line_2, string codePostal, string city, string country) { _id = Guid.NewGuid(); _address_line_1 = address_line_1; _address_line_2 = address_line_2; _codePostal = codePostal; _city = city; _country = country; } public Address(Guid id ,string address_line_1, string address_line_2, string codePostal, string city, string country) { _id = id; _address_line_1 = address_line_1; _address_line_2 = address_line_2; _codePostal = codePostal; _city = city; _country = country; } public Address(Guid _id) { _id = Guid.NewGuid(); _address_line_1 = ""; _address_line_2 = ""; _codePostal = ""; _city = ""; _country = ""; } public Address() { _id = Guid.NewGuid() ; _address_line_1 = ""; _address_line_2 = ""; _codePostal = ""; _city = ""; _country = ""; } public string read() { return $"adress_ : {_address_line_1} adress_ : {_address_line_2} codePostal :{ _codePostal} city : { _city} country : { _country}"; } } }
26.184211
143
0.548744
[ "MIT" ]
POEC-DOTNET-CLERMONT-2022/ProjetStock
ApplicationStock/ApplicationConsole/ProjectStockLibrary/Address.cs
1,992
C#
using AutoFixture; using FreeParkingSystem.Accounts.Contract; using FreeParkingSystem.Accounts.Data.Mappers; using FreeParkingSystem.Accounts.Data.Models; using FreeParkingSystem.Common.ExtensionMethods; using FreeParkingSystem.Testing; using Shouldly; using Xunit; namespace FreeParkingSystem.Accounts.Tests.Mappers { public class ClaimsMapperTests { private static void ContainerSetup(IFixture fixture) { fixture.Build<DbClaims>() .Without(claim => claim.User) .ToCustomization() .Customize(fixture); } [Theory, FixtureData] public void Map_WhenDbClaimsIsNull_ShouldReturnNull( ClaimsMapper sut) { // Act var result = sut.Map((DbClaims)null); // Assert result.ShouldBeNull(); } [Theory, FixtureData] public void Map_WhenUserClaimIsNull_ShouldReturnNull( ClaimsMapper sut) { // Act var result = sut.Map((UserClaim)null); // Assert result.ShouldBeNull(); } [Theory, FixtureData] public void Map_DbClaims_WhenValid_ShouldReturnTheMappedInstance( DbClaims dbClaim, ClaimsMapper sut) { // Arrange // Act var result = sut.Map(dbClaim); // Assert result.ShouldNotBeNull(); result.Id.ShouldBe(dbClaim.Id); result.UserId.ShouldBe(dbClaim.UserId); result.Type.ShouldBe(dbClaim.ClaimType); result.Value.ShouldBe(dbClaim.ClaimValue); } [Theory, FixtureData] public void Map_UserClaim_WhenValid_ShouldReturnTheMappedInstance( UserClaim claim, ClaimsMapper sut) { // Arrange // Act var result = sut.Map(claim); // Assert result.ShouldNotBeNull(); result.Id.ShouldBe(claim.Id); result.ClaimType.ShouldBe(claim.Type); result.ClaimValue.ShouldBe(claim.Value); result.UserId.ShouldBe(claim.UserId); } } }
21.414634
68
0.727221
[ "MIT" ]
NickPolyder/FreeParkingSystem
Tests/FreeParkingSystem.Accounts.Tests/Mappers/ClaimsMapperTests.cs
1,758
C#
using System; using System.Collections.Generic; using System.Text; namespace DynamicDLL { public class Test { public void A(string value) { Console.WriteLine("Test.A"); Console.WriteLine(value); } public static void B(string value) { Console.WriteLine("Test.B"); Console.WriteLine(value); } } }
17.695652
42
0.547912
[ "Apache-2.0" ]
Lc3586/Microservice
src/Test/DynamicDLL/Test.cs
409
C#
using System.Xml; using System.Xml.Linq; namespace ReQube.Utils { public static class XmlUtils { public static XElement RequiredElement(this XElement xElement, XName name) { return xElement.Element(name) ?? throw new XmlException($"Invalid xml. Required element {name} is not found."); } } }
23.933333
97
0.626741
[ "MIT" ]
IagoPaz/dotnet-reqube
src/dotnet-reqube/Utils/XmlUtils.cs
361
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Collections.Generic; using System.Collections.Immutable; using Microsoft.VisualStudio.TestTools.UnitTesting; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Metamodel.Facet; using NakedFramework.ParallelReflector.Component; using NakedObjects.Reflector.Component; namespace NakedObjects.Reflector.Test.Reflect { [TestClass] public class ReflectorGenericSetTest : AbstractReflectorTest { protected override (ITypeSpecBuilder, IImmutableDictionary<string, ITypeSpecBuilder>) LoadSpecification(IReflector reflector) { var objectReflector = (ObjectReflector) reflector; IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); (_, metamodel) = reflector.LoadSpecification(typeof(ISet<TestPoco>), metamodel); return ((AbstractParallelReflector) reflector).IntrospectSpecification(typeof(ISet<TestPoco>), metamodel); } [TestMethod] public void TestCollectionFacet() { var facet = Specification.GetFacet(typeof(ICollectionFacet)); Assert.IsNotNull(facet); AssertIsInstanceOfType<GenericCollectionFacet>(facet); } [TestMethod] public void TestDescriptionFaced() { var facet = Specification.GetFacet(typeof(IDescribedAsFacet)); Assert.IsNotNull(facet); AssertIsInstanceOfType<DescribedAsFacetNone>(facet); } [TestMethod] public void TestElementTypeFacet() { var facet = (IElementTypeFacet) Specification.GetFacet(typeof(IElementTypeFacet)); Assert.IsNull(facet); } [TestMethod] public void TestTypeOfFacet() { var facet = (ITypeOfFacet) Specification.GetFacet(typeof(ITypeOfFacet)); Assert.IsNotNull(facet); AssertIsInstanceOfType<TypeOfFacetInferredFromGenerics>(facet); } [TestMethod] public void TestFacets() { Assert.AreEqual(13, Specification.FacetTypes.Length); } [TestMethod] public void TestName() { Assert.AreEqual("System.Collections.Generic.ISet`1", Specification.FullName); } [TestMethod] public void TestNamedFaced() { var facet = Specification.GetFacet(typeof(INamedFacet)); Assert.IsNotNull(facet); AssertIsInstanceOfType<NamedFacetInferred>(facet); } [TestMethod] public void TestPluralFaced() { var facet = Specification.GetFacet(typeof(IPluralFacet)); Assert.IsNotNull(facet); AssertIsInstanceOfType<PluralFacetInferred>(facet); } [TestMethod] public void TestType() { Assert.IsTrue(Specification.IsCollection); } } // Copyright (c) Naked Objects Group Ltd. }
42.162791
138
0.691671
[ "Apache-2.0" ]
NakedObjectsGroup/NakedObjectsFramework
NakedObjects/NakedObjects.Reflector.Test/Reflect/ReflectorGenericSetTest.cs
3,626
C#
#region License /* Copyright © 2014-2019 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.Enums; using Amdocs.Ginger.Common.Repository; using Amdocs.Ginger.Repository; using Amdocs.Ginger.UserControls; using GingerCore.GeneralLib; using GingerWPF.DragDropLib; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace Ginger.UserControlsLib.UCListView { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class UcListView : UserControl, IDragDrop, IClipboardOperations { IObservableList mObjList; ICollectionView filteredView; private string mSearchString; public ObservableList<Guid> Tags = null; CollectionView mGroupView; public delegate void UcListViewEventHandler(UcListViewEventArgs EventArgs); public event UcListViewEventHandler UcListViewEvent; public void OnUcListViewEvent(UcListViewEventArgs.eEventType eventType, Object eventObject = null) { UcListViewEventHandler handler = UcListViewEvent; if (handler != null) { handler(new UcListViewEventArgs(eventType, eventObject)); } } NotifyCollectionChangedEventHandler CollectionChangedHandler; // DragDrop event handler public event EventHandler ItemDropped; public delegate void ItemDroppedEventHandler(DragInfo DragInfo); public event EventHandler SameFrameItemDropped; public delegate void SameFrameItemDroppedEventHandler(DragInfo DragInfo); public event EventHandler PreviewDragItem; public event PasteItemEventHandler PasteItemEvent; public delegate void PreviewDragItemEventHandler(DragInfo DragInfo); private bool mIsDragDropCompatible; public bool IsDragDropCompatible { get { return mIsDragDropCompatible; } set { if (mIsDragDropCompatible == value) return; else if (value == false) { DragDrop2.UnHookEventHandlers(this); mIsDragDropCompatible = value; return; } else if (value == true) { DragDrop2.HookEventHandlers(this); mIsDragDropCompatible = value; return; } } } IListViewHelper mListViewHelper = null; public UcListView() { InitializeComponent(); //Hook Drag Drop handler mIsDragDropCompatible = true; DragDrop2.HookEventHandlers(this); if (Tags == null) { Tags = new ObservableList<Guid>(); } xTagsFilter.Init(Tags); xTagsFilter.TagsStackPanlChanged += TagsFilter_TagsStackPanlChanged; } private void TagsFilter_TagsStackPanlChanged(object sender, EventArgs e) { this.Dispatcher.Invoke(() => { CollectFilterData(); filteredView.Refresh(); }); } public ListView List { get { return xListView; } set { xListView = value; } } public SelectionMode ListSelectionMode { get { return xListView.SelectionMode; } set { xListView.SelectionMode = value; } } public IObservableList DataSourceList { set { try { if (mObjList != null) { mObjList.PropertyChanged -= ObjListPropertyChanged; mObjList.CollectionChanged -= CollectionChangedHandler; OnUcListViewEvent(UcListViewEventArgs.eEventType.ClearBindings);//so all list items will release their binding } mObjList = value; filteredView = CollectionViewSource.GetDefaultView(mObjList); if (filteredView != null) { CollectFilterData(); //if(filteredView.Filter == null) filteredView.Filter = LVItemFilter; } this.Dispatcher.Invoke(() => { xSearchTextBox.Text = ""; xListView.ItemsSource = mObjList; // Make the first row selected if (value != null && value.Count > 0) { xListView.SelectedIndex = 0; xListView.SelectedItem = value[0]; // Make sure that in case we have only one item it will be the current - otherwise gives err when one record if (mObjList.SyncCurrentItemWithViewSelectedItem && mObjList.Count > 0) { mObjList.CurrentItem = value[0]; } } //show items as collapsed mListViewHelper.ExpandItemOnLoad = false; xExpandCollapseBtn.ButtonImageType = eImageType.ExpandAll; }); } catch (Exception ex) { Reporter.ToLog(eLogLevel.ERROR, "Failed to set ucListView.DataSourceList", ex); } if (mObjList != null) { mObjList.PropertyChanged += ObjListPropertyChanged; BindingOperations.EnableCollectionSynchronization(mObjList, mObjList);//added to allow collection changes from other threads CollectionChangedHandler = new NotifyCollectionChangedEventHandler(CollectionChangedMethod); mObjList.CollectionChanged += CollectionChangedHandler; UpdateTitleListCount(); } } get { return mObjList; } } List<Guid> mFilterSelectedTags = null; private void CollectFilterData() { //collect search values this.Dispatcher.Invoke(() => { mObjList.FilterStringData = xSearchTextBox.Text; mFilterSelectedTags = xTagsFilter.GetSelectedTagsList(); }); } bool LVItemFilter(object item) { if (string.IsNullOrWhiteSpace(mObjList.FilterStringData) && (mFilterSelectedTags == null || mFilterSelectedTags.Count == 0)) return true; //Filter by search text if (!string.IsNullOrEmpty(mObjList.FilterStringData)) { return ((item as RepositoryItemBase).ItemName.IndexOf(mObjList.FilterStringData, StringComparison.OrdinalIgnoreCase) >= 0); } //Filter by Tags if (mFilterSelectedTags != null && mFilterSelectedTags.Count > 0) { return TagsFilter(item, mFilterSelectedTags); } return false; } private bool TagsFilter(object obj, List<Guid> selectedTagsGUID) { if (obj is ISearchFilter) { return ((ISearchFilter)obj).FilterBy(eFilterBy.Tags, selectedTagsGUID); } return false; } private void ObjListPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { GingerCore.General.DoEvents(); if (e.PropertyName == nameof(IObservableList.CurrentItem)) { if (mObjList.SyncViewSelectedItemWithCurrentItem) { SetListSelectedItemAsSourceCurrentItem(); } } if (e.PropertyName == nameof(IObservableList.FilterStringData)) { this.Dispatcher.Invoke(() => xSearchTextBox.Text = mObjList.FilterStringData); } } private void SetListSelectedItemAsSourceCurrentItem() { this.Dispatcher.Invoke(() => { if (mObjList.CurrentItem != xListView.SelectedItem) { xListView.SelectedItem = mObjList.CurrentItem; int index = xListView.Items.IndexOf(mObjList.CurrentItem); xListView.SelectedIndex = index; ScrollToViewCurrentItem(); } }); } private void CollectionChangedMethod(object sender, NotifyCollectionChangedEventArgs e) { this.Dispatcher.Invoke(() => { //different kind of changes that may have occurred in collection if (e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace || e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Move) { OnUcListViewEvent(UcListViewEventArgs.eEventType.UpdateIndex); } UpdateTitleListCount(); }); } private void UpdateTitleListCount() { this.Dispatcher.Invoke(() => { xListCountTitleLbl.Content = string.Format("({0})", mObjList.Count); }); } public object CurrentItem { get { object o = null; this.Dispatcher.Invoke(() => { o = xListView.SelectedItem; }); return o; } } public int CurrentItemIndex { get { if (xListView.Items != null && xListView.Items.Count > 0) { return xListView.Items.IndexOf(xListView.SelectedItem); } else { return -1; } } } public Visibility ExpandCollapseBtnVisiblity { get { return xExpandCollapseBtn.Visibility; } set { xExpandCollapseBtn.Visibility = value; } } public void ResetExpandCollapseBtn() { xExpandCollapseBtn.ButtonImageType = eImageType.ExpandAll; } public Visibility ListOperationsBarPnlVisiblity { get { return xAllListOperationsBarPnl.Visibility; } set { xAllListOperationsBarPnl.Visibility = value; } } public Visibility ListTitleVisibility { get { return xListTitlePnl.Visibility; } set { xListTitlePnl.Visibility = value; } } public string Title { get { if (xListTitleLbl.Content != null) { return xListTitleLbl.Content.ToString(); ; } else { return string.Empty; } } set { xListTitleLbl.Content = value; } } public eImageType ListImageType { get { return xListTitleImage.ImageType; } set { xListTitleImage.ImageType = value; } } public void ScrollToViewCurrentItem() { if (mObjList.CurrentItem != null) { this.Dispatcher.Invoke(() => { xListView.ScrollIntoView(mObjList.CurrentItem); }); } } private void xListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (mObjList != null && mObjList.SyncCurrentItemWithViewSelectedItem) { SetSourceCurrentItemAsListSelectedItem(); } //e.Handled = true; } private void SetSourceCurrentItemAsListSelectedItem() { if (mObjList == null) return; if (mObjList.CurrentItem == xListView.SelectedItem) return; if (mObjList != null) { mObjList.CurrentItem = xListView.SelectedItem; ScrollToViewCurrentItem(); } } private void XExpandCollapseBtn_Click(object sender, RoutedEventArgs e) { if (xExpandCollapseBtn.ButtonImageType == eImageType.ExpandAll) { OnUcListViewEvent(UcListViewEventArgs.eEventType.ExpandAllItems); xExpandCollapseBtn.ButtonImageType = eImageType.CollapseAll; mListViewHelper.ExpandItemOnLoad = true; } else { OnUcListViewEvent(UcListViewEventArgs.eEventType.CollapseAllItems); xExpandCollapseBtn.ButtonImageType = eImageType.ExpandAll; mListViewHelper.ExpandItemOnLoad = false; } } public void SetDefaultListDataTemplate(IListViewHelper listViewHelper) { mListViewHelper = listViewHelper; mListViewHelper.ListView = this; this.Dispatcher.Invoke(() => { DataTemplate dataTemp = new DataTemplate(); FrameworkElementFactory listItemFac = new FrameworkElementFactory(typeof(UcListViewItem)); listItemFac.SetBinding(UcListViewItem.ItemProperty, new Binding()); listItemFac.SetValue(UcListViewItem.ListHelperProperty, listViewHelper); dataTemp.VisualTree = listItemFac; xListView.ItemTemplate = dataTemp; SetListOperations(); SetListExtraOperations(); }); } public void SetListOperations() { List<ListItemOperation> listOperations = mListViewHelper.GetListOperations(); if (listOperations != null && listOperations.Count > 0) { xListOperationsPnl.Visibility = Visibility.Visible; foreach (ListItemOperation operation in listOperations.Where(x => x.SupportedViews.Contains(mListViewHelper.PageViewMode)).ToList()) { ucButton operationBtn = new ucButton(); operationBtn.ButtonType = Amdocs.Ginger.Core.eButtonType.CircleImageButton; operationBtn.ButtonImageType = operation.ImageType; operationBtn.ToolTip = operation.ToolTip; operationBtn.Margin = new Thickness(-2, 0, -2, 0); operationBtn.ButtonImageHeight = 16; operationBtn.ButtonImageWidth = 16; operationBtn.ButtonFontImageSize = operation.ImageSize; if (operation.ImageForeground == null) { //operationBtn.ButtonImageForground = (SolidColorBrush)FindResource("$BackgroundColor_DarkBlue"); } else { operationBtn.ButtonImageForground = operation.ImageForeground; } if (operation.ImageBindingObject != null) { if (operation.ImageBindingConverter == null) { BindingHandler.ObjFieldBinding(operationBtn, ucButton.ButtonImageTypeProperty, operation.ImageBindingObject, operation.ImageBindingFieldName, BindingMode.OneWay); } else { BindingHandler.ObjFieldBinding(operationBtn, ucButton.ButtonImageTypeProperty, operation.ImageBindingObject, operation.ImageBindingFieldName, bindingConvertor: operation.ImageBindingConverter, BindingMode.OneWay); } } operationBtn.Click += operation.OperationHandler; operationBtn.Tag = xListView.ItemsSource; xListOperationsPnl.Children.Add(operationBtn); } } if (xListOperationsPnl.Children.Count == 0) { xListOperationsPnl.Visibility = Visibility.Collapsed; } } private void SetListExtraOperations() { List<ListItemOperation> extraOperations = mListViewHelper.GetListExtraOperations(); if (extraOperations != null && extraOperations.Count > 0) { xListExtraOperationsMenu.Visibility = Visibility.Visible; foreach (ListItemOperation operation in extraOperations.Where(x => x.SupportedViews.Contains(mListViewHelper.PageViewMode)).ToList()) { MenuItem menuitem = new MenuItem(); menuitem.Style = (Style)FindResource("$MenuItemStyle"); ImageMakerControl iconImage = new ImageMakerControl(); iconImage.ImageType = operation.ImageType; iconImage.SetAsFontImageWithSize = operation.ImageSize; iconImage.HorizontalAlignment = HorizontalAlignment.Left; menuitem.Icon = iconImage; menuitem.Header = operation.Header; menuitem.ToolTip = operation.ToolTip; if (operation.ImageForeground == null) { //iconImage.ImageForeground = (SolidColorBrush)FindResource("$BackgroundColor_DarkBlue"); } else { iconImage.ImageForeground = operation.ImageForeground; } if (operation.ImageBindingObject != null) { if (operation.ImageBindingConverter == null) { BindingHandler.ObjFieldBinding(iconImage, ImageMaker.ContentProperty, operation.ImageBindingObject, operation.ImageBindingFieldName, BindingMode.OneWay); } else { BindingHandler.ObjFieldBinding(iconImage, ImageMaker.ContentProperty, operation.ImageBindingObject, operation.ImageBindingFieldName, bindingConvertor: operation.ImageBindingConverter, BindingMode.OneWay); } } menuitem.Click += operation.OperationHandler; menuitem.Tag = xListView.ItemsSource; if (string.IsNullOrEmpty(operation.Group)) { ((MenuItem)(xListExtraOperationsMenu.Items[0])).Items.Add(menuitem); } else { //need to add to Group bool addedToGroup = false; foreach (MenuItem item in ((MenuItem)(xListExtraOperationsMenu.Items[0])).Items) { if (item.Header.ToString() == operation.Group) { //adding to existing group item.Items.Add(menuitem); addedToGroup = true; break; } } if (!addedToGroup) { //creating the group and adding MenuItem groupMenuitem = new MenuItem(); groupMenuitem.Style = (Style)FindResource("$MenuItemStyle"); ImageMakerControl groupIconImage = new ImageMakerControl(); groupIconImage.ImageType = operation.GroupImageType; groupIconImage.SetAsFontImageWithSize = operation.ImageSize; groupIconImage.HorizontalAlignment = HorizontalAlignment.Left; groupMenuitem.Icon = groupIconImage; groupMenuitem.Header = operation.Group; groupMenuitem.ToolTip = operation.Group; ((MenuItem)(xListExtraOperationsMenu.Items[0])).Items.Add(groupMenuitem); groupMenuitem.Items.Add(menuitem); } } } } if (((MenuItem)(xListExtraOperationsMenu.Items[0])).Items.Count == 0) { xListExtraOperationsMenu.Visibility = Visibility.Collapsed; } } //public void ClearBindings() //{ // if (xTagsFilter != null) // { // xTagsFilter.TagsStackPanlChanged -= TagsFilter_TagsStackPanlChanged; // xTagsFilter.ClearBinding(); // xTagsFilter.ClearControlsBindings(); // xTagsFilter = null; // } // if (mObjList != null) // { // mObjList.PropertyChanged -= ObjListPropertyChanged; // BindingOperations.DisableCollectionSynchronization(mObjList); // mObjList.CollectionChanged -= CollectionChangedHandler; // } // foreach (ucButton operation in xListOperationsPnl.Children) // { // BindingOperations.ClearAllBindings(operation); // } // foreach (MenuItem extraOperation in xListExtraOperationsMenu.Items) // { // BindingOperations.ClearAllBindings(extraOperation); // } // OnUcListViewEvent(UcListViewEventArgs.eEventType.ClearBindings); // this.ClearControlsBindings(); //} void IDragDrop.StartDrag(DragInfo Info) { // Get the item under the mouse, or nothing, avoid selecting scroll bars. or empty areas etc.. Info.DragSource = this; var rowItem = ItemsControl.ContainerFromElement(this.xListView, (DependencyObject)Info.OriginalSource); if (rowItem != null) { if (rowItem is ListViewItem) { int selectedItemsCount = this.GetSelectedItems().Count; if (selectedItemsCount > 1) { Info.Data = this.GetSelectedItems(); int identityTextLength = (rowItem as ListViewItem).Content.ToString().ToCharArray().Length; if (identityTextLength > 16) { identityTextLength = 16; } Info.Header = (rowItem as ListViewItem).Content.ToString().Substring(0, identityTextLength) + ".. + " + (selectedItemsCount - 1); } else { Info.Data = (rowItem as ListViewItem).Content; Info.Header = Info.Data.ToString(); } } else if (rowItem is GroupItem) { Info.Data = ((GroupItem)ItemsControl.ContainerFromElement(this.xListView, (DependencyObject)Info.OriginalSource)).Content; Info.Header = Info.Data.GetType().GetProperty("Name").GetValue(Info.Data).ToString(); } } } void IDragDrop.DragOver(DragInfo Info) { } void IDragDrop.Drop(DragInfo Info) { // first check if we did drag and drop on the same ListView then it is a move - reorder if (Info.DragSource == this) { EventHandler mHandler = SameFrameItemDropped; if (mHandler != null) { mHandler(Info, new EventArgs()); } else { RepositoryItemBase draggedItem = Info.Data as RepositoryItemBase; if (draggedItem != null) { RepositoryItemBase draggedOnItem = DragDrop2.GetRepositoryItemHit(this) as RepositoryItemBase; if (draggedOnItem != null) { DragDrop2.ShuffleControlsItems(draggedItem, draggedOnItem, this); } } } //if (!(xMoveUpBtn.Visibility == System.Windows.Visibility.Visible)) return; // Do nothing if reorder up/down arrow are not allowed return; } // OK this is a dropped from external EventHandler handler = ItemDropped; if (handler != null) { handler(Info, new EventArgs()); } // TODO: if in same grid then do move, } void IDragDrop.DragEnter(DragInfo Info) { Info.DragTarget = this; if (Info.DragSource == Info.DragTarget) { DragDrop2.DrgInfo.DragIcon = DragInfo.eDragIcon.Move; } else { EventHandler handler = PreviewDragItem; if (handler != null) { handler(Info, new EventArgs()); } } } private void XDeleteGroupBtn_Click(object sender, RoutedEventArgs e) { } string mGroupByProperty = string.Empty; public void AddGrouping(string groupByProperty) { mGroupByProperty = groupByProperty; DoGrouping(); } public void UpdateGrouping() { mGroupView.Refresh(); ResetExpandCollapseBtn(); //if (xExpandCollapseBtn.ButtonImageType == eImageType.CollapseAll) //{ // OnUcListViewEvent(UcListViewEventArgs.eEventType.ExpandAllItems); //} } private void DoGrouping() { mGroupView = (CollectionView)CollectionViewSource.GetDefaultView(xListView.ItemsSource); PropertyGroupDescription groupDescription = new PropertyGroupDescription(mGroupByProperty); mGroupView.GroupDescriptions.Clear(); mGroupView.GroupDescriptions.Add(groupDescription); } private void SetGroupNotifications(DockPanel panel) { this.Dispatcher.Invoke(() => { if (panel.Tag != null) { List<ListItemNotification> notifications = mListViewHelper.GetItemGroupNotificationsList(panel.Tag.ToString()); if (notifications != null && notifications.Count > 0) { panel.Visibility = Visibility.Visible; foreach (ListItemNotification notification in notifications) { ImageMakerControl itemInd = new ImageMakerControl(); itemInd.SetValue(AutomationProperties.AutomationIdProperty, notification.AutomationID); itemInd.ImageType = notification.ImageType; itemInd.ToolTip = notification.ToolTip; itemInd.Margin = new Thickness(3, 0, 3, 0); itemInd.Height = 16; itemInd.Width = 16; itemInd.SetAsFontImageWithSize = notification.ImageSize; if (notification.ImageForeground == null) { itemInd.ImageForeground = System.Windows.Media.Brushes.LightPink; } else { itemInd.ImageForeground = notification.ImageForeground; } if (notification.BindingConverter == null) { BindingHandler.ObjFieldBinding(itemInd, ImageMakerControl.VisibilityProperty, notification.BindingObject, notification.BindingFieldName, BindingMode.OneWay); } else { BindingHandler.ObjFieldBinding(itemInd, ImageMakerControl.VisibilityProperty, notification.BindingObject, notification.BindingFieldName, bindingConvertor: notification.BindingConverter, BindingMode.OneWay); } panel.Children.Add(itemInd); } } else { panel.Visibility = Visibility.Collapsed; } } }); } private void SetGroupOperations(Menu menu) { List<ListItemGroupOperation> groupOperations = mListViewHelper.GetItemGroupOperationsList(); if (groupOperations != null && groupOperations.Count > 0) { foreach (ListItemGroupOperation operation in groupOperations.Where(x => x.SupportedViews.Contains(mListViewHelper.PageViewMode)).ToList()) { MenuItem menuitem = new MenuItem(); menuitem.Style = (Style)FindResource("$MenuItemStyle"); ImageMakerControl iconImage = new ImageMakerControl(); iconImage.ImageType = operation.ImageType; iconImage.SetAsFontImageWithSize = operation.ImageSize; iconImage.HorizontalAlignment = HorizontalAlignment.Left; menuitem.Icon = iconImage; menuitem.Header = operation.Header; menuitem.ToolTip = operation.ToolTip; menuitem.Click += operation.OperationHandler; menuitem.Tag = menu.Tag; if (string.IsNullOrEmpty(operation.Group)) { ((MenuItem)menu.Items[0]).Items.Add(menuitem); } else { //need to add to Group bool addedToGroup = false; foreach (MenuItem item in (((MenuItem)menu.Items[0]).Items)) { if (item.Header.ToString() == operation.Group) { //adding to existing group item.Items.Add(menuitem); addedToGroup = true; break; } } if (!addedToGroup) { //creating the group and adding MenuItem groupMenuitem = new MenuItem(); groupMenuitem.Style = (Style)FindResource("$MenuItemStyle"); ImageMakerControl groupIconImage = new ImageMakerControl(); groupIconImage.ImageType = operation.GroupImageType; groupIconImage.SetAsFontImageWithSize = operation.ImageSize; groupIconImage.HorizontalAlignment = HorizontalAlignment.Left; groupMenuitem.Icon = groupIconImage; groupMenuitem.Header = operation.Group; groupMenuitem.ToolTip = operation.Group; ((MenuItem)menu.Items[0]).Items.Add(groupMenuitem); groupMenuitem.Items.Add(menuitem); } } } } } private void XGroupOperationsMenu_Loaded(object sender, RoutedEventArgs e) { if (((MenuItem)((Menu)sender).Items[0]).Items.Count == 0) { SetGroupOperations((Menu)sender); } } private void XGroupNotificationsPnl_Loaded(object sender, RoutedEventArgs e) { if (((DockPanel)sender).Children.Count == 0) { SetGroupNotifications((DockPanel)sender); } } private async void xSearchTextBox_TextChangedAsync(object sender, TextChangedEventArgs e) { if (string.IsNullOrWhiteSpace(xSearchTextBox.Text)) { xSearchClearBtn.Visibility = Visibility.Collapsed; xSearchBtn.Visibility = Visibility.Visible; } else { xSearchClearBtn.Visibility = Visibility.Visible; xSearchBtn.Visibility = Visibility.Collapsed; // this inner method checks if user is still typing async Task<bool> UserKeepsTyping() { string txt = xSearchTextBox.Text; await Task.Delay(1000); return txt != xSearchTextBox.Text; } if (await UserKeepsTyping() || xSearchTextBox.Text == mSearchString) return; } mSearchString = xSearchTextBox.Text; CollectFilterData(); filteredView.Refresh(); } private void xSearchClearBtn_Click(object sender, RoutedEventArgs e) { xSearchTextBox.Text = ""; mSearchString = null; } private void xSearchBtn_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrWhiteSpace(xSearchTextBox.Text)) { mSearchString = xSearchTextBox.Text; CollectFilterData(); filteredView.Refresh(); } } public ObservableList<RepositoryItemBase> GetSelectedItems() { ObservableList<RepositoryItemBase> selectedItemsList = new ObservableList<RepositoryItemBase>(); foreach (object selectedItem in xListView.SelectedItems) { if (selectedItem is RepositoryItemBase) { selectedItemsList.Add((RepositoryItemBase)selectedItem); } } return selectedItemsList; } public IObservableList GetSourceItemsAsIList() { return DataSourceList; } public ObservableList<RepositoryItemBase> GetSourceItemsAsList() { ObservableList<RepositoryItemBase> list = new ObservableList<RepositoryItemBase>(); foreach (RepositoryItemBase item in mObjList) { list.Add(item); } return list; } public void SetSelectedIndex(int index) { xListView.SelectedIndex = index; } public void OnPasteItemEvent(PasteItemEventArgs.ePasteType pasteType, RepositoryItemBase item) { PasteItemEvent?.Invoke(new PasteItemEventArgs(pasteType, item)); } private void UserControl_KeyDown(object sender, KeyEventArgs e) { if (Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl)) { if (Keyboard.IsKeyDown(Key.C)) { //Do Copy mListViewHelper.CopySelected(); } else if(Keyboard.IsKeyDown(Key.X)) { //Do Cut mListViewHelper.CutSelected(); } else if (Keyboard.IsKeyDown(Key.V)) { //Do Paste mListViewHelper.Paste(); } } else if(Keyboard.IsKeyDown(Key.Delete)) { //delete selected mListViewHelper.DeleteSelected(); } } } public class UcListViewEventArgs { public enum eEventType { ExpandAllItems, ExpandItem, CollapseAllItems, UpdateIndex, ClearBindings, } public eEventType EventType; public Object EventObject; public UcListViewEventArgs(eEventType eventType, object eventObject = null) { this.EventType = eventType; this.EventObject = eventObject; } } }
37.207969
241
0.51336
[ "Apache-2.0" ]
fainagof/Ginger
Ginger/Ginger/UserControlsLib/UCListView/UcListView.xaml.cs
38,288
C#
using UnityEngine; using UnityEngine.PostProcessing; using UnityEngine.UI; namespace ldjam41 { public class BrightnessController : MonoBehaviour { public PostProcessingProfile PostProcessingProfile; public Slider Slider; public float Brightness = 0.0f; private float _lastBrightness = 0.0f; private const string BRIGHTNESS_KEY = "BRIGHTNESS"; private void Start() { Brightness = PlayerPrefs.GetFloat(BRIGHTNESS_KEY, 0.0f); Slider.value = Brightness; } public void SetBrightness(float value) { // PlayerPrefs.SetFloat(BRIGHTNESS_KEY, value); Brightness = value; } private void Update() { if (!Mathf.Approximately(_lastBrightness, Brightness)) { var colorGradingSettings = PostProcessingProfile.colorGrading.settings; colorGradingSettings.basic.postExposure = Brightness; PostProcessingProfile.colorGrading.settings = colorGradingSettings; _lastBrightness = Brightness; PlayerPrefs.SetFloat(BRIGHTNESS_KEY, Brightness); } } } }
32.805556
87
0.640982
[ "MIT" ]
ma-ver-ick/ldjam41
Assets/Scripts/BrightnessController.cs
1,183
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MoneyTrackDatabaseAPI.DataAccess; namespace MoneyTrackDatabaseAPI.Migrations { [DbContext(typeof(UserCredentialsDbContext))] [Migration("20211216202244_Update")] partial class Update { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.8"); modelBuilder.Entity("MoneyTrackDatabaseAPI.Models.Device", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Eui") .HasColumnType("TEXT"); b.Property<int?>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Device"); }); modelBuilder.Entity("MoneyTrackDatabaseAPI.Models.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ApiVersion") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<bool>("EmailConfirmed") .HasColumnType("INTEGER"); b.Property<string>("HashVersion") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("Password") .IsRequired() .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<DateTime>("RegistrationDate") .HasColumnType("TEXT"); b.Property<string>("Salt") .HasMaxLength(256) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("Email") .IsUnique(); b.ToTable("Users"); }); modelBuilder.Entity("MoneyTrackDatabaseAPI.Models.Device", b => { b.HasOne("MoneyTrackDatabaseAPI.Models.User", null) .WithMany("Devices") .HasForeignKey("UserId"); }); modelBuilder.Entity("MoneyTrackDatabaseAPI.Models.User", b => { b.Navigation("Devices"); }); #pragma warning restore 612, 618 } } }
32.29703
75
0.465972
[ "MIT" ]
OZoneSQT/Sep4-Greenhouse
AuthServer/AuthAPI/Migrations/20211216202244_Update.Designer.cs
3,264
C#
using System; using Castle.DynamicProxy; namespace Core.Utilities.Helpers.InterceptorHelpers { public static class AutofacInterceptorHelper { public static void ChangeReturnValue(IInvocation invocation, Type returnType, dynamic error, string message) { if (invocation.MethodInvocationTarget.ReturnType.GenericTypeArguments.Length > 0) { var typeGeneric = returnType.MakeGenericType(invocation.Method.ReturnType .GenericTypeArguments[0]); var resultGeneric = Activator.CreateInstance(typeGeneric, error, message); invocation.ReturnValue = resultGeneric; return; } var type = returnType.MakeGenericType(typeof(object)); var result = Activator.CreateInstance(type, error, message); invocation.ReturnValue = result; } } }
34.296296
100
0.640389
[ "Apache-2.0" ]
ismailkaygisiz/ArtChitecture
Core/Utilities/Helpers/InterceptorHelpers/AutofacInterceptorHelper.cs
928
C#
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit) // Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus // Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues // License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved. #if FULL || AUDIT || BATCH_DELETE || BATCH_UPDATE || QUERY_FILTER #if EF6 using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure.Interception; using System.Linq; using System.Reflection; namespace Z.EntityFramework.Plus { internal static partial class InternalExtensions { public static DbContext GetDbContext(this ObjectContext context) { var property = context.GetType().GetProperty("InterceptionContext", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var interceptionContext = property.GetValue(context, null) as DbInterceptionContext; if (interceptionContext == null) { return null; } return interceptionContext.DbContexts.FirstOrDefault(); } } } #endif #endif
40.428571
191
0.722261
[ "MIT" ]
borismod/EntityFramework-Plus
src/Z.EntityFramework.Plus.EF5.NET40/_Internal/EF6/ObjectContext/GetDbContext.cs
1,418
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Collections.Generic; using Sce.PlayStation.Core.Input; using Sce.PlayStation.Core.Graphics; using PssGamePad = Sce.PlayStation.Core.Input.GamePad; using PssGamePadButtons = Sce.PlayStation.Core.Input.GamePadButtons; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Microsoft.Xna.Framework.Input { static partial class GamePad { #region PSMButtons -> Buttons Map private static readonly Dictionary<PssGamePadButtons, Buttons> _buttonsMap = new Dictionary<PssGamePadButtons, Buttons>{ { PssGamePadButtons.Cross, Buttons.A }, { PssGamePadButtons.Circle, Buttons.B }, { PssGamePadButtons.Square, Buttons.X }, { PssGamePadButtons.Triangle, Buttons.Y }, { PssGamePadButtons.Left, Buttons.DPadLeft }, { PssGamePadButtons.Right, Buttons.DPadRight }, { PssGamePadButtons.Up, Buttons.DPadUp }, { PssGamePadButtons.Down, Buttons.DPadDown }, { PssGamePadButtons.Select, Buttons.Back }, { PssGamePadButtons.Start, Buttons.Start }, { PssGamePadButtons.L, Buttons.LeftShoulder }, { PssGamePadButtons.R, Buttons.RightShoulder } }; #endregion private static GamePadCapabilities PlatformGetCapabilities(int index) { GamePadCapabilities capabilities = new GamePadCapabilities(); capabilities.IsConnected = (index == 0); capabilities.HasAButton = true; capabilities.HasBButton = true; capabilities.HasXButton = true; capabilities.HasYButton = true; capabilities.HasBackButton = true; capabilities.HasStartButton = true; capabilities.HasDPadUpButton = true; capabilities.HasDPadDownButton = true; capabilities.HasDPadLeftButton = true; capabilities.HasDPadRightButton = true; capabilities.HasLeftXThumbStick = true; capabilities.HasLeftYThumbStick = true; capabilities.HasRightXThumbStick = true; capabilities.HasRightYThumbStick = true; capabilities.HasLeftShoulderButton = true; capabilities.HasRightShoulderButton = true; return capabilities; } private static GamePadState PlatformGetState(int index, GamePadDeadZone deadZoneMode) { // PSM only has a single player game pad. if (index != 0) return new GamePadState(); //See PSS GamePadSample for details var buttons = 0; var leftStick = Vector2.Zero; var rightStick = Vector2.Zero; try { var gamePadData = PssGamePad.GetData(0); //map the buttons foreach (var kvp in _buttonsMap) { if ((gamePadData.Buttons & kvp.Key) != 0) buttons |= (int)kvp.Value; } //Analog sticks leftStick = new Vector2(gamePadData.AnalogLeftX, -gamePadData.AnalogLeftY); rightStick = new Vector2(gamePadData.AnalogRightX, -gamePadData.AnalogRightY); } catch (Sce.PlayStation.Core.InputSystemException exc) { if (exc.Message.ToLowerInvariant().Trim() == "native function returned error.") throw new InvalidOperationException("GamePad must be listed in your features list in app.xml in order to use the GamePad API on PlayStation Mobile.", exc); else throw; } var state = new GamePadState(new GamePadThumbSticks(leftStick, rightStick, deadZoneMode), new GamePadTriggers(), new GamePadButtons((Buttons)buttons), new GamePadDPad((Buttons)buttons)); return state; } private static bool PlatformSetVibration(int index, float leftMotor, float rightMotor) { return false; //No support on the Vita } } }
35.821429
198
0.662512
[ "MIT" ]
Whitebeard86/Gibbo2D
MonoGame.Framework/MonoGame.Framework/Input/GamePad.PSM.cs
4,014
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved. * */ #endregion namespace Krypton.Toolkit { #region SchemeOfficeColors internal enum SchemeOfficeColors { TextLabelControl = 0, TextButtonNormal = 1, TextButtonChecked = 2, ButtonNormalBorder = 3, ButtonNormalDefaultBorder = 4, ButtonNormalBack1 = 5, ButtonNormalBack2 = 6, ButtonNormalDefaultBack1 = 7, ButtonNormalDefaultBack2 = 8, ButtonNormalNavigatorBack1 = 9, ButtonNormalNavigatorBack2 = 10, PanelClient = 11, PanelAlternative = 12, ControlBorder = 13, SeparatorHighBorder1 = 14, SeparatorHighBorder2 = 15, HeaderPrimaryBack1 = 16, HeaderPrimaryBack2 = 17, HeaderSecondaryBack1 = 18, HeaderSecondaryBack2 = 19, HeaderText = 20, StatusStripText = 21, ButtonBorder = 22, SeparatorLight = 23, SeparatorDark = 24, GripLight = 25, GripDark = 26, ToolStripBack = 27, StatusStripLight = 28, StatusStripDark = 29, ImageMargin = 30, ToolStripBegin = 31, ToolStripMiddle = 32, ToolStripEnd = 33, OverflowBegin = 34, OverflowMiddle = 35, OverflowEnd = 36, ToolStripBorder = 37, FormBorderActive = 38, FormBorderInactive = 39, FormBorderActiveLight = 40, FormBorderActiveDark = 41, FormBorderInactiveLight = 42, FormBorderInactiveDark = 43, FormBorderHeaderActive = 44, FormBorderHeaderInactive = 45, FormBorderHeaderActive1 = 46, FormBorderHeaderActive2 = 47, FormBorderHeaderInactive1 = 48, FormBorderHeaderInactive2 = 49, FormHeaderShortActive = 50, FormHeaderShortInactive = 51, FormHeaderLongActive = 52, FormHeaderLongInactive = 53, FormButtonBorderTrack = 54, FormButtonBack1Track = 55, FormButtonBack2Track = 56, FormButtonBorderPressed = 57, FormButtonBack1Pressed = 58, FormButtonBack2Pressed = 59, TextButtonFormNormal = 60, TextButtonFormTracking = 61, TextButtonFormPressed = 62, LinkNotVisitedOverrideControl = 63, LinkVisitedOverrideControl = 64, LinkPressedOverrideControl = 65, LinkNotVisitedOverridePanel = 66, LinkVisitedOverridePanel = 67, LinkPressedOverridePanel = 68, TextLabelPanel = 69, RibbonTabTextNormal = 70, RibbonTabTextChecked = 71, RibbonTabSelected1 = 72, RibbonTabSelected2 = 73, RibbonTabSelected3 = 74, RibbonTabSelected4 = 75, RibbonTabSelected5 = 76, RibbonTabTracking1 = 77, RibbonTabTracking2 = 78, RibbonTabHighlight1 = 79, RibbonTabHighlight2 = 80, RibbonTabHighlight3 = 81, RibbonTabHighlight4 = 82, RibbonTabHighlight5 = 83, RibbonTabSeparatorColor = 84, RibbonGroupsArea1 = 85, RibbonGroupsArea2 = 86, RibbonGroupsArea3 = 87, RibbonGroupsArea4 = 88, RibbonGroupsArea5 = 89, RibbonGroupBorder1 = 90, RibbonGroupBorder2 = 91, RibbonGroupTitle1 = 92, RibbonGroupTitle2 = 93, RibbonGroupBorderContext1 = 94, RibbonGroupBorderContext2 = 95, RibbonGroupTitleContext1 = 96, RibbonGroupTitleContext2 = 97, RibbonGroupDialogDark = 98, RibbonGroupDialogLight = 99, RibbonGroupTitleTracking1 = 100, RibbonGroupTitleTracking2 = 101, RibbonMinimizeBarDark = 102, RibbonMinimizeBarLight = 103, RibbonGroupCollapsedBorder1 = 104, RibbonGroupCollapsedBorder2 = 105, RibbonGroupCollapsedBorder3 = 106, RibbonGroupCollapsedBorder4 = 107, RibbonGroupCollapsedBack1 = 108, RibbonGroupCollapsedBack2 = 109, RibbonGroupCollapsedBack3 = 110, RibbonGroupCollapsedBack4 = 111, RibbonGroupCollapsedBorderT1 = 112, RibbonGroupCollapsedBorderT2 = 113, RibbonGroupCollapsedBorderT3 = 114, RibbonGroupCollapsedBorderT4 = 115, RibbonGroupCollapsedBackT1 = 116, RibbonGroupCollapsedBackT2 = 117, RibbonGroupCollapsedBackT3 = 118, RibbonGroupCollapsedBackT4 = 119, RibbonGroupFrameBorder1 = 120, RibbonGroupFrameBorder2 = 121, RibbonGroupFrameInside1 = 122, RibbonGroupFrameInside2 = 123, RibbonGroupFrameInside3 = 124, RibbonGroupFrameInside4 = 125, RibbonGroupCollapsedText = 126, AlternatePressedBack1 = 127, AlternatePressedBack2 = 128, AlternatePressedBorder1 = 129, AlternatePressedBorder2 = 130, FormButtonBack1Checked = 131, FormButtonBack2Checked = 132, FormButtonBorderCheck = 133, FormButtonBack1CheckTrack = 134, FormButtonBack2CheckTrack= 135, RibbonQATMini1 = 136, RibbonQATMini2 = 137, RibbonQATMini3 = 138, RibbonQATMini4 = 139, RibbonQATMini5 = 140, RibbonQATMini1I = 141, RibbonQATMini2I = 142, RibbonQATMini3I = 143, RibbonQATMini4I = 144, RibbonQATMini5I = 145, RibbonQATFullbar1 = 146, RibbonQATFullbar2 = 147, RibbonQATFullbar3 = 148, RibbonQATButtonDark = 149, RibbonQATButtonLight = 150, RibbonQATOverflow1 = 151, RibbonQATOverflow2 = 152, RibbonGroupSeparatorDark = 153, RibbonGroupSeparatorLight = 154, ButtonClusterButtonBack1 = 155, ButtonClusterButtonBack2 = 156, ButtonClusterButtonBorder1 = 157, ButtonClusterButtonBorder2 = 158, NavigatorMiniBackColor = 159, GridListNormal1 = 160, GridListNormal2 = 161, GridListPressed1 = 162, GridListPressed2 = 163, GridListSelected = 164, GridSheetColNormal1 = 165, GridSheetColNormal2 = 166, GridSheetColPressed1 = 167, GridSheetColPressed2 = 168, GridSheetColSelected1 = 169, GridSheetColSelected2 = 170, GridSheetRowNormal = 171, GridSheetRowPressed = 172, GridSheetRowSelected = 173, GridDataCellBorder = 174, GridDataCellSelected = 175, InputControlTextNormal = 176, InputControlTextDisabled = 177, InputControlBorderNormal = 178, InputControlBorderDisabled = 179, InputControlBackNormal = 180, InputControlBackDisabled = 181, InputControlBackInactive = 182, InputDropDownNormal1 = 183, InputDropDownNormal2 = 184, InputDropDownDisabled1 = 185, InputDropDownDisabled2 = 186, ContextMenuHeadingBack = 187, ContextMenuHeadingText = 188, ContextMenuImageColumn = 189, AppButtonBack1 = 190, AppButtonBack2 = 191, AppButtonBorder = 192, AppButtonOuter1 = 193, AppButtonOuter2 = 194, AppButtonOuter3 = 195, AppButtonInner1 = 196, AppButtonInner2 = 197, AppButtonMenuDocsBack = 198, AppButtonMenuDocsText = 199, SeparatorHighInternalBorder1 = 200, SeparatorHighInternalBorder2 = 201, RibbonGalleryBorder = 202, RibbonGalleryBackNormal = 203, RibbonGalleryBackTracking = 204, RibbonGalleryBack1 = 205, RibbonGalleryBack2 = 206, RibbonTabTracking3 = 207, RibbonTabTracking4 = 208, RibbonGroupBorder3 = 209, RibbonGroupBorder4 = 210, RibbonGroupBorder5 = 211, RibbonGroupTitleText = 212, RibbonDropArrowLight = 213, RibbonDropArrowDark = 214, HeaderDockInactiveBack1 = 215, HeaderDockInactiveBack2 = 216, ButtonNavigatorBorder = 217, ButtonNavigatorText = 218, ButtonNavigatorTrack1 = 219, ButtonNavigatorTrack2 = 220, ButtonNavigatorPressed1 = 221, ButtonNavigatorPressed2 = 222, ButtonNavigatorChecked1 = 223, ButtonNavigatorChecked2 = 224, ToolTipBottom = 225, } #endregion /// <summary> /// Provide KryptonColorTable2007 values using an array of Color values as the source. /// </summary> public class KryptonColorTable2007 : KryptonColorTable { #region Static Fields private static readonly Color _menuBorder = Color.FromArgb(134, 134, 134); private static readonly Color _menuItemSelectedBegin = Color.FromArgb(255, 213, 103); private static readonly Color _menuItemSelectedEnd = Color.FromArgb(255, 228, 145); private static readonly Color _contextMenuBackground = Color.FromArgb(250, 250, 250); private static readonly Color _checkBackground = Color.FromArgb(255, 227, 149); private static readonly Color _buttonSelectedBegin = Color.FromArgb(255, 235, 166); private static readonly Color _buttonSelectedEnd = Color.FromArgb(255, 213, 103); private static readonly Color _buttonPressedBegin = Color.FromArgb(253, 164, 97); private static readonly Color _buttonPressedEnd = Color.FromArgb(252, 143, 61); private static readonly Color _buttonCheckedBegin = Color.FromArgb(252, 180, 100); private static readonly Color _buttonCheckedEnd = Color.FromArgb(252, 161, 54); private static Font _menuToolFont; private static Font _statusFont; #endregion #region Instance Fields #endregion #region Identity static KryptonColorTable2007() { // Get the font settings from the system DefineFonts(); // We need to notice when system color settings change SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged; } /// <summary> /// Initialize a new instance of the KryptonColorTable2007 class. /// </summary> /// <param name="colors">Source of </param> /// <param name="roundedEdges">Should have rounded edges.</param> /// <param name="palette">Associated palette instance.</param> public KryptonColorTable2007(Color[] colors, InheritBool roundedEdges, IPalette palette) : base(palette) { Debug.Assert(colors != null); Colors = colors; UseRoundedEdges = roundedEdges; } #endregion #region Colors /// <summary> /// Gets the raw set of colors. /// </summary> public Color[] Colors { get; } #endregion #region RoundedEdges /// <summary> /// Gets a value indicating if rounded egdes are required. /// </summary> public override InheritBool UseRoundedEdges { get; } #endregion #region ButtonPressed #region ButtonPressedBorder /// <summary> /// Gets the border color for a button being pressed. /// </summary> public override Color ButtonPressedBorder => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #region ButtonPressedGradientBegin /// <summary> /// Gets the background starting color for a button being pressed. /// </summary> public override Color ButtonPressedGradientBegin => _buttonPressedBegin; #endregion #region ButtonPressedGradientMiddle /// <summary> /// Gets the background middle color for a button being pressed. /// </summary> public override Color ButtonPressedGradientMiddle => _buttonPressedBegin; #endregion #region ButtonPressedGradientEnd /// <summary> /// Gets the background ending color for a button being pressed. /// </summary> public override Color ButtonPressedGradientEnd => _buttonPressedEnd; #endregion #region ButtonPressedHighlight /// <summary> /// Gets the highlight background for a pressed button. /// </summary> public override Color ButtonPressedHighlight => _buttonPressedBegin; #endregion #region ButtonPressedHighlightBorder /// <summary> /// Gets the highlight border for a pressed button. /// </summary> public override Color ButtonPressedHighlightBorder => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #endregion #region ButtonSelected #region ButtonSelectedBorder /// <summary> /// Gets the border color for a button being selected. /// </summary> public override Color ButtonSelectedBorder => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #region ButtonSelectedGradientBegin /// <summary> /// Gets the background starting color for a button being selected. /// </summary> public override Color ButtonSelectedGradientBegin => _buttonSelectedBegin; #endregion #region ButtonSelectedGradientMiddle /// <summary> /// Gets the background middle color for a button being selected. /// </summary> public override Color ButtonSelectedGradientMiddle => _buttonSelectedBegin; #endregion #region ButtonSelectedGradientEnd /// <summary> /// Gets the background ending color for a button being selected. /// </summary> public override Color ButtonSelectedGradientEnd => _buttonSelectedEnd; #endregion #region ButtonSelectedHighlight /// <summary> /// Gets the highlight background for a selected button. /// </summary> public override Color ButtonSelectedHighlight => _buttonSelectedBegin; #endregion #region ButtonSelectedHighlightBorder /// <summary> /// Gets the highlight border for a selected button. /// </summary> public override Color ButtonSelectedHighlightBorder => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #endregion #region ButtonChecked #region ButtonCheckedGradientBegin /// <summary> /// Gets the background starting color for a checked button. /// </summary> public override Color ButtonCheckedGradientBegin => _buttonCheckedBegin; #endregion #region ButtonCheckedGradientMiddle /// <summary> /// Gets the background middle color for a checked button. /// </summary> public override Color ButtonCheckedGradientMiddle => _buttonCheckedBegin; #endregion #region ButtonCheckedGradientEnd /// <summary> /// Gets the background ending color for a checked button. /// </summary> public override Color ButtonCheckedGradientEnd => _buttonCheckedEnd; #endregion #region ButtonCheckedHighlight /// <summary> /// Gets the highlight background for a checked button. /// </summary> public override Color ButtonCheckedHighlight => _buttonCheckedBegin; #endregion #region ButtonCheckedHighlightBorder /// <summary> /// Gets the highlight border for a checked button. /// </summary> public override Color ButtonCheckedHighlightBorder => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #endregion #region Check #region CheckBackground /// <summary> /// Get background of the check mark area. /// </summary> public override Color CheckBackground => _checkBackground; #endregion #region CheckBackground /// <summary> /// Get background of a pressed check mark area. /// </summary> public override Color CheckPressedBackground => _checkBackground; #endregion #region CheckBackground /// <summary> /// Get background of a selected check mark area. /// </summary> public override Color CheckSelectedBackground => _checkBackground; #endregion #endregion #region Grip #region GripLight /// <summary> /// Gets the light color used to draw grips. /// </summary> public override Color GripLight => Colors[(int)SchemeOfficeColors.GripLight]; #endregion #region GripDark /// <summary> /// Gets the dark color used to draw grips. /// </summary> public override Color GripDark => Colors[(int)SchemeOfficeColors.GripDark]; #endregion #endregion #region ImageMargin #region ImageMarginGradientBegin /// <summary> /// Gets the starting color for the context menu margin. /// </summary> public override Color ImageMarginGradientBegin => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #region ImageMarginGradientMiddle /// <summary> /// Gets the middle color for the context menu margin. /// </summary> public override Color ImageMarginGradientMiddle => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #region ImageMarginGradientEnd /// <summary> /// Gets the ending color for the context menu margin. /// </summary> public override Color ImageMarginGradientEnd => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #region ImageMarginRevealedGradientBegin /// <summary> /// Gets the starting color for the context menu margin revealed. /// </summary> public override Color ImageMarginRevealedGradientBegin => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #region ImageMarginRevealedGradientMiddle /// <summary> /// Gets the middle color for the context menu margin revealed. /// </summary> public override Color ImageMarginRevealedGradientMiddle => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #region ImageMarginRevealedGradientEnd /// <summary> /// Gets the ending color for the context menu margin revealed. /// </summary> public override Color ImageMarginRevealedGradientEnd => Colors[(int)SchemeOfficeColors.ImageMargin]; #endregion #endregion #region MenuBorder /// <summary> /// Gets the color of the border around menus. /// </summary> public override Color MenuBorder => _menuBorder; #endregion #region MenuItem #region MenuItemBorder /// <summary> /// Gets the border color for around the menu item. /// </summary> public override Color MenuItemBorder => _menuBorder; #endregion #region MenuItemSelected /// <summary> /// Gets the color of a selected menu item. /// </summary> public override Color MenuItemSelected => Colors[(int)SchemeOfficeColors.ButtonBorder]; #endregion #region MenuItemPressedGradientBegin /// <summary> /// Gets the starting color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBegin]; #endregion #region MenuItemPressedGradientEnd /// <summary> /// Gets the end color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripEnd]; #endregion #region MenuItemPressedGradientMiddle /// <summary> /// Gets the middle color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientMiddle => Colors[(int)SchemeOfficeColors.ToolStripMiddle]; #endregion #region MenuItemSelectedGradientBegin /// <summary> /// Gets the starting color of the gradient used when the ToolStripMenuItem is selected. /// </summary> public override Color MenuItemSelectedGradientBegin => _menuItemSelectedBegin; #endregion #region MenuItemSelectedGradientEnd /// <summary> /// Gets the end color of the gradient used when the ToolStripMenuItem is selected. /// </summary> public override Color MenuItemSelectedGradientEnd => _menuItemSelectedEnd; #endregion #endregion #region MenuStrip #region MenuStripGradientBegin /// <summary> /// Gets the starting color of the gradient used in the MenuStrip. /// </summary> public override Color MenuStripGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #region MenuStripGradientEnd /// <summary> /// Gets the end color of the gradient used in the MenuStrip. /// </summary> public override Color MenuStripGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #endregion #region OverflowButton #region OverflowButtonGradientBegin /// <summary> /// Gets the starting color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientBegin => Colors[(int)SchemeOfficeColors.OverflowBegin]; #endregion #region OverflowButtonGradientEnd /// <summary> /// Gets the end color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientEnd => Colors[(int)SchemeOfficeColors.OverflowEnd]; #endregion #region OverflowButtonGradientMiddle /// <summary> /// Gets the middle color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientMiddle => Colors[(int)SchemeOfficeColors.OverflowMiddle]; #endregion #endregion #region RaftingContainer #region RaftingContainerGradientBegin /// <summary> /// Gets the starting color of the gradient used in the ToolStripContainer. /// </summary> public override Color RaftingContainerGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #region RaftingContainerGradientEnd /// <summary> /// Gets the end color of the gradient used in the ToolStripContainer. /// </summary> public override Color RaftingContainerGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #endregion #region Separator #region SeparatorLight /// <summary> /// Gets the light separator color. /// </summary> public override Color SeparatorLight => Colors[(int)SchemeOfficeColors.SeparatorLight]; #endregion #region SeparatorDark /// <summary> /// Gets the dark separator color. /// </summary> public override Color SeparatorDark => Colors[(int)SchemeOfficeColors.SeparatorDark]; #endregion #endregion #region StatusStrip #region StatusStripGradientBegin /// <summary> /// Gets the starting color for the status strip background. /// </summary> public override Color StatusStripGradientBegin => Colors[(int)SchemeOfficeColors.StatusStripLight]; #endregion #region StatusStripGradientEnd /// <summary> /// Gets the ending color for the status strip background. /// </summary> public override Color StatusStripGradientEnd => Colors[(int)SchemeOfficeColors.StatusStripDark]; #endregion #endregion #region Text #region MenuItemText /// <summary> /// Gets the text color used on the menu items. /// </summary> public override Color MenuItemText => Colors[(int)SchemeOfficeColors.TextButtonNormal]; #endregion #region MenuStripText /// <summary> /// Gets the text color used on the menu strip. /// </summary> public override Color MenuStripText => Colors[(int)SchemeOfficeColors.TextLabelPanel]; #endregion #region ToolStripText /// <summary> /// Gets the text color used on the tool strip. /// </summary> public override Color ToolStripText => Colors[(int)SchemeOfficeColors.TextButtonNormal]; #endregion #region StatusStripText /// <summary> /// Gets the text color used on the status strip. /// </summary> public override Color StatusStripText => Colors[(int)SchemeOfficeColors.StatusStripText]; #endregion #region MenuStripFont /// <summary> /// Gets the font used on the menu strip. /// </summary> public override Font MenuStripFont => _menuToolFont; #endregion #region ToolStripFont /// <summary> /// Gets the font used on the tool strip. /// </summary> public override Font ToolStripFont => _menuToolFont; #endregion #region StatusStripFont /// <summary> /// Gets the font used on the status strip. /// </summary> public override Font StatusStripFont => _statusFont; #endregion #endregion #region ToolStrip #region ToolStripBorder /// <summary> /// Gets the border color to use on the bottom edge of the ToolStrip. /// </summary> public override Color ToolStripBorder => Colors[(int)SchemeOfficeColors.ToolStripBorder]; #endregion #region ToolStripContentPanelGradientBegin /// <summary> /// Gets the starting color for the content panel background. /// </summary> public override Color ToolStripContentPanelGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #region ToolStripContentPanelGradientEnd /// <summary> /// Gets the ending color for the content panel background. /// </summary> public override Color ToolStripContentPanelGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #region ToolStripDropDownBackground /// <summary> /// Gets the background color for drop down menus. /// </summary> public override Color ToolStripDropDownBackground => _contextMenuBackground; #endregion #region ToolStripGradientBegin /// <summary> /// Gets the starting color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBegin]; #endregion #region ToolStripGradientEnd /// <summary> /// Gets the end color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripEnd]; #endregion #region ToolStripGradientMiddle /// <summary> /// Gets the middle color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientMiddle => Colors[(int)SchemeOfficeColors.ToolStripMiddle]; #endregion #region ToolStripPanelGradientBegin /// <summary> /// Gets the starting color of the gradient used in the ToolStripPanel. /// </summary> public override Color ToolStripPanelGradientBegin => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #region ToolStripPanelGradientEnd /// <summary> /// Gets the end color of the gradient used in the ToolStripPanel. /// </summary> public override Color ToolStripPanelGradientEnd => Colors[(int)SchemeOfficeColors.ToolStripBack]; #endregion #endregion #region Implementation private static void DefineFonts() { // Release existing resources _menuToolFont?.Dispose(); _statusFont?.Dispose(); // Create new font using system information _menuToolFont = new Font("Segoe UI", SystemFonts.MenuFont.SizeInPoints, FontStyle.Regular); _statusFont = new Font("Segoe UI", SystemFonts.StatusFont.SizeInPoints, FontStyle.Regular); } private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { // Update fonts to reflect any change in system settings DefineFonts(); } #endregion } }
33.964409
119
0.634317
[ "BSD-3-Clause" ]
cuteofdragon/Standard-Toolkit
Source/Krypton Components/Krypton.Toolkit/Palette Controls/KryptonColorTable2007.cs
29,586
C#
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // 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 Behaviac.Design { partial class ConnectDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConnectDialog)); this.tbServer = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.btnOk = new System.Windows.Forms.Button(); this.tbPort = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.localIPCheckBox = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // tbServer // resources.ApplyResources(this.tbServer, "tbServer"); this.tbServer.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this.tbServer.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbServer.ForeColor = System.Drawing.Color.LightGray; this.tbServer.Name = "tbServer"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(56)))), ((int)(((byte)(56)))), ((int)(((byte)(56))))); this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.FlatAppearance.MouseDownBackColor = System.Drawing.Color.DarkGray; this.btnOk.FlatAppearance.MouseOverBackColor = System.Drawing.Color.DarkGray; this.btnOk.Name = "btnOk"; this.btnOk.UseVisualStyleBackColor = false; // // tbPort // resources.ApplyResources(this.tbPort, "tbPort"); this.tbPort.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this.tbPort.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbPort.ForeColor = System.Drawing.Color.LightGray; this.tbPort.Name = "tbPort"; this.tbPort.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tbPort_KeyPress); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(56)))), ((int)(((byte)(56)))), ((int)(((byte)(56))))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.FlatAppearance.MouseDownBackColor = System.Drawing.Color.DarkGray; this.btnCancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.DarkGray; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = false; // // localIPCheckBox // resources.ApplyResources(this.localIPCheckBox, "localIPCheckBox"); this.localIPCheckBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(65)))), ((int)(((byte)(65))))); this.localIPCheckBox.Checked = true; this.localIPCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.localIPCheckBox.ForeColor = System.Drawing.Color.LightGray; this.localIPCheckBox.Name = "localIPCheckBox"; this.localIPCheckBox.UseVisualStyleBackColor = false; this.localIPCheckBox.CheckedChanged += new System.EventHandler(this.localIPCheckBox_CheckedChanged); // // ConnectDialog // this.AcceptButton = this.btnOk; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(56)))), ((int)(((byte)(56)))), ((int)(((byte)(56))))); this.CancelButton = this.btnCancel; this.Controls.Add(this.localIPCheckBox); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label2); this.Controls.Add(this.tbPort); this.Controls.Add(this.btnOk); this.Controls.Add(this.label1); this.Controls.Add(this.tbServer); this.ForeColor = System.Drawing.Color.LightGray; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ConnectDialog"; this.ShowInTaskbar = false; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox tbServer; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.TextBox tbPort; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox localIPCheckBox; } }
50.206897
145
0.594505
[ "BSD-3-Clause" ]
675492062/behaviac
tools/designer/BehaviacDesigner/ConnectDialog.Designer.cs
7,280
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace iot.solution.host.Models { public partial class qaelevatorContext : DbContext { public qaelevatorContext() { } public qaelevatorContext(DbContextOptions<qaelevatorContext> options) : base(options) { } public virtual DbSet<AdminRule> AdminRule { get; set; } public virtual DbSet<AdminUser> AdminUser { get; set; } public virtual DbSet<AttributeValue> AttributeValue { get; set; } public virtual DbSet<Company> Company { get; set; } public virtual DbSet<CompanyConfig> CompanyConfig { get; set; } public virtual DbSet<Configuration> Configuration { get; set; } public virtual DbSet<DebugInfo> DebugInfo { get; set; } public virtual DbSet<Elevator> Elevator { get; set; } public virtual DbSet<Entity> Entity { get; set; } public virtual DbSet<HardwareKit> HardwareKit { get; set; } public virtual DbSet<KitType> KitType { get; set; } public virtual DbSet<KitTypeAttribute> KitTypeAttribute { get; set; } public virtual DbSet<KitTypeCommand> KitTypeCommand { get; set; } public virtual DbSet<Module> Module { get; set; } public virtual DbSet<Role> Role { get; set; } public virtual DbSet<RoleModulePermission> RoleModulePermission { get; set; } public virtual DbSet<TelemetrySummaryDaywise> TelemetrySummaryDaywise { get; set; } public virtual DbSet<TelemetrySummaryHourwise> TelemetrySummaryHourwise { get; set; } public virtual DbSet<User> User { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlServer("Server=192.168.3.166;initial catalog=qa-elevator;user id=qaelevatoruser;password=softweb#123;MultipleActiveResultSets=True;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<AdminRule>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__AdminRul__497F6CB426B05957"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.AttributeGuid) .HasColumnName("attributeGuid") .HasMaxLength(1000); entity.Property(e => e.CommandText) .HasColumnName("commandText") .HasMaxLength(500); entity.Property(e => e.CommandValue) .HasColumnName("commandValue") .HasMaxLength(100); entity.Property(e => e.ConditionText) .HasColumnName("conditionText") .HasMaxLength(1000); entity.Property(e => e.ConditionValue) .HasColumnName("conditionValue") .HasMaxLength(1000); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.Name) .HasColumnName("name") .HasMaxLength(100); entity.Property(e => e.NotificationType).HasColumnName("notificationType"); entity.Property(e => e.RuleType) .HasColumnName("ruleType") .HasDefaultValueSql("((1))"); entity.Property(e => e.SeverityLevelGuid).HasColumnName("severityLevelGuid"); entity.Property(e => e.TemplateGuid).HasColumnName("templateGuid"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<AdminUser>(entity => { entity.HasKey(e => e.Guid); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.ContactNo) .HasColumnName("contactNo") .HasMaxLength(25); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("email") .HasMaxLength(100); entity.Property(e => e.FirstName) .IsRequired() .HasColumnName("firstName") .HasMaxLength(50); entity.Property(e => e.IsActive).HasColumnName("isActive"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.LastName) .IsRequired() .HasColumnName("lastName") .HasMaxLength(50); entity.Property(e => e.Password) .IsRequired() .HasColumnName("password") .HasMaxLength(500); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<AttributeValue>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Attribut__497F6CB4D64B11C0"); entity.ToTable("AttributeValue", "IOTConnect"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.AggregateType).HasColumnName("aggregateType"); entity.Property(e => e.AttributeValue1) .HasColumnName("attributeValue") .HasMaxLength(1000); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.DeviceUpdatedDate) .HasColumnName("deviceUpdatedDate") .HasColumnType("datetime"); entity.Property(e => e.GatewayUpdatedDate) .HasColumnName("gatewayUpdatedDate") .HasColumnType("datetime"); entity.Property(e => e.LocalName) .HasColumnName("localName") .HasMaxLength(100); entity.Property(e => e.SdkUpdatedDate) .HasColumnName("sdkUpdatedDate") .HasColumnType("datetime"); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(200); entity.Property(e => e.UniqueId) .HasColumnName("uniqueId") .HasMaxLength(200); }); modelBuilder.Entity<Company>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Company__497F6CB411118A97"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Address) .HasColumnName("address") .HasMaxLength(500); entity.Property(e => e.AdminUserGuid).HasColumnName("adminUserGuid"); entity.Property(e => e.City) .HasColumnName("city") .HasMaxLength(50); entity.Property(e => e.ContactNo) .HasColumnName("contactNo") .HasMaxLength(25); entity.Property(e => e.CountryGuid).HasColumnName("countryGuid"); entity.Property(e => e.CpId) .IsRequired() .HasColumnName("cpId") .HasMaxLength(200); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.EntityGuid).HasColumnName("entityGuid"); entity.Property(e => e.Image) .HasColumnName("image") .HasMaxLength(250); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(100); entity.Property(e => e.ParentGuid).HasColumnName("parentGuid"); entity.Property(e => e.PostalCode) .HasColumnName("postalCode") .HasMaxLength(30); entity.Property(e => e.StateGuid).HasColumnName("stateGuid"); entity.Property(e => e.TimezoneGuid).HasColumnName("timezoneGuid"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<CompanyConfig>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__CompanyC__497F6CB473711EEF"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.ConfigurationGuid).HasColumnName("configurationGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); entity.Property(e => e.Value).HasColumnName("value"); }); modelBuilder.Entity<Configuration>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Configur__497F6CB468E58C36"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.ConfigKey) .IsRequired() .HasColumnName("configKey") .HasMaxLength(100); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); entity.Property(e => e.Value) .HasColumnName("value") .HasMaxLength(500); }); modelBuilder.Entity<DebugInfo>(entity => { entity.HasNoKey(); entity.Property(e => e.Data) .IsRequired() .HasColumnName("data"); entity.Property(e => e.Dt) .HasColumnName("dt") .HasColumnType("datetime") .HasDefaultValueSql("(getutcdate())"); entity.Property(e => e.Id) .HasColumnName("id") .ValueGeneratedOnAdd(); }); modelBuilder.Entity<Elevator>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Elevator__497F6CB4A9E84FFD"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.Description) .HasColumnName("description") .HasMaxLength(1000); entity.Property(e => e.EntityGuid).HasColumnName("entityGuid"); entity.Property(e => e.Image) .HasColumnName("image") .HasMaxLength(200); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.IsProvisioned).HasColumnName("isProvisioned"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(500); entity.Property(e => e.Note) .HasColumnName("note") .HasMaxLength(1000); entity.Property(e => e.Specification) .HasColumnName("specification") .HasMaxLength(1000); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(50); entity.Property(e => e.TemplateGuid).HasColumnName("templateGuid"); entity.Property(e => e.TypeGuid).HasColumnName("typeGuid"); entity.Property(e => e.UniqueId) .IsRequired() .HasColumnName("uniqueId") .HasMaxLength(500); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<Entity>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Entity__497F6CB475C7652E"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Address) .IsRequired() .HasColumnName("address") .HasMaxLength(500); entity.Property(e => e.Address2) .HasColumnName("address2") .HasMaxLength(500); entity.Property(e => e.City) .HasColumnName("city") .HasMaxLength(50); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CountryGuid).HasColumnName("countryGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.Description) .HasColumnName("description") .HasMaxLength(1000); entity.Property(e => e.Image) .HasColumnName("image") .HasMaxLength(250); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.Latitude) .HasColumnName("latitude") .HasMaxLength(50); entity.Property(e => e.Longitude) .HasColumnName("longitude") .HasMaxLength(50); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(500); entity.Property(e => e.ParentEntityGuid).HasColumnName("parentEntityGuid"); entity.Property(e => e.StateGuid).HasColumnName("stateGuid"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); entity.Property(e => e.Zipcode) .HasColumnName("zipcode") .HasMaxLength(10); }); modelBuilder.Entity<HardwareKit>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Hardware__497F6CB4048EB41D"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.EntityGuid).HasColumnName("entityGuid"); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.IsProvisioned) .IsRequired() .HasColumnName("isProvisioned") .HasDefaultValueSql("((1))"); entity.Property(e => e.KitCode) .IsRequired() .HasColumnName("kitCode") .HasMaxLength(50); entity.Property(e => e.KitTypeGuid).HasColumnName("kitTypeGuid"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(500); entity.Property(e => e.Note) .IsRequired() .HasColumnName("note") .HasMaxLength(1000); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(50); entity.Property(e => e.UniqueId) .IsRequired() .HasColumnName("uniqueId") .HasMaxLength(500); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<KitType>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__KitType__497F6CB4F9806AB2"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Code) .HasColumnName("code") .HasMaxLength(50); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(200); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(50); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<KitTypeAttribute>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__KitTypeA__497F6CB4AFF441C6"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Code) .IsRequired() .HasColumnName("code") .HasMaxLength(50); entity.Property(e => e.Description) .HasColumnName("description") .HasMaxLength(100); entity.Property(e => e.LocalName) .IsRequired() .HasColumnName("localName") .HasMaxLength(100); entity.Property(e => e.ParentTemplateAttributeGuid).HasColumnName("parentTemplateAttributeGuid"); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(50); entity.Property(e => e.TemplateGuid).HasColumnName("templateGuid"); }); modelBuilder.Entity<KitTypeCommand>(entity => { entity.HasNoKey(); entity.Property(e => e.Command) .HasColumnName("command") .HasMaxLength(100) .IsFixedLength(); entity.Property(e => e.Guid).HasColumnName("guid"); entity.Property(e => e.IsOtacommand).HasColumnName("isOTACommand"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(100); entity.Property(e => e.RequiredAck).HasColumnName("requiredAck"); entity.Property(e => e.RequiredParam).HasColumnName("requiredParam"); entity.Property(e => e.Tag) .HasColumnName("tag") .HasMaxLength(100) .IsFixedLength(); entity.Property(e => e.TemplateGuid).HasColumnName("templateGuid"); }); modelBuilder.Entity<Module>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Module__497F6CB4A1228A79"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.ApplyTo).HasColumnName("applyTo"); entity.Property(e => e.CategoryName) .HasColumnName("categoryName") .HasMaxLength(200); entity.Property(e => e.IsAdminModule).HasColumnName("isAdminModule"); entity.Property(e => e.ModuleSequence).HasColumnName("moduleSequence"); entity.Property(e => e.Name) .HasColumnName("name") .HasMaxLength(50); entity.Property(e => e.Permission).HasColumnName("permission"); }); modelBuilder.Entity<Role>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Role__497F6CB433C166E2"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.Description) .HasColumnName("description") .HasMaxLength(500); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsAdminRole).HasColumnName("isAdminRole"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.Name) .IsRequired() .HasColumnName("name") .HasMaxLength(100); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); modelBuilder.Entity<RoleModulePermission>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__RoleModu__497F6CB4B4D3EDA0"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.ModuleGuid).HasColumnName("moduleGuid"); entity.Property(e => e.Permission).HasColumnName("permission"); entity.Property(e => e.RoleGuid).HasColumnName("roleGuid"); }); modelBuilder.Entity<TelemetrySummaryDaywise>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Telemetr__497F6CB4E1416FBB"); entity.ToTable("TelemetrySummary_Daywise"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Attribute) .HasColumnName("attribute") .HasMaxLength(1000); entity.Property(e => e.Avg).HasColumnName("avg"); entity.Property(e => e.Date) .HasColumnName("date") .HasColumnType("date"); entity.Property(e => e.DeviceGuid).HasColumnName("deviceGuid"); entity.Property(e => e.Latest).HasColumnName("latest"); entity.Property(e => e.Max).HasColumnName("max"); entity.Property(e => e.Min).HasColumnName("min"); entity.Property(e => e.Sum).HasColumnName("sum"); }); modelBuilder.Entity<TelemetrySummaryHourwise>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__Telemetr__497F6CB4212900FD"); entity.ToTable("TelemetrySummary_Hourwise"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.Attribute) .HasColumnName("attribute") .HasMaxLength(1000); entity.Property(e => e.Avg).HasColumnName("avg"); entity.Property(e => e.Date) .HasColumnName("date") .HasColumnType("datetime"); entity.Property(e => e.DeviceGuid).HasColumnName("deviceGuid"); entity.Property(e => e.Latest).HasColumnName("latest"); entity.Property(e => e.Max).HasColumnName("max"); entity.Property(e => e.Min).HasColumnName("min"); entity.Property(e => e.Sum).HasColumnName("sum"); }); modelBuilder.Entity<User>(entity => { entity.HasKey(e => e.Guid) .HasName("PK__User__497F6CB4FD41A318"); entity.Property(e => e.Guid) .HasColumnName("guid") .ValueGeneratedNever(); entity.Property(e => e.CompanyGuid).HasColumnName("companyGuid"); entity.Property(e => e.ContactNo) .HasColumnName("contactNo") .HasMaxLength(25); entity.Property(e => e.CreatedBy).HasColumnName("createdBy"); entity.Property(e => e.CreatedDate) .HasColumnName("createdDate") .HasColumnType("datetime"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("email") .HasMaxLength(100); entity.Property(e => e.EntityGuid).HasColumnName("entityGuid"); entity.Property(e => e.FirstName) .IsRequired() .HasColumnName("firstName") .HasMaxLength(50); entity.Property(e => e.ImageName) .HasColumnName("imageName") .HasMaxLength(100); entity.Property(e => e.IsActive) .IsRequired() .HasColumnName("isActive") .HasDefaultValueSql("((1))"); entity.Property(e => e.IsDeleted).HasColumnName("isDeleted"); entity.Property(e => e.LastName) .IsRequired() .HasColumnName("lastName") .HasMaxLength(50); entity.Property(e => e.RoleGuid).HasColumnName("roleGuid"); entity.Property(e => e.TimeZoneGuid).HasColumnName("timeZoneGuid"); entity.Property(e => e.UpdatedBy).HasColumnName("updatedBy"); entity.Property(e => e.UpdatedDate) .HasColumnName("updatedDate") .HasColumnType("datetime"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
36.12932
213
0.495341
[ "MIT" ]
iotconnect-apps/AppConnect-SmartElevator
iot.solution.host/Models/qaelevatorContext.cs
32,410
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Windows.Forms; namespace Concision.Controls { public class ConcisionCombobox : ConcisionButton { /// <summary> /// 当选择的下拉项发生改变后 /// </summary> [Description("当选择的下拉项发生改变后")] public event Action<Object, ComboboxToolStripItem> SelectItemChanged; /// <summary> /// 获取或设置Item的字体 /// </summary> public Font ItemFont { get; set; } /// <summary> /// 当前下拉项的计数 /// </summary> public Int32 ItemCount { get { return this._toolStripDropDown.Items.Count; } } /// <summary> /// 获取当前选中的项 /// </summary> [Browsable(false)] public ComboboxToolStripItem SelectedItem { get; private set; } /// <summary> /// 获取当前选中项的索引,或将当前项设置为具有指定索引的项 /// </summary> [Browsable(true)] public Int32 SelectedIndex { get { if (this.SelectedItem != null) { return this.SelectedItem.Index; } return -1; } set { if (this.ItemCount > 0 && value >= 0 && value < this.ItemCount) { ComboboxToolStripItem item = (ComboboxToolStripItem)this._toolStripDropDown.Items[value]; this.OnSelectItemChanged(this, item); } } } /// <summary> /// 获取当前选中项的文本或将当前项设置为具有指定文本的项 /// </summary> [Description("获取当前选中项的文本")] [Browsable(true)] public String SelectedText { get { return this.SelectedItem?.Text; } set { if (this.ItemCount > 0 && !String.IsNullOrEmpty(value)) { foreach (ComboboxToolStripItem item in this._toolStripDropDown.Items) { if (item.Text == value) { this.OnSelectItemChanged(this, item); break; } } } } } /// <summary> /// 获取当前选中项包含的至 /// </summary> [Browsable(false)] public Object SelectedValue { get { return this.SelectedItem?.Value; } set { if (this.SelectedItem != null) { this.SelectedItem.Value = value; } } } /// <summary> /// 是否根据条目数量自动调整下拉框的高度 /// </summary> public Boolean AutoDropDownHeight { get { return this._autoDropDownHeight; } set { this._autoDropDownHeight = value; if (value) { this.RecalcuteDropDownHeight(); } } } /// <summary> /// 设置下拉框的宽度 /// </summary> public Int32 DropDownWidth { get { return this._toolStripDropDown.Width; } set { this._toolStripDropDown.Width = value; } } public Int32 DropDownHeight { get { return this._toolStripDropDown.Height; } set { if (!this.AutoDropDownHeight) { this._toolStripDropDown.Height = value; } } } /// <summary> /// 是否已显示下拉框 /// </summary> public Boolean DropDownShown { get; private set; } /// <summary> /// 获取或设置下拉条目的高度 /// </summary> public Int32 ItemHeight { get; set; } = 30; public ToolStripItemCollection Items { get { return this._toolStripDropDown.Items; } } public override Font Font { get { return base.Font; } set { base.Font = value; if (this.Font.FontFamily != value.FontFamily) { Graphics g = this.CreateGraphics(); this.CalcuteSymbolSize(g, true); g.Dispose(); } } } /// <summary> /// 下拉图标的颜色 /// </summary> public Color SymbolColor { get; set; } = Color.FromArgb(175, 175, 175); /// <summary> /// 下拉图标的大小 /// </summary> public Single SymbolSize { get { return this._symbolSize; } set { if (this._symbolSize != value) { this._symbolSize = value; Graphics g = this.CreateGraphics(); this.CalcuteSymbolSize(g, true); g.Dispose(); } } } /********************************/ private ToolStripDropDown _toolStripDropDown = new ToolStripDropDown(); private Int32 _heightExtra = 2; private const String SymbolDown = "▼"; private SizeF _symbolSizeCache = SizeF.Empty; private Single _symbolSize = 10F; private Boolean _autoDropDownHeight = true; /********************************/ public ConcisionCombobox() : base() { this._toolStripDropDown.AutoSize = false; this._toolStripDropDown.ItemAdded += this.ToolStripDropDown_ItemAdded; this._toolStripDropDown.ItemRemoved += this.ToolStripDropDown_ItemRemoved; this.Size = new Size(250, 35); this.DropDownWidth = 250; this._toolStripDropDown.Height = 0; this.Font = new Font("微软雅黑", 10.5F); this.ItemFont = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134))); this.NormalColor = Color.WhiteSmoke; this.BackColor = this.NormalColor; this.ForeColor = Color.FromArgb(90, 90, 90); } protected override void OnResize(EventArgs e) { if (this._toolStripDropDown.Width < this.Width) { this._toolStripDropDown.Width = this.Width; } base.OnResize(e); } /// <summary> /// 重新计算 DropDown 的高度,在将 <see cref="AutoDropDownHeight"/> 属性false设置为自动后,高度应该从固定值变回为根据Item项适应的高度 /// </summary> private void RecalcuteDropDownHeight() { Int32 height = 0; this._toolStripDropDown.Height = 0; foreach (ComboboxToolStripItem item in this._toolStripDropDown.Items) { //height = item.Height + this._heightExtra; height += item.Height + item.Margin.Top + item.Margin.Bottom; } this._toolStripDropDown.Height = height + this._heightExtra; } /// <summary> /// 向下拉框添加具有指定文本,值,名称的Item /// </summary> public void Add(String text, Object value = null, String name = null) { ComboboxToolStripItem item = new ComboboxToolStripItem(); item.Padding = new Padding(); item.Text = text; item.Size = new Size(this._toolStripDropDown.Width, this.ItemHeight); item.AutoSize = false; item.Value = value; item.Name = name ?? Guid.NewGuid().ToString("N"); item.Font = this.ItemFont; item.Size = new Size(this._toolStripDropDown.Width, this.ItemHeight); item.Index = this._toolStripDropDown.Items.Count - 1; item.TextAlignFormat = this.TextAlignFormat; item.Click += (s, e) => { this.OnSelectItemChanged(this, item); }; this._toolStripDropDown.Items.Add(item); } public void AddRange(IEnumerable<String> texts) { foreach (String text in texts) { this.Add(text); } } public void AddRange(IEnumerable<Tuple<String, Object, String>> items) { foreach (var item in items) { this.Add(item.Item1, item.Item2); } } protected virtual void OnSelectItemChanged(Object sender, ComboboxToolStripItem item) { this.SelectedItem = item; this.Text = this.SelectedItem.Text; this.SelectItemChanged?.Invoke(sender, item); } protected override void OnPaint(PaintEventArgs pevent) { Graphics g = pevent.Graphics; SizeF size = this.CalcuteSymbolSize(g); Brush brush = new SolidBrush(this.SymbolColor); base.OnPaint(pevent); g.DrawString(SymbolDown, new Font(this.Font.FontFamily, this._symbolSize), brush, this.Width - size.Width.RoundToInt32() - (0.05 * this.Width).RoundToInt32(), ((this.Height - size.Height) / 2.0F).RoundToInt32()); brush.Dispose(); g.Dispose(); } protected SizeF CalcuteSymbolSize(Graphics g, Boolean force = false) { if (this._symbolSizeCache == SizeF.Empty || force) { this._symbolSizeCache = g.MeasureString(SymbolDown, new Font(this.Font.FontFamily, this._symbolSize)); } return this._symbolSizeCache; } protected override void OnClick(EventArgs e) { this._toolStripDropDown.Show(this, 3, this.Height); this.DropDownShown = true; base.OnClick(e); } private void ToolStripDropDown_ItemRemoved(Object sender, ToolStripItemEventArgs e) { if (this.AutoDropDownHeight) { this._toolStripDropDown.Height -= e.Item.Height + this._heightExtra; } this.RecalculateItemIndex(); } /// <summary> /// 重新计算Item的索引 /// </summary> private void RecalculateItemIndex() { Int32 index = -1; foreach (ComboboxToolStripItem item in this._toolStripDropDown.Items) { item.Index = index++; } } private void ToolStripDropDown_ItemAdded(Object sender, ToolStripItemEventArgs e) { if (this.AutoDropDownHeight) { this.RecalcuteDropDownHeight(); } } } public class ComboboxToolStripItem : ToolStripItem { /// <summary> /// 文本的对齐方式 /// </summary> public StringFormat TextAlignFormat { get; set; } = StringFormat.GenericDefault; /// <summary> ///获取该Item在所属于 <see cref="ToolStrip"/> 的Item集合中的索引 /// </summary> public Int32 Index { get; internal set; } /// <summary> /// 获取或设置该 Item 包含的值 /// </summary> public Object Value { get; set; } public Color HoverColor { get; set; } = Color.FromArgb(204, 204, 204); public Color NormalColor { get; set; } = Color.WhiteSmoke; public Color PressColor { get; set; } = Color.FromArgb(175, 175, 175); public Color HoverForeColor { get; set; } = Color.White; public Color NormalForeColor { get; set; } = Color.FromArgb(30, 30, 30); public Color PressForeColor { get; set; } = Color.White; public ComboboxToolStripItem() { this.Margin = new Padding(1, 0, 1, 0); this.BackColor = this.NormalColor; this.ForeColor = this.NormalForeColor; } protected override void OnMouseEnter(EventArgs e) { this.BackColor = this.HoverColor; this.ForeColor = this.HoverForeColor; base.OnMouseEnter(e); } //protected override void OnMouseHover(EventArgs e) //{ // base.OnMouseHover(e); //} protected override void OnMouseLeave(EventArgs e) { this.BackColor = this.NormalColor; this.ForeColor = this.NormalForeColor; base.OnMouseLeave(e); } protected override void OnMouseDown(MouseEventArgs e) { this.BackColor = this.PressColor; this.ForeColor = this.PressForeColor; base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { this.BackColor = this.HoverColor; this.ForeColor = this.HoverForeColor; base.OnMouseUp(e); } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; Brush backBrush = new SolidBrush(this.BackColor); Brush textBrush = new SolidBrush(this.ForeColor); g.FillRectangle(backBrush, new RectangleF(0, 0, this.Width, this.Height)); SizeF textSize = g.MeasureString(this.Text, this.Font); g.DrawString( this.Text, this.Font, textBrush, new RectangleF(10, 0, this.Width, this.Height), this.TextAlignFormat); backBrush.Dispose(); textBrush.Dispose(); base.OnPaint(e); } } }
31.511364
224
0.497872
[ "MIT" ]
DegageTech/Concision
Concision/Control/ConcisionCombobox.cs
14,437
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Veruthian.Library.Collections.Extensions { public static class CollectionExtensions { // Array extensions public static T[] Resize<T>(this T[] array, int newSize) { T[] newArray = new T[newSize]; Array.Copy(array, newArray, Math.Min(newSize, array.Length)); return newArray; } // Repeat public static IEnumerable<T> Repeat<T>(this T value, int times = 1) { for (int i = 0; i < times; i++) yield return value; } public static T[] RepeatAsArray<T>(this T value, int times = 1) { var items = new T[times]; for (int i = 0; i < times; i++) items[i] = value; return items; } public static List<T> RepeatAsList<T>(this T value, int times = 1) { var items = new List<T>(times); for (int i = 0; i < times; i++) items.Add(value); return items; } public static DataArray<T> RepeatAsDataArray<T>(this T value, int times = 1) { var items = new DataArray<T>(times); for (int i = 0; i < times; i++) items[i] = value; return items; } public static DataList<T> RepeatAsDataList<T>(this T value, int times = 1) { var items = new DataList<T>(times); for (int i = 0; i < times; i++) items.Add( value); return items; } // Strings public static string ToListString<T>(this IEnumerable<T> items, string start = "[", string end = "]", string separator = ", ") { var builder = new StringBuilder(); builder.Append(start); bool started = false; foreach (var item in items) { if (started) builder.Append(separator); else started = true; builder.Append(item.ToString()); } builder.Append(end); return builder.ToString(); } public static string ToTableString<K, V>(this IEnumerable<(K, V)> items, string tableStart = "{", string tableEnd = "}", string pairStart = "", string pairEnd = "", string pairSeparator = ",", string keyStart = "[", string keyEnd = "] = ", string valueStart = "'", string valueEnd = "'") { var builder = new StringBuilder(); bool started = false; builder.Append(tableStart); foreach ((K key, V value) in items) { if (started) builder.Append(pairSeparator); else started = true; builder.Append(pairStart); // Key builder.Append(keyStart); builder.Append(key); builder.Append(keyEnd); // Value builder.Append(valueStart); builder.Append(value); builder.Append(valueEnd); builder.Append(pairEnd); } builder.Append(tableEnd); return builder.ToString(); } } }
29.167939
232
0.430777
[ "MIT" ]
Veruthas/Dotnet-Veruthian.Library
Solution/Projects/Veruthian.Library/Collections/Extensions/CollectionExtensions.cs
3,821
C#
namespace GenericScriptableArchitecture { using System; using System.Collections.Generic; using System.Linq; using SolidUtilities; using UnityEngine; using Object = UnityEngine.Object; public class EventHelper<T1, T2> : IEventHelper<T1, T2>, IDisposable { private readonly IEvent<T1, T2> _parentEvent; private readonly List<ScriptableEventListener<T1, T2>> _scriptableListeners = new List<ScriptableEventListener<T1, T2>>(); private readonly List<IEventListener<T1, T2>> _singleEventListeners = new List<IEventListener<T1, T2>>(); private readonly List<IMultipleEventsListener<T1, T2>> _multipleEventsListeners = new List<IMultipleEventsListener<T1, T2>>(); private readonly List<Action<T1, T2>> _responses = new List<Action<T1, T2>>(); public List<Object> Listeners => _responses .Select(response => response.Target) .Concat(_scriptableListeners) .Concat(_singleEventListeners) .Concat(_multipleEventsListeners) #if UNIRX .Concat(_observableHelper?.Targets ?? Enumerable.Empty<object>()) #endif .OfType<Object>() .ToList(); public EventHelper() { } public EventHelper(IEvent<T1, T2> parentEvent) { _parentEvent = parentEvent; } public void AddListener(IListener<T1, T2> listener) { if (listener == null) return; if (listener is ScriptableEventListener<T1, T2> scriptableListener) { _scriptableListeners.Add(scriptableListener); return; } if (listener is IEventListener<T1, T2> eventListener) { _singleEventListeners.AddIfMissing(eventListener); } if (listener is IMultipleEventsListener<T1, T2> multipleEventsListener) { _multipleEventsListeners.AddIfMissing(multipleEventsListener); } } public void RemoveListener(IListener<T1, T2> listener) { if (listener is ScriptableEventListener<T1, T2> scriptableListener) { _scriptableListeners.Remove(scriptableListener); return; } bool isValidListener = false; if (listener is IEventListener<T1, T2> eventListener) { isValidListener = true; _singleEventListeners.AddIfMissing(eventListener); } if (listener is IMultipleEventsListener<T1, T2> multipleEventsListener) { isValidListener = true; _multipleEventsListeners.AddIfMissing(multipleEventsListener); } if ( ! isValidListener) Debug.LogWarning($"Tried to subscribe to {_parentEvent?.ToString() ?? "an event"} with a listener that does not implement any of supported interfaces."); } public void AddListener(Action<T1, T2> listener) { if (listener == null) return; _responses.AddIfMissing(listener); } public void RemoveListener(Action<T1, T2> listener) => _responses.Remove(listener); public void NotifyListeners(T1 arg0, T2 arg1) { for (int i = _scriptableListeners.Count - 1; i != -1; i--) { _scriptableListeners[i].OnEventInvoked(arg0, arg1); } for (int i = _singleEventListeners.Count - 1; i != -1; i--) { _singleEventListeners[i].OnEventInvoked(arg0, arg1); } for (int i = _multipleEventsListeners.Count - 1; i != -1; i--) { _multipleEventsListeners[i].OnEventInvoked(_parentEvent ?? this, arg0, arg1); } for (int i = _responses.Count - 1; i != -1; i--) { _responses[i].Invoke(arg0, arg1); } #if UNIRX _observableHelper?.RaiseOnNext((arg0, arg1)); #endif } #region UniRx #if UNIRX private ObservableHelper<(T1, T2)> _observableHelper; public IDisposable Subscribe(IObserver<(T1, T2)> observer) { _observableHelper ??= new ObservableHelper<(T1, T2)>(); return _observableHelper.Subscribe(observer); } #endif public void Dispose() { #if UNIRX _observableHelper?.Dispose(); #endif } #endregion } }
32.5
169
0.578901
[ "MIT" ]
Walter-Hulsebos/GenericScriptableArchitecture
Runtime/EventHelpers/EventHelper`2.cs
4,552
C#
using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Threading.Tasks; using CoreWCF.Runtime; using CoreWCF.Description; using CoreWCF.Diagnostics; using CoreWCF.Dispatcher; using System.Collections.Concurrent; using System.Diagnostics.Contracts; using System.Runtime; using System.Runtime.CompilerServices; using System.Threading; namespace CoreWCF.Channels { public class ServiceChannelProxy : DispatchProxy, ICommunicationObject, IChannel, IClientChannel, IOutputChannel, IRequestChannel, IServiceChannel, IDuplexContextChannel { private const string activityIdSlotName = "E2ETrace.ActivityID"; private Type _proxiedType; private ServiceChannel _serviceChannel; private ImmutableClientRuntime _proxyRuntime; private MethodDataCache _methodDataCache; // ServiceChannelProxy serves 2 roles. It is the TChannel proxy called by the client, // and it is also the handler of those calls that dispatches them to the appropriate service channel. // In .Net Remoting terms, it is conceptually the same as a RealProxy and a TransparentProxy combined. internal static TChannel CreateProxy<TChannel>(MessageDirection direction, ServiceChannel serviceChannel) { TChannel proxy = DispatchProxy.Create<TChannel, ServiceChannelProxy>(); if (proxy == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.FailedToCreateTypedProxy, typeof(TChannel)))); } ServiceChannelProxy channelProxy = (ServiceChannelProxy)(object)proxy; channelProxy._proxiedType = typeof(TChannel); channelProxy._serviceChannel = serviceChannel; channelProxy._proxyRuntime = serviceChannel.ClientRuntime.GetRuntime(); channelProxy._methodDataCache = new MethodDataCache(); return proxy; } //Workaround is to set the activityid in remoting call's LogicalCallContext // Override ToString() to reveal only the expected proxy type, not the generated one public override string ToString() { return _proxiedType.ToString(); } private MethodData GetMethodData(MethodCall methodCall) { MethodData methodData; MethodBase method = methodCall.MethodBase; if (_methodDataCache.TryGetMethodData(method, out methodData)) { return methodData; } bool canCacheMessageData; Type declaringType = method.DeclaringType; if (declaringType == typeof(object) && method == typeof(object).GetMethod("GetType")) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.GetType); } else if (declaringType.IsAssignableFrom(_serviceChannel.GetType())) { canCacheMessageData = true; methodData = new MethodData(method, MethodType.Channel); } else { ProxyOperationRuntime operation = _proxyRuntime.GetOperation(method, methodCall.Args, out canCacheMessageData); if (operation == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupportedOnCallback1, method.Name))); } MethodType methodType; if (operation.IsTaskCall(methodCall)) { methodType = MethodType.TaskService; } else if (operation.IsSyncCall(methodCall)) { methodType = MethodType.Service; } else if (operation.IsBeginCall(methodCall)) { methodType = MethodType.BeginService; } else { methodType = MethodType.EndService; } methodData = new MethodData(method, methodType, operation); } if (canCacheMessageData) { _methodDataCache.SetMethodData(methodData); } return methodData; } internal ServiceChannel GetServiceChannel() { return _serviceChannel; } protected override object Invoke(MethodInfo targetMethod, object[] args) { if (args == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(args)); } if (targetMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidTypedProxyMethodHandle, _proxiedType.Name))); } MethodCall methodCall = new MethodCall(targetMethod, args); MethodData methodData = GetMethodData(methodCall); switch (methodData.MethodType) { case MethodType.Service: return InvokeService(methodCall, methodData.Operation); case MethodType.BeginService: return InvokeBeginService(methodCall, methodData.Operation); case MethodType.EndService: return InvokeEndService(methodCall, methodData.Operation); case MethodType.TaskService: return InvokeTaskService(methodCall, methodData.Operation); case MethodType.Channel: return InvokeChannel(methodCall); case MethodType.GetType: return InvokeGetType(methodCall); default: Fx.Assert("Invalid proxy method type"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid proxy method type"))); } } internal static class TaskCreator { public static Task CreateTask(ServiceChannel channel, MethodCall methodCall, ProxyOperationRuntime operation) { if (operation.TaskTResult == ServiceReflector.VoidType) { return TaskCreator.CreateTask(channel, operation, methodCall.Args); } return TaskCreator.CreateGenericTask(channel, operation, methodCall.Args); } private static Task CreateGenericTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSourceProxy tcsp = new TaskCompletionSourceProxy(operation.TaskTResult); Action<Task<object>, object> completeCallDelegate = (antecedent, obj) => { var tcsProxy = obj as TaskCompletionSourceProxy; Contract.Assert(tcsProxy != null); if (antecedent.IsFaulted) tcsProxy.TrySetException(antecedent.Exception.InnerException); else if (antecedent.IsCanceled) tcsProxy.TrySetCanceled(); else tcsProxy.TrySetResult(antecedent.Result); }; try { channel.CallAsync(operation.Action, operation.IsOneWay, operation, inputParameters, Array.Empty<object>()).ContinueWith(completeCallDelegate, tcsp); } catch (Exception e) { tcsp.TrySetException(e); } return tcsp.Task; } private static Task CreateTask(ServiceChannel channel, ProxyOperationRuntime operation, object[] inputParameters) { TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); Action<Task<object>, object> completeCallDelegate = (antecedent, obj) => { var tcsObj = obj as TaskCompletionSource<object>; Contract.Assert(tcsObj != null); if (antecedent.IsFaulted) tcsObj.TrySetException(antecedent.Exception.InnerException); else if (antecedent.IsCanceled) tcsObj.TrySetCanceled(); else tcsObj.TrySetResult(antecedent.Result); }; try { channel.CallAsync(operation.Action, operation.IsOneWay, operation, inputParameters, Array.Empty<object>()).ContinueWith(completeCallDelegate, tcs); } catch (Exception e) { tcs.TrySetException(e); } return tcs.Task; } } private class TaskCompletionSourceProxy { private TaskCompletionSourceInfo _tcsInfo; private object _tcsInstance; public TaskCompletionSourceProxy(Type resultType) { _tcsInfo = TaskCompletionSourceInfo.GetTaskCompletionSourceInfo(resultType); _tcsInstance = Activator.CreateInstance(_tcsInfo.GenericType); } public Task Task { get { return (Task)_tcsInfo.TaskProperty.GetValue(_tcsInstance); } } public bool TrySetResult(object result) { return (bool)_tcsInfo.TrySetResultMethod.Invoke(_tcsInstance, new object[] { result }); } public bool TrySetException(Exception exception) { return (bool)_tcsInfo.TrySetExceptionMethod.Invoke(_tcsInstance, new object[] { exception }); } public bool TrySetCanceled() { return (bool)_tcsInfo.TrySetCanceledMethod.Invoke(_tcsInstance, Array.Empty<object>()); } } private class TaskCompletionSourceInfo { private static ConcurrentDictionary<Type, TaskCompletionSourceInfo> s_cache = new ConcurrentDictionary<Type, TaskCompletionSourceInfo>(); public TaskCompletionSourceInfo(Type resultType) { ResultType = resultType; Type tcsType = typeof(TaskCompletionSource<>); GenericType = tcsType.MakeGenericType(new Type[] { resultType }); TaskProperty = GenericType.GetTypeInfo().GetDeclaredProperty("Task"); TrySetResultMethod = GenericType.GetTypeInfo().GetDeclaredMethod("TrySetResult"); TrySetExceptionMethod = GenericType.GetRuntimeMethod("TrySetException", new Type[] { typeof(Exception) }); TrySetCanceledMethod = GenericType.GetRuntimeMethod("TrySetCanceled", Array.Empty<Type>()); } public Type ResultType { get; private set; } public Type GenericType { get; private set; } public PropertyInfo TaskProperty { get; private set; } public MethodInfo TrySetResultMethod { get; private set; } public MethodInfo TrySetExceptionMethod { get; set; } public MethodInfo TrySetCanceledMethod { get; set; } public static TaskCompletionSourceInfo GetTaskCompletionSourceInfo(Type resultType) { return s_cache.GetOrAdd(resultType, t => new TaskCompletionSourceInfo(t)); } } private object InvokeTaskService(MethodCall methodCall, ProxyOperationRuntime operation) { Task task = TaskCreator.CreateTask(_serviceChannel, methodCall, operation); return task; } private object InvokeChannel(MethodCall methodCall) { //string activityName = null; //ActivityType activityType = ActivityType.Unknown; //if (DiagnosticUtility.ShouldUseActivity) //{ // if (ServiceModelActivity.Current == null || // ServiceModelActivity.Current.ActivityType != ActivityType.Close) // { // MethodData methodData = this.GetMethodData(methodCall); // if (methodData.MethodBase.DeclaringType == typeof(System.ServiceModel.ICommunicationObject) // && methodData.MethodBase.Name.Equals("Close", StringComparison.Ordinal)) // { // activityName = SR.Format(SR.ActivityClose, _serviceChannel.GetType().FullName); // activityType = ActivityType.Close; // } // } //} //using (ServiceModelActivity activity = string.IsNullOrEmpty(activityName) ? null : ServiceModelActivity.CreateBoundedActivity()) //{ // if (DiagnosticUtility.ShouldUseActivity) // { // ServiceModelActivity.Start(activity, activityName, activityType); // } return ExecuteMessage(_serviceChannel, methodCall); //} } private object InvokeGetType(MethodCall methodCall) { return _proxiedType; } private object InvokeBeginService(MethodCall methodCall, ProxyOperationRuntime operation) { AsyncCallback callback; object asyncState; object[] ins = operation.MapAsyncBeginInputs(methodCall, out callback, out asyncState); object ret = _serviceChannel.BeginCall(operation.Action, operation.IsOneWay, operation, ins, callback, asyncState); return ret; } private object InvokeEndService(MethodCall methodCall, ProxyOperationRuntime operation) { IAsyncResult result; object[] outs; operation.MapAsyncEndInputs(methodCall, out result, out outs); object ret = _serviceChannel.EndCall(operation.Action, outs, result); operation.MapAsyncOutputs(methodCall, outs, ref ret); return ret; } private object InvokeService(MethodCall methodCall, ProxyOperationRuntime operation) { object[] outs; object[] ins = operation.MapSyncInputs(methodCall, out outs); object ret; using (TaskHelpers.RunTaskContinuationsOnOurThreads()) { ret = _serviceChannel.CallAsync(operation.Action, operation.IsOneWay, operation, ins, outs).GetAwaiter().GetResult(); } operation.MapSyncOutputs(methodCall, outs, ref ret); return ret; } private object ExecuteMessage(object target, MethodCall methodCall) { MethodBase targetMethod = methodCall.MethodBase; object[] args = methodCall.Args; object returnValue = null; try { returnValue = targetMethod.Invoke(target, args); } catch (TargetInvocationException e) { throw e.InnerException; } return returnValue; } internal class MethodDataCache { private MethodData[] _methodDatas; public MethodDataCache() { _methodDatas = new MethodData[4]; } private object ThisLock { get { return this; } } public bool TryGetMethodData(MethodBase method, out MethodData methodData) { lock (ThisLock) { MethodData[] methodDatas = _methodDatas; int index = FindMethod(methodDatas, method); if (index >= 0) { methodData = methodDatas[index]; return true; } else { methodData = new MethodData(); return false; } } } private static int FindMethod(MethodData[] methodDatas, MethodBase methodToFind) { for (int i = 0; i < methodDatas.Length; i++) { MethodBase method = methodDatas[i].MethodBase; if (method == null) { break; } if (method == methodToFind) { return i; } } return -1; } public void SetMethodData(MethodData methodData) { lock (ThisLock) { int index = FindMethod(_methodDatas, methodData.MethodBase); if (index < 0) { for (int i = 0; i < _methodDatas.Length; i++) { if (_methodDatas[i].MethodBase == null) { _methodDatas[i] = methodData; return; } } MethodData[] newMethodDatas = new MethodData[_methodDatas.Length * 2]; Array.Copy(_methodDatas, newMethodDatas, _methodDatas.Length); newMethodDatas[_methodDatas.Length] = methodData; _methodDatas = newMethodDatas; } } } } internal enum MethodType { Service, BeginService, EndService, Channel, Object, GetType, TaskService } internal struct MethodData { private MethodBase _methodBase; private MethodType _methodType; private ProxyOperationRuntime _operation; public MethodData(MethodBase methodBase, MethodType methodType) : this(methodBase, methodType, null) { } public MethodData(MethodBase methodBase, MethodType methodType, ProxyOperationRuntime operation) { _methodBase = methodBase; _methodType = methodType; _operation = operation; } public MethodBase MethodBase { get { return _methodBase; } } public MethodType MethodType { get { return _methodType; } } public ProxyOperationRuntime Operation { get { return _operation; } } } #region Channel interfaces // These channel methods exist only to implement additional channel interfaces for ServiceChannelProxy. // This is required because clients can down-cast typed proxies to the these channel interfaces. // On the desktop, the .Net Remoting layer allowed that type cast, and subsequent calls against the // interface went back through the RealProxy and invoked the underlying ServiceChannel. // Net Native and CoreClr do not have .Net Remoting and therefore cannot use that mechanism. // But because typed proxies derive from ServiceChannelProxy, implementing these interfaces // on ServiceChannelProxy permits casting the typed proxy to these interfaces. // All interface implementations delegate directly to the underlying ServiceChannel. T IChannel.GetProperty<T>() { return _serviceChannel.GetProperty<T>(); } CommunicationState ICommunicationObject.State { get { return _serviceChannel.State; } } event EventHandler ICommunicationObject.Closed { add { _serviceChannel.Closed += value; } remove { _serviceChannel.Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { _serviceChannel.Closing += value; } remove { _serviceChannel.Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { _serviceChannel.Faulted += value; } remove { _serviceChannel.Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { _serviceChannel.Opened += value; } remove { _serviceChannel.Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { _serviceChannel.Opening += value; } remove { _serviceChannel.Opening -= value; } } void ICommunicationObject.Abort() { _serviceChannel.Abort(); } Task ICommunicationObject.CloseAsync() { return _serviceChannel.CloseAsync(); } Task ICommunicationObject.CloseAsync(CancellationToken token) { return _serviceChannel.CloseAsync(token); } Task ICommunicationObject.OpenAsync() { return _serviceChannel.OpenAsync(); } Task ICommunicationObject.OpenAsync(CancellationToken token) { return _serviceChannel.OpenAsync(token); } //Uri IClientChannel.Via //{ // get { return _serviceChannel.Via; } //} event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived { add { ((IClientChannel)_serviceChannel).UnknownMessageReceived += value; } remove { ((IClientChannel)_serviceChannel).UnknownMessageReceived -= value; } } void IDisposable.Dispose() { ((IClientChannel)_serviceChannel).Dispose(); } //bool IContextChannel.AllowOutputBatching //{ // get // { // return ((IContextChannel)_serviceChannel).AllowOutputBatching; // } // set // { // ((IContextChannel)_serviceChannel).AllowOutputBatching = value; // } //} IInputSession IContextChannel.InputSession { get { return ((IContextChannel)_serviceChannel).InputSession; } } EndpointAddress IContextChannel.LocalAddress { get { return ((IContextChannel)_serviceChannel).LocalAddress; } } TimeSpan IContextChannel.OperationTimeout { get { return ((IContextChannel)_serviceChannel).OperationTimeout; } set { ((IContextChannel)_serviceChannel).OperationTimeout = value; } } IOutputSession IContextChannel.OutputSession { get { return ((IContextChannel)_serviceChannel).OutputSession; } } EndpointAddress IOutputChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IOutputChannel.Via { get { return _serviceChannel.Via; } } EndpointAddress IContextChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } string IContextChannel.SessionId { get { return ((IContextChannel)_serviceChannel).SessionId; } } IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions { get { return ((IContextChannel)_serviceChannel).Extensions; } } Task IOutputChannel.SendAsync(Message message) { return _serviceChannel.SendAsync(message); } Task IOutputChannel.SendAsync(Message message, CancellationToken token) { return _serviceChannel.SendAsync(message, token); } Task<Message> IRequestChannel.RequestAsync(Message message) { return _serviceChannel.RequestAsync(message); } Task<Message> IRequestChannel.RequestAsync(Message message, CancellationToken token) { return _serviceChannel.RequestAsync(message, token); } public Task CloseOutputSessionAsync(CancellationToken token) { return ((IDuplexContextChannel)_serviceChannel).CloseOutputSessionAsync(token); } EndpointAddress IRequestChannel.RemoteAddress { get { return ((IContextChannel)_serviceChannel).RemoteAddress; } } Uri IRequestChannel.Via { get { return _serviceChannel.Via; } } Uri IServiceChannel.ListenUri { get { return _serviceChannel.ListenUri; } } public bool AutomaticInputSessionShutdown { get { return ((IDuplexContextChannel)_serviceChannel).AutomaticInputSessionShutdown; } set { ((IDuplexContextChannel)_serviceChannel).AutomaticInputSessionShutdown = value; } } public InstanceContext CallbackInstance { get { return ((IDuplexContextChannel)_serviceChannel).CallbackInstance; } set { ((IDuplexContextChannel)_serviceChannel).CallbackInstance = value; } } #endregion // Channel interfaces } }
36.518414
183
0.569777
[ "MIT" ]
ammogcoder/CoreWCF
src/CoreWCF.Primitives/src/CoreWCF/Channels/ServiceChannelProxy.cs
25,784
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Thomas Hövel // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.PdfSharpCore.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System.Collections.Generic; using System.IO; using Didstopia.PDFSharp.Pdf; namespace Didstopia.PDFSharp.Drawing.Internal { /// <summary> /// The class that imports images of various formats. /// </summary> internal class ImageImporter { // TODO Make a singleton! /// <summary> /// Gets the image importer. /// </summary> public static ImageImporter GetImageImporter() { return new ImageImporter(); } private ImageImporter() { _importers.Add(new ImageImporterJpeg()); _importers.Add(new ImageImporterBmp()); // TODO: Special importer for PDF? Or dealt with at a higher level? } /// <summary> /// Imports the image. /// </summary> public ImportedImage ImportImage(Stream stream, PdfDocument document) { StreamReaderHelper helper = new StreamReaderHelper(stream); // Try all registered importers to see if any of them can handle the image. foreach (IImageImporter importer in _importers) { helper.Reset(); ImportedImage image = importer.ImportImage(helper, document); if (image != null) return image; } return null; } #if GDI || WPF || CORE /// <summary> /// Imports the image. /// </summary> public ImportedImage ImportImage(string filename, PdfDocument document) { ImportedImage ii; using (Stream fs = File.OpenRead(filename)) { ii = ImportImage(fs, document); } return ii; } #endif private readonly List<IImageImporter> _importers = new List<IImageImporter>(); } }
34.150538
87
0.638854
[ "MPL-2.0" ]
Dejers/Card-Game-Simulator
Assets/Plugins/PdfSharp/Didstopia/Drawing_Internal/ImageImporter.cs
3,177
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using ClassHelper; public class BookConfirmCanvas : ControlableUI { int bookId; public GameObject content; public void AddUI(int _bookId) { bookId = _bookId; AddUI(); } public override void AddUI() { BookData _bd = ResourcePointManager.Instance.GetBookData(bookId); content.transform.Find("Name").GetComponent<Text>().text = _bd.name.GetString(); content.transform.Find("Text").GetComponent<Text>().text = _bd.GetBookDescription(); base.AddUI(); UIManager.Instance.choiceUI.Setup(new Vector2(Screen.width / 2f, Screen.height / 2f), new List<string> { "Confirm", "Cancel" }, new List<Callback> { Confirm, Cancel }); } void Confirm() { BookData _bd = ResourcePointManager.Instance.GetBookData(bookId); Database.TimePass(_bd.time * 60); Database.AddBook(bookId); OnBackPressed(); OnBackPressed(); } void Cancel() { OnBackPressed(); OnBackPressed(); MainGameView.Instance.libraryCanvas.AddUI(); } }
25.12766
176
0.646909
[ "CC0-1.0" ]
simonbut/GemHero
Assets/Scripts/BookConfirmCanvas.cs
1,181
C#
// [[[[INFO> // Copyright 2015 Epicycle (http://epicycle.org, https://github.com/open-epicycle) // // 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. // // For more information check https://github.com/open-epicycle/Epicycle.Math-cs // ]]]] using NUnit.Framework; using System.Collections.Generic; namespace Epicycle.Math.Geometry { [TestFixture] public sealed class Vector3Test : AssertionHelper { private const double _tolerance = 1e-10; [Test] public void Two_Vector3_with_equal_components_are_equal_as_objects() { var x = 1.1; var y = 2.2; var z = 3.3; object v = new Vector3(x, y, z); object w = new Vector3(x, y, z); Expect(v.Equals(w)); } [Test] public void Two_Vector3_with_a_different_component_are_not_equal_as_objects() { var x = 1.1; var y = 2.2; var z = 3.3; object v = new Vector3(x, y, z); object w = new Vector3(x, y, z + 0.1); Expect(!v.Equals(w)); } [Test] public void A_Vector3_is_not_equal_to_an_object_which_is_not_a_Vector3() { var x = 1.1; var y = 2.2; var z = 3.3; object v = new Vector3(x, y, z); object w = "Hello world"; Expect(!v.Equals(w)); } private IEnumerable<Vector3> VectorOrthogonalTo_TestCases() { yield return new Vector3(1, 2, 3); yield return new Vector3(0, 1, 2); yield return new Vector3(-1, 0, 1); yield return new Vector3(1.5, -0.8, 0); yield return new Vector3(3.141, 0, 0); yield return new Vector3(0, 2.718, 0); yield return new Vector3(0, 0, -0.577); } [Test] public void VectorOrthogonalTo_returns_Vector3_orthogonal_to_input_Vector3_which_is_not_zero_when_input_Vector3_is_not_zero ([ValueSource("VectorOrthogonalTo_TestCases")] Vector3 v) { var result = Vector3Utils.VectorOrthogonalTo(v); Expect(v * result, Is.EqualTo(0).Within(_tolerance)); Expect(result.Norm, Is.GreaterThan(0.8 * v.Norm)); } } }
30.434783
131
0.5925
[ "Apache-2.0" ]
open-epicycle/Epicycle.Math-cs
projects/Epicycle.Math_cs-Test/Geometry/Vector3Test.cs
2,802
C#
namespace TweetTail.Controls.FormsVideoLibrary { public class VideoInfo { public string DisplayName { set; get; } public VideoSource VideoSource { set; get; } public override string ToString() { return DisplayName; } } }
19.2
52
0.59375
[ "MIT" ]
leekcake/TweetTail
TweetTail/TweetTail/Controls/FormsVideoLibrary/VideoInfo.cs
290
C#
using static System.Console; public class Program { public static void Main() { Compara(20, 15); Compara(20, 14); Compara(20, 11); Compara(20, 8); Compara(20, 2); } private static void Compara(int aniversario, int ano) { var idade = aniversario - ano; string texto; if (idade < 6) texto = "Infatil A"; else if (idade < 7) texto = "Infantil B"; else if (idade < 10) texto = "Juvenil A"; else if (idade < 13) texto = "Juvenil B"; else if (idade > 17) texto = "Adulto"; //e os que estão entre 13 e 17 não existem? else texto = "Não existe categoria"; WriteLine(texto); } } //https://pt.stackoverflow.com/q/386515/101
25.92
84
0.648148
[ "MIT" ]
Everton75/estudo
CSharp/Other/Simplification.cs
651
C#
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Hosting; using System.Web.Http; using CfgDotNet; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CommandR.WebApi { [RoutePrefix("jsonrpc")] public class JsonRpcController : ApiController { private readonly JsonRpc _jsonRpc; private readonly Commander _commander; private readonly Settings _settings; public JsonRpcController(JsonRpc jsonRpc, Commander commander, Settings settings) { _jsonRpc = jsonRpc; _commander = commander; _settings = settings; } [Route("{command?}")] public async Task<dynamic> Post(string command = null) { var json = await RetrieveJsonFromRequest(Request.Content); return await _jsonRpc.Execute(json); } [Route("{command}")] public async Task<dynamic> Get(string command) { var queryString = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value); var json = JsonConvert.SerializeObject(queryString); return await _commander.Send(command, json); } //REF: http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/ private async Task<string> RetrieveJsonFromRequest(HttpContent content) { if (!content.IsMimeMultipartContent()) { return await content.ReadAsStringAsync(); } var provider = LoadMultipartStreamProvider(); var result = await content.ReadAsMultipartAsync(provider); return MapFilePathsToCommandJson(result); } private MultipartFormDataStreamProvider LoadMultipartStreamProvider() { var path = _settings.UploadFolder; if (path == null) throw new ApplicationException("JsonRpcController ERROR null uploads path"); if (path.StartsWith("~")) { path = HostingEnvironment.MapPath(path) ?? string.Empty; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } return new FilenameMultipartFormDataStreamProvider(path); } private static string MapFilePathsToCommandJson(MultipartFormDataStreamProvider result) { var json = result.FormData["json"]; if (json == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var jObject = JObject.Parse(json); foreach (var file in result.FileData) { var name = file.Headers.ContentDisposition.Name.Replace("\"", string.Empty); jObject["params"][name] = file.LocalFileName; } return jObject.ToString(); } public class Settings : BaseSettings { public string UploadFolder { get; set; } public override void Validate() { if (string.IsNullOrWhiteSpace(UploadFolder)) UploadFolder = "~/App_Data/JsonRpcUploads/"; if (UploadFolder.StartsWith("~")) return; //allow mapped paths, but can't fail fast if (!Directory.Exists(UploadFolder)) Directory.CreateDirectory(UploadFolder); } }; }; }
32.378378
107
0.58542
[ "MIT" ]
Command-R/Command-R
CommandR.WebApi/JsonRpcController.cs
3,596
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; using System.Reflection; using OISCommon; /// +------------------------------------------------------------------------------------------------------------------------------+ /// ¦ TERMS OF USE: MIT License ¦ /// +------------------------------------------------------------------------------------------------------------------------------¦ /// ¦Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation ¦ /// ¦files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, ¦ /// ¦modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software¦ /// ¦is furnished to do so, subject to the following conditions: ¦ /// ¦ ¦ /// ¦The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.¦ /// ¦ ¦ /// ¦THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE ¦ /// ¦WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR ¦ /// ¦COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ¦ /// ¦ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ¦ /// +------------------------------------------------------------------------------------------------------------------------------+ namespace LineGrinder { /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// A control to contain portions of filenames and the actions we take /// when we open a gerber file with that name. /// /// For example, these configurations enable us to see /// a file with a name like [something]_bottom.ngc and because we match /// "_bottom.ngc" we know to flip it before creating the gcode, /// the output extension and various other actions we might want to take /// with it /// </summary> public partial class ctlFileManagersDisplay : ctlOISBase { private BindingList<FileManager> fileManagersList = new BindingList<FileManager>(); // this keeps track of whether any options changed private bool optionsChanged = false; private ApplicationUnitsEnum defaultApplicationUnits = ApplicationImplicitSettings.DEFAULT_APPLICATION_UNITS; /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Constructor /// </summary> public ctlFileManagersDisplay() { InitializeComponent(); listBoxFileManagers.DataSource = fileManagersList; listBoxFileManagers.DisplayMember = "FilenamePattern"; SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets/Sets the currently set Default Application Units as an enum /// </summary> [Browsable(false)] public ApplicationUnitsEnum DefaultApplicationUnits { get { return defaultApplicationUnits; } set { defaultApplicationUnits = value; } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Accepts an incoming filename and returns the matching file manager object. /// We never return null. If we do not have a match we return a default /// object. The caller should check IsAtDefaults() on it upon return /// </summary> /// <param name="filePathAndNameIn">file name to find the object for, can contain a path</param> /// <param name="wantDeepClone">if true we return a deep clone</param> public FileManager GetMatchingFileManager(string filePathAndNameIn, bool wantDeepClone) { if (filePathAndNameIn == null) return new FileManager(); if (filePathAndNameIn.Length == 0) return new FileManager(); LogMessage("GetMatchingFileManagersObject called with>" + filePathAndNameIn); // strip the path (if any) off the filename string fileName = Path.GetFileName(filePathAndNameIn); if ((fileName == null) || (fileName.Length == 0)) { LogMessage("GetMatchingFileManagersObject no filename after stripping path off>" + filePathAndNameIn); return new FileManager(); } // now pattern match each FileManagers object in our list foreach(FileManager optObj in FileManagersList) { if (filePathAndNameIn.Contains(optObj.FilenamePattern) == true) { // we found it if (wantDeepClone == true) return FileManager.DeepClone(optObj); else return optObj; } } // not found, return a default object return GetDefaultFileManagerObject(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets/sets the list of file options. Will never get/set a null /// </summary> [Browsable(false)] [DefaultValue(null)] [ReadOnlyAttribute(true)] public BindingList<FileManager> FileManagersList { get { if (fileManagersList == null) fileManagersList = new BindingList<FileManager>(); return fileManagersList; } set { fileManagersList = value; if (fileManagersList == null) fileManagersList = new BindingList<FileManager>(); ResetListBoxContents(); } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// We have to reset the listbox contents. This is pretty ugly but neither /// Invalidate() or Refresh() seem to work with this binding /// </summary> private void ResetListBoxContents() { listBoxFileManagers.DataSource = null; listBoxFileManagers.DataSource = fileManagersList; listBoxFileManagers.DisplayMember = "FilenamePattern"; GetDefaultFileManagerObject(); SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Sets the currently selected file manager by name /// </summary> /// <param name="selectedManagerFilenamePattern">the file name pattern we match</param> public void SetSelectedManagerByName(string selectedManagerFilenamePattern) { if((selectedManagerFilenamePattern==null) || (selectedManagerFilenamePattern.Length==0)) return; for (int i = 0; i < listBoxFileManagers.Items.Count; i++) { if (((FileManager)listBoxFileManagers.Items[i]).FilenamePattern == selectedManagerFilenamePattern) { listBoxFileManagers.SelectedIndex = i; return; } } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets the name of the currently selected file manager /// </summary> /// <returns>the filename pattern of the selected file manager</returns> public string GetSelectedManagerName() { if(listBoxFileManagers.SelectedItem == null) return null; if((listBoxFileManagers.SelectedItem is FileManager)==false) return null; return ((FileManager)listBoxFileManagers.SelectedItem).FilenamePattern; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets the default file options object we just make this up new each time /// </summary> public FileManager GetDefaultFileManagerObject() { // if we get here it was not found FileManager tmpObj = new FileManager(); tmpObj.OperationMode = FileManager.OperationModeEnum.Default; return tmpObj; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets/sets the optionsChanged flag /// </summary> [Browsable(false)] public bool OptionsChanged { get { return optionsChanged; } set { optionsChanged = value; } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a selected object changed event in the listbox /// </summary> private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { FileManager selectedManager = (FileManager)listBoxFileManagers.SelectedItem; propertyGridFileManager.SelectedObject = selectedManager; SetPropertyStateAppropriateToOperationMode(selectedManager); // this double sort is necessary. Or sometimes the weird reflection // code in SetPropertyStateAppropriateToOperationMode will take two // activations to properly display the properties propertyGridFileManager.PropertySort = PropertySort.Alphabetical; propertyGridFileManager.PropertySort = PropertySort.Categorized; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a property value changed event in the listbox /// </summary> private void propertyGridFileManager_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { // always flag this optionsChanged = true; // we need to update the listbox if the FilenamePattern property // changes. This is so the user sees the new name if (e.ChangedItem.Label == "FilenamePattern") { ResetListBoxContents(); return; } if (e.ChangedItem.Label == "OperationMode") { if ((e.ChangedItem.Value is FileManager.OperationModeEnum) == false) return; if ((propertyGridFileManager.SelectedObject is FileManager) == false) return; SetPropertyStateAppropriateToOperationMode((FileManager)propertyGridFileManager.SelectedObject); } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets the index of the specfied object /// </summary> /// <returns>index or zero for not found</returns> public int GetIndexForFileManagersObject(FileManager fileManagerObj) { if (fileManagerObj == null) return -1; return FileManagersList.IndexOf(fileManagerObj); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Selects the file options object based on the filename pattern /// </summary> /// <returns>index or zero for not found</returns> public void SelectFileManagersObjectByFilenamePattern(string filenamePatternIn) { if ((filenamePatternIn == null) || (filenamePatternIn.Length == 0)) return; for (int index = 0; index < FileManagersList.Count; index++) { if (FileManagersList[index].FilenamePattern == filenamePatternIn) { listBoxFileManagers.SelectedIndex = index; return; } } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Adds a file option object to the current display. Note that all file /// managers are created in INCHES by default. This is what sets them /// to MM if the default application units setting is in MM. /// </summary> public void AddFileManager(FileManager fileManagerObj) { optionsChanged = true; // do we have to convert? We do if it is not the default of inches if (DefaultApplicationUnits == ApplicationUnitsEnum.MILLIMETERS) { // this will automatically convert fileManagerObj.ConvertFromInchToMM(); } fileManagersList.Add(fileManagerObj); ResetListBoxContents(); // this will create the default object if it is not present GetDefaultFileManagerObject(); SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a click on the reset button /// </summary> private void buttonReset_Click(object sender, EventArgs e) { DialogResult dlgRes = OISMessageBox_YesNo("The options in the selected File Manager will be reset to their default state. The FileNamePattern, Description and OperationMode items will not be changed.\n\nDo you wish to proceed?"); if (dlgRes != DialogResult.Yes) return; optionsChanged = true; FileManager selectedManager = (FileManager)listBoxFileManagers.SelectedItem; if (selectedManager == null) return; selectedManager.Reset(false, DefaultApplicationUnits); // select the newly reset item listBox1_SelectedIndexChanged(this, new EventArgs()); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a click on the remove button /// </summary> private void buttonRemove_Click(object sender, EventArgs e) { DialogResult dlgRes = OISMessageBox_YesNo("This option will remove the selected File Manager.\n\nDo you wish to proceed?"); if (dlgRes != DialogResult.Yes) return; // removed selected RemoveSelectedFileManager(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a click on the remove all button /// </summary> private void buttonRemoveAll_Click(object sender, EventArgs e) { DialogResult dlgRes = OISMessageBox_YesNo("This option will remove all File Managers.\n\nDo you wish to proceed?"); if (dlgRes != DialogResult.Yes) return; // remove all RemoveAllFileManagers(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Removes the selected file manager /// </summary> public void RemoveSelectedFileManager() { // remove the current selection in the list box int index = listBoxFileManagers.SelectedIndex; if (index < 0) return; optionsChanged = true; // cannot remove when datasource is set listBoxFileManagers.DataSource = null; fileManagersList.RemoveAt(index); listBoxFileManagers.DataSource = fileManagersList; listBoxFileManagers.DisplayMember = "FilenamePattern"; // this will create the default object if it is not present GetDefaultFileManagerObject(); SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Removes all file managers /// </summary> public void RemoveAllFileManagers() { optionsChanged = true; // cannot remove when datasource is set listBoxFileManagers.DataSource = null; fileManagersList.Clear(); listBoxFileManagers.DataSource = fileManagersList; listBoxFileManagers.DisplayMember = "FilenamePattern"; // this will create the default object if it is not present GetDefaultFileManagerObject(); SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Adds a new file manager /// </summary> public void AddNewFileManager() { // ask the user what type of file manager they would like to use frmFileManagerChooser optChooser = new frmFileManagerChooser(GetDefaultFileManagerObject()); // this is modal optChooser.ShowDialog(); if (optChooser.DialogResult != DialogResult.OK) return; if (optChooser.OutputFileManagerObject == null) return; AddFileManager(optChooser.OutputFileManagerObject); // select the newly added item int index = GetIndexForFileManagersObject(optChooser.OutputFileManagerObject); listBoxFileManagers.SelectedIndex = index; SyncButtonStates(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Builds and returns a default file manager for a specified file extension /// </summary> /// <param name="fileExt">the file extension</param> /// <param name="addItToDisplay">true, add to the display, false, do not add</param> /// <param name="opMode">the operation mode of the file manager to create</param> public FileManager GetDefaultFileManagerForExtension(string fileExt, FileManager.OperationModeEnum opMode, bool addItToDisplay) { FileManager mgrObject = null; if ((fileExt==null) || (fileExt.Length==0)) return null; // get a default file manager mgrObject = GetDefaultFileManagerObject(); mgrObject.OperationMode = opMode; mgrObject.FilenamePattern = fileExt; // add it, if required if (addItToDisplay == true) { AddFileManager(mgrObject); } return mgrObject; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Handles a click on the add button /// </summary> private void buttonAdd_Click(object sender, EventArgs e) { AddNewFileManager(); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Syncs the remove button enabled or disabled state /// </summary> private void SyncButtonStates() { if (fileManagersList.Count() == 0) { buttonRemove.Enabled = false; } else { buttonRemove.Enabled = true; } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Syncs the enabled state of the control. This is the overall enabled/disabled /// state of the control. We are disabled when a file is open /// </summary> /// <param name="ctrlEnabledState">the enabled state for the control</param> public void SyncEnabledState(bool ctrlEnabledState) { // these stay enabled //labelFileManagers.Enabled = ctrlEnabledState; //labelFileManagerProperties.Enabled = ctrlEnabledState; //listBoxFileManagers.Enabled = ctrlEnabledState; propertyGridFileManager.Enabled = ctrlEnabledState; buttonAdd.Enabled = ctrlEnabledState; buttonRemove.Enabled = ctrlEnabledState; buttonRemoveAll.Enabled = ctrlEnabledState; buttonReset.Enabled = ctrlEnabledState; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Sets the readonly state of the properties so the user can only adjust /// the ones appropriate to the current operation mode /// </summary> private void SetPropertyStateAppropriateToOperationMode(FileManager optObject) { bool isoCutROState = false; bool edgeMillROState = false; bool excellonROState = false; // bool textLabelROState = false; if (optObject == null) return; // IMPORTANT NOTE: this function will attempt to make certain // options readonly based on the setting of the current operation mode // in the FileManagers object. If each and every property in the FileManagers // object does not have a [ReadOnlyAttribute(false)] attribute set on it then // the act of setting one property to readonly will mark them ALL as readonly. // So make sure each property in the FileManagers object has a // [ReadOnlyAttribute(false)] attribute whether it needs it or not!!! switch (optObject.OperationMode) { case FileManager.OperationModeEnum.IsolationCut: isoCutROState = false; edgeMillROState = true; excellonROState = true; // textLabelROState = true; break; case FileManager.OperationModeEnum.BoardEdgeMill: isoCutROState = true; edgeMillROState = false; excellonROState = true; //textLabelROState = true; break; case FileManager.OperationModeEnum.TextAndLabels: isoCutROState = true; edgeMillROState = true; excellonROState = true; // textLabelROState = false; break; case FileManager.OperationModeEnum.Excellon: isoCutROState = true; edgeMillROState = true; excellonROState = false; // textLabelROState = false; break; default: isoCutROState = false; edgeMillROState = false; excellonROState = false; // textLabelROState = false; break; } // isocut SetPropertyBrowsableState(optObject, "IsoGCodeFileOutputExtension", isoCutROState); SetPropertyBrowsableState(optObject, "IsoFlipMode", isoCutROState); SetPropertyBrowsableState(optObject, "IsoZCutLevel", isoCutROState); SetPropertyBrowsableState(optObject, "IsoZMoveLevel", isoCutROState); SetPropertyBrowsableState(optObject, "IsoZClearLevel", isoCutROState); SetPropertyBrowsableState(optObject, "IsoZFeedRate", isoCutROState); SetPropertyBrowsableState(optObject, "IsoXYFeedRate", isoCutROState); SetPropertyBrowsableState(optObject, "IsoCutWidth", isoCutROState); SetPropertyBrowsableState(optObject, "IsoPadTouchDownsWanted", isoCutROState); SetPropertyBrowsableState(optObject, "IsoPadTouchDownZLevel", isoCutROState); SetPropertyBrowsableState(optObject, "IsoCutGCodeEnabled", isoCutROState); // edge mill SetPropertyBrowsableState(optObject, "EdgeMillGCodeFileOutputExtension", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillZCutLevel", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillZMoveLevel", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillZClearLevel", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillZFeedRate", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillXYFeedRate", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillCutWidth", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillingGCodeEnabled", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillNumTabs", edgeMillROState); SetPropertyBrowsableState(optObject, "EdgeMillTabWidth", edgeMillROState); // bed flattening SetPropertyBrowsableState(optObject, "BedFlatteningSizeMode", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningSizeX", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningSizeY", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningGCodeEnabled", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningGCodeFileOutputExtension", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningZCutLevel", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningZClearLevel", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningZFeedRate", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningXYFeedRate", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningMillWidth", edgeMillROState); SetPropertyBrowsableState(optObject, "BedFlatteningMargin", edgeMillROState); // reference pins SetPropertyBrowsableState(optObject, "ReferencePinGCodeEnabled", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsGCodeFileOutputExtension", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsZDrillDepth", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsZClearLevel", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsZFeedRate", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsXYFeedRate", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinsMaxNumber", isoCutROState); SetPropertyBrowsableState(optObject, "ReferencePinPadDiameter", isoCutROState); // excellon SetPropertyBrowsableState(optObject, "DrillingCoordinateZerosMode", excellonROState); SetPropertyBrowsableState(optObject, "DrillingNumberOfDecimalPlaces", excellonROState); SetPropertyBrowsableState(optObject, "DrillingGCodeFileOutputExtension", excellonROState); SetPropertyBrowsableState(optObject, "DrillingZDepth", excellonROState); SetPropertyBrowsableState(optObject, "DrillingZClearLevel", excellonROState); SetPropertyBrowsableState(optObject, "DrillingZFeedRate", excellonROState); SetPropertyBrowsableState(optObject, "DrillingXYFeedRate", excellonROState); SetPropertyBrowsableState(optObject, "DrillingGCodeEnabled", excellonROState); // text and labels return; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Sets the readonly attribute on a property so the user cannot adjust if if /// it is not appropriate to the current operation mode /// </summary> /// <remarks> /// Credits: the basic mechanisim for performing this operation is derived /// from: http://www.codeproject.com/KB/tabs/ExploringPropertyGrid.aspx</remarks> private void SetPropertyReadOnlyState(FileManager fileManagersObj, string propertyName, bool readOnlyState) { if (fileManagersObj == null) return; if ((propertyName == null) || (propertyName.Length == 0)) return; PropertyDescriptor descriptor = TypeDescriptor.GetProperties(fileManagersObj.GetType())[propertyName]; ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)]; FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance); isReadOnly.SetValue(attrib, readOnlyState); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Sets the readonly attribute on a property so the user cannot adjust if if /// it is not appropriate to the current operation mode /// </summary> /// <remarks> /// Credits: the basic mechanisim for performing this operation is derived /// from: http://www.codeproject.com/KB/tabs/ExploringPropertyGrid.aspx</remarks> private void SetPropertyBrowsableState(FileManager fileManagersObj, string propertyName, bool isNonBrowsable) { bool wantBrowsable; if (fileManagersObj == null) return; if ((propertyName == null) || (propertyName.Length == 0)) return; if (isNonBrowsable == true) wantBrowsable = false; else wantBrowsable = true; PropertyDescriptor descriptor = TypeDescriptor.GetProperties(fileManagersObj.GetType())[propertyName]; BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; FieldInfo browsable = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance); browsable.SetValue(attrib, wantBrowsable); } } }
48.526814
241
0.555646
[ "MIT" ]
OfItselfSo/LineGrinder
LineGrinder - Source/ctlFileManagerDisplay.cs
30,791
C#
using System; using System.Collections.Generic; using System.DirectoryServices.Protocols; namespace Application.Models { public class ConnectionInformation : IConnectionInformation { #region Properties public virtual IList<string> Attributes { get; } = new List<string>(); public virtual AuthType? AuthenticationType { get; set; } public virtual TimeSpan Duration { get; set; } public virtual string Filter { get; set; } public virtual int? Port { get; set; } public virtual int ProtocolVersion { get; set; } public virtual string RootDistinguishedName { get; set; } public virtual IList<string> Servers { get; } = new List<string>(); public virtual TimeSpan Timeout { get; set; } #endregion } }
31.434783
72
0.737206
[ "MIT" ]
HansKindberg/Ldap-Code-Tool
Source/Application/Models/ConnectionInformation.cs
723
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Text; namespace System.Management.Automation { /// <summary> /// This is the interface between the CommandProcessor and the various /// parameter binders required to bind parameters to a cmdlet. /// </summary> internal class CmdletParameterBinderController : ParameterBinderController { #region tracer [TraceSource("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s).")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderController", "Controls the interaction between the command processor and the parameter binder(s)."); #endregion tracer #region ctor /// <summary> /// Initializes the cmdlet parameter binder controller for /// the specified cmdlet and engine context. /// </summary> /// <param name="cmdlet"> /// The cmdlet that the parameters will be bound to. /// </param> /// <param name="commandMetadata"> /// The metadata about the cmdlet. /// </param> /// <param name="parameterBinder"> /// The default parameter binder to use. /// </param> internal CmdletParameterBinderController( Cmdlet cmdlet, CommandMetadata commandMetadata, ParameterBinderBase parameterBinder) : base( cmdlet.MyInvocation, cmdlet.Context, parameterBinder) { if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetadata"); } this.Command = cmdlet; _commandRuntime = (MshCommandRuntime)cmdlet.CommandRuntime; _commandMetadata = commandMetadata; // Add the static parameter metadata to the bindable parameters // And add them to the unbound parameters list if (commandMetadata.ImplementsDynamicParameters) { // ReplaceMetadata makes a copy for us, so we can use that collection as is. this.UnboundParameters = this.BindableParameters.ReplaceMetadata(commandMetadata.StaticCommandParameterMetadata); } else { _bindableParameters = commandMetadata.StaticCommandParameterMetadata; // Must make a copy of the list because we'll modify it. this.UnboundParameters = new List<MergedCompiledCommandParameter>(_bindableParameters.BindableParameters.Values); } } #endregion ctor #region helper_methods /// <summary> /// Binds the specified command-line parameters to the target. /// </summary> /// <param name="arguments"> /// Parameters to the command. /// </param> /// <exception cref="ParameterBindingException"> /// If any parameters fail to bind, /// or /// If any mandatory parameters are missing. /// </exception> /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> internal void BindCommandLineParameters(Collection<CommandParameterInternal> arguments) { s_tracer.WriteLine("Argument count: {0}", arguments.Count); BindCommandLineParametersNoValidation(arguments); // Is pipeline input expected? bool isPipelineInputExpected = !(_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty); int validParameterSetCount; if (!isPipelineInputExpected) { // Since pipeline input is not expected, ensure that we have a single // parameter set and that all the mandatory // parameters for the working parameter set are specified, or prompt validParameterSetCount = ValidateParameterSets(false, true); } else { // Use ValidateParameterSets to get the number of valid parameter // sets. // NTRAID#Windows Out Of Band Releases-2005/11/07-923917-JonN validParameterSetCount = ValidateParameterSets(true, false); } // If the parameter set is determined and the default parameters are not used // we try the default parameter binding again because it may contain some mandatory // parameters if (validParameterSetCount == 1 && !DefaultParameterBindingInUse) { ApplyDefaultParameterBinding("Mandatory Checking", false); } // If there are multiple valid parameter sets and we are expecting pipeline inputs, // we should filter out those parameter sets that cannot take pipeline inputs anymore. if (validParameterSetCount > 1 && isPipelineInputExpected) { uint filteredValidParameterSetFlags = FilterParameterSetsTakingNoPipelineInput(); if (filteredValidParameterSetFlags != _currentParameterSetFlag) { _currentParameterSetFlag = filteredValidParameterSetFlags; // The valid parameter set flag is narrowed down, we get the new validParameterSetCount validParameterSetCount = ValidateParameterSets(true, false); } } using (ParameterBinderBase.bindingTracer.TraceScope( "MANDATORY PARAMETER CHECK on cmdlet [{0}]", _commandMetadata.Name)) { try { // The missingMandatoryParameters out parameter is used for error reporting when binding from the pipeline. // We're not binding from the pipeline here, and if a mandatory non-pipeline parameter is missing, it will // be prompted for, or an exception will be raised, so we can ignore the missingMandatoryParameters out parameter. Collection<MergedCompiledCommandParameter> missingMandatoryParameters; // We shouldn't prompt for mandatory parameters if this command is private. bool promptForMandatoryParameters = (Command.CommandInfo.Visibility == SessionStateEntryVisibility.Public); HandleUnboundMandatoryParameters(validParameterSetCount, true, promptForMandatoryParameters, isPipelineInputExpected, out missingMandatoryParameters); if (DefaultParameterBinder is ScriptParameterBinder) { BindUnboundScriptParameters(); } } catch (ParameterBindingException pbex) { if (!DefaultParameterBindingInUse) { throw; } ThrowElaboratedBindingException(pbex); } } // If there is no more expected input, ensure there is a single // parameter set selected if (!isPipelineInputExpected) { VerifyParameterSetSelected(); } // Set the prepipeline parameter set flags so that they can be restored // between each pipeline object. _prePipelineProcessingParameterSetFlags = _currentParameterSetFlag; } /// <summary> /// Binds the unbound arguments to parameters but does not /// perform mandatory parameter validation or parameter set validation. /// </summary> internal void BindCommandLineParametersNoValidation(Collection<CommandParameterInternal> arguments) { var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; if (psCompiledScriptCmdlet != null) { psCompiledScriptCmdlet.PrepareForBinding(this.CommandLineParameters); } // Add the passed in arguments to the unboundArguments collection foreach (CommandParameterInternal argument in arguments) { UnboundArguments.Add(argument); } CommandMetadata cmdletMetadata = _commandMetadata; // Clear the warningSet at the beginning. _warningSet.Clear(); // Parse $PSDefaultParameterValues to get all valid <parameter, value> pairs _allDefaultParameterValuePairs = this.GetDefaultParameterValuePairs(true); // Set to false at the beginning DefaultParameterBindingInUse = false; // Clear the bound default parameters at the beginning BoundDefaultParameters.Clear(); // Reparse the arguments based on the merged metadata ReparseUnboundArguments(); using (ParameterBinderBase.bindingTracer.TraceScope( "BIND NAMED cmd line args [{0}]", _commandMetadata.Name)) { // Bind the actual arguments UnboundArguments = BindParameters(_currentParameterSetFlag, this.UnboundArguments); } ParameterBindingException reportedBindingException; ParameterBindingException currentBindingException; using (ParameterBinderBase.bindingTracer.TraceScope( "BIND POSITIONAL cmd line args [{0}]", _commandMetadata.Name)) { // Now that we know the parameter set, bind the positional parameters UnboundArguments = BindPositionalParameters( UnboundArguments, _currentParameterSetFlag, cmdletMetadata.DefaultParameterSetFlag, out currentBindingException); reportedBindingException = currentBindingException; } // Try applying the default parameter binding after POSITIONAL BIND so that the default parameter // values can influence the parameter set selection earlier than the default parameter set. ApplyDefaultParameterBinding("POSITIONAL BIND", false); // We need to make sure there is at least one valid parameter set. Its // OK to allow more than one as long as one of them takes pipeline input. // NTRAID#Windows Out Of Band Releases-2006/02/14-928660-JonN // Pipeline input fails to bind to pipeline enabled parameter // second parameter changed from true to false ValidateParameterSets(true, false); // Always get the dynamic parameters as there may be mandatory parameters there // Now try binding the dynamic parameters HandleCommandLineDynamicParameters(out currentBindingException); // Try binding the default parameters again. After dynamic binding, new parameter metadata are // included, so it's possible a previously unsuccessful binding will succeed. ApplyDefaultParameterBinding("DYNAMIC BIND", true); // If this generated an exception (but we didn't have one from the non-dynamic // parameters, report on this one. if (reportedBindingException == null) reportedBindingException = currentBindingException; // If the cmdlet implements a ValueFromRemainingArguments parameter (VarArgs) // bind the unbound arguments to that parameter. HandleRemainingArguments(); VerifyArgumentsProcessed(reportedBindingException); } /// <summary> /// Process all valid parameter sets, and filter out those that don't take any pipeline input. /// </summary> /// <returns> /// The new valid parameter set flags /// </returns> private uint FilterParameterSetsTakingNoPipelineInput() { uint parameterSetsTakingPipeInput = 0; bool findPipeParameterInAllSets = false; foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> entry in _delayBindScriptBlocks) { parameterSetsTakingPipeInput |= entry.Key.Parameter.ParameterSetFlags; } foreach (MergedCompiledCommandParameter parameter in UnboundParameters) { // If a parameter doesn't take pipeline input at all, we can skip it if (!parameter.Parameter.IsPipelineParameterInSomeParameterSet) { continue; } var matchingParameterSetMetadata = parameter.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag); foreach (ParameterSetSpecificMetadata parameterSetMetadata in matchingParameterSetMetadata) { if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName) { if (parameterSetMetadata.ParameterSetFlag == 0 && parameterSetMetadata.IsInAllSets) { // The parameter takes pipeline input and is in all sets, we don't change the _currentParameterSetFlag parameterSetsTakingPipeInput = 0; findPipeParameterInAllSets = true; break; } else { parameterSetsTakingPipeInput |= parameterSetMetadata.ParameterSetFlag; } } } if (findPipeParameterInAllSets) break; } // If parameterSetsTakingPipeInput is 0, then no parameter set from the _currentParameterSetFlag can take piped objects. // Then we just leave what it was, and the pipeline binding deal with the error later if (parameterSetsTakingPipeInput != 0) return _currentParameterSetFlag & parameterSetsTakingPipeInput; else return _currentParameterSetFlag; } /// <summary> /// Apply the binding for the default parameter defined by the user. /// </summary> /// <param name="bindingStage"> /// Dictate which binding stage this default binding happens /// </param> /// <param name="isDynamic"> /// Special operation needed if the default binding happens at the dynamic binding stage /// </param> /// <returns></returns> private void ApplyDefaultParameterBinding(string bindingStage, bool isDynamic) { if (!_useDefaultParameterBinding) { return; } if (isDynamic) { // Get user defined default parameter value pairs again, so that the // dynamic parameter value pairs could be involved. _allDefaultParameterValuePairs = GetDefaultParameterValuePairs(false); } Dictionary<MergedCompiledCommandParameter, object> qualifiedParameterValuePairs = GetQualifiedParameterValuePairs(_currentParameterSetFlag, _allDefaultParameterValuePairs); if (qualifiedParameterValuePairs != null) { bool isSuccess = false; using (ParameterBinderBase.bindingTracer.TraceScope( "BIND DEFAULT <parameter, value> pairs after [{0}] for [{1}]", bindingStage, _commandMetadata.Name)) { isSuccess = BindDefaultParameters(_currentParameterSetFlag, qualifiedParameterValuePairs); if (isSuccess && !DefaultParameterBindingInUse) { DefaultParameterBindingInUse = true; } } s_tracer.WriteLine("BIND DEFAULT after [{0}] result [{1}]", bindingStage, isSuccess); } return; } /// <summary> /// Bind the default parameter value pairs. /// </summary> /// <param name="validParameterSetFlag">ValidParameterSetFlag.</param> /// <param name="defaultParameterValues">Default value pairs.</param> /// <returns> /// true if there is at least one default parameter bound successfully /// false if there is no default parameter bound successfully /// </returns> private bool BindDefaultParameters(uint validParameterSetFlag, Dictionary<MergedCompiledCommandParameter, object> defaultParameterValues) { bool ret = false; foreach (var pair in defaultParameterValues) { MergedCompiledCommandParameter parameter = pair.Key; object argumentValue = pair.Value; string parameterName = parameter.Parameter.Name; try { ScriptBlock scriptBlockArg = argumentValue as ScriptBlock; if (scriptBlockArg != null) { // Get the current binding state, and pass it to the ScriptBlock as the argument // The 'arg' includes HashSet properties 'BoundParameters', 'BoundPositionalParameters', // 'BoundDefaultParameters', and 'LastBindingStage'. So the user can set value // to a parameter depending on the current binding state. PSObject arg = WrapBindingState(); Collection<PSObject> results = scriptBlockArg.Invoke(arg); if (results == null || results.Count == 0) { continue; } else if (results.Count == 1) { argumentValue = results[0]; } else { argumentValue = results; } } CommandParameterInternal bindableArgument = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, parameterName, "-" + parameterName + ":", /*argumentAst*/null, argumentValue, false); bool bindResult = BindParameter( validParameterSetFlag, bindableArgument, parameter, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock); if (bindResult && !ret) { ret = true; } if (bindResult) { BoundDefaultParameters.Add(parameterName); } } catch (ParameterBindingException ex) { // We don't want the failures in default binding affect the command line binding, // so we write out a warning and ignore this binding failure if (!_warningSet.Contains(_commandMetadata.Name + Separator + parameterName)) { string message = string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.FailToBindDefaultParameter, LanguagePrimitives.IsNull(argumentValue) ? "null" : argumentValue.ToString(), parameterName, ex.Message); _commandRuntime.WriteWarning(message); _warningSet.Add(_commandMetadata.Name + Separator + parameterName); } continue; } } return ret; } /// <summary> /// Wrap up current binding state to provide more information to the user. /// </summary> /// <returns></returns> private PSObject WrapBindingState() { HashSet<string> boundParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HashSet<string> boundPositionalParameterNames = this.DefaultParameterBinder.CommandLineParameters.CopyBoundPositionalParameters(); HashSet<string> boundDefaultParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string paramName in BoundParameters.Keys) { boundParameterNames.Add(paramName); } foreach (string paramName in BoundDefaultParameters) { boundDefaultParameterNames.Add(paramName); } PSObject result = new PSObject(); result.Properties.Add(new PSNoteProperty("BoundParameters", boundParameterNames)); result.Properties.Add(new PSNoteProperty("BoundPositionalParameters", boundPositionalParameterNames)); result.Properties.Add(new PSNoteProperty("BoundDefaultParameters", boundDefaultParameterNames)); return result; } /// <summary> /// Get all qualified default parameter value pairs based on the /// given currentParameterSetFlag. /// </summary> /// <param name="currentParameterSetFlag"></param> /// <param name="availableParameterValuePairs"></param> /// <returns>Null if no qualified pair found.</returns> private Dictionary<MergedCompiledCommandParameter, object> GetQualifiedParameterValuePairs( uint currentParameterSetFlag, Dictionary<MergedCompiledCommandParameter, object> availableParameterValuePairs) { if (availableParameterValuePairs == null) { return null; } Dictionary<MergedCompiledCommandParameter, object> result = new Dictionary<MergedCompiledCommandParameter, object>(); uint possibleParameterFlag = uint.MaxValue; foreach (var pair in availableParameterValuePairs) { MergedCompiledCommandParameter param = pair.Key; if ((param.Parameter.ParameterSetFlags & currentParameterSetFlag) == 0 && !param.Parameter.IsInAllSets) { continue; } if (BoundArguments.ContainsKey(param.Parameter.Name)) { continue; } // check if this param's set conflicts with other possible params. if (param.Parameter.ParameterSetFlags != 0) { possibleParameterFlag &= param.Parameter.ParameterSetFlags; if (possibleParameterFlag == 0) { return null; } } result.Add(param, pair.Value); } if (result.Count > 0) { return result; } return null; } /// <summary> /// Get the aliases of the the current cmdlet. /// </summary> /// <returns></returns> private List<string> GetAliasOfCurrentCmdlet() { var results = Context.SessionState.Internal.GetAliasesByCommandName(_commandMetadata.Name).ToList(); return results.Count > 0 ? results : null; } /// <summary> /// Check if the passed-in aliasName matches an alias name in _aliasList. /// </summary> /// <param name="aliasName"></param> /// <returns></returns> private bool MatchAnyAlias(string aliasName) { if (_aliasList == null) { return false; } bool result = false; WildcardPattern aliasPattern = WildcardPattern.Get(aliasName, WildcardOptions.IgnoreCase); foreach (string alias in _aliasList) { if (aliasPattern.IsMatch(alias)) { result = true; break; } } return result; } internal IDictionary DefaultParameterValues { get; set; } /// <summary> /// Get all available default parameter value pairs. /// </summary> /// <returns>Return the available parameter value pairs. Otherwise return null.</returns> private Dictionary<MergedCompiledCommandParameter, object> GetDefaultParameterValuePairs(bool needToGetAlias) { if (DefaultParameterValues == null) { _useDefaultParameterBinding = false; return null; } var availablePairs = new Dictionary<MergedCompiledCommandParameter, object>(); if (needToGetAlias && DefaultParameterValues.Count > 0) { // Get all aliases of the current cmdlet _aliasList = GetAliasOfCurrentCmdlet(); } // Set flag to true by default _useDefaultParameterBinding = true; string currentCmdletName = _commandMetadata.Name; IDictionary<string, MergedCompiledCommandParameter> bindableParameters = BindableParameters.BindableParameters; IDictionary<string, MergedCompiledCommandParameter> bindableAlias = BindableParameters.AliasedParameters; // Contains parameters that are set with different values by settings in $PSDefaultParameterValues. // We should ignore those settings and write out a warning var parametersToRemove = new HashSet<MergedCompiledCommandParameter>(); var wildcardDefault = new Dictionary<string, object>(); // Contains keys that are in bad format. For every bad format key, we should write out a warning message // the first time we encounter it, and remove it from the $PSDefaultParameterValues var keysToRemove = new List<object>(); foreach (DictionaryEntry entry in DefaultParameterValues) { string key = entry.Key as string; if (key == null) { continue; } key = key.Trim(); string cmdletName = null; string parameterName = null; // The key is not in valid format if (!DefaultParameterDictionary.CheckKeyIsValid(key, ref cmdletName, ref parameterName)) { if (key.Equals("Disabled", StringComparison.OrdinalIgnoreCase) && LanguagePrimitives.IsTrue(entry.Value)) { _useDefaultParameterBinding = false; return null; } // Write out a warning message if the key is not 'Disabled' if (!key.Equals("Disabled", StringComparison.OrdinalIgnoreCase)) { keysToRemove.Add(entry.Key); } continue; } Diagnostics.Assert(cmdletName != null && parameterName != null, "The cmdletName and parameterName should be set in CheckKeyIsValid"); if (WildcardPattern.ContainsWildcardCharacters(key)) { wildcardDefault.Add(cmdletName + Separator + parameterName, entry.Value); continue; } // Continue to process this entry only if the specified cmdletName is the name // of the current cmdlet, or is an alias name of the current cmdlet. if (!cmdletName.Equals(currentCmdletName, StringComparison.OrdinalIgnoreCase) && !MatchAnyAlias(cmdletName)) { continue; } GetDefaultParameterValuePairsHelper( cmdletName, parameterName, entry.Value, bindableParameters, bindableAlias, availablePairs, parametersToRemove); } foreach (KeyValuePair<string, object> wildcard in wildcardDefault) { string key = wildcard.Key; string cmdletName = key.Substring(0, key.IndexOf(Separator, StringComparison.OrdinalIgnoreCase)); string parameterName = key.Substring(key.IndexOf(Separator, StringComparison.OrdinalIgnoreCase) + Separator.Length); WildcardPattern cmdletPattern = WildcardPattern.Get(cmdletName, WildcardOptions.IgnoreCase); // Continue to process this entry only if the cmdletName matches the name of the current // cmdlet, or matches an alias name of the current cmdlet if (!cmdletPattern.IsMatch(currentCmdletName) && !MatchAnyAlias(cmdletName)) { continue; } if (!WildcardPattern.ContainsWildcardCharacters(parameterName)) { GetDefaultParameterValuePairsHelper( cmdletName, parameterName, wildcard.Value, bindableParameters, bindableAlias, availablePairs, parametersToRemove); continue; } WildcardPattern parameterPattern = MemberMatch.GetNamePattern(parameterName); var matches = new List<MergedCompiledCommandParameter>(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in bindableParameters) { if (parameterPattern.IsMatch(entry.Key)) { matches.Add(entry.Value); } } foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in bindableAlias) { if (parameterPattern.IsMatch(entry.Key)) { matches.Add(entry.Value); } } if (matches.Count > 1) { // The parameterPattern matches more than one parameters, so we write out a warning message and ignore this setting if (!_warningSet.Contains(cmdletName + Separator + parameterName)) { _commandRuntime.WriteWarning( string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.MultipleParametersMatched, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } continue; } if (matches.Count == 1) { if (!availablePairs.ContainsKey(matches[0])) { availablePairs.Add(matches[0], wildcard.Value); continue; } if (!wildcard.Value.Equals(availablePairs[matches[0]])) { if (!_warningSet.Contains(cmdletName + Separator + parameterName)) { _commandRuntime.WriteWarning( string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, parameterName)); _warningSet.Add(cmdletName + Separator + parameterName); } parametersToRemove.Add(matches[0]); } } } if (keysToRemove.Count > 0) { var keysInError = new StringBuilder(); foreach (object badFormatKey in keysToRemove) { if (DefaultParameterValues.Contains(badFormatKey)) DefaultParameterValues.Remove(badFormatKey); keysInError.Append(badFormatKey.ToString() + ", "); } keysInError.Remove(keysInError.Length - 2, 2); var multipleKeys = keysToRemove.Count > 1; string formatString = multipleKeys ? ParameterBinderStrings.MultipleKeysInBadFormat : ParameterBinderStrings.SingleKeyInBadFormat; _commandRuntime.WriteWarning( string.Format(CultureInfo.InvariantCulture, formatString, keysInError)); } foreach (MergedCompiledCommandParameter param in parametersToRemove) { availablePairs.Remove(param); } if (availablePairs.Count > 0) { return availablePairs; } return null; } /// <summary> /// A helper method for GetDefaultParameterValuePairs. /// </summary> /// <param name="cmdletName"></param> /// <param name="paramName"></param> /// <param name="paramValue"></param> /// <param name="bindableParameters"></param> /// <param name="bindableAlias"></param> /// <param name="result"></param> /// <param name="parametersToRemove"></param> private void GetDefaultParameterValuePairsHelper( string cmdletName, string paramName, object paramValue, IDictionary<string, MergedCompiledCommandParameter> bindableParameters, IDictionary<string, MergedCompiledCommandParameter> bindableAlias, Dictionary<MergedCompiledCommandParameter, object> result, HashSet<MergedCompiledCommandParameter> parametersToRemove) { // No exception should be thrown if we cannot find a match for the 'paramName', // because the 'paramName' could be a dynamic parameter name, and this dynamic parameter // hasn't been introduced at the current stage. bool writeWarning = false; MergedCompiledCommandParameter matchParameter; object resultObject; if (bindableParameters.TryGetValue(paramName, out matchParameter)) { if (!result.TryGetValue(matchParameter, out resultObject)) { result.Add(matchParameter, paramValue); return; } if (!paramValue.Equals(resultObject)) { writeWarning = true; parametersToRemove.Add(matchParameter); } } else { if (bindableAlias.TryGetValue(paramName, out matchParameter)) { if (!result.TryGetValue(matchParameter, out resultObject)) { result.Add(matchParameter, paramValue); return; } if (!paramValue.Equals(resultObject)) { writeWarning = true; parametersToRemove.Add(matchParameter); } } } if (writeWarning && !_warningSet.Contains(cmdletName + Separator + paramName)) { _commandRuntime.WriteWarning( string.Format(CultureInfo.InvariantCulture, ParameterBinderStrings.DifferentValuesAssignedToSingleParameter, paramName)); _warningSet.Add(cmdletName + Separator + paramName); } } /// <summary> /// Verify if all arguments from the command line are bound. /// </summary> /// <param name="originalBindingException"> /// Previous binding exceptions that possibly causes the failure /// </param> private void VerifyArgumentsProcessed(ParameterBindingException originalBindingException) { // Now verify that all the arguments that were passed in were processed. if (UnboundArguments.Count > 0) { ParameterBindingException bindingException; CommandParameterInternal parameter = UnboundArguments[0]; // Get the argument type that was specified Type specifiedType = null; object argumentValue = parameter.ArgumentValue; if (argumentValue != null && argumentValue != UnboundParameter.Value) { specifiedType = argumentValue.GetType(); } if (parameter.ParameterNameSpecified) { bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, GetParameterErrorExtent(parameter), parameter.ParameterName, null, specifiedType, ParameterBinderStrings.NamedParameterNotFound, "NamedParameterNotFound"); } else { // If this was a positional parameter, and we have the original exception, // report on the original error if (originalBindingException != null) { bindingException = originalBindingException; } // Otherwise, give a generic error. else { string argument = StringLiterals.DollarNull; if (parameter.ArgumentValue != null) { try { argument = parameter.ArgumentValue.ToString(); } catch (Exception e) { bindingException = new ParameterBindingArgumentTransformationException( e, ErrorCategory.InvalidData, this.InvocationInfo, null, null, null, parameter.ArgumentValue.GetType(), ParameterBinderStrings.ParameterArgumentTransformationErrorMessageOnly, "ParameterArgumentTransformationErrorMessageOnly", e.Message); if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } } } bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, argument, null, specifiedType, ParameterBinderStrings.PositionalParameterNotFound, "PositionalParameterNotFound"); } } if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } } } /// <summary> /// Verifies that a single parameter set is selected and throws an exception if /// one of there are multiple and one of them is not the default parameter set. /// </summary> private void VerifyParameterSetSelected() { // Now verify that a parameter set has been selected if any parameter sets // were defined. if (this.BindableParameters.ParameterSetCount > 1) { if (_currentParameterSetFlag == uint.MaxValue) { if ((_currentParameterSetFlag & _commandMetadata.DefaultParameterSetFlag) != 0 && _commandMetadata.DefaultParameterSetFlag != uint.MaxValue) { ParameterBinderBase.bindingTracer.WriteLine( "{0} valid parameter sets, using the DEFAULT PARAMETER SET: [{0}]", this.BindableParameters.ParameterSetCount.ToString(), _commandMetadata.DefaultParameterSetName); _currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; } else { ParameterBinderBase.bindingTracer.TraceError( "ERROR: {0} valid parameter sets, but NOT DEFAULT PARAMETER SET.", this.BindableParameters.ParameterSetCount); // Throw an exception for ambiguous parameter set ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } } } } /// <summary> /// Restores the specified parameter to the original value. /// </summary> /// <param name="argumentToBind"> /// The argument containing the value to restore. /// </param> /// <param name="parameter"> /// The metadata for the parameter to restore. /// </param> /// <returns> /// True if the parameter was restored correctly, or false otherwise. /// </returns> private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCompiledCommandParameter parameter) { switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: DefaultParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.CommonParameters: CommonParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); ShouldProcessParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); PagingParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( _commandMetadata.SupportsTransactions, "The metadata for the TransactionParameters should only be available if the command supports Transactions"); TransactionParametersBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) { _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); } break; } return true; } /// <summary> /// Binds the actual arguments to only the formal parameters /// for only the parameters in the specified parameter set. /// </summary> /// <param name="parameterSets"> /// The parameter set used to bind the arguments. /// </param> /// <param name="arguments"> /// The arguments that should be attempted to bind to the parameters of the specified /// parameter binder. /// </param> /// <exception cref="ParameterBindingException"> /// if multiple parameters are found matching the name. /// or /// if no match could be found. /// or /// If argument transformation fails. /// or /// The argument could not be coerced to the appropriate type for the parameter. /// or /// The parameter argument transformation, prerequisite, or validation failed. /// or /// If the binding to the parameter fails. /// </exception> private Collection<CommandParameterInternal> BindParameters(uint parameterSets, Collection<CommandParameterInternal> arguments) { Collection<CommandParameterInternal> result = new Collection<CommandParameterInternal>(); foreach (CommandParameterInternal argument in arguments) { if (!argument.ParameterNameSpecified) { result.Add(argument); continue; } // We don't want to throw an exception yet because // the parameter might be a positional argument or it // might match up to a dynamic parameter MergedCompiledCommandParameter parameter = BindableParameters.GetMatchingParameter( argument.ParameterName, false, true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); // If the parameter is not in the specified parameter set, // throw a binding exception if (parameter != null) { // Now check to make sure it hasn't already been // bound by looking in the boundParameters collection if (BoundParameters.ContainsKey(parameter.Parameter.Name)) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.InvocationInfo, GetParameterErrorExtent(argument), argument.ParameterName, null, null, ParameterBinderStrings.ParameterAlreadyBound, nameof(ParameterBinderStrings.ParameterAlreadyBound)); // Multiple values assigned to the same parameter. // Not caused by default parameter binding throw bindingException; } if ((parameter.Parameter.ParameterSetFlags & parameterSets) == 0 && !parameter.Parameter.IsInAllSets) { string parameterSetName = BindableParameters.GetParameterSetName(parameterSets); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, argument.ParameterName, null, null, ParameterBinderStrings.ParameterNotInParameterSet, "ParameterNotInParameterSet", parameterSetName); // Might be caused by default parameter binding if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } } try { BindParameter(parameterSets, argument, parameter, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.DelayBindScriptBlock); } catch (ParameterBindingException pbex) { if (!DefaultParameterBindingInUse) { throw; } ThrowElaboratedBindingException(pbex); } } else if (argument.ParameterName.Equals(Parser.VERBATIM_PARAMETERNAME, StringComparison.Ordinal)) { // We sometimes send a magic parameter from a remote machine with the values referenced via // a using expression ($using:x). We then access these values via PSBoundParameters, so // "bind" them here. DefaultParameterBinder.CommandLineParameters.SetImplicitUsingParameters(argument.ArgumentValue); } else { result.Add(argument); } } return result; } /// <summary> /// Determines if a ScriptBlock can be bound directly to the type of the specified parameter. /// </summary> /// <param name="parameter"> /// The metadata of the parameter to check the type of. /// </param> /// <returns> /// true if the parameter type is Object, ScriptBlock, derived from ScriptBlock, a /// collection of ScriptBlocks, a collection of Objects, or a collection of types derived from /// ScriptBlock. /// False otherwise. /// </returns> private static bool IsParameterScriptBlockBindable(MergedCompiledCommandParameter parameter) { bool result = false; Type parameterType = parameter.Parameter.Type; do // false loop { if (parameterType == typeof(object)) { result = true; break; } if (parameterType == typeof(ScriptBlock)) { result = true; break; } if (parameterType.IsSubclassOf(typeof(ScriptBlock))) { result = true; break; } ParameterCollectionTypeInformation parameterCollectionTypeInfo = parameter.Parameter.CollectionTypeInformation; if (parameterCollectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection) { if (parameterCollectionTypeInfo.ElementType == typeof(object)) { result = true; break; } if (parameterCollectionTypeInfo.ElementType == typeof(ScriptBlock)) { result = true; break; } if (parameterCollectionTypeInfo.ElementType.IsSubclassOf(typeof(ScriptBlock))) { result = true; break; } } } while (false); s_tracer.WriteLine("IsParameterScriptBlockBindable: result = {0}", result); return result; } /// <summary> /// Binds the specified parameters to the cmdlet. /// </summary> /// <param name="parameters"> /// The parameters to bind. /// </param> internal override Collection<CommandParameterInternal> BindParameters(Collection<CommandParameterInternal> parameters) { return BindParameters(uint.MaxValue, parameters); } /// <summary> /// Binds the specified argument to the specified parameter using the appropriate /// parameter binder. If the argument is of type ScriptBlock and the parameter takes /// pipeline input, then the ScriptBlock is saved off in the delay-bind ScriptBlock /// container for further processing of pipeline input and is not bound as the argument /// to the parameter. /// </summary> /// <param name="parameterSets"> /// The parameter set used to bind the arguments. /// </param> /// <param name="argument"> /// The argument to be bound. /// </param> /// <param name="parameter"> /// The metadata for the parameter to bind the argument to. /// </param> /// <param name="flags"> /// Flags for type coercion, validation, and script block binding. /// /// ParameterBindingFlags.DelayBindScriptBlock: /// If set, arguments that are of type ScriptBlock where the parameter is not of type ScriptBlock, /// Object, or PSObject will be stored for execution during pipeline input and not bound as /// an argument to the parameter. /// </param> /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type. /// </returns> internal override bool BindParameter( uint parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { // Now we need to check to see if the argument value is // a ScriptBlock. If it is and the parameter type is // not ScriptBlock and not Object, then we need to delay // binding until a pipeline object is provided to invoke // the ScriptBlock. // Note: we haven't yet determined that only a single parameter // set is valid, so we have to take a best guess on pipeline input // based on the current valid parameter sets. bool continueWithBinding = true; if ((flags & ParameterBindingFlags.DelayBindScriptBlock) != 0 && parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets) && argument.ArgumentSpecified) { object argumentValue = argument.ArgumentValue; if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) && !IsParameterScriptBlockBindable(parameter)) { // Now check to see if the command expects to have pipeline input. // If not, we should throw an exception now to inform the // user with more information than they would get if it was // considered an unbound mandatory parameter. if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.MetadataError, this.Command.MyInvocation, GetErrorExtent(argument), parameter.Parameter.Name, parameter.Parameter.Type, null, ParameterBinderStrings.ScriptBlockArgumentNoInput, "ScriptBlockArgumentNoInput"); throw bindingException; } ParameterBinderBase.bindingTracer.WriteLine( "Adding ScriptBlock to delay-bind list for parameter '{0}'", parameter.Parameter.Name); // We need to delay binding of this argument to the parameter DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument ?? new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this }; if (!_delayBindScriptBlocks.ContainsKey(parameter)) { _delayBindScriptBlocks.Add(parameter, delayedArg); } // We treat the parameter as bound, but really the // script block gets run for each pipeline object and // the result is bound. if (parameter.Parameter.ParameterSetFlags != 0) { _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } UnboundParameters.Remove(parameter); BoundParameters[parameter.Parameter.Name] = parameter; BoundArguments[parameter.Parameter.Name] = argument; if (DefaultParameterBinder.RecordBoundParameters && !DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name)) { DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, delayedArg); } continueWithBinding = false; } } bool result = false; if (continueWithBinding) { try { result = BindParameter(argument, parameter, flags); } catch (Exception e) { bool rethrow = true; if ((flags & ParameterBindingFlags.ShouldCoerceType) == 0) { // Attributes are used to do type coercion and result in various exceptions. // We assume that if we aren't trying to do type coercion, we should avoid // propagating type conversion exceptions. while (e != null) { if (e is PSInvalidCastException) { rethrow = false; break; } e = e.InnerException; } } if (rethrow) { throw; } } } return result; } /// <summary> /// Binds the specified argument to the specified parameter using the appropriate /// parameter binder. /// </summary> /// <param name="argument"> /// The argument to be bound. /// </param> /// <param name="parameter"> /// The metadata for the parameter to bind the argument to. /// </param> /// <param name="flags"> /// Flags for type coercion and validation. /// </param> /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type. /// </returns> private bool BindParameter( CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool result = false; switch (parameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: result = DefaultParameterBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.CommonParameters: result = CommonParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.ShouldProcessParameters: Diagnostics.Assert( _commandMetadata.SupportsShouldProcess, "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess"); result = ShouldProcessParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.PagingParameters: Diagnostics.Assert( _commandMetadata.SupportsPaging, "The metadata for the PagingParameters should only be available if the command supports paging"); result = PagingParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.TransactionParameters: Diagnostics.Assert( _commandMetadata.SupportsTransactions, "The metadata for the TransactionsParameters should only be available if the command supports transactions"); result = TransactionParametersBinder.BindParameter( argument, parameter.Parameter, flags); break; case ParameterBinderAssociation.DynamicParameters: Diagnostics.Assert( _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); if (_dynamicParameterBinder != null) { result = _dynamicParameterBinder.BindParameter( argument, parameter.Parameter, flags); } break; } if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0)) { // Update the current valid parameter set flags if (parameter.Parameter.ParameterSetFlags != 0) { _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags; } UnboundParameters.Remove(parameter); if (!BoundParameters.ContainsKey(parameter.Parameter.Name)) { BoundParameters.Add(parameter.Parameter.Name, parameter); } if (!BoundArguments.ContainsKey(parameter.Parameter.Name)) { BoundArguments.Add(parameter.Parameter.Name, argument); } if (parameter.Parameter.ObsoleteAttribute != null && (flags & ParameterBindingFlags.IsDefaultValue) == 0 && !BoundObsoleteParameterNames.Contains(parameter.Parameter.Name)) { string obsoleteWarning = string.Format( CultureInfo.InvariantCulture, ParameterBinderStrings.UseOfDeprecatedParameterWarning, parameter.Parameter.Name, parameter.Parameter.ObsoleteAttribute.Message); var warningRecord = new WarningRecord(ParameterBinderBase.FQIDParameterObsolete, obsoleteWarning); BoundObsoleteParameterNames.Add(parameter.Parameter.Name); if (ObsoleteParameterWarningList == null) ObsoleteParameterWarningList = new List<WarningRecord>(); ObsoleteParameterWarningList.Add(warningRecord); } } return result; } /// <summary> /// Binds the remaining arguments to an unbound ValueFromRemainingArguments parameter (Varargs) /// </summary> /// <exception cref="ParameterBindingException"> /// If there was an error binding the arguments to the parameters. /// </exception> private void HandleRemainingArguments() { if (UnboundArguments.Count > 0) { // Find the parameters that take the remaining args, if there are more // than one and the parameter set has not been defined, this is an error MergedCompiledCommandParameter varargsParameter = null; foreach (MergedCompiledCommandParameter parameter in UnboundParameters) { ParameterSetSpecificMetadata parameterSetData = parameter.Parameter.GetParameterSetData(_currentParameterSetFlag); if (parameterSetData == null) { continue; } // If the parameter takes the remaining arguments, bind them. if (parameterSetData.ValueFromRemainingArguments) { if (varargsParameter != null) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.MetadataError, this.Command.MyInvocation, null, parameter.Parameter.Name, parameter.Parameter.Type, null, ParameterBinderStrings.AmbiguousParameterSet, "AmbiguousParameterSet"); // Might be caused by the default parameter binding if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } } varargsParameter = parameter; } } if (varargsParameter != null) { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND REMAININGARGUMENTS cmd line args to param: [{0}]", varargsParameter.Parameter.Name)) { // Accumulate the unbound arguments in to an list and then bind it to the parameter List<object> valueFromRemainingArguments = new List<object>(); foreach (CommandParameterInternal argument in UnboundArguments) { if (argument.ParameterNameSpecified) { Diagnostics.Assert(!string.IsNullOrEmpty(argument.ParameterText), "Don't add a null argument"); valueFromRemainingArguments.Add(argument.ParameterText); } if (argument.ArgumentSpecified) { object argumentValue = argument.ArgumentValue; if (argumentValue != AutomationNull.Value && argumentValue != UnboundParameter.Value) { valueFromRemainingArguments.Add(argumentValue); } } } // If there are multiple arguments, it's not clear how best to represent the extent as the extent // may be disjoint, as in 'echo a -verbose b', we have 'a' and 'b' in UnboundArguments. var argumentAst = UnboundArguments.Count == 1 ? UnboundArguments[0].ArgumentAst : null; var cpi = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, varargsParameter.Parameter.Name, "-" + varargsParameter.Parameter.Name + ":", argumentAst, valueFromRemainingArguments, false); // To make all of the following work similarly (the first is handled elsewhere, but second and third are // handled here): // Set-ClusterOwnerNode -Owners foo,bar // Set-ClusterOwnerNode foo bar // Set-ClusterOwnerNode foo,bar // we unwrap our List, but only if there is a single argument which is a collection. if (valueFromRemainingArguments.Count == 1 && LanguagePrimitives.IsObjectEnumerable(valueFromRemainingArguments[0])) { cpi.SetArgumentValue(UnboundArguments[0].ArgumentAst, valueFromRemainingArguments[0]); } try { BindParameter(cpi, varargsParameter, ParameterBindingFlags.ShouldCoerceType); } catch (ParameterBindingException pbex) { if (!DefaultParameterBindingInUse) { throw; } else { ThrowElaboratedBindingException(pbex); } } UnboundArguments.Clear(); } } } } /// <summary> /// Determines if the cmdlet supports dynamic parameters. If it does, /// the dynamic parameter bindable object is retrieved and the unbound /// arguments are bound to it. /// </summary> /// <param name="outgoingBindingException"> /// Returns the underlying parameter binding exception if any was generated. /// </param> /// <exception cref="MetadataException"> /// If there was an error compiling the parameter metadata. /// </exception> /// <exception cref="ParameterBindingException"> /// If there was an error binding the arguments to the parameters. /// </exception> private void HandleCommandLineDynamicParameters(out ParameterBindingException outgoingBindingException) { outgoingBindingException = null; if (_commandMetadata.ImplementsDynamicParameters) { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND cmd line args to DYNAMIC parameters.")) { s_tracer.WriteLine("The Cmdlet supports the dynamic parameter interface"); IDynamicParameters dynamicParameterCmdlet = this.Command as IDynamicParameters; if (dynamicParameterCmdlet != null) { if (_dynamicParameterBinder == null) { s_tracer.WriteLine("Getting the bindable object from the Cmdlet"); // Now get the dynamic parameter bindable object. object dynamicParamBindableObject; try { dynamicParamBindableObject = dynamicParameterCmdlet.GetDynamicParameters(); } catch (Exception e) // Catch-all OK, this is a third-party callout { if (e is ProviderInvocationException) { throw; } ParameterBindingException bindingException = new ParameterBindingException( e, ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, null, ParameterBinderStrings.GetDynamicParametersException, "GetDynamicParametersException", e.Message); // This exception is caused because failure happens when retrieving the dynamic parameters, // this is not caused by introducing the default parameter binding. throw bindingException; } if (dynamicParamBindableObject != null) { ParameterBinderBase.bindingTracer.WriteLine( "DYNAMIC parameter object: [{0}]", dynamicParamBindableObject.GetType()); s_tracer.WriteLine("Creating a new parameter binder for the dynamic parameter object"); InternalParameterMetadata dynamicParameterMetadata; RuntimeDefinedParameterDictionary runtimeParamDictionary = dynamicParamBindableObject as RuntimeDefinedParameterDictionary; if (runtimeParamDictionary != null) { // Generate the type metadata for the runtime-defined parameters dynamicParameterMetadata = InternalParameterMetadata.Get(runtimeParamDictionary, true, true); _dynamicParameterBinder = new RuntimeDefinedParameterBinder( runtimeParamDictionary, this.Command, this.CommandLineParameters); } else { // Generate the type metadata or retrieve it from the cache dynamicParameterMetadata = InternalParameterMetadata.Get(dynamicParamBindableObject.GetType(), Context, true); // Create the parameter binder for the dynamic parameter object _dynamicParameterBinder = new ReflectionParameterBinder( dynamicParamBindableObject, this.Command, this.CommandLineParameters); } // Now merge the metadata with other metadata for the command var dynamicParams = BindableParameters.AddMetadataForBinder( dynamicParameterMetadata, ParameterBinderAssociation.DynamicParameters); foreach (var param in dynamicParams) { UnboundParameters.Add(param); } // Now set the parameter set flags for the new type metadata. _commandMetadata.DefaultParameterSetFlag = this.BindableParameters.GenerateParameterSetMappingFromMetadata(_commandMetadata.DefaultParameterSetName); } } if (_dynamicParameterBinder == null) { s_tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet"); return; } if (UnboundArguments.Count > 0) { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND NAMED args to DYNAMIC parameters")) { // Try to bind the unbound arguments as static parameters to the // dynamic parameter object. ReparseUnboundArguments(); UnboundArguments = BindParameters(_currentParameterSetFlag, UnboundArguments); } using (ParameterBinderBase.bindingTracer.TraceScope( "BIND POSITIONAL args to DYNAMIC parameters")) { UnboundArguments = BindPositionalParameters( UnboundArguments, _currentParameterSetFlag, _commandMetadata.DefaultParameterSetFlag, out outgoingBindingException); } } } } } } /// <summary> /// This method determines if the unbound mandatory parameters take pipeline input or /// if we can use the default parameter set. If all the unbound mandatory parameters /// take pipeline input and the default parameter set is valid, then the default parameter /// set is set as the current parameter set and processing can continue. If there are /// more than one valid parameter sets and the unbound mandatory parameters are not /// consistent across parameter sets or there is no default parameter set then a /// ParameterBindingException is thrown with an errorId of AmbiguousParameterSet. /// </summary> /// <param name="validParameterSetCount"> /// The number of valid parameter sets. /// </param> /// <param name="isPipelineInputExpected"> /// True if the pipeline is open to receive input. /// </param> /// <exception cref="ParameterBindingException"> /// If there are multiple valid parameter sets and the missing mandatory parameters are /// not consistent across parameter sets, or there is no default parameter set. /// </exception> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Justification = "Consider Simplifying it.")] private Collection<MergedCompiledCommandParameter> GetMissingMandatoryParameters( int validParameterSetCount, bool isPipelineInputExpected) { Collection<MergedCompiledCommandParameter> result = new Collection<MergedCompiledCommandParameter>(); uint defaultParameterSet = _commandMetadata.DefaultParameterSetFlag; uint commandMandatorySets = 0; Dictionary<uint, ParameterSetPromptingData> promptingData = new Dictionary<uint, ParameterSetPromptingData>(); bool missingAMandatoryParameter = false; bool missingAMandatoryParameterInAllSet = false; // See if any of the unbound parameters are mandatory foreach (MergedCompiledCommandParameter parameter in UnboundParameters) { // If a parameter is never mandatory, we can skip lots of work here. if (!parameter.Parameter.IsMandatoryInSomeParameterSet) { continue; } var matchingParameterSetMetadata = parameter.Parameter.GetMatchingParameterSetData(_currentParameterSetFlag); uint parameterMandatorySets = 0; bool thisParameterMissing = false; foreach (ParameterSetSpecificMetadata parameterSetMetadata in matchingParameterSetMetadata) { uint newMandatoryParameterSetFlag = NewParameterSetPromptingData(promptingData, parameter, parameterSetMetadata, defaultParameterSet, isPipelineInputExpected); if (newMandatoryParameterSetFlag != 0) { missingAMandatoryParameter = true; thisParameterMissing = true; if (newMandatoryParameterSetFlag != uint.MaxValue) { parameterMandatorySets |= (_currentParameterSetFlag & newMandatoryParameterSetFlag); commandMandatorySets |= (_currentParameterSetFlag & parameterMandatorySets); } else { missingAMandatoryParameterInAllSet = true; } } } // We are not expecting pipeline input if (!isPipelineInputExpected) { // The parameter is mandatory so we need to prompt for it if (thisParameterMissing) { result.Add(parameter); continue; } // The parameter was not mandatory in any parameter set } } if (missingAMandatoryParameter && isPipelineInputExpected) { if (commandMandatorySets == 0) { commandMandatorySets = _currentParameterSetFlag; } if (missingAMandatoryParameterInAllSet) { uint availableParameterSetFlags = this.BindableParameters.AllParameterSetFlags; if (availableParameterSetFlags == 0) { availableParameterSetFlags = uint.MaxValue; } commandMandatorySets = (_currentParameterSetFlag & availableParameterSetFlags); } // First we need to see if there are multiple valid parameter sets, and if one is // the default parameter set, and it is not missing any mandatory parameters, then // use the default parameter set. if (validParameterSetCount > 1 && defaultParameterSet != 0 && (defaultParameterSet & commandMandatorySets) == 0 && (defaultParameterSet & _currentParameterSetFlag) != 0) { // If no other set takes pipeline input, then latch on to the default set uint setThatTakesPipelineInput = 0; foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & _currentParameterSetFlag) != 0 && (promptingSetData.ParameterSet & defaultParameterSet) == 0 && !promptingSetData.IsAllSet) { if (promptingSetData.PipelineableMandatoryParameters.Count > 0) { setThatTakesPipelineInput = promptingSetData.ParameterSet; break; } } } if (setThatTakesPipelineInput == 0) { // Old algorithm starts // // latch on to the default parameter set // commandMandatorySets = defaultParameterSet; // _currentParameterSetFlag = defaultParameterSet; // Command.SetParameterSetName(CurrentParameterSetName); // Old algorithm ends // At this point, we have the following information: // 1. There are unbound mandatory parameter(s) // 2. No unbound mandatory parameter is in AllSet // 3. All unbound mandatory parameters don't take pipeline input // 4. Default parameter set is valid // 5. Default parameter set doesn't contain unbound mandatory parameters // // We ignore those parameter sets that contain unbound mandatory parameters, but leave // all other parameter sets remain valid. The other parameter sets contains the default // parameter set and have one characteristic: NONE of them contain unbound mandatory parameters // // Comparing to the old algorithm, we keep more possible parameter sets here, but // we need to prioritize the default parameter set for pipeline binding, so as NOT to // make breaking changes. This is to handle the following scenario: // Old Algorithm New Algorithm (without prioritizing default) New Algorithm (with prioritizing default) // Remaining Parameter Sets A(default) A(default), B A(default), B // Pipeline parameter P1(string) A: P1(string); B: P2(System.DateTime) A: P1(string); B: P2(System.DateTime) // Pipeline parameter type P1:By Value P1:By Value; P2:By Value P1:By Value; P2:By Value // Pipeline input $a (System.DateTime) $a (System.DateTime) $a (System.DateTime) // Pipeline binding result P1 --> $a.ToString() P2 --> $a P1 --> $a.ToString() // Pipeline binding type ByValueWithCoercion ByValueWithoutCoercion ByValueWithCoercion commandMandatorySets = _currentParameterSetFlag & (~commandMandatorySets); _currentParameterSetFlag = commandMandatorySets; if (_currentParameterSetFlag == defaultParameterSet) Command.SetParameterSetName(CurrentParameterSetName); else _parameterSetToBePrioritizedInPipelineBinding = defaultParameterSet; } } // We need to analyze the prompting data that was gathered to determine what parameter // set to use, which parameters need prompting for, and which parameters take pipeline input. int commandMandatorySetsCount = ValidParameterSetCount(commandMandatorySets); if (commandMandatorySetsCount == 0) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } else if (commandMandatorySetsCount == 1) { // Since we have only one valid parameter set, add all foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 || promptingSetData.IsAllSet) { foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys) { result.Add(mandatoryParameter); } } } } else if (_parameterSetToBePrioritizedInPipelineBinding == 0) { // We have more than one valid parameter set. Need to figure out which one to // use. // First we need to process the default parameter set if it can fill its parameters // from the pipeline. bool latchOnToDefault = false; if (defaultParameterSet != 0 && (commandMandatorySets & defaultParameterSet) != 0) { // Determine if another set could be satisfied by pipeline input - that is, it // has mandatory pipeline input parameters but no mandatory command-line only parameters. bool anotherSetTakesPipelineInput = false; foreach (ParameterSetPromptingData paramPromptingData in promptingData.Values) { if (!paramPromptingData.IsAllSet && !paramPromptingData.IsDefaultSet && paramPromptingData.PipelineableMandatoryParameters.Count > 0 && paramPromptingData.NonpipelineableMandatoryParameters.Count == 0) { anotherSetTakesPipelineInput = true; break; } } // Determine if another set takes pipeline input by property name bool anotherSetTakesPipelineInputByPropertyName = false; foreach (ParameterSetPromptingData paramPromptingData in promptingData.Values) { if (!paramPromptingData.IsAllSet && !paramPromptingData.IsDefaultSet && paramPromptingData.PipelineableMandatoryByPropertyNameParameters.Count > 0) { anotherSetTakesPipelineInputByPropertyName = true; break; } } // See if we should pick the default set if it can bind strongly to the incoming objects ParameterSetPromptingData defaultSetPromptingData; if (promptingData.TryGetValue(defaultParameterSet, out defaultSetPromptingData)) { bool defaultSetTakesPipelineInput = defaultSetPromptingData.PipelineableMandatoryParameters.Count > 0; bool defaultSetTakesPipelineInputByPropertyName = defaultSetPromptingData.PipelineableMandatoryByPropertyNameParameters.Count > 0; if (defaultSetTakesPipelineInputByPropertyName && !anotherSetTakesPipelineInputByPropertyName) { latchOnToDefault = true; } else if (defaultSetTakesPipelineInput && !anotherSetTakesPipelineInput) { latchOnToDefault = true; } } if (!latchOnToDefault) { // If only the all set takes pipeline input then latch on to the // default set if (!anotherSetTakesPipelineInput) { latchOnToDefault = true; } } if (!latchOnToDefault) { // Need to see if there are nonpipelineable mandatory parameters in the // all set. ParameterSetPromptingData allSetPromptingData; if (promptingData.TryGetValue(uint.MaxValue, out allSetPromptingData)) { if (allSetPromptingData.NonpipelineableMandatoryParameters.Count > 0) { latchOnToDefault = true; } } } if (latchOnToDefault) { // latch on to the default parameter set commandMandatorySets = defaultParameterSet; _currentParameterSetFlag = defaultParameterSet; Command.SetParameterSetName(CurrentParameterSetName); // Add all missing mandatory parameters that don't take pipeline input foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 || promptingSetData.IsAllSet) { foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys) { result.Add(mandatoryParameter); } } } } } if (!latchOnToDefault) { // When we select a mandatory set to latch on, we should try to preserve other parameter sets that contain no mandatory parameters or contain only common mandatory parameters // as much as possible, so as to support the binding for the following scenarios: // // (1) Scenario 1: // Valid parameter sets when it comes to the mandatory checking: A, B // Mandatory parameters in A, B: // Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory // A N/A N/A N/A AllParam (of type DateTime) // B N/A ParamB (of type TimeSpan) N/A AllParam (of type DateTime) // // Piped-in object: Get-Date // // (2) Scenario 2: // Valid parameter sets when it comes to the mandatory checking: A, B, C, Default // Mandatory parameters in A, B, C and Default: // Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory // A N/A N/A N/A AllParam (of type DateTime) // B N/A ParamB (of type TimeSpan) N/A AllParam (of type DateTime) // C N/A N/A N/A AllParam (of type DateTime) // Default N/A N/A N/A AllParam (of type DateTime) // // Piped-in object: Get-Date // // Before the fix, the mandatory checking will resolve the parameter set to be B in both scenario 1 and 2, which will fail in the subsequent pipeline binding. // After the fix, the parameter set "A" in the scenario 1 and the set "A", "C", "Default" in the scenario 2 will be preserved, and the subsequent pipeline binding will succeed. // // (3) Scenario 3: // Valid parameter sets when it comes to the mandatory checking: A, B, C // Mandatory parameters in A, B and C: // Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Pipelineable-Nonmandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory Common-Pipelineable-Nonmandatory // A N/A ParamA (of type TimeSpan) N/A N/A N/A N/A // B ParamB-1 N/A ParamB-2 (of type string[]) N/A N/A N/A // C N/A N/A ParamC (of type DateTime) N/A N/A N/A // // (4) Scenario 4: // Valid parameter sets when it comes to the mandatory checking: A, B, C, Default // Mandatory parameters in A, B, C and Default: // Set Nonpipelineable-Mandatory-InSet Pipelineable-Mandatory-InSet Pipelineable-Nonmandatory-InSet Common-Nonpipelineable-Mandatory Common-Pipelineable-Mandatory Common-Pipelineable-Nonmandatory // A N/A ParamA (of type TimeSpan) N/A N/A N/A AllParam (of type DateTime) // B ParamB-1 N/A ParamB-2 (of type string[]) N/A N/A AllParam (of type DateTime) // C N/A N/A N/A N/A N/A AllParam (of type DateTime) // Default N/A N/A N/A N/A N/A AllParam (of type DateTime) // // Piped-in object: Get-Date // // Before the fix, the mandatory checking will resolve the parameter set to be A in both scenario 3 and 4, which will fail in the subsequent pipeline binding. // After the fix, the parameter set "C" in the scenario 1 and the set "C" and "Default" in the scenario 2 will be preserved, and the subsequent pipeline binding will succeed. // // Examples: // (1) Scenario 1 // Function Get-Cmdlet // { // [CmdletBinding()] // param( // [Parameter(Mandatory=$true, ValueFromPipeline=$true)] // [System.DateTime] // $Date, // [Parameter(ParameterSetName="computer")] // [Parameter(ParameterSetName="session")] // $ComputerName, // [Parameter(ParameterSetName="session", Mandatory=$true, ValueFromPipeline=$true)] // [System.TimeSpan] // $TimeSpan // ) // // Process // { // Write-Output $PsCmdlet.ParameterSetName // } // } // // PS:\> Get-Date | Get-Cmdlet // PS:\> computer // // (2) Scenario 2 // // Function Get-Cmdlet // { // [CmdletBinding(DefaultParameterSetName="computer")] // param( // [Parameter(ParameterSetName="new")] // $NewName, // [Parameter(Mandatory=$true, ValueFromPipeline=$true)] // [System.DateTime] // $Date, // [Parameter(ParameterSetName="computer")] // [Parameter(ParameterSetName="session")] // $ComputerName, // [Parameter(ParameterSetName="session", Mandatory=$true, ValueFromPipeline=$true)] // [System.TimeSpan] // $TimeSpan // ) // // Process // { // Write-Output $PsCmdlet.ParameterSetName // } // } // // PS:\> Get-Date | Get-Cmdlet // PS:\> computer // // (3) Scenario 3 // // Function Get-Cmdlet // { // [CmdletBinding()] // param( // [Parameter(ParameterSetName="network", Mandatory=$true, ValueFromPipeline=$true)] // [TimeSpan] // $network, // // [Parameter(ParameterSetName="computer", ValueFromPipelineByPropertyName=$true)] // [string[]] // $ComputerName, // // [Parameter(ParameterSetName="computer", Mandatory=$true)] // [switch] // $DisableComputer, // // [Parameter(ParameterSetName="session", ValueFromPipeline=$true)] // [DateTime] // $Date // ) // // Process // { // Write-Output $PsCmdlet.ParameterSetName // } // } // // PS:\> Get-Date | Get-Cmdlet // PS:\> session // // (4) Scenario 4 // // Function Get-Cmdlet // { // [CmdletBinding(DefaultParameterSetName="server")] // param( // [Parameter(ParameterSetName="network", Mandatory=$true, ValueFromPipeline=$true)] // [TimeSpan] // $network, // // [Parameter(ParameterSetName="computer", ValueFromPipelineByPropertyName=$true)] // [string[]] // $ComputerName, // // [Parameter(ParameterSetName="computer", Mandatory=$true)] // [switch] // $DisableComputer, // // [Parameter(ParameterSetName="session")] // [Parameter(ParameterSetName="server")] // [string] // $Param, // // [Parameter(ValueFromPipeline=$true)] // [DateTime] // $Date // ) // Process // { // Write-Output $PsCmdlet.ParameterSetName // } // } // // PS:\> Get-Date | Get-Cmdlet // PS:\> server // uint setThatTakesPipelineInputByValue = 0; uint setThatTakesPipelineInputByPropertyName = 0; // Find the single set that takes pipeline input by value bool foundSetThatTakesPipelineInputByValue = false; bool foundMultipleSetsThatTakesPipelineInputByValue = false; foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 && !promptingSetData.IsAllSet) { if (promptingSetData.PipelineableMandatoryByValueParameters.Count > 0) { if (foundSetThatTakesPipelineInputByValue) { foundMultipleSetsThatTakesPipelineInputByValue = true; setThatTakesPipelineInputByValue = 0; break; } setThatTakesPipelineInputByValue = promptingSetData.ParameterSet; foundSetThatTakesPipelineInputByValue = true; } } } // Find the single set that takes pipeline input by property name bool foundSetThatTakesPipelineInputByPropertyName = false; bool foundMultipleSetsThatTakesPipelineInputByPropertyName = false; foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 && !promptingSetData.IsAllSet) { if (promptingSetData.PipelineableMandatoryByPropertyNameParameters.Count > 0) { if (foundSetThatTakesPipelineInputByPropertyName) { foundMultipleSetsThatTakesPipelineInputByPropertyName = true; setThatTakesPipelineInputByPropertyName = 0; break; } setThatTakesPipelineInputByPropertyName = promptingSetData.ParameterSet; foundSetThatTakesPipelineInputByPropertyName = true; } } } // If we have one or the other, we can latch onto that set without difficulty uint uniqueSetThatTakesPipelineInput = 0; if ((foundSetThatTakesPipelineInputByValue & foundSetThatTakesPipelineInputByPropertyName) && (setThatTakesPipelineInputByValue == setThatTakesPipelineInputByPropertyName)) { uniqueSetThatTakesPipelineInput = setThatTakesPipelineInputByValue; } if (foundSetThatTakesPipelineInputByValue ^ foundSetThatTakesPipelineInputByPropertyName) { uniqueSetThatTakesPipelineInput = foundSetThatTakesPipelineInputByValue ? setThatTakesPipelineInputByValue : setThatTakesPipelineInputByPropertyName; } if (uniqueSetThatTakesPipelineInput != 0) { // latch on to the set that takes pipeline input commandMandatorySets = uniqueSetThatTakesPipelineInput; uint otherMandatorySetsToBeIgnored = 0; bool chosenMandatorySetContainsNonpipelineableMandatoryParameters = false; // Add all missing mandatory parameters that don't take pipeline input foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 || promptingSetData.IsAllSet) { if (!promptingSetData.IsAllSet) { chosenMandatorySetContainsNonpipelineableMandatoryParameters = promptingSetData.NonpipelineableMandatoryParameters.Count > 0; } foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys) { result.Add(mandatoryParameter); } } else { otherMandatorySetsToBeIgnored |= promptingSetData.ParameterSet; } } // Preserve potential parameter sets as much as possible PreservePotentialParameterSets(uniqueSetThatTakesPipelineInput, otherMandatorySetsToBeIgnored, chosenMandatorySetContainsNonpipelineableMandatoryParameters); } else { // Now if any valid parameter sets have nonpipelineable mandatory parameters we have // an error bool foundMissingParameters = false; uint setsThatContainNonpipelineableMandatoryParameter = 0; foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 || promptingSetData.IsAllSet) { if (promptingSetData.NonpipelineableMandatoryParameters.Count > 0) { foundMissingParameters = true; if (!promptingSetData.IsAllSet) { setsThatContainNonpipelineableMandatoryParameter |= promptingSetData.ParameterSet; } } } } if (foundMissingParameters) { // As a last-ditch effort, bind to the set that takes pipeline input by value if (setThatTakesPipelineInputByValue != 0) { // latch on to the set that takes pipeline input commandMandatorySets = setThatTakesPipelineInputByValue; uint otherMandatorySetsToBeIgnored = 0; bool chosenMandatorySetContainsNonpipelineableMandatoryParameters = false; // Add all missing mandatory parameters that don't take pipeline input foreach (ParameterSetPromptingData promptingSetData in promptingData.Values) { if ((promptingSetData.ParameterSet & commandMandatorySets) != 0 || promptingSetData.IsAllSet) { if (!promptingSetData.IsAllSet) { chosenMandatorySetContainsNonpipelineableMandatoryParameters = promptingSetData.NonpipelineableMandatoryParameters.Count > 0; } foreach (MergedCompiledCommandParameter mandatoryParameter in promptingSetData.NonpipelineableMandatoryParameters.Keys) { result.Add(mandatoryParameter); } } else { otherMandatorySetsToBeIgnored |= promptingSetData.ParameterSet; } } // Preserve potential parameter sets as much as possible PreservePotentialParameterSets(setThatTakesPipelineInputByValue, otherMandatorySetsToBeIgnored, chosenMandatorySetContainsNonpipelineableMandatoryParameters); } else { if ((!foundMultipleSetsThatTakesPipelineInputByValue) && (!foundMultipleSetsThatTakesPipelineInputByPropertyName)) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } // Remove the data set that contains non-pipelineable mandatory parameters, since we are not // prompting for them and they will not be bound later. // If no data set left, throw ambiguous parameter set exception if (setsThatContainNonpipelineableMandatoryParameter != 0) { IgnoreOtherMandatoryParameterSets(setsThatContainNonpipelineableMandatoryParameter); if (_currentParameterSetFlag == 0) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } if (ValidParameterSetCount(_currentParameterSetFlag) == 1) { Command.SetParameterSetName(CurrentParameterSetName); } } } } } } } } return result; } /// <summary> /// Preserve potential parameter sets as much as possible. /// </summary> /// <param name="chosenMandatorySet">The mandatory set we choose to latch on.</param> /// <param name="otherMandatorySetsToBeIgnored">Other mandatory parameter sets to be ignored.</param> /// <param name="chosenSetContainsNonpipelineableMandatoryParameters">Indicate if the chosen mandatory set contains any non-pipelineable mandatory parameters.</param> private void PreservePotentialParameterSets(uint chosenMandatorySet, uint otherMandatorySetsToBeIgnored, bool chosenSetContainsNonpipelineableMandatoryParameters) { // If the chosen set contains nonpipelineable mandatory parameters, then we set it as the only valid parameter set since we will prompt for those mandatory parameters if (chosenSetContainsNonpipelineableMandatoryParameters) { _currentParameterSetFlag = chosenMandatorySet; Command.SetParameterSetName(CurrentParameterSetName); } else { // Otherwise, we additionally preserve those valid parameter sets that contain no mandatory parameter, or contain only the common mandatory parameters IgnoreOtherMandatoryParameterSets(otherMandatorySetsToBeIgnored); Command.SetParameterSetName(CurrentParameterSetName); if (_currentParameterSetFlag != chosenMandatorySet) { _parameterSetToBePrioritizedInPipelineBinding = chosenMandatorySet; } } } /// <summary> /// Update _currentParameterSetFlag to ignore the specified mandatory sets. /// </summary> /// <remarks> /// This method is used only when we try to preserve parameter sets during the mandatory parameter checking. /// In cases where this method is used, there must be at least one parameter set declared. /// </remarks> /// <param name="otherMandatorySetsToBeIgnored">The mandatory parameter sets to be ignored.</param> private void IgnoreOtherMandatoryParameterSets(uint otherMandatorySetsToBeIgnored) { if (otherMandatorySetsToBeIgnored == 0) return; if (_currentParameterSetFlag == uint.MaxValue) { // We cannot update the _currentParameterSetFlag to remove some parameter sets directly when it's AllSet as that will get it to an incorrect state. uint availableParameterSets = this.BindableParameters.AllParameterSetFlags; Diagnostics.Assert(availableParameterSets != 0, "At least one parameter set must be declared"); _currentParameterSetFlag = availableParameterSets & (~otherMandatorySetsToBeIgnored); } else { _currentParameterSetFlag &= (~otherMandatorySetsToBeIgnored); } } private uint NewParameterSetPromptingData( Dictionary<uint, ParameterSetPromptingData> promptingData, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetMetadata, uint defaultParameterSet, bool pipelineInputExpected) { uint parameterMandatorySets = 0; uint parameterSetFlag = parameterSetMetadata.ParameterSetFlag; if (parameterSetFlag == 0) { parameterSetFlag = uint.MaxValue; } bool isDefaultSet = (defaultParameterSet != 0) && ((defaultParameterSet & parameterSetFlag) != 0); bool isMandatory = false; if (parameterSetMetadata.IsMandatory) { parameterMandatorySets |= parameterSetFlag; isMandatory = true; } bool isPipelineable = false; if (pipelineInputExpected) { if (parameterSetMetadata.ValueFromPipeline || parameterSetMetadata.ValueFromPipelineByPropertyName) { isPipelineable = true; } } if (isMandatory) { ParameterSetPromptingData promptingDataForSet; if (!promptingData.TryGetValue(parameterSetFlag, out promptingDataForSet)) { promptingDataForSet = new ParameterSetPromptingData(parameterSetFlag, isDefaultSet); promptingData.Add(parameterSetFlag, promptingDataForSet); } if (isPipelineable) { promptingDataForSet.PipelineableMandatoryParameters[parameter] = parameterSetMetadata; if (parameterSetMetadata.ValueFromPipeline) { promptingDataForSet.PipelineableMandatoryByValueParameters[parameter] = parameterSetMetadata; } if (parameterSetMetadata.ValueFromPipelineByPropertyName) { promptingDataForSet.PipelineableMandatoryByPropertyNameParameters[parameter] = parameterSetMetadata; } } else { promptingDataForSet.NonpipelineableMandatoryParameters[parameter] = parameterSetMetadata; } } return parameterMandatorySets; } /// <summary> /// Ensures that only one parameter set is valid or throws an appropriate exception. /// </summary> /// <param name="prePipelineInput"> /// If true, it is acceptable to have multiple valid parameter sets as long as one /// of those parameter sets take pipeline input. /// </param> /// <param name="setDefault"> /// If true, the default parameter set will be selected if there is more than /// one valid parameter set and one is the default set. /// If false, the count of valid parameter sets will be returned but no error /// will occur and the default parameter set will not be used. /// </param> /// <returns> /// The number of valid parameter sets. /// </returns> /// <exception cref="ParameterBindingException"> /// If the more than one or zero parameter sets were resolved from the named /// parameters. /// </exception> private int ValidateParameterSets(bool prePipelineInput, bool setDefault) { // Compute how many parameter sets are still valid int validParameterSetCount = ValidParameterSetCount(_currentParameterSetFlag); if (validParameterSetCount == 0 && _currentParameterSetFlag != uint.MaxValue) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } else if (validParameterSetCount > 1) { uint defaultParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; bool hasDefaultSetDefined = defaultParameterSetFlag != 0; bool validSetIsAllSet = _currentParameterSetFlag == uint.MaxValue; bool validSetIsDefault = _currentParameterSetFlag == defaultParameterSetFlag; // If no default parameter set is defined and the valid set is the "all" set // then use the all set. if (validSetIsAllSet && !hasDefaultSetDefined) { // The current parameter set flags are valid. // Note: this is the same as having a single valid parameter set flag. validParameterSetCount = 1; } // If the valid parameter set is the default parameter set, or if the default // parameter set has been defined and one of the valid parameter sets is // the default parameter set, then use the default parameter set. else if (!prePipelineInput && validSetIsDefault || (hasDefaultSetDefined && (_currentParameterSetFlag & defaultParameterSetFlag) != 0)) { // NTRAID#Windows Out Of Band Releases-2006/02/14-928660-JonN // Set currentParameterSetName regardless of setDefault string currentParameterSetName = BindableParameters.GetParameterSetName(defaultParameterSetFlag); Command.SetParameterSetName(currentParameterSetName); if (setDefault) { _currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; validParameterSetCount = 1; } } // There are multiple valid parameter sets but at least one parameter set takes // pipeline input else if (prePipelineInput && AtLeastOneUnboundValidParameterSetTakesPipelineInput(_currentParameterSetFlag)) { // We haven't fixated on a valid parameter set yet, but will wait for pipeline input to // determine which parameter set to use. } else { int resolvedParameterSetCount = ResolveParameterSetAmbiguityBasedOnMandatoryParameters(); if (resolvedParameterSetCount != 1) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } validParameterSetCount = resolvedParameterSetCount; } } else // validParameterSetCount == 1 { // If the valid parameter set is the "all" set, and a default set was defined, // then set the current parameter set to the default set. if (_currentParameterSetFlag == uint.MaxValue) { // Since this is the "all" set, default the parameter set count to the // number of parameter sets that were defined for the cmdlet or 1 if // none were defined. validParameterSetCount = (this.BindableParameters.ParameterSetCount > 0) ? this.BindableParameters.ParameterSetCount : 1; if (prePipelineInput && AtLeastOneUnboundValidParameterSetTakesPipelineInput(_currentParameterSetFlag)) { // Don't fixate on the default parameter set yet. Wait until after // we have processed pipeline input. } else if (_commandMetadata.DefaultParameterSetFlag != 0) { if (setDefault) { _currentParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; validParameterSetCount = 1; } } // NTRAID#Windows Out Of Band Releases-2005/11/07-923917-JonN else if (validParameterSetCount > 1) { int resolvedParameterSetCount = ResolveParameterSetAmbiguityBasedOnMandatoryParameters(); if (resolvedParameterSetCount != 1) { ThrowAmbiguousParameterSetException(_currentParameterSetFlag, BindableParameters); } validParameterSetCount = resolvedParameterSetCount; } } Command.SetParameterSetName(CurrentParameterSetName); } return validParameterSetCount; } private int ResolveParameterSetAmbiguityBasedOnMandatoryParameters() { return ResolveParameterSetAmbiguityBasedOnMandatoryParameters(this.BoundParameters, this.UnboundParameters, this.BindableParameters, ref _currentParameterSetFlag, Command); } internal static int ResolveParameterSetAmbiguityBasedOnMandatoryParameters( Dictionary<string, MergedCompiledCommandParameter> boundParameters, ICollection<MergedCompiledCommandParameter> unboundParameters, MergedCommandParameterMetadata bindableParameters, ref uint _currentParameterSetFlag, Cmdlet command ) { uint remainingParameterSetsWithNoMandatoryUnboundParameters = _currentParameterSetFlag; IEnumerable<ParameterSetSpecificMetadata> allParameterSetMetadatas = boundParameters.Values .Concat(unboundParameters) .SelectMany(p => p.Parameter.ParameterSetData.Values); uint allParameterSetFlags = 0; foreach (ParameterSetSpecificMetadata parameterSetMetadata in allParameterSetMetadatas) { allParameterSetFlags |= parameterSetMetadata.ParameterSetFlag; } remainingParameterSetsWithNoMandatoryUnboundParameters &= allParameterSetFlags; Diagnostics.Assert( ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters) > 1, "This method should only be called when there is an ambiguity wrt parameter sets"); IEnumerable<ParameterSetSpecificMetadata> parameterSetMetadatasForUnboundMandatoryParameters = unboundParameters .SelectMany(p => p.Parameter.ParameterSetData.Values) .Where(p => p.IsMandatory); foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetMetadatasForUnboundMandatoryParameters) { remainingParameterSetsWithNoMandatoryUnboundParameters &= (~parameterSetMetadata.ParameterSetFlag); } int finalParameterSetCount = ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters); if (finalParameterSetCount == 1) { _currentParameterSetFlag = remainingParameterSetsWithNoMandatoryUnboundParameters; if (command != null) { string currentParameterSetName = bindableParameters.GetParameterSetName(_currentParameterSetFlag); command.SetParameterSetName(currentParameterSetName); } return finalParameterSetCount; } return -1; } private void ThrowAmbiguousParameterSetException(uint parameterSetFlags, MergedCommandParameterMetadata bindableParameters) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, null, ParameterBinderStrings.AmbiguousParameterSet, "AmbiguousParameterSet"); // Trace the parameter sets still active uint currentParameterSet = 1; while (parameterSetFlags != 0) { uint currentParameterSetActive = parameterSetFlags & 0x1; if (currentParameterSetActive == 1) { string parameterSetName = bindableParameters.GetParameterSetName(currentParameterSet); if (!string.IsNullOrEmpty(parameterSetName)) { ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", parameterSetName); } } parameterSetFlags >>= 1; currentParameterSet <<= 1; } if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } } /// <summary> /// Determines if there are any unbound parameters that take pipeline input /// for the specified parameter sets. /// </summary> /// <param name="validParameterSetFlags"> /// The parameter sets that should be checked for each unbound parameter to see /// if it accepts pipeline input. /// </param> /// <returns> /// True if there is at least one parameter that takes pipeline input for the /// specified parameter sets, or false otherwise. /// </returns> private bool AtLeastOneUnboundValidParameterSetTakesPipelineInput(uint validParameterSetFlags) { bool result = false; // Loop through all the unbound parameters to see if there are any // that take pipeline input for the specified parameter sets. foreach (MergedCompiledCommandParameter parameter in UnboundParameters) { if (parameter.Parameter.DoesParameterSetTakePipelineInput(validParameterSetFlags)) { result = true; break; } } return result; } /// <summary> /// Checks for unbound mandatory parameters. If any are found, an exception is thrown. /// </summary> /// <param name="missingMandatoryParameters"> /// Returns the missing mandatory parameters, if any. /// </param> /// <returns> /// True if there are no unbound mandatory parameters. False if there are unbound mandatory parameters. /// </returns> internal bool HandleUnboundMandatoryParameters(out Collection<MergedCompiledCommandParameter> missingMandatoryParameters) { return HandleUnboundMandatoryParameters( ValidParameterSetCount(_currentParameterSetFlag), false, false, false, out missingMandatoryParameters); } /// <summary> /// Checks for unbound mandatory parameters. If any are found and promptForMandatory is true, /// the user will be prompted for the missing mandatory parameters. /// </summary> /// <param name="validParameterSetCount"> /// The number of valid parameter sets. /// </param> /// <param name="processMissingMandatory"> /// If true, unbound mandatory parameters will be processed via user prompting (if allowed by promptForMandatory). /// If false, unbound mandatory parameters will cause false to be returned. /// </param> /// <param name="promptForMandatory"> /// If true, unbound mandatory parameters will cause the user to be prompted. If false, unbound /// mandatory parameters will cause an exception to be thrown. /// </param> /// <param name="isPipelineInputExpected"> /// If true, then only parameters that don't take pipeline input will be prompted for. /// If false, any mandatory parameter that has not been specified will be prompted for. /// </param> /// <param name="missingMandatoryParameters"> /// Returns the missing mandatory parameters, if any. /// </param> /// <returns> /// True if there are no unbound mandatory parameters. False if there are unbound mandatory parameters /// and promptForMandatory if false. /// </returns> /// <exception cref="ParameterBindingException"> /// If prompting didn't result in a value for the parameter (only when <paramref name="promptForMandatory"/> is true.) /// </exception> internal bool HandleUnboundMandatoryParameters( int validParameterSetCount, bool processMissingMandatory, bool promptForMandatory, bool isPipelineInputExpected, out Collection<MergedCompiledCommandParameter> missingMandatoryParameters) { bool result = true; missingMandatoryParameters = GetMissingMandatoryParameters(validParameterSetCount, isPipelineInputExpected); if (missingMandatoryParameters.Count > 0) { if (processMissingMandatory) { // If the host interface wasn't specified or we were instructed not to prmopt, then throw // an exception instead if ((Context.EngineHostInterface == null) || (!promptForMandatory)) { Diagnostics.Assert( Context.EngineHostInterface != null, "The EngineHostInterface should never be null"); ParameterBinderBase.bindingTracer.WriteLine( "ERROR: host does not support prompting for missing mandatory parameters"); string missingParameters = BuildMissingParamsString(missingMandatoryParameters); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, missingParameters, null, null, ParameterBinderStrings.MissingMandatoryParameter, "MissingMandatoryParameter"); throw bindingException; } // Create a collection to store the prompt descriptions of unbound mandatory parameters Collection<FieldDescription> fieldDescriptionList = CreatePromptDataStructures(missingMandatoryParameters); Dictionary<string, PSObject> parameters = PromptForMissingMandatoryParameters( fieldDescriptionList, missingMandatoryParameters); using (ParameterBinderBase.bindingTracer.TraceScope( "BIND PROMPTED mandatory parameter args")) { // Now bind any parameters that were retrieved. foreach (KeyValuePair<string, PSObject> entry in parameters) { var argument = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, entry.Key, "-" + entry.Key + ":", /*argumentAst*/null, entry.Value, false); // Ignore the result since any failure should cause an exception result = BindParameter(argument, ParameterBindingFlags.ShouldCoerceType | ParameterBindingFlags.ThrowOnParameterNotFound); Diagnostics.Assert( result, "Any error in binding the parameter with type coercion should result in an exception"); } result = true; } } else { result = false; } } return result; } private Dictionary<string, PSObject> PromptForMissingMandatoryParameters( Collection<FieldDescription> fieldDescriptionList, Collection<MergedCompiledCommandParameter> missingMandatoryParameters) { Dictionary<string, PSObject> parameters = null; Exception error = null; // Prompt try { ParameterBinderBase.bindingTracer.WriteLine( "PROMPTING for missing mandatory parameters using the host"); string msg = ParameterBinderStrings.PromptMessage; InvocationInfo invoInfo = Command.MyInvocation; string caption = StringUtil.Format(ParameterBinderStrings.PromptCaption, invoInfo.MyCommand.Name, invoInfo.PipelinePosition); parameters = Context.EngineHostInterface.UI.Prompt(caption, msg, fieldDescriptionList); } catch (NotImplementedException notImplemented) { error = notImplemented; } catch (HostException hostException) { error = hostException; } catch (PSInvalidOperationException invalidOperation) { error = invalidOperation; } if (error != null) { ParameterBinderBase.bindingTracer.WriteLine( "ERROR: host does not support prompting for missing mandatory parameters"); string missingParameters = BuildMissingParamsString(missingMandatoryParameters); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, missingParameters, null, null, ParameterBinderStrings.MissingMandatoryParameter, "MissingMandatoryParameter"); throw bindingException; } if ((parameters == null) || (parameters.Count == 0)) { ParameterBinderBase.bindingTracer.WriteLine( "ERROR: still missing mandatory parameters after PROMPTING"); string missingParameters = BuildMissingParamsString(missingMandatoryParameters); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, missingParameters, null, null, ParameterBinderStrings.MissingMandatoryParameter, "MissingMandatoryParameter"); throw bindingException; } return parameters; } internal static string BuildMissingParamsString(Collection<MergedCompiledCommandParameter> missingMandatoryParameters) { StringBuilder missingParameters = new StringBuilder(); foreach (MergedCompiledCommandParameter missingParameter in missingMandatoryParameters) { missingParameters.AppendFormat(CultureInfo.InvariantCulture, " {0}", missingParameter.Parameter.Name); } return missingParameters.ToString(); } private Collection<FieldDescription> CreatePromptDataStructures( Collection<MergedCompiledCommandParameter> missingMandatoryParameters) { StringBuilder usedHotKeys = new StringBuilder(); Collection<FieldDescription> fieldDescriptionList = new Collection<FieldDescription>(); // See if any of the unbound parameters are mandatory foreach (MergedCompiledCommandParameter parameter in missingMandatoryParameters) { ParameterSetSpecificMetadata parameterSetMetadata = parameter.Parameter.GetParameterSetData(_currentParameterSetFlag); FieldDescription fDesc = new FieldDescription(parameter.Parameter.Name); string helpInfo = null; try { helpInfo = parameterSetMetadata.GetHelpMessage(Command); } catch (InvalidOperationException) { } catch (ArgumentException) { } if (!string.IsNullOrEmpty(helpInfo)) { fDesc.HelpMessage = helpInfo; } fDesc.SetParameterType(parameter.Parameter.Type); fDesc.Label = BuildLabel(parameter.Parameter.Name, usedHotKeys); foreach (ValidateArgumentsAttribute vaAttr in parameter.Parameter.ValidationAttributes) { fDesc.Attributes.Add(vaAttr); } foreach (ArgumentTransformationAttribute arAttr in parameter.Parameter.ArgumentTransformationAttributes) { fDesc.Attributes.Add(arAttr); } fDesc.IsMandatory = true; fieldDescriptionList.Add(fDesc); } return fieldDescriptionList; } /// <summary> /// Creates a label with a Hotkey from <paramref name="parameterName"/>. The Hotkey is /// <paramref name="parameterName"/>'s first capital character not in <paramref name="usedHotKeys"/>. /// If <paramref name="parameterName"/> does not have any capital character, the first lower /// case character is used. The Hotkey is preceded by an ampersand in the label. /// </summary> /// <param name="parameterName"> /// The parameter name from which the Hotkey is created /// </param> /// <param name="usedHotKeys"> /// A list of used HotKeys /// </param> /// <returns> /// A label made from parameterName with a HotKey indicated by an ampersand /// </returns> private static string BuildLabel(string parameterName, StringBuilder usedHotKeys) { Diagnostics.Assert(!string.IsNullOrEmpty(parameterName), "parameterName is not set"); const char hotKeyPrefix = '&'; bool built = false; StringBuilder label = new StringBuilder(parameterName); string usedHotKeysStr = usedHotKeys.ToString(); for (int i = 0; i < parameterName.Length; i++) { // try Upper case if (char.IsUpper(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); built = true; break; } } if (!built) { // try Lower case for (int i = 0; i < parameterName.Length; i++) { if (char.IsLower(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); built = true; break; } } } if (!built) { // try non-letters for (int i = 0; i < parameterName.Length; i++) { if (!char.IsLetter(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); built = true; break; } } } if (!built) { // use first char label.Insert(0, hotKeyPrefix); } return label.ToString(); } /// <summary> /// Gets the parameter set name for the current parameter set. /// </summary> internal string CurrentParameterSetName { get { string currentParameterSetName = BindableParameters.GetParameterSetName(_currentParameterSetFlag); s_tracer.WriteLine("CurrentParameterSetName = {0}", currentParameterSetName); return currentParameterSetName; } } /// <summary> /// Binds the specified object or its properties to parameters /// that accept pipeline input. /// </summary> /// <param name="inputToOperateOn"> /// The pipeline object to bind. /// </param> /// <returns> /// True if the pipeline input was bound successfully or there was nothing /// to bind, or false if there was an error. /// </returns> internal bool BindPipelineParameters(PSObject inputToOperateOn) { bool result; try { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND PIPELINE object to parameters: [{0}]", _commandMetadata.Name)) { // First run any of the delay bind ScriptBlocks and bind the // result to the appropriate parameter. bool thereWasSomethingToBind; bool invokeScriptResult = InvokeAndBindDelayBindScriptBlock(inputToOperateOn, out thereWasSomethingToBind); bool continueBindingAfterScriptBlockProcessing = !thereWasSomethingToBind || invokeScriptResult; bool bindPipelineParametersResult = false; if (continueBindingAfterScriptBlockProcessing) { // If any of the parameters in the parameter set which are not yet bound // accept pipeline input, process the input object and bind to those // parameters bindPipelineParametersResult = BindPipelineParametersPrivate(inputToOperateOn); } // We are successful at binding the pipeline input if there was a ScriptBlock to // run and it ran successfully or if we successfully bound a parameter based on // the pipeline input. result = (thereWasSomethingToBind && invokeScriptResult) || bindPipelineParametersResult; } } catch (ParameterBindingException) { // Reset the default values // This prevents the last pipeline object from being bound during EndProcessing // if it failed some post binding verification step. this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput); // Let the parameter binding errors propagate out throw; } try { // Now make sure we have latched on to a single parameter set. VerifyParameterSetSelected(); } catch (ParameterBindingException) { // Reset the default values // This prevents the last pipeline object from being bound during EndProcessing // if it failed some post binding verification step. this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput); throw; } if (!result) { // Reset the default values // This prevents the last pipeline object from being bound during EndProcessing // if it failed some post binding verification step. this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput); } return result; } /// <summary> /// Binds the pipeline parameters using the specified input and parameter set. /// </summary> /// <param name="inputToOperateOn"> /// The pipeline input to be bound to the parameters. /// </param> /// <exception cref="ParameterBindingException"> /// If argument transformation fails. /// or /// The argument could not be coerced to the appropriate type for the parameter. /// or /// The parameter argument transformation, prerequisite, or validation failed. /// or /// If the binding to the parameter fails. /// or /// If there is a failure resetting values prior to binding from the pipeline /// </exception> /// <remarks> /// The algorithm for binding the pipeline object is as follows. If any /// step is successful true gets returned immediately. /// /// - If parameter supports ValueFromPipeline /// - attempt to bind input value without type coercion /// - If parameter supports ValueFromPipelineByPropertyName /// - attempt to bind the value of the property with the matching name without type coercion /// /// Now see if we have a single valid parameter set and reset the validParameterSets flags as /// necessary. If there are still multiple valid parameter sets, then we need to use TypeDistance /// to determine which parameters to do type coercion binding on. /// /// - If parameter supports ValueFromPipeline /// - attempt to bind input value using type coercion /// - If parameter support ValueFromPipelineByPropertyName /// - attempt to bind the vlue of the property with the matching name using type coercion /// </remarks> private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) { if (ParameterBinderBase.bindingTracer.IsEnabled) { ConsolidatedString dontuseInternalTypeNames; ParameterBinderBase.bindingTracer.WriteLine( "PIPELINE object TYPE = [{0}]", inputToOperateOn == null || inputToOperateOn == AutomationNull.Value ? "null" : ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] != null) ? dontuseInternalTypeNames[0] : inputToOperateOn.BaseObject.GetType().FullName); ParameterBinderBase.bindingTracer.WriteLine("RESTORING pipeline parameter's original values"); } bool result = false; // Reset the default values this.RestoreDefaultParameterValues(ParametersBoundThroughPipelineInput); // Now clear the parameter names from the previous pipeline input ParametersBoundThroughPipelineInput.Clear(); // Now restore the parameter set flags _currentParameterSetFlag = _prePipelineProcessingParameterSetFlags; uint validParameterSets = _currentParameterSetFlag; bool needToPrioritizeOneSpecificParameterSet = _parameterSetToBePrioritizedInPipelineBinding != 0; int steps = needToPrioritizeOneSpecificParameterSet ? 2 : 1; if (needToPrioritizeOneSpecificParameterSet) { // _parameterSetToBePrioritizedInPipelineBinding is set, so we are certain that the specified parameter set must be valid, // and it's not the only valid parameter set. Diagnostics.Assert((_currentParameterSetFlag & _parameterSetToBePrioritizedInPipelineBinding) != 0, "_parameterSetToBePrioritizedInPipelineBinding should be valid if it's set"); validParameterSets = _parameterSetToBePrioritizedInPipelineBinding; } for (int i = 0; i < steps; i++) { for (CurrentlyBinding currentlyBinding = CurrentlyBinding.ValueFromPipelineNoCoercion; currentlyBinding <= CurrentlyBinding.ValueFromPipelineByPropertyNameWithCoercion; ++currentlyBinding) { // The parameterBoundForCurrentlyBindingState will be true as long as there is one parameter gets bound, even if it belongs to AllSet bool parameterBoundForCurrentlyBindingState = BindUnboundParametersForBindingState( inputToOperateOn, currentlyBinding, validParameterSets); if (parameterBoundForCurrentlyBindingState) { // Now validate the parameter sets again and update the valid sets. // No need to validate the parameter sets and update the valid sets when dealing with the prioritized parameter set, // this is because the prioritized parameter set is a single set, and when binding succeeds, _currentParameterSetFlag // must be equal to the specific prioritized parameter set. if (!needToPrioritizeOneSpecificParameterSet || i == 1) { ValidateParameterSets(true, true); validParameterSets = _currentParameterSetFlag; } result = true; } } // Update the validParameterSets after the binding attempt for the prioritized parameter set if (needToPrioritizeOneSpecificParameterSet && i == 0) { // If the prioritized set can be bound successfully, there is no need to do the second round binding if (_currentParameterSetFlag == _parameterSetToBePrioritizedInPipelineBinding) break; validParameterSets = _currentParameterSetFlag & (~_parameterSetToBePrioritizedInPipelineBinding); } } // Now make sure we only have one valid parameter set // Note, this will throw if we have more than one. ValidateParameterSets(false, true); if (!DefaultParameterBindingInUse) { ApplyDefaultParameterBinding("PIPELINE BIND", false); } return result; } private bool BindUnboundParametersForBindingState( PSObject inputToOperateOn, CurrentlyBinding currentlyBinding, uint validParameterSets) { bool aParameterWasBound = false; // First check to see if the default parameter set has been defined and if it // is still valid. uint defaultParameterSetFlag = _commandMetadata.DefaultParameterSetFlag; if (defaultParameterSetFlag != 0 && (validParameterSets & defaultParameterSetFlag) != 0) { // Since we have a default parameter set and it is still valid, give preference to the // parameters in the default set. aParameterWasBound = BindUnboundParametersForBindingStateInParameterSet( inputToOperateOn, currentlyBinding, defaultParameterSetFlag); if (!aParameterWasBound) { validParameterSets &= ~(defaultParameterSetFlag); } } if (!aParameterWasBound) { // Since nothing was bound for the default parameter set, try all // the other parameter sets that are still valid. aParameterWasBound = BindUnboundParametersForBindingStateInParameterSet( inputToOperateOn, currentlyBinding, validParameterSets); } s_tracer.WriteLine("aParameterWasBound = {0}", aParameterWasBound); return aParameterWasBound; } private bool BindUnboundParametersForBindingStateInParameterSet( PSObject inputToOperateOn, CurrentlyBinding currentlyBinding, uint validParameterSets) { bool aParameterWasBound = false; // For all unbound parameters in the parameter set, see if we can bind // from the input object directly from pipeline without type coercion. // // We loop the unbound parameters in reversed order, so that we can move // items from the unboundParameters collection to the boundParameters // collection as we process, without the need to make a copy of the // unboundParameters collection. // // We used to make a copy of UnboundParameters and loop from the head of the // list. Now we are processing the unbound parameters from the end of the list. // This change should NOT be a breaking change. The 'validParameterSets' in // this method never changes, so no matter we start from the head or the end of // the list, every unbound parameter in the list that takes pipeline input and // satisfy the 'validParameterSets' will be bound. If parameters from more than // one sets got bound, then "parameter set cannot be resolved" error will be thrown, // which is expected. for (int i = UnboundParameters.Count - 1; i >= 0; i--) { var parameter = UnboundParameters[i]; // if the parameter is never a pipeline parameter, don't consider it if (!parameter.Parameter.IsPipelineParameterInSomeParameterSet) continue; // if the parameter is not in the specified parameter set, don't consider it if ((validParameterSets & parameter.Parameter.ParameterSetFlags) == 0 && !parameter.Parameter.IsInAllSets) { continue; } // Get the appropriate parameter set data var parameterSetData = parameter.Parameter.GetMatchingParameterSetData(validParameterSets); bool bindResult = false; foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetData) { // In the first phase we try to bind the value from the pipeline without // type coercion if (currentlyBinding == CurrentlyBinding.ValueFromPipelineNoCoercion && parameterSetMetadata.ValueFromPipeline) { bindResult = BindValueFromPipeline(inputToOperateOn, parameter, ParameterBindingFlags.None); } // In the next phase we try binding the value from the pipeline by matching // the property name else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameNoCoercion && parameterSetMetadata.ValueFromPipelineByPropertyName && inputToOperateOn != null) { bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.None); } // The third step is to attempt to bind the value from the pipeline with // type coercion. else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineWithCoercion && parameterSetMetadata.ValueFromPipeline) { bindResult = BindValueFromPipeline(inputToOperateOn, parameter, ParameterBindingFlags.ShouldCoerceType); } // The final step is to attempt to bind the value from the pipeline by matching // the property name else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameWithCoercion && parameterSetMetadata.ValueFromPipelineByPropertyName && inputToOperateOn != null) { bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.ShouldCoerceType); } if (bindResult) { aParameterWasBound = true; break; } } } return aParameterWasBound; } private bool BindValueFromPipeline( PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool bindResult = false; // Attempt binding the value from the pipeline // without type coercion ParameterBinderBase.bindingTracer.WriteLine( ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION", parameter.Parameter.Name); ParameterBindingException parameterBindingException = null; try { bindResult = BindPipelineParameter(inputToOperateOn, parameter, flags); } catch (ParameterBindingArgumentTransformationException e) { PSInvalidCastException invalidCast; if (e.InnerException is ArgumentTransformationMetadataException) { invalidCast = e.InnerException.InnerException as PSInvalidCastException; } else { invalidCast = e.InnerException as PSInvalidCastException; } if (invalidCast == null) { parameterBindingException = e; } // Just ignore and continue; bindResult = false; } catch (ParameterBindingValidationException e) { parameterBindingException = e; } catch (ParameterBindingParameterDefaultValueException e) { parameterBindingException = e; } catch (ParameterBindingException) { // Just ignore and continue; bindResult = false; } if (parameterBindingException != null) { if (!DefaultParameterBindingInUse) { throw parameterBindingException; } else { ThrowElaboratedBindingException(parameterBindingException); } } return bindResult; } private bool BindValueFromPipelineByPropertyName( PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool bindResult = false; ParameterBinderBase.bindingTracer.WriteLine( ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION", parameter.Parameter.Name); PSMemberInfo member = inputToOperateOn.Properties[parameter.Parameter.Name]; if (member == null) { // Since a member matching the name of the parameter wasn't found, // check the aliases. foreach (string alias in parameter.Parameter.Aliases) { member = inputToOperateOn.Properties[alias]; if (member != null) { break; } } } if (member != null) { ParameterBindingException parameterBindingException = null; try { bindResult = BindPipelineParameter( member.Value, parameter, flags); } catch (ParameterBindingArgumentTransformationException e) { parameterBindingException = e; } catch (ParameterBindingValidationException e) { parameterBindingException = e; } catch (ParameterBindingParameterDefaultValueException e) { parameterBindingException = e; } catch (ParameterBindingException) { // Just ignore and continue; bindResult = false; } if (parameterBindingException != null) { if (!DefaultParameterBindingInUse) { throw parameterBindingException; } else { ThrowElaboratedBindingException(parameterBindingException); } } } return bindResult; } /// <summary> /// Used for defining the state of the binding state machine. /// </summary> private enum CurrentlyBinding { ValueFromPipelineNoCoercion = 0, ValueFromPipelineByPropertyNameNoCoercion = 1, ValueFromPipelineWithCoercion = 2, ValueFromPipelineByPropertyNameWithCoercion = 3 } /// <summary> /// Invokes any delay bind script blocks and binds the resulting value /// to the appropriate parameter. /// </summary> /// <param name="inputToOperateOn"> /// The input to the script block. /// </param> /// <param name="thereWasSomethingToBind"> /// Returns True if there was a ScriptBlock to invoke and bind, or false if there /// are no ScriptBlocks to invoke. /// </param> /// <returns> /// True if the binding succeeds, or false otherwise. /// </returns> /// <exception cref="ArgumentNullException"> /// if <paramref name="inputToOperateOn"/> is null. /// </exception> /// <exception cref="ParameterBindingException"> /// If execution of the script block throws an exception or if it doesn't produce /// any output. /// </exception> private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bool thereWasSomethingToBind) { thereWasSomethingToBind = false; bool result = true; // NOTE: we are not doing backup and restore of default parameter // values here. It is not needed because each script block will be // invoked and each delay bind parameter bound for each pipeline object. // This is unlike normal pipeline object processing which may bind // different parameters depending on the type of the incoming pipeline // object. // Loop through each of the delay bind script blocks and invoke them. // Bind the result to the associated parameter foreach (KeyValuePair<MergedCompiledCommandParameter, DelayedScriptBlockArgument> delayedScriptBlock in _delayBindScriptBlocks) { thereWasSomethingToBind = true; CommandParameterInternal argument = delayedScriptBlock.Value._argument; MergedCompiledCommandParameter parameter = delayedScriptBlock.Key; ScriptBlock script = argument.ArgumentValue as ScriptBlock; Diagnostics.Assert( script != null, "An argument should only be put in the delayBindScriptBlocks collection if it is a ScriptBlock"); Collection<PSObject> output = null; Exception error = null; using (ParameterBinderBase.bindingTracer.TraceScope( "Invoking delay-bind ScriptBlock")) { if (delayedScriptBlock.Value._parameterBinder == this) { try { output = script.DoInvoke(inputToOperateOn, inputToOperateOn, Array.Empty<object>()); delayedScriptBlock.Value._evaluatedArgument = output; } catch (RuntimeException runtimeException) { error = runtimeException; } } else { output = delayedScriptBlock.Value._evaluatedArgument; } } if (error != null) { ParameterBindingException bindingException = new ParameterBindingException( error, ErrorCategory.InvalidArgument, this.Command.MyInvocation, GetErrorExtent(argument), parameter.Parameter.Name, null, null, ParameterBinderStrings.ScriptBlockArgumentInvocationFailed, "ScriptBlockArgumentInvocationFailed", error.Message); throw bindingException; } if (output == null || output.Count == 0) { ParameterBindingException bindingException = new ParameterBindingException( null, ErrorCategory.InvalidArgument, this.Command.MyInvocation, GetErrorExtent(argument), parameter.Parameter.Name, null, null, ParameterBinderStrings.ScriptBlockArgumentNoOutput, "ScriptBlockArgumentNoOutput"); throw bindingException; } // Check the output. If it is only a single value, just pass the single value, // if not, pass in the whole collection. object newValue = output; if (output.Count == 1) { newValue = output[0]; } // Create a new CommandParameterInternal for the output of the script block. var newArgument = CommandParameterInternal.CreateParameterWithArgument( argument.ParameterAst, argument.ParameterName, "-" + argument.ParameterName + ":", argument.ArgumentAst, newValue, false); if (!BindParameter(newArgument, parameter, ParameterBindingFlags.ShouldCoerceType)) { result = false; } } return result; } /// <summary> /// Determines the number of valid parameter sets based on the valid parameter /// set flags. /// </summary> /// <param name="parameterSetFlags"> /// The valid parameter set flags. /// </param> /// <returns> /// The number of valid parameter sets in the parameterSetFlags. /// </returns> private static int ValidParameterSetCount(uint parameterSetFlags) { int result = 0; if (parameterSetFlags == uint.MaxValue) { result = 1; } else { while (parameterSetFlags != 0) { result += (int)(parameterSetFlags & 0x1); parameterSetFlags >>= 1; } } return result; } #endregion helper_methods #region private_members /// <summary> /// This method gets a backup of the default value of a parameter. /// Derived classes may override this method to get the default parameter /// value in a different way. /// </summary> /// <param name="name"> /// The name of the parameter to get the default value of. /// </param> /// <returns> /// The value of the parameter specified by name. /// </returns> /// <exception cref="ParameterBindingParameterDefaultValueException"> /// If the parameter binder encounters an error getting the default value. /// </exception> internal object GetDefaultParameterValue(string name) { MergedCompiledCommandParameter matchingParameter = BindableParameters.GetMatchingParameter( name, false, true, null); object result = null; try { switch (matchingParameter.BinderAssociation) { case ParameterBinderAssociation.DeclaredFormalParameters: result = DefaultParameterBinder.GetDefaultParameterValue(name); break; case ParameterBinderAssociation.CommonParameters: result = CommonParametersBinder.GetDefaultParameterValue(name); break; case ParameterBinderAssociation.ShouldProcessParameters: result = ShouldProcessParametersBinder.GetDefaultParameterValue(name); break; case ParameterBinderAssociation.DynamicParameters: if (_dynamicParameterBinder != null) { result = _dynamicParameterBinder.GetDefaultParameterValue(name); } break; } } catch (GetValueException getValueException) { ParameterBindingParameterDefaultValueException bindingError = new ParameterBindingParameterDefaultValueException( getValueException, ErrorCategory.ReadError, this.Command.MyInvocation, null, name, null, null, "ParameterBinderStrings", "GetDefaultValueFailed", getValueException.Message); throw bindingError; } return result; } /// <summary> /// Gets or sets the command that this parameter binder controller /// will bind parameters to. /// </summary> internal Cmdlet Command { get; private set; } #region DefaultParameterBindingStructures /// <summary> /// The separator used in GetDefaultParameterValuePairs function. /// </summary> private const string Separator = ":::"; // Hold all aliases of the current cmdlet private List<string> _aliasList; // Method GetDefaultParameterValuePairs() will be invoked twice, one time before the Named Bind, // one time after Dynamic Bind. We don't want the same warning message to be written out twice. // Put the key(in case the key format is invalid), or cmdletName+separator+parameterName(in case // setting resolves to multiple parameters or multiple different values are assigned to the same // parameter) in warningSet when the corresponding warnings are written out, so they won't get // written out the second time GetDefaultParameterValuePairs() is called. private readonly HashSet<string> _warningSet = new HashSet<string>(); // Hold all user defined default parameter values private Dictionary<MergedCompiledCommandParameter, object> _allDefaultParameterValuePairs; private bool _useDefaultParameterBinding = true; #endregion DefaultParameterBindingStructures private uint _parameterSetToBePrioritizedInPipelineBinding = 0; /// <summary> /// The cmdlet metadata. /// </summary> private readonly CommandMetadata _commandMetadata; /// <summary> /// THe command runtime object for this cmdlet. /// </summary> private readonly MshCommandRuntime _commandRuntime; /// <summary> /// Keep the obsolete parameter warnings generated from parameter binding. /// </summary> internal List<WarningRecord> ObsoleteParameterWarningList { get; private set; } /// <summary> /// Keep names of the parameters for which we have generated obsolete warning messages. /// </summary> private HashSet<string> BoundObsoleteParameterNames { get { return _boundObsoleteParameterNames ?? (_boundObsoleteParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)); } } private HashSet<string> _boundObsoleteParameterNames; /// <summary> /// The parameter binder for the dynamic parameters. Currently this /// can be either a ReflectionParameterBinder or a RuntimeDefinedParameterBinder. /// </summary> private ParameterBinderBase _dynamicParameterBinder; /// <summary> /// The parameter binder for the ShouldProcess parameters. /// </summary> internal ReflectionParameterBinder ShouldProcessParametersBinder { get { if (_shouldProcessParameterBinder == null) { // Construct a new instance of the should process parameters object ShouldProcessParameters shouldProcessParameters = new ShouldProcessParameters(_commandRuntime); // Create reflection binder for this object _shouldProcessParameterBinder = new ReflectionParameterBinder( shouldProcessParameters, this.Command, this.CommandLineParameters); } return _shouldProcessParameterBinder; } } private ReflectionParameterBinder _shouldProcessParameterBinder; /// <summary> /// The parameter binder for the Paging parameters. /// </summary> internal ReflectionParameterBinder PagingParametersBinder { get { if (_pagingParameterBinder == null) { // Construct a new instance of the should process parameters object PagingParameters pagingParameters = new PagingParameters(_commandRuntime); // Create reflection binder for this object _pagingParameterBinder = new ReflectionParameterBinder( pagingParameters, this.Command, this.CommandLineParameters); } return _pagingParameterBinder; } } private ReflectionParameterBinder _pagingParameterBinder; /// <summary> /// The parameter binder for the Transactions parameters. /// </summary> internal ReflectionParameterBinder TransactionParametersBinder { get { if (_transactionParameterBinder == null) { // Construct a new instance of the transactions parameters object TransactionParameters transactionParameters = new TransactionParameters(_commandRuntime); // Create reflection binder for this object _transactionParameterBinder = new ReflectionParameterBinder( transactionParameters, this.Command, this.CommandLineParameters); } return _transactionParameterBinder; } } private ReflectionParameterBinder _transactionParameterBinder; /// <summary> /// The parameter binder for the CommonParameters. /// </summary> internal ReflectionParameterBinder CommonParametersBinder { get { if (_commonParametersBinder == null) { // Construct a new instance of the user feedback parameters object CommonParameters commonParameters = new CommonParameters(_commandRuntime); // Create reflection binder for this object _commonParametersBinder = new ReflectionParameterBinder( commonParameters, this.Command, this.CommandLineParameters); } return _commonParametersBinder; } } private ReflectionParameterBinder _commonParametersBinder; private class DelayedScriptBlockArgument { // Remember the parameter binder so we know when to invoke the script block // and when to use the evaluated argument. internal CmdletParameterBinderController _parameterBinder; internal CommandParameterInternal _argument; internal Collection<PSObject> _evaluatedArgument; public override string ToString() { return _argument.ArgumentValue.ToString(); } } /// <summary> /// This dictionary is used to contain the arguments that were passed in as ScriptBlocks /// but the parameter isn't a ScriptBlock. So we have to wait to bind the parameter /// until there is a pipeline object available to invoke the ScriptBlock with. /// </summary> private readonly Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument> _delayBindScriptBlocks = new Dictionary<MergedCompiledCommandParameter, DelayedScriptBlockArgument>(); /// <summary> /// A collection of the default values of the parameters. /// </summary> private readonly Dictionary<string, CommandParameterInternal> _defaultParameterValues = new Dictionary<string, CommandParameterInternal>(StringComparer.OrdinalIgnoreCase); #endregion private_members /// <summary> /// Binds the specified value to the specified parameter. /// </summary> /// <param name="parameterValue"> /// The value to bind to the parameter /// </param> /// <param name="parameter"> /// The parameter to bind the value to. /// </param> /// <param name="flags"> /// Parameter binding flags for type coercion and validation. /// </param> /// <returns> /// True if the parameter was successfully bound. False if <paramref name="flags"/> /// specifies no coercion and the type does not match the parameter type. /// </returns> /// <exception cref="ParameterBindingParameterDefaultValueException"> /// If the parameter binder encounters an error getting the default value. /// </exception> private bool BindPipelineParameter( object parameterValue, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) { bool result = false; if (parameterValue != AutomationNull.Value) { s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", parameter.Parameter.Name, parameterValue ?? "null"); // Backup the default value BackupDefaultParameter(parameter); // Now bind the new value CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", /*argumentAst*/null, parameterValue, false); flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock; result = BindParameter(_currentParameterSetFlag, param, parameter, flags); if (result) { // Now make sure to remember that the default value needs to be restored // if we get another pipeline object ParametersBoundThroughPipelineInput.Add(parameter); } } return result; } protected override void SaveDefaultScriptParameterValue(string name, object value) { _defaultParameterValues.Add(name, CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, name, "-" + name + ":", /*argumentAst*/null, value, false)); } /// <summary> /// Backs up the specified parameter value by calling the GetDefaultParameterValue /// abstract method. /// /// This method is called when binding a parameter value that came from a pipeline /// object. /// </summary> /// <exception cref="ParameterBindingParameterDefaultValueException"> /// If the parameter binder encounters an error getting the default value. /// </exception> private void BackupDefaultParameter(MergedCompiledCommandParameter parameter) { if (!_defaultParameterValues.ContainsKey(parameter.Parameter.Name)) { object defaultParameterValue = GetDefaultParameterValue(parameter.Parameter.Name); _defaultParameterValues.Add( parameter.Parameter.Name, CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", /*argumentAst*/null, defaultParameterValue, false)); } } /// <summary> /// Replaces the values of the parameters with their initial value for the /// parameters specified. /// </summary> /// <param name="parameters"> /// The parameters that should have their default values restored. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="parameters"/> is null. /// </exception> private void RestoreDefaultParameterValues(IEnumerable<MergedCompiledCommandParameter> parameters) { if (parameters == null) { throw PSTraceSource.NewArgumentNullException("parameters"); } // Get all the matching arguments from the defaultParameterValues collection // and bind those that had parameters that were bound via pipeline input foreach (MergedCompiledCommandParameter parameter in parameters) { if (parameter == null) { continue; } CommandParameterInternal argumentToBind = null; // If the argument was found then bind it to the parameter // and manage the bound and unbound parameter list if (_defaultParameterValues.TryGetValue(parameter.Parameter.Name, out argumentToBind)) { // Don't go through the normal binding routine to run data generation, // type coercion, validation, or prerequisites since we know the // type is already correct, and we don't want data generation to // run when resetting the default value. Exception error = null; try { // We shouldn't have to coerce the type here so its // faster to pass false bool bindResult = RestoreParameter(argumentToBind, parameter); Diagnostics.Assert( bindResult, "Restoring the default value should not require type coercion"); } catch (SetValueException setValueException) { error = setValueException; } if (error != null) { Type specifiedType = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType(); ParameterBindingException bindingException = new ParameterBindingException( error, ErrorCategory.WriteError, this.InvocationInfo, GetErrorExtent(argumentToBind), parameter.Parameter.Name, parameter.Parameter.Type, specifiedType, ParameterBinderStrings.ParameterBindingFailed, "ParameterBindingFailed", error.Message); throw bindingException; } // Since the parameter was returned to its original value, // ensure that it is not in the boundParameters list but // is in the unboundParameters list BoundParameters.Remove(parameter.Parameter.Name); if (!UnboundParameters.Contains(parameter)) { UnboundParameters.Add(parameter); } BoundArguments.Remove(parameter.Parameter.Name); } else { // Since the parameter was not reset, ensure that the parameter // is in the bound parameters list and not in the unbound // parameters list if (!BoundParameters.ContainsKey(parameter.Parameter.Name)) { BoundParameters.Add(parameter.Parameter.Name, parameter); } // Ensure the parameter is not in the unboundParameters list UnboundParameters.Remove(parameter); } } } } /// <summary> /// A versionable hashtable, so the caching of UserInput -> ParameterBindingResult will work. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "DefaultParameterDictionary will only be used for $PSDefaultParameterValues.")] public sealed class DefaultParameterDictionary : Hashtable { private bool _isChanged; /// <summary> /// Check to see if the hashtable has been changed since last check. /// </summary> /// <returns>True for changed; false for not changed.</returns> public bool ChangeSinceLastCheck() { bool ret = _isChanged; _isChanged = false; return ret; } #region Constructor /// <summary> /// Default constructor. /// </summary> public DefaultParameterDictionary() : base(StringComparer.OrdinalIgnoreCase) { _isChanged = true; } /// <summary> /// Constructor takes a hash table. /// </summary> /// <remarks> /// Check for the keys' formats and make it versionable /// </remarks> /// <param name="dictionary">A hashtable instance.</param> public DefaultParameterDictionary(IDictionary dictionary) : this() { if (dictionary == null) { throw PSTraceSource.NewArgumentNullException("dictionary"); } // Contains keys that are in bad format. For every bad format key, we should write out a warning message // the first time we encounter it, and remove it from the $PSDefaultParameterValues var keysInBadFormat = new List<object>(); foreach (DictionaryEntry entry in dictionary) { var entryKey = entry.Key as string; if (entryKey != null) { string key = entryKey.Trim(); string cmdletName = null; string parameterName = null; bool isSpecialKey = false; // The key is 'Disabled' // The key is not with valid format if (!CheckKeyIsValid(key, ref cmdletName, ref parameterName)) { isSpecialKey = key.Equals("Disabled", StringComparison.OrdinalIgnoreCase); if (!isSpecialKey) { keysInBadFormat.Add(entryKey); continue; } } Diagnostics.Assert(isSpecialKey || (cmdletName != null && parameterName != null), "The cmdletName and parameterName should be set in CheckKeyIsValid"); if (keysInBadFormat.Count == 0 && !base.ContainsKey(key)) { base.Add(key, entry.Value); } } else { keysInBadFormat.Add(entry.Key); } } var keysInError = new StringBuilder(); foreach (object badFormatKey in keysInBadFormat) { keysInError.Append(badFormatKey.ToString() + ", "); } if (keysInError.Length > 0) { keysInError.Remove(keysInError.Length - 2, 2); string resourceString = keysInBadFormat.Count > 1 ? ParameterBinderStrings.MultipleKeysInBadFormat : ParameterBinderStrings.SingleKeyInBadFormat; throw PSTraceSource.NewInvalidOperationException(resourceString, keysInError); } } #endregion Constructor /// <summary> /// Override Contains. /// </summary> public override bool Contains(object key) { return this.ContainsKey(key); } /// <summary> /// Override ContainsKey. /// </summary> public override bool ContainsKey(object key) { if (key == null) { throw PSTraceSource.NewArgumentNullException("key"); } var strKey = key as string; if (strKey == null) { return false; } string keyAfterTrim = strKey.Trim(); return base.ContainsKey(keyAfterTrim); } /// <summary> /// Override the Add to check for key's format and make it versionable. /// </summary> /// <param name="key">Key.</param> /// <param name="value">Value.</param> public override void Add(object key, object value) { AddImpl(key, value, isSelfIndexing: false); } /// <summary> /// Actual implementation for Add. /// </summary> private void AddImpl(object key, object value, bool isSelfIndexing) { if (key == null) { throw PSTraceSource.NewArgumentNullException("key"); } var strKey = key as string; if (strKey == null) { throw PSTraceSource.NewArgumentException("key", ParameterBinderStrings.StringValueKeyExpected, key, key.GetType().FullName); } string keyAfterTrim = strKey.Trim(); string cmdletName = null; string parameterName = null; if (base.ContainsKey(keyAfterTrim)) { if (isSelfIndexing) { _isChanged = true; base[keyAfterTrim] = value; return; } throw PSTraceSource.NewArgumentException("key", ParameterBinderStrings.KeyAlreadyAdded, key); } if (!CheckKeyIsValid(keyAfterTrim, ref cmdletName, ref parameterName)) { // The key is not in valid format if (!keyAfterTrim.Equals("Disabled", StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewInvalidOperationException(ParameterBinderStrings.SingleKeyInBadFormat, key); } } _isChanged = true; base.Add(keyAfterTrim, value); } /// <summary> /// Override the indexing to check for key's format and make it versionable. /// </summary> /// <param name="key"></param> /// <returns></returns> public override object this[object key] { get { if (key == null) { throw PSTraceSource.NewArgumentNullException("key"); } var strKey = key as string; if (strKey == null) { return null; } string keyAfterTrim = strKey.Trim(); return base[keyAfterTrim]; } set { AddImpl(key, value, isSelfIndexing: true); } } /// <summary> /// Override the Remove to make it versionable. /// </summary> /// <param name="key">Key.</param> public override void Remove(object key) { if (key == null) { throw PSTraceSource.NewArgumentNullException("key"); } var strKey = key as string; if (strKey == null) { return; } string keyAfterTrim = strKey.Trim(); if (base.ContainsKey(keyAfterTrim)) { base.Remove(keyAfterTrim); _isChanged = true; } } /// <summary> /// Override the Clear to make it versionable. /// </summary> public override void Clear() { base.Clear(); _isChanged = true; } #region KeyValidation /// <summary> /// Check if the key is in valid format. If it is, get the cmdlet name and parameter name. /// </summary> /// <param name="key"></param> /// <param name="cmdletName"></param> /// <param name="parameterName"></param> /// <returns>Return true if the key is valid, false if not.</returns> internal static bool CheckKeyIsValid(string key, ref string cmdletName, ref string parameterName) { if (key == string.Empty) { return false; } // The index returned should point to the separator or a character that is before the separator int index = GetValueToken(0, key, ref cmdletName, true); if (index == -1) { return false; } // The index returned should point to the first non-whitespace character, and it should be the separator index = SkipWhiteSpace(index, key); if (index == -1 || key[index] != ':') { return false; } // The index returned should point to the first non-whitespace character after the separator index = SkipWhiteSpace(index + 1, key); if (index == -1) { return false; } // The index returned should point to the last character in key index = GetValueToken(index, key, ref parameterName, false); if (index == -1 || index != key.Length) { return false; } return true; } /// <summary> /// Get the cmdlet name and the parameter name. /// </summary> /// <param name="index">Point to a non-whitespace character.</param> /// <param name="key">The key to iterate over.</param> /// <param name="name"></param> /// <param name="getCmdletName">Specify whether to get the cmdlet name or parameter name.</param> /// <returns> /// For cmdletName: /// When the name is enclosed by quotes, the index returned should be the index of the character right after the second quote; /// When the name is not enclosed by quotes, the index returned should be the index of the separator; /// /// For parameterName: /// When the name is enclosed by quotes, the index returned should be the index of the second quote plus 1 (the length of the key if the key is in a valid format); /// When the name is not enclosed by quotes, the index returned should be the length of the key. /// </returns> private static int GetValueToken(int index, string key, ref string name, bool getCmdletName) { char quoteChar = '\0'; if (key[index].IsSingleQuote() || key[index].IsDoubleQuote()) { quoteChar = key[index]; index++; } StringBuilder builder = new StringBuilder(string.Empty); for (; index < key.Length; index++) { if (quoteChar != '\0') { if ((quoteChar.IsSingleQuote() && key[index].IsSingleQuote()) || (quoteChar.IsDoubleQuote() && key[index].IsDoubleQuote())) { name = builder.ToString().Trim(); // Make the index point to the character right after the quote return name.Length == 0 ? -1 : index + 1; } builder.Append(key[index]); continue; } if (getCmdletName) { if (key[index] != ':') { builder.Append(key[index]); continue; } name = builder.ToString().Trim(); return name.Length == 0 ? -1 : index; } else { builder.Append(key[index]); } } if (!getCmdletName && quoteChar == '\0') { name = builder.ToString().Trim(); Diagnostics.Assert(name.Length > 0, "name should not be empty at this point"); return index; } return -1; } /// <summary> /// Skip whitespace characters. /// </summary> /// <param name="index">Start index.</param> /// <param name="key">The string to iterate over.</param> /// <returns> /// Return -1 if we reach the end of the key, otherwise return the index of the first /// non-whitespace character we encounter. /// </returns> private static int SkipWhiteSpace(int index, string key) { for (; index < key.Length; index++) { if (key[index].IsWhitespace() || key[index] == '\r' || key[index] == '\n') continue; return index; } return -1; } #endregion KeyValidation } }
45.445732
256
0.517038
[ "MIT" ]
3v1lW1th1n/PowerShell-1
src/System.Management.Automation/engine/CmdletParameterBinderController.cs
215,640
C#
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; namespace EmbeddedMail { // Shamelessly ripped out of Fleck. Thanks, Jason ;) public interface ISocket { string RemoteIpAddress { get; } bool Connected { get; } Stream Stream { get; } Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error); Task Send(byte[] buffer, Action callback, Action<Exception> error); Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset = 0); void Dispose(); void Close(); void Bind(EndPoint ipLocal); void Listen(int backlog); } public class SocketWrapper : ISocket { private readonly Socket _socket; private Stream _stream; public string RemoteIpAddress { get { var endpoint = _socket.RemoteEndPoint as IPEndPoint; return endpoint != null ? endpoint.Address.ToString() : null; } } public SocketWrapper(Socket socket) { _socket = socket; if (_socket.Connected) _stream = new NetworkStream(_socket); } public void Listen(int backlog) { _socket.Listen(backlog); } public void Bind(EndPoint endPoint) { _socket.Bind(endPoint); } public bool Connected { get { return _socket.Connected; } } public Stream Stream { get { return _stream; } } public Task<int> Receive(byte[] buffer, Action<int> callback, Action<Exception> error, int offset) { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginRead(buffer, offset, buffer.Length, cb, s); Task<int> task = Task.Factory.FromAsync<int>(begin, _stream.EndRead, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public Task<ISocket> Accept(Action<ISocket> callback, Action<Exception> error) { Func<IAsyncResult, ISocket> end = r => new SocketWrapper(_socket.EndAccept(r)); var task = Task.Factory.FromAsync(_socket.BeginAccept, end, null); task.ContinueWith(t => callback(t.Result), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } public void Dispose() { if (_stream != null) _stream.Dispose(); if (_socket != null) _socket.Dispose(); } public void Close() { if (_stream != null) _stream.Close(); if (_socket != null) _socket.Close(); } public int EndSend(IAsyncResult asyncResult) { _stream.EndWrite(asyncResult); return 0; } public Task Send(byte[] buffer, Action callback, Action<Exception> error) { Func<AsyncCallback, object, IAsyncResult> begin = (cb, s) => _stream.BeginWrite(buffer, 0, buffer.Length, cb, s); Task task = Task.Factory.FromAsync(begin, _stream.EndWrite, null); task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted) .ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted); return task; } } }
34.191667
107
0.570802
[ "Apache-2.0" ]
jmarnold/EmbeddedMail
src/EmbeddedMail/ISocket.cs
4,103
C#
// File generated from our OpenAPI spec namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class InvoiceCreateOptions : BaseOptions, IHasMetadata { /// <summary> /// The account tax IDs associated with the invoice. Only editable when the invoice is a /// draft. /// </summary> [JsonProperty("account_tax_ids")] public List<string> AccountTaxIds { get; set; } /// <summary> /// A fee in %s that will be applied to the invoice and transferred to the application /// owner's Stripe account. The request must be made with an OAuth key or the Stripe-Account /// header in order to take an application fee. For more information, see the application /// fees <a /// href="https://stripe.com/docs/billing/invoices/connect#collecting-fees">documentation</a>. /// </summary> [JsonProperty("application_fee_amount")] public long? ApplicationFeeAmount { get; set; } /// <summary> /// Controls whether Stripe will perform <a /// href="https://stripe.com/docs/billing/invoices/workflow/#auto_advance">automatic /// collection</a> of the invoice. When <c>false</c>, the invoice's state will not /// automatically advance without an explicit action. /// </summary> [JsonProperty("auto_advance")] public bool? AutoAdvance { get; set; } /// <summary> /// Settings for automatic tax lookup for this invoice. /// </summary> [JsonProperty("automatic_tax")] public InvoiceAutomaticTaxOptions AutomaticTax { get; set; } /// <summary> /// Either <c>charge_automatically</c>, or <c>send_invoice</c>. When charging automatically, /// Stripe will attempt to pay this invoice using the default source attached to the /// customer. When sending an invoice, Stripe will email this invoice to the customer with /// payment instructions. Defaults to <c>charge_automatically</c>. /// One of: <c>charge_automatically</c>, or <c>send_invoice</c>. /// </summary> [JsonProperty("collection_method")] public string CollectionMethod { get; set; } /// <summary> /// A list of up to 4 custom fields to be displayed on the invoice. /// </summary> [JsonProperty("custom_fields")] public List<InvoiceCustomFieldOptions> CustomFields { get; set; } /// <summary> /// The ID of the customer who will be billed. /// </summary> [JsonProperty("customer")] public string Customer { get; set; } /// <summary> /// The number of days from when the invoice is created until it is due. Valid only for /// invoices where <c>collection_method=send_invoice</c>. /// </summary> [JsonProperty("days_until_due")] public long? DaysUntilDue { get; set; } /// <summary> /// ID of the default payment method for the invoice. It must belong to the customer /// associated with the invoice. If not set, defaults to the subscription's default payment /// method, if any, or to the default payment method in the customer's invoice settings. /// </summary> [JsonProperty("default_payment_method")] public string DefaultPaymentMethod { get; set; } /// <summary> /// ID of the default payment source for the invoice. It must belong to the customer /// associated with the invoice and be in a chargeable state. If not set, defaults to the /// subscription's default source, if any, or to the customer's default source. /// </summary> [JsonProperty("default_source")] public string DefaultSource { get; set; } /// <summary> /// The tax rates that will apply to any line item that does not have <c>tax_rates</c> set. /// </summary> [JsonProperty("default_tax_rates")] public List<string> DefaultTaxRates { get; set; } /// <summary> /// An arbitrary string attached to the object. Often useful for displaying to users. /// Referenced as 'memo' in the Dashboard. /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// The coupons to redeem into discounts for the invoice. If not specified, inherits the /// discount from the invoice's customer. Pass an empty string to avoid inheriting any /// discounts. /// </summary> [JsonProperty("discounts")] public List<InvoiceDiscountOptions> Discounts { get; set; } /// <summary> /// The date on which payment for this invoice is due. Valid only for invoices where /// <c>collection_method=send_invoice</c>. /// </summary> [JsonProperty("due_date")] [JsonConverter(typeof(UnixDateTimeConverter))] public DateTime? DueDate { get; set; } /// <summary> /// Footer to be displayed on the invoice. /// </summary> [JsonProperty("footer")] public string Footer { get; set; } /// <summary> /// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can /// attach to an object. This can be useful for storing additional information about the /// object in a structured format. Individual keys can be unset by posting an empty value to /// them. All keys can be unset by posting an empty value to <c>metadata</c>. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// The account (if any) for which the funds of the invoice payment are intended. If set, /// the invoice will be presented with the branding and support information of the specified /// account. See the <a href="https://stripe.com/docs/billing/invoices/connect">Invoices /// with Connect</a> documentation for details. /// </summary> [JsonProperty("on_behalf_of")] public string OnBehalfOf { get; set; } /// <summary> /// Configuration settings for the PaymentIntent that is generated when the invoice is /// finalized. /// </summary> [JsonProperty("payment_settings")] public InvoicePaymentSettingsOptions PaymentSettings { get; set; } /// <summary> /// How to handle pending invoice items on invoice creation. One of <c>include</c>, /// <c>exclude</c>, or <c>include_and_require</c>. <c>include</c> will include any pending /// invoice items, and will create an empty draft invoice if no pending invoice items exist. /// <c>include_and_require</c> will include any pending invoice items, if no pending invoice /// items exist then the request will fail. <c>exclude</c> will always create an empty /// invoice draft regardless if there are pending invoice items or not. Defaults to /// <c>include_and_require</c> if the parameter is omitted. /// One of: <c>exclude</c>, <c>include</c>, or <c>include_and_require</c>. /// </summary> [JsonProperty("pending_invoice_items_behavior")] public string PendingInvoiceItemsBehavior { get; set; } /// <summary> /// Extra information about a charge for the customer's credit card statement. It must /// contain at least one letter. If not specified and this invoice is part of a /// subscription, the default <c>statement_descriptor</c> will be set to the first /// subscription item's product's <c>statement_descriptor</c>. /// </summary> [JsonProperty("statement_descriptor")] public string StatementDescriptor { get; set; } /// <summary> /// The ID of the subscription to invoice, if any. If not set, the created invoice will /// include all pending invoice items for the customer. If set, the created invoice will /// only include pending invoice items for that subscription and pending invoice items not /// associated with any subscription. The subscription's billing cycle and regular /// subscription events won't be affected. /// </summary> [JsonProperty("subscription")] public string Subscription { get; set; } /// <summary> /// If specified, the funds from the invoice will be transferred to the destination and the /// ID of the resulting transfer will be found on the invoice's charge. /// </summary> [JsonProperty("transfer_data")] public InvoiceTransferDataOptions TransferData { get; set; } } }
47.170213
102
0.629567
[ "Apache-2.0" ]
Gofundraise/stripe-dotnet
src/Stripe.net/Services/Invoices/InvoiceCreateOptions.cs
8,868
C#
using System.Linq; using System.Reflection; namespace _02BlackBoxInteger { using System; public class BlackBoxIntegerTests { public static void Main() { Type classType = typeof(BlackBoxInt); BlackBoxInt blackBox = (BlackBoxInt)Activator.CreateInstance(classType, true); // altenative //ConstructorInfo classTypeConstructor = // classType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, // new Type[] { }, null); string input; while ((input = Console.ReadLine()) != "END") { string[] tokens = input.Split('_'); string methodName = tokens[0]; int value = int.Parse(tokens[1]); classType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(blackBox, new object[] { value }); string innerStateValue = classType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic) .First() .GetValue(blackBox) .ToString(); Console.WriteLine(innerStateValue); } } } }
31.65
110
0.555292
[ "MIT" ]
PhilipYordanov/Software-University-C-Fundamentals-track
CSharpOOPAdvance/Reflection - Exercises/02BlackBoxInteger/BlackBoxIntegerTests.cs
1,268
C#
using EasyDb.Data; using EasyDb.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace EasyDb.ViewModel { public class DatabaseVM : ViewModelBase { public string Name { get; set; } private ObservableCollection<TableVM> _tableVMs; public ObservableCollection<TableVM> TableVMs { get { return _tableVMs; } set { SetValue(ref _tableVMs, value, "TableVMs"); } } private TableVM _selectedTable; public TableVM SelectedTable { get { return _selectedTable; } set { SetValue(ref _selectedTable, value, "SelectedTable"); } } private TableVM _newTable; public TableVM NewTable { get { return _newTable; } set { SetValue(ref _newTable, value, "NewTable"); } } public ICommand AddTableCommand { get { return new RelayCommand(parameter => AddTable()); } } public ICommand DatabaseChangedCommand { get { return new RelayCommand(parameter => LoadTables()); } } public DatabaseVM() { TableVMs = new ObservableCollection<TableVM>(); NewTable = new TableVM(); } public DatabaseVM(string name) { Name = name; } public void LoadTables() { try { DatabaseInteractor currentDb = new DatabaseInteractor(Name); SetTables(currentDb.GetTables()); } catch (Exception ex) { HandleException(ex); } } private void SetTables(DataTable table) { TableVMs.Clear(); foreach (DataRow row in table.Rows) { TableVMs.Add(new TableVM(Name, row)); } } private void AddTable() { if (TableVMs.Any(t => t.Name == NewTable.Name) || string.IsNullOrEmpty(NewTable.Name)) { return; } SqlColumnDescriptionVM columnDescription = new SqlColumnDescriptionVM() { Value = 9 }; ColumnVM idColumn = new ColumnVM() { Name = "Id", ColumnType = "int", Description = columnDescription, IsIdentity = true, IsNullable = false }; NewTable.ColumnVMs.Add(idColumn); TableVMs.Add(NewTable); NewTable = new TableVM(); SelectedTable = NewTable; } public List<SqlTable> ToTables() { List<SqlTable> tables = new List<SqlTable>(); foreach (var tableVM in TableVMs) { tables.Add(tableVM.Table); } return tables; } } }
30.204082
156
0.538514
[ "MIT" ]
garvanb/EasyDb
Source/EasyDb.ViewModel/DatabaseVM.cs
2,962
C#
using System; namespace JetBrains.ReSharper.Koans.Editing { // Rearrange Code // // Move code up/down/left/right/in/out // // <shortcut id="Move Element Left">Left - Ctrl+Shift+Alt+Left</shortcut> // <shortcut id="Move Element Right">Right - Ctrl+Shift+Alt+Right</shortcut> // <shortcut id="Move Statement Up">Up - Ctrl+Shift+Alt+Up</shortcut> // <shortcut id="Move Statement Down">Down - Ctrl+Shift+Alt+Down</shortcut> public class RearrangingCode { public void RearrangeLines() { // 1. Place caret on one of the line below // use // <shortcut id="Move Statement Up">Up - Ctrl+Shift+Alt+Up</shortcut> // <shortcut id="Move Statement Down">Down - Ctrl+Shift+Alt+Down</shortcut> Console.WriteLine("One"); Console.WriteLine("Two"); Console.WriteLine("Three"); Console.WriteLine("Four"); Console.WriteLine("Five"); } public void RearrangeExpressionOrder() { var value = 42; var newValue = 34; newValue++; // 2. Place caret on newValue // <shortcut id="Move Element Left">Left - Ctrl+Shift+Alt+Left</shortcut> // <shortcut id="Move Element Right">Right - Ctrl+Shift+Alt+Right</shortcut> value = newValue; Console.WriteLine(value); } public void RearrangeParameterOrder() { const string hello = "hello"; const string world = "world"; const string foo = "foo"; const string bar = "bar"; // 3. Place caret on hello // rearrange parameter order // <shortcut id="Move Element Left">Left - Ctrl+Shift+Alt+Left</shortcut> // <shortcut id="Move Element Right">Right - Ctrl+Shift+Alt+Right</shortcut> MethodWithParameters(hello, world, foo, bar); } public void RearrangeInAndOut() { if (true) { // 4. Place caret on WriteLine // Rearrange within the if statement // Move out of if statement // Move above and below if statement // Move into the if statement Console.WriteLine("Hello"); Console.WriteLine("World"); } } // 5. Rearrange the comment // <shortcut id="Move Statement Up">Up - Ctrl+Shift+Alt+Up</shortcut> // <shortcut id="Move Statement Down">Down - Ctrl+Shift+Alt+Down</shortcut> public void RearrangeComment() { // Move me Console.WriteLine("Hello"); Console.WriteLine("World"); } public void ExtendBlockWithGreedyBraces() { // 5. Place caret on outside of closing brace // <shortcut id="Move Statement Up">Up - Ctrl+Shift+Alt+Up</shortcut> // <shortcut id="Move Statement Down">Down - Ctrl+Shift+Alt+Down</shortcut> // // Move block to include next statement // move up block to exclude current last statement if (true) { Console.WriteLine("Hello"); } Console.WriteLine("World"); } private void MethodWithParameters(string p1, string p2, string p3, string p4) { } } }
34.584158
89
0.533925
[ "Apache-2.0" ]
BrainyXS/resharper-rider-samples
02-Editing/05-Rearranging_code.cs
3,495
C#
using System.IO; namespace Chainsaw { public interface ISerializer { void Serialize(object obj, Stream stream); T Deserialize<T>(Stream stream); } }
16.272727
50
0.642458
[ "MIT" ]
richorama/chainsaw
Chainsaw/ISerializer.cs
181
C#
namespace iRMCSystemReportConverter { partial class MainWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow)); this.InputLabel = new System.Windows.Forms.Label(); this.InputTextBox = new System.Windows.Forms.TextBox(); this.InputBrowse = new System.Windows.Forms.Button(); this.OutputLabel = new System.Windows.Forms.Label(); this.OutputTextBox = new System.Windows.Forms.TextBox(); this.OutputBrowse = new System.Windows.Forms.Button(); this.CreateButton = new System.Windows.Forms.Button(); this.CloseButton = new System.Windows.Forms.Button(); this.openInputFileDialog = new System.Windows.Forms.OpenFileDialog(); this.outputFolderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.quitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.infoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // InputLabel // this.InputLabel.AutoSize = true; this.InputLabel.Location = new System.Drawing.Point(13, 40); this.InputLabel.Name = "InputLabel"; this.InputLabel.Size = new System.Drawing.Size(48, 13); this.InputLabel.TabIndex = 0; this.InputLabel.Text = "XML File"; // // InputTextBox // this.InputTextBox.AllowDrop = true; this.InputTextBox.Location = new System.Drawing.Point(13, 57); this.InputTextBox.Name = "InputTextBox"; this.InputTextBox.Size = new System.Drawing.Size(327, 20); this.InputTextBox.TabIndex = 1; this.InputTextBox.DragDrop += new System.Windows.Forms.DragEventHandler(this.InputTextBox_DragDrop); this.InputTextBox.DragEnter += new System.Windows.Forms.DragEventHandler(this.InputTextBox_DragEnter); // // InputBrowse // this.InputBrowse.Location = new System.Drawing.Point(346, 55); this.InputBrowse.Name = "InputBrowse"; this.InputBrowse.Size = new System.Drawing.Size(75, 23); this.InputBrowse.TabIndex = 2; this.InputBrowse.Text = "Browse"; this.InputBrowse.UseVisualStyleBackColor = true; this.InputBrowse.Click += new System.EventHandler(this.InputBrowse_Click); // // OutputLabel // this.OutputLabel.AutoSize = true; this.OutputLabel.Location = new System.Drawing.Point(13, 94); this.OutputLabel.Name = "OutputLabel"; this.OutputLabel.Size = new System.Drawing.Size(71, 13); this.OutputLabel.TabIndex = 3; this.OutputLabel.Text = "Output Folder"; // // OutputTextBox // this.OutputTextBox.Location = new System.Drawing.Point(13, 111); this.OutputTextBox.Name = "OutputTextBox"; this.OutputTextBox.Size = new System.Drawing.Size(327, 20); this.OutputTextBox.TabIndex = 4; // // OutputBrowse // this.OutputBrowse.Location = new System.Drawing.Point(346, 109); this.OutputBrowse.Name = "OutputBrowse"; this.OutputBrowse.Size = new System.Drawing.Size(75, 23); this.OutputBrowse.TabIndex = 5; this.OutputBrowse.Text = "Browse"; this.OutputBrowse.UseVisualStyleBackColor = true; this.OutputBrowse.Click += new System.EventHandler(this.OutputBrowse_Click); // // CreateButton // this.CreateButton.Location = new System.Drawing.Point(264, 154); this.CreateButton.Name = "CreateButton"; this.CreateButton.Size = new System.Drawing.Size(75, 23); this.CreateButton.TabIndex = 6; this.CreateButton.Text = "Create"; this.CreateButton.UseVisualStyleBackColor = true; this.CreateButton.Click += new System.EventHandler(this.CreateButton_Click); // // CloseButton // this.CloseButton.Location = new System.Drawing.Point(346, 154); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(75, 23); this.CloseButton.TabIndex = 7; this.CloseButton.Text = "Close"; this.CloseButton.UseVisualStyleBackColor = true; this.CloseButton.Click += new System.EventHandler(this.CancelButton_Click); // // openInputFileDialog // this.openInputFileDialog.Filter = "XML|*.xml|All files|*.*"; this.openInputFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk); // // outputFolderBrowserDialog // this.outputFolderBrowserDialog.Description = "Select the output folder."; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(434, 24); this.menuStrip1.TabIndex = 8; this.menuStrip1.Text = "menuStrip"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.quitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // quitToolStripMenuItem // this.quitToolStripMenuItem.Name = "quitToolStripMenuItem"; this.quitToolStripMenuItem.Size = new System.Drawing.Size(97, 22); this.quitToolStripMenuItem.Text = "Quit"; this.quitToolStripMenuItem.Click += new System.EventHandler(this.quitToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.infoToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // infoToolStripMenuItem // this.infoToolStripMenuItem.Name = "infoToolStripMenuItem"; this.infoToolStripMenuItem.Size = new System.Drawing.Size(137, 22); this.infoToolStripMenuItem.Text = "Information"; this.infoToolStripMenuItem.Click += new System.EventHandler(this.infoToolStripMenuItem_Click); // // MainWindow // this.ClientSize = new System.Drawing.Size(434, 189); this.Controls.Add(this.CloseButton); this.Controls.Add(this.CreateButton); this.Controls.Add(this.OutputBrowse); this.Controls.Add(this.OutputTextBox); this.Controls.Add(this.OutputLabel); this.Controls.Add(this.InputBrowse); this.Controls.Add(this.InputTextBox); this.Controls.Add(this.InputLabel); this.Controls.Add(this.menuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MainWindow"; this.Text = "iRMC S4/S5 System Report Converter"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label InputLabel; private System.Windows.Forms.TextBox InputTextBox; private System.Windows.Forms.Button InputBrowse; private System.Windows.Forms.Label OutputLabel; private System.Windows.Forms.TextBox OutputTextBox; private System.Windows.Forms.Button OutputBrowse; private System.Windows.Forms.Button CreateButton; private System.Windows.Forms.Button CloseButton; private System.Windows.Forms.OpenFileDialog openInputFileDialog; private System.Windows.Forms.FolderBrowserDialog outputFolderBrowserDialog; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem quitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem; } }
47.954338
142
0.616264
[ "MIT" ]
mmurayama/fujitsu-irmc-system-report-converter
iRMCSystemReportConverter/MainWindow.Designer.cs
10,504
C#
using System; using System.IO; namespace GM.Workflow { public class DirectoryWatcher { public delegate void DoWorkOnFile(string filename); DoWorkOnFile doWork; public void watch(string path, string filter, DoWorkOnFile _doWork) { doWork = _doWork; FileSystemWatcher watcher = new FileSystemWatcher() { Path = path, IncludeSubdirectories = false, NotifyFilter = NotifyFilters.LastWrite, Filter = filter, }; // Start monitoring events watcher.Changed += new FileSystemEventHandler(OnChanged); // Toddo - OnChanged only gets fired if the file is COPIED to the folder and // not if it is MOVED to the folder. I tried these two event handlers // but neither get called either when the file is moved. //watcher.Created += new FileSystemEventHandler(OnCreated); //watcher.Renamed += new RenamedEventHandler(OnRenamed); watcher.EnableRaisingEvents = true; } // FileSystemWatcher has a number of problems that are discussed often in SO and elsewhere. // The two main ones, which we are concerned with are: // 1. There can be many events fired when a single new file appears in a directory. // 2. When the OnChanged event is fired, the last write on the file may not have completed so the // file is not yet ready. // When we receive the OnChanged event, we will try to open the file to see if it is ready. // If not, we will wait and keep trying for a few seconds. // The DirectoryWatcher is for a background batch process, so we are not concerned with immediately // responding to the new file. private void OnChanged(object source, FileSystemEventArgs e) { if (!IsFileReady(e.FullPath)) return; //first notification the file is arriving //The file has completed arrived, so lets process it doWork(e.FullPath); } private void OnCreated(object source, FileSystemEventArgs e) { if (!IsFileReady(e.FullPath)) return; //first notification the file is arriving //The file has completed arrived, so lets process it doWork(e.FullPath); } private void OnRenamed(object source, FileSystemEventArgs e) { if (!IsFileReady(e.FullPath)) return; //first notification the file is arriving //The file has completed arrived, so lets process it doWork(e.FullPath); } private bool IsFileReady(string path) { //One exception per file rather than several like in the polling pattern int retryCount = 20; int timeBetweenRetries = 200; // in milliseconds int x = 0; while (x++ <= retryCount) { try { //If we can't open the file, it's still copying using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { Console.WriteLine($"We had {x} retries."); return true; } } catch (IOException) { System.Threading.Thread.Sleep(timeBetweenRetries); } } // Retry count is exhausted. We failed. return false; } } }
38.212766
107
0.574889
[ "MIT" ]
johnpankowicz/govmeeting-before-bfg
BackEnd/WorkflowApp/DirectoryWatcher.cs
3,592
C#
using Restaurant.Common.DataTransferObjects; namespace Restaurant.Abstractions.ViewModels { public interface IOrderViewModel { IFoodViewModel Food { get; } decimal Quantity { get; set; } decimal TotalPrice { get; } string TotalPriceAnimated { get; set; } IOrderViewModel Clone(); } }
25.230769
45
0.679878
[ "MIT" ]
armohamm/Restaurant-App
src/Client/Restaurant.Client/Restaurant.Abstractions/ViewModels/IOrderViewModel.cs
330
C#