text
stringlengths
3
1.02M
namespace Mondop.Mockables { public interface IFileInfo: IFileSystemInfo { IDirectoryInfo Directory { get; } string DirectoryName { get; } long Length { get; } string Name { get; } bool IsReadOnly { get; set; } bool Exists { get; } //StreamWriter AppendText(); IFileInfo CopyTo(string destFileName); IFileInfo CopyTo(string destFileName, bool overwrite); //FileStream Create(); //StreamWriter CreateText(); #if !NETSTANDARD1_3 void Decrypt(); void Encrypt(); IFileInfo Replace(string destinationFileName, string destinationBackupFileName); IFileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); #endif void Delete(); //FileSecurity GetAccessControl(); //FileSecurity GetAccessControl(AccessControlSections includeSections); void MoveTo(string destFileName); //FileStream Open(FileMode mode); //FileStream Open(FileMode mode, FileAccess access, FileShare share); //FileStream Open(FileMode mode, FileAccess access); //FileStream OpenRead(); //StreamReader OpenText(); //FileStream OpenWrite(); //void SetAccessControl(FileSecurity fileSecurity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using TEditXNA.Terraria; namespace TEditXna.View.Popups { /// <summary> /// Interaction logic for ChestsContentsPopup.xaml /// </summary> public partial class ChestPopup : Popup { public ChestPopup(Chest chest) { InitializeComponent(); DataContext = chest.Items; } public void OpenChest(Chest chest) { DataContext = chest.Items; } private void Popup_MouseDown(object sender, MouseButtonEventArgs e) { //IsOpen = false; } private void Popup_MouseLeave(object sender, MouseEventArgs e) { //IsOpen = false; } private void ClosePopup(object sender, RoutedEventArgs e) { IsOpen = false; } } }
#region Copyright © 2020-2021 Vladimir Deryagin. All rights reserved /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; namespace MIS.Domain.Providers { public class DefaultDateTimeProvider : IDateTimeProvider { public DefaultDateTimeProvider(DateTime now) { Now = now; } public DateTime Now { get; } } }
using BussinessLogicLayer; using DataAcessLayer; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace ApplicationLayer { public partial class UpdatePassForm : Form { readonly PassAccModel _passAccModel; readonly MasterAccModel _masterAccModel; public UpdatePassForm() { InitializeComponent(); } public UpdatePassForm(PassAccModel passAccModel,MasterAccModel masterAccModel) { InitializeComponent(); this._passAccModel = passAccModel; this._masterAccModel = masterAccModel; } private void UpdatePassForm_Load(object sender, EventArgs e) { titleTextBox.Text = _passAccModel.title; passwordTextBox.Text = _passAccModel.password; linkTextBox.Text = _passAccModel.link; } private bool ValidateForm() { bool output = true; if (string.IsNullOrWhiteSpace(titleTextBox.Text.Trim()) || string.IsNullOrWhiteSpace(passwordTextBox.Text.Trim())) { output = false; } if (!string.IsNullOrWhiteSpace(linkTextBox.Text.Trim()) && (!Regex.IsMatch(linkTextBox.Text.Trim(), Patterns.MailPattern) && !Regex.IsMatch(linkTextBox.Text.Trim(), Patterns.UrlPattern)) ) { output = false; } return output; } private void updatePassBtn_Click(object sender, EventArgs e) { if (ValidateForm()) { PassAccModel passAccModel = new PassAccModel(); passAccModel.id = _passAccModel.id; passAccModel.title = titleTextBox.Text.Trim(); passAccModel.password = EncryptPass.Encrypt(passwordTextBox.Text.Trim(), _masterAccModel.master_password); passAccModel.link = linkTextBox.Text.Trim(); passAccModel.m_id = _masterAccModel.id; bool duplicateAcc = false; SQLiteConnector db = new SQLiteConnector(); duplicateAcc = db.VerifyStorePass(passAccModel); if (!duplicateAcc) { db.UpdatePass(passAccModel); DialogResult r = ValidationMessage.SucessMsgResult("Password updated sucessfully!"); if (r == DialogResult.OK) { Close(); } } else { ValidationMessage.AlertMsg("A password for this account is already saved.Please save password for a different account."); } } else { ValidationMessage.AlertMsg("Form data given is invalid. Please check and try again."); } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // // This template generates PublicResXFileCodeGenerator compatible code plus some // useful extensions. // // The original version provided by ResXResourceManager is restricted to resource key names // that are valid c# identifiers to keep this template simple (KISS!). // // Us it as it is or as a scaffold to generate the code you need. // // As long as you have ResXResourceManager running in the background, the generated code // will be kept up to date. // //------------------------------------------------------------------------------ namespace tomenglertde.ResXManager.Properties { using System; using System.Diagnostics.Contracts; using JetBrains.Annotations; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by a text template. // To add or remove a member, edit your .ResX file. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("ResXResourceManager", "1.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("tomenglertde.ResXManager.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Assembly location: {0}. /// </summary> [NotNull] public static string AssemblyLocation { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("AssemblyLocation", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to ResX Resource Manager loaded.&amp;#13;&amp;#10;Hom.... /// </summary> [NotNull] public static string IntroMessage { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("IntroMessage", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to The project has no resource file for the language .... /// </summary> [NotNull] public static string ProjectHasNoResourceFile { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("ProjectHasNoResourceFile", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to Some files in your project are not writable. You m.... /// </summary> [NotNull] public static string ProjectHasReadOnlyFiles { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("ProjectHasReadOnlyFiles", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to Do you want to save the changes?. /// </summary> [NotNull] public static string QuerySaveChanges { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("QuerySaveChanges", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to Version: {0}. /// </summary> /// <remarks> /// @Invariant /// </remarks> [NotNull] public static string Version { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("Version", resourceCulture) ?? string.Empty; } } /// <summary> /// Looks up a localized string similar to You have unsaved changes; reloading all resources .... /// </summary> [NotNull] public static string WarningUnsavedChanges { get { Contract.Ensures(Contract.Result<string>() != null); return ResourceManager.GetString("WarningUnsavedChanges", resourceCulture) ?? string.Empty; } } } /// <summary> /// Keys of all available strings in the applications resx-resources. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGenerated] public enum StringResourceKey { /// <summary> /// Looks up a localized string similar to Assembly location: {0}. /// </summary> AssemblyLocation, /// <summary> /// Looks up a localized string similar to ResX Resource Manager loaded.&amp;#13;&amp;#10;Hom.... /// </summary> IntroMessage, /// <summary> /// Looks up a localized string similar to The project has no resource file for the language .... /// </summary> ProjectHasNoResourceFile, /// <summary> /// Looks up a localized string similar to Some files in your project are not writable. You m.... /// </summary> ProjectHasReadOnlyFiles, /// <summary> /// Looks up a localized string similar to Do you want to save the changes?. /// </summary> QuerySaveChanges, /// <summary> /// Looks up a localized string similar to Version: {0}. /// </summary> /// <remarks> /// @Invariant /// </remarks> Version, /// <summary> /// Looks up a localized string similar to You have unsaved changes; reloading all resources .... /// </summary> WarningUnsavedChanges, } /// <summary> /// Specifies a localized description for an object. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.All, AllowMultiple=false)] public sealed class LocalizedDescriptionAttribute : System.ComponentModel.DescriptionAttribute { private readonly StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="LocalizedDescriptionAttribute"/> class. /// </summary> /// <param name="resourceKey">The resource key of the associated resource.</param> public LocalizedDescriptionAttribute(StringResourceKey resourceKey) { _resourceKey = resourceKey; } /// <summary> /// Gets the localized description from the resource id stored in this attribute. /// </summary> public override string Description { get { return Resources.ResourceManager.GetString(_resourceKey.ToString()); } } } /// <summary> /// Specifies a localized display name for an object. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.All, AllowMultiple=false)] public sealed class LocalizedDisplayNameAttribute : System.ComponentModel.DisplayNameAttribute { private readonly StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="LocalizedDisplayNameAttribute"/> class. /// </summary> /// <param name="resourceKey">The resource key of the associated resource.</param> public LocalizedDisplayNameAttribute(StringResourceKey resourceKey) { _resourceKey = resourceKey; } /// <summary> /// Gets the localized display name from the resource id stored in this attribute. /// </summary> public override string DisplayName { get { return Resources.ResourceManager.GetString(_resourceKey.ToString()); } } } /// <summary> /// Specifies a localized display name for an object. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.All, AllowMultiple=false)] public sealed class LocalizedCategoryAttribute : System.ComponentModel.CategoryAttribute { /// <summary> /// Initializes a new instance of the <see cref="LocalizedCategoryAttribute"/> class. /// </summary> /// <param name="resourceKey">The resource key of the associated resource.</param> public LocalizedCategoryAttribute(StringResourceKey resourceKey) : base(resourceKey.ToString()) { } /// <summary> /// Gets the localized category name from the resource id stored in this attribute. /// </summary> protected override string GetLocalizedString(string value) { return Resources.ResourceManager.GetString(value); } } /// <summary> /// Specifies a localized display name for an object. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public sealed class LocalizedTextAttribute : global::TomsToolbox.Desktop.TextAttribute { // This code is generated by Resources.Designer.t4 // If you get compile errors because you don't use the TomsToolbox.Desktop NuGet package, remove this part in the Resources.Designer.t4 file. // Just search for this text and follow the instructions above. private readonly StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="LocalizedTextAttribute"/> class. /// </summary> /// <param name="key">Any user defined key to specify the usage of this text.</param> /// <param name="resourceKey">The resource key of the associated resource.</param> public LocalizedTextAttribute(object key, StringResourceKey resourceKey) : base(key) { _resourceKey = resourceKey; } /// <summary> /// Gets the localized text from the resource id stored in this attribute. /// </summary> public override string Text { get { return Resources.ResourceManager.GetString(_resourceKey.ToString()); } } } /// <summary> /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.DataTypeAttribute"/> class. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class DataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute { private StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="DataTypeAttribute"/> class. /// </summary> public DataTypeAttribute(StringResourceKey resourceKey, System.ComponentModel.DataAnnotations.DataType dataType) : base(dataType) { ResourceKey = resourceKey; } /// <summary> /// Initializes a new instance of the <see cref="DataTypeAttribute"/> class. /// </summary> public DataTypeAttribute(StringResourceKey resourceKey, string customDataType) : base(customDataType) { ResourceKey = resourceKey; } /// <summary> /// Gets or sets the resource key. /// </summary> public StringResourceKey ResourceKey { get { return _resourceKey; } set { _resourceKey = value; ErrorMessageResourceType = typeof(Resources); ErrorMessageResourceName = value.ToString(); } } } /// <summary> /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RangeAttribute"/> class. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class RangeAttribute : System.ComponentModel.DataAnnotations.RangeAttribute { private StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="RangeAttribute"/> class. /// </summary> public RangeAttribute(StringResourceKey resourceKey, int minimum, int maximum) : base(minimum, maximum) { ResourceKey = resourceKey; } /// <summary> /// Initializes a new instance of the <see cref="RangeAttribute"/> class. /// </summary> public RangeAttribute(StringResourceKey resourceKey, double minimum, double maximum) : base(minimum, maximum) { ResourceKey = resourceKey; } /// <summary> /// Initializes a new instance of the <see cref="RangeAttribute"/> class. /// </summary> public RangeAttribute(StringResourceKey resourceKey, Type type, string minimum, string maximum) : base(type, minimum, maximum) { ResourceKey = resourceKey; } /// <summary> /// Gets or sets the resource key. /// </summary> public StringResourceKey ResourceKey { get { return _resourceKey; } set { _resourceKey = value; ErrorMessageResourceType = typeof(Resources); ErrorMessageResourceName = value.ToString(); } } } /// <summary> /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RegularExpressionAttribute"/> class. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute { private StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="RegularExpressionAttribute"/> class. /// </summary> public RegularExpressionAttribute(StringResourceKey resourceKey, string pattern) : base(pattern) { ResourceKey = resourceKey; } /// <summary> /// Gets or sets the resource key. /// </summary> public StringResourceKey ResourceKey { get { return _resourceKey; } set { _resourceKey = value; ErrorMessageResourceType = typeof(Resources); ErrorMessageResourceName = value.ToString(); } } } /// <summary> /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RequiredAttribute"/> class. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute { private StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="RequiredAttribute"/> class. /// </summary> public RequiredAttribute(StringResourceKey resourceKey) : base() { ResourceKey = resourceKey; } /// <summary> /// Gets or sets the resource key. /// </summary> public StringResourceKey ResourceKey { get { return _resourceKey; } set { _resourceKey = value; ErrorMessageResourceType = typeof(Resources); ErrorMessageResourceName = value.ToString(); } } } /// <summary> /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.StringLengthAttribute"/> class. /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)] public class StringLengthAttribute : System.ComponentModel.DataAnnotations.StringLengthAttribute { private StringResourceKey _resourceKey; /// <summary> /// Initializes a new instance of the <see cref="StringLengthAttribute"/> class. /// </summary> public StringLengthAttribute(StringResourceKey resourceKey, int maximumLength) : base(maximumLength) { ResourceKey = resourceKey; } /// <summary> /// Gets or sets the resource key. /// </summary> public StringResourceKey ResourceKey { get { return _resourceKey; } set { _resourceKey = value; ErrorMessageResourceType = typeof(Resources); ErrorMessageResourceName = value.ToString(); } } } }
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>This is the Auth0 ASP.NET Core MVC Starter Project</p> <p>To learn more, please check out the <a href="https://auth0.com/docs/quickstart/webapp/aspnet-core">Auth0 ASP.NET Core Quickstart</a>.</p> </div>
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.PhysXVehicles.Native; using UE4.Engine; namespace UE4.PhysXVehicles { ///<summary>Vehicle Wheel</summary> public unsafe partial class VehicleWheel : UObject { ///<summary>Get Rotation Angle</summary> public float GetRotationAngle() => VehicleWheel_methods.GetRotationAngle_method.Invoke(ObjPointer); ///<summary>Get Steer Angle</summary> public float GetSteerAngle() => VehicleWheel_methods.GetSteerAngle_method.Invoke(ObjPointer); ///<summary>Get Suspension Offset</summary> public float GetSuspensionOffset() => VehicleWheel_methods.GetSuspensionOffset_method.Invoke(ObjPointer); ///<summary>Is in Air</summary> public bool IsInAir() => VehicleWheel_methods.IsInAir_method.Invoke(ObjPointer); ///<summary>Static mesh with collision setup for wheel, will be used to create wheel shape</summary> ///<remarks>(if empty, sphere will be added as wheel shape, check bDontCreateShape flag)</remarks> public unsafe StaticMesh CollisionMesh { get {return VehicleWheel_ptr->CollisionMesh;} set {VehicleWheel_ptr->CollisionMesh = value;} } public bool bDontCreateShape { get {return Main.GetGetBoolPropertyByName(this, "bDontCreateShape"); } set {Main.SetGetBoolPropertyByName(this, "bDontCreateShape", value); } } public bool bAutoAdjustCollisionSize { get {return Main.GetGetBoolPropertyByName(this, "bAutoAdjustCollisionSize"); } set {Main.SetGetBoolPropertyByName(this, "bAutoAdjustCollisionSize", value); } } ///<summary>If BoneName is specified, offset the wheel from the bone's location.</summary> ///<remarks>Otherwise this offsets the wheel from the vehicle's origin.</remarks> public unsafe Vector Offset { get {return VehicleWheel_ptr->Offset;} set {VehicleWheel_ptr->Offset = value;} } ///<summary>Radius of the wheel</summary> public unsafe float ShapeRadius { get {return VehicleWheel_ptr->ShapeRadius;} set {VehicleWheel_ptr->ShapeRadius = value;} } ///<summary>Width of the wheel</summary> public unsafe float ShapeWidth { get {return VehicleWheel_ptr->ShapeWidth;} set {VehicleWheel_ptr->ShapeWidth = value;} } ///<summary>Mass of this wheel</summary> public unsafe float Mass { get {return VehicleWheel_ptr->Mass;} set {VehicleWheel_ptr->Mass = value;} } ///<summary>Damping rate for this wheel (Kgm^2/s)</summary> public unsafe float DampingRate { get {return VehicleWheel_ptr->DampingRate;} set {VehicleWheel_ptr->DampingRate = value;} } ///<summary>steer angle in degrees for this wheel</summary> public unsafe float SteerAngle { get {return VehicleWheel_ptr->SteerAngle;} set {VehicleWheel_ptr->SteerAngle = value;} } public bool bAffectedByHandbrake { get {return Main.GetGetBoolPropertyByName(this, "bAffectedByHandbrake"); } set {Main.SetGetBoolPropertyByName(this, "bAffectedByHandbrake", value); } } ///<summary>Deprecated</summary> public unsafe TireType TireType { get {return VehicleWheel_ptr->TireType;} set {VehicleWheel_ptr->TireType = value;} } ///<summary>Tire type for the wheel. Determines friction</summary> public unsafe TireConfig TireConfig { get {return VehicleWheel_ptr->TireConfig;} set {VehicleWheel_ptr->TireConfig = value;} } ///<summary>Max normalized tire load at which the tire can deliver no more lateral stiffness no matter how much extra load is applied to the tire.</summary> public unsafe float LatStiffMaxLoad { get {return VehicleWheel_ptr->LatStiffMaxLoad;} set {VehicleWheel_ptr->LatStiffMaxLoad = value;} } ///<summary>How much lateral stiffness to have given lateral slip</summary> public unsafe float LatStiffValue { get {return VehicleWheel_ptr->LatStiffValue;} set {VehicleWheel_ptr->LatStiffValue = value;} } ///<summary>How much longitudinal stiffness to have given longitudinal slip</summary> public unsafe float LongStiffValue { get {return VehicleWheel_ptr->LongStiffValue;} set {VehicleWheel_ptr->LongStiffValue = value;} } ///<summary>Vertical offset from where suspension forces are applied (along Z-axis)</summary> public unsafe float SuspensionForceOffset { get {return VehicleWheel_ptr->SuspensionForceOffset;} set {VehicleWheel_ptr->SuspensionForceOffset = value;} } ///<summary>How far the wheel can go above the resting position</summary> public unsafe float SuspensionMaxRaise { get {return VehicleWheel_ptr->SuspensionMaxRaise;} set {VehicleWheel_ptr->SuspensionMaxRaise = value;} } ///<summary>How far the wheel can drop below the resting position</summary> public unsafe float SuspensionMaxDrop { get {return VehicleWheel_ptr->SuspensionMaxDrop;} set {VehicleWheel_ptr->SuspensionMaxDrop = value;} } ///<summary>Oscillation frequency of suspension. Standard cars have values between 5 and 10</summary> public unsafe float SuspensionNaturalFrequency { get {return VehicleWheel_ptr->SuspensionNaturalFrequency;} set {VehicleWheel_ptr->SuspensionNaturalFrequency = value;} } ///<summary>The rate at which energy is dissipated from the spring.</summary> ///<remarks> ///Standard cars have values between 0.8 and 1.2. ///values < 1 are more sluggish, values > 1 or more twitchy ///</remarks> public unsafe float SuspensionDampingRatio { get {return VehicleWheel_ptr->SuspensionDampingRatio;} set {VehicleWheel_ptr->SuspensionDampingRatio = value;} } ///<summary>Whether wheel suspension considers simple, complex, or both</summary> public unsafe byte SweepType { get {return VehicleWheel_ptr->SweepType;} set {VehicleWheel_ptr->SweepType = value;} } ///<summary>max brake torque for this wheel (Nm)</summary> public unsafe float MaxBrakeTorque { get {return VehicleWheel_ptr->MaxBrakeTorque;} set {VehicleWheel_ptr->MaxBrakeTorque = value;} } ///<summary>Max handbrake brake torque for this wheel (Nm).</summary> ///<remarks> ///A handbrake should have a stronger brake torque ///than the brake. This will be ignored for wheels that are not affected by the handbrake. ///</remarks> public unsafe float MaxHandBrakeTorque { get {return VehicleWheel_ptr->MaxHandBrakeTorque;} set {VehicleWheel_ptr->MaxHandBrakeTorque = value;} } ///<summary>The vehicle that owns us</summary> public unsafe WheeledVehicleMovementComponent VehicleSim { get {return VehicleWheel_ptr->VehicleSim;} set {VehicleWheel_ptr->VehicleSim = value;} } ///<summary>Our index in the vehicle's (and setup's) wheels array</summary> public unsafe int WheelIndex { get {return VehicleWheel_ptr->WheelIndex;} set {VehicleWheel_ptr->WheelIndex = value;} } ///<summary>Longitudinal slip experienced by the wheel</summary> public unsafe float DebugLongSlip { get {return VehicleWheel_ptr->DebugLongSlip;} set {VehicleWheel_ptr->DebugLongSlip = value;} } ///<summary>Lateral slip experienced by the wheel</summary> public unsafe float DebugLatSlip { get {return VehicleWheel_ptr->DebugLatSlip;} set {VehicleWheel_ptr->DebugLatSlip = value;} } ///<summary>How much force the tire experiences at rest divided by how much force it is experiencing now</summary> public unsafe float DebugNormalizedTireLoad { get {return VehicleWheel_ptr->DebugNormalizedTireLoad;} set {VehicleWheel_ptr->DebugNormalizedTireLoad = value;} } ///<summary>Wheel torque</summary> public unsafe float DebugWheelTorque { get {return VehicleWheel_ptr->DebugWheelTorque;} set {VehicleWheel_ptr->DebugWheelTorque = value;} } ///<summary>Longitudinal force the wheel is applying to the chassis</summary> public unsafe float DebugLongForce { get {return VehicleWheel_ptr->DebugLongForce;} set {VehicleWheel_ptr->DebugLongForce = value;} } ///<summary>Lateral force the wheel is applying to the chassis</summary> public unsafe float DebugLatForce { get {return VehicleWheel_ptr->DebugLatForce;} set {VehicleWheel_ptr->DebugLatForce = value;} } ///<summary>Worldspace location of this wheel</summary> public unsafe Vector Location { get {return VehicleWheel_ptr->Location;} set {VehicleWheel_ptr->Location = value;} } ///<summary>Worldspace location of this wheel last frame</summary> public unsafe Vector OldLocation { get {return VehicleWheel_ptr->OldLocation;} set {VehicleWheel_ptr->OldLocation = value;} } ///<summary>Current velocity of the wheel center (change in location over time)</summary> public unsafe Vector Velocity { get {return VehicleWheel_ptr->Velocity;} set {VehicleWheel_ptr->Velocity = value;} } static VehicleWheel() { StaticClass = Main.GetClass("VehicleWheel"); } internal unsafe VehicleWheel_fields* VehicleWheel_ptr => (VehicleWheel_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator VehicleWheel(IntPtr p) => UObject.Make<VehicleWheel>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static VehicleWheel DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static VehicleWheel New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using GoogleTestAdapter.Tests.Common; using static GoogleTestAdapter.Tests.Common.TestMetadata.TestCategories; namespace GoogleTestAdapter.TestAdapter.Helpers { [TestClass] public class ThrottleTests { struct Event { public int Id; public DateTime Time; } private static readonly List<Event> Events = new List<Event>(); private const int MaxEvents = 10; private const int TotalEvents = 100; private static readonly TimeSpan TimeSpan = TimeSpan.FromMilliseconds(100); [ClassInitialize] public static void GenerateEventList(TestContext context) { var throttle = new Throttle(MaxEvents, TimeSpan); for (int i = 0; i < TotalEvents; i++) { var id = i; throttle.Execute(() => { Events.Add(new Event { Id = id, Time = DateTime.Now }); }); } } [TestMethod] [TestCategory(Unit)] public void EventsAreInOrder() { Events.Should().HaveCount(TotalEvents); for (int i = 0; i < Events.Count; i++) Events[i].Id.Should().Be(i); } [TestMethod] [TestCategory(Unit)] public void DoesNotTakeMuchLongerThanExpected() { var duration = (Events.Last().Time - Events.First().Time).TotalMilliseconds; var minimumDuration = ((TotalEvents / MaxEvents - 1) * TimeSpan.TotalMilliseconds); duration.Should().BeGreaterThan(minimumDuration - TestMetadata.ToleranceInMs); duration.Should().BeLessThan(minimumDuration + TimeSpan.TotalMilliseconds + TestMetadata.ToleranceInMs); } [TestMethod] [TestCategory(Unit)] public void HasNoTimeFrameWithTooManyElements() { var firstEvent = Events.First().Time; var lastEvent = Events.Last().Time; var step = TimeSpan.FromMilliseconds(77); for (DateTime start = firstEvent; start < lastEvent; start += step) { var theStart = start; var theEnd = start + TimeSpan; var eventsInTimeFrame = Events.Where(e => e.Time >= theStart && e.Time <= theEnd); if (eventsInTimeFrame.Count() > MaxEvents) { Assert.Inconclusive("Size of Events should never be greater than MaxEvents - but this test is unstable :-)"); } } } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace ay.Controls { public class OrderConditions { public static Tuple<string, string> Convert(string ordercondition) { var _1 = ordercondition.Split(' '); return Tuple.Create<string, string>(_1[0], _1[1]); } } public class AyTableViewUtils { // searches a template tree for an element public static T FindParent<T>(FrameworkElement element) where T : class { for (FrameworkElement element2 = element.TemplatedParent as FrameworkElement; element2 != null; element2 = element2.TemplatedParent as FrameworkElement) { T local = element2 as T; if (local != null) return local; } return default(T); } // Searches the visual tree for the element of the specified type public static T GetAncestorByType<T>(DependencyObject element) where T : class { if (element == null) return default(T); if (element as T != null) return element as T; return GetAncestorByType<T>(VisualTreeHelper.GetParent(element)); } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Condition of type `Collision2D`. Inherits from `AtomCondition&lt;Collision2D&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] public abstract class Collision2DCondition : AtomCondition<Collision2D> { } }
using System.Linq; namespace HarmonyLibTests.Assets { public class TraverseMethods_Instance { public bool Method1_called; #pragma warning disable IDE0051 private void Method1() { Method1_called = true; } private string Method2(string arg1) { return arg1 + arg1; } #pragma warning restore IDE0051 } public static class TraverseMethods_Static { #pragma warning disable IDE0051 private static int StaticMethod(int a, int b) { return a * b; } #pragma warning restore IDE0051 } public static class TraverseMethods_VarArgs { #pragma warning disable IDE0051 private static int Test1(int a, int b) { return a + b; } private static int Test2(int a, int b, int c) { return a + b + c; } private static int Test3(int multiplier, params int[] n) { return n.Aggregate(0, (acc, x) => acc + x) * multiplier; } #pragma warning restore IDE0051 } public static class TraverseMethods_Parameter { #pragma warning disable IDE0051 private static string WithRefParameter(ref string refParameter) { refParameter = "hello"; return "ok"; } private static string WithOutParameter(out string refParameter) { refParameter = "hello"; return "ok"; } private static T WithGenericParameter<T>(T refParameter) { return refParameter; } #pragma warning restore IDE0051 } }
/* * SHS -- The Scalable Hyperlink Store * * Copyright (c) Microsoft Corporation * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.IO; using System.Runtime.InteropServices; // to bring DllImport into scope namespace SHS { public unsafe class CachedStream : System.Runtime.ConstrainedExecution.CriticalFinalizerObject { private readonly IntPtr ph; // Native process heap private readonly byte* bytes; // Unmanaged byte array private readonly ulong size; /// <summary> /// Read a number of bytes from a stream into unmanaged main memory, and construct /// a container object around it. /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="numBytes">The number of bytes to read</param> public CachedStream(Stream stream, ulong numBytes) { this.size = numBytes; // Allocate unmanaged byte array unsafe { /* This recipe is taken from chapter 18.9 of "The C# Programming Language" (3rd edition) by Hejlsberg et al. According to Yuan Yu, an alternative and possibly better way would be to use System.Runtime.InteropServices.AllocHGlobal. */ this.ph = GetProcessHeap(); this.bytes = (byte*)HeapAlloc(ph, 0, (UIntPtr)this.size); if (this.bytes == null) throw new OutOfMemoryException(); } const int chunkSize = 8192; byte[] buf = new byte[chunkSize]; ulong pos = 0; ulong rem = numBytes; while (rem > 0) { int max = rem < chunkSize ? (int)rem : chunkSize; int n = stream.Read(buf, 0, max); if (n == 0) throw new FileFormatException(string.Format("Stream too short, expected {0} extra bytes", rem)); rem -= (ulong)n; for (int i = 0; i < n; i++) { this.bytes[pos++] = buf[i]; } } if (pos != size) throw new Exception(); } ~CachedStream() { HeapFree(this.ph, 0, this.bytes); } public int GetInt32(ulong bo) { if (bo + sizeof(int) > this.size) throw new IndexOutOfRangeException(); return *((int*)(this.bytes + bo)); } public long GetInt64(ulong bo) { if (bo + sizeof(long) > this.size) throw new IndexOutOfRangeException(); return *((long*)(this.bytes + bo)); } public byte GetUInt8(ulong bo) { if (bo + sizeof(byte) > this.size) throw new IndexOutOfRangeException(string.Format("bo={0} size={1}", bo, size)); return *((byte*)(this.bytes + bo)); } public uint GetUInt32(ulong bo) { if (bo + sizeof(uint) > this.size) throw new IndexOutOfRangeException(); return *((uint*)(this.bytes + bo)); } public ulong GetUInt64(ulong bo) { if (bo + sizeof(ulong) > this.size) throw new IndexOutOfRangeException(); return *((ulong*)(this.bytes + bo)); } // ... same for other types, as needed public ulong Size { get { return this.size; } } [DllImport("kernel32", SetLastError = true)] static extern IntPtr GetProcessHeap(); [DllImport("kernel32", SetLastError = true)] static extern void* HeapAlloc(IntPtr hHeap, int flags, UIntPtr numBytes); [DllImport("kernel32", SetLastError = true)] static extern bool HeapFree(IntPtr hHeap, int flags, void* block); } }
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; using Microsoft.AspNetCore.Mvc.Testing; using PowerUtils.AspNetCore.ErrorHandler.Samples; namespace PowerUtils.AspNetCore.Extensions.Tests.Config; [CollectionDefinition(nameof(IntegrationApiTestsFixtureCollection))] public class IntegrationApiTestsFixtureCollection : ICollectionFixture<IntegrationTestsFixture> { } public class IntegrationTestsFixture : IDisposable { public HttpClient Client; private readonly WebAPIFactory<Startup> _factory; public IntegrationTestsFixture() { var clientOptions = new WebApplicationFactoryClientOptions(); _factory = new WebAPIFactory<Startup>(); Client = _factory.CreateClient(clientOptions); Client.DefaultRequestHeaders.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); } public void Dispose() { Client.Dispose(); _factory.Dispose(); GC.SuppressFinalize(this); } }
using System.Collections; using System.Collections.Generic; using OVRTouchSample; using UnityEngine; public class objectSpawnCallibration : MonoBehaviour { public GlobalCallibration storePos; public GameObject callibrationObj; public GameObject continueUI; public GameObject[] instructions; [SerializeField] Vector3 handDistance; [SerializeField] Quaternion handRotation; bool isCallibrated; float timer; float instructionNum = 0; [SerializeField] public List<GameObject> calliObjs; public List<Vector3> calliPos; // Start is called before the first frame update void Start() { calliObjs = new List<GameObject>(); calliPos = new List<Vector3>(); } // Update is called once per frame void Update() { timer += Time.deltaTime; if (isCallibrated == false){ spawnObject(callibrationObj); } else if (timer > 2.0f) { isCallibrated = false; timer = 0; } ClearCalibration(); DisplayInstructions(); } public void spawnObject(GameObject callibrationObj) { handDistance = gameObject.transform.position; handRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch); if (OVRInput.GetDown(OVRInput.Button.PrimaryIndexTrigger)) { isCallibrated = true; calliObjs.Add(Instantiate(callibrationObj, handDistance, handRotation)); calliPos.Add(handDistance); instructionNum += 1; if (calliObjs.Count > 3) { Destroy(calliObjs[0]); calliObjs.RemoveAt(0); calliPos.RemoveAt(0); } } if (calliObjs.Count == 3) { storePos.callibrationPos = calliPos; continueUI.SetActive(true); } else { continueUI.SetActive(false); } } public void ClearCalibration() { if (OVRInput.GetDown(OVRInput.Button.Four) && OVRInput.GetDown(OVRInput.Button.Two)){ for (int i = 0; i <= calliObjs.Count; i++) { Destroy(calliObjs[i]); } calliObjs.Clear(); calliPos.Clear(); continueUI.SetActive(false); instructionNum = 0; } } public void DisplayInstructions() { if (instructionNum == 0) { instructions[0].SetActive(true); instructions[1].SetActive(false); instructions[2].SetActive(false); } if (instructionNum == 1) { instructions[0].SetActive(false); instructions[1].SetActive(true); instructions[2].SetActive(false); } if (instructionNum == 2) { instructions[0].SetActive(false); instructions[1].SetActive(false); instructions[2].SetActive(true); } if (instructionNum > 2) { instructionNum = 0; } } }
// OData .NET Libraries // Copyright (c) Microsoft Corporation. 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 Microsoft.OData.Core.UriParser.Parsers { using System.Diagnostics; using Microsoft.OData.Edm; using Microsoft.OData.Core.Metadata; using Microsoft.OData.Core.UriParser.Binders; using Microsoft.OData.Core.UriParser.Metadata; using Microsoft.OData.Core.UriParser.Semantic; using Microsoft.OData.Core.UriParser.Syntactic; using ODataErrorStrings = Microsoft.OData.Core.Strings; /// <summary> /// Class that knows how to bind CastTokens. /// </summary> internal sealed class DottedIdentifierBinder : BinderBase { /// <summary> /// Constructs a DottedIdentifierBinder with the given method to be used binding the parent token if needed. /// </summary> /// <param name="bindMethod">Method to use for binding the parent token, if needed.</param> /// <param name="state">State of the metadata binding.</param> internal DottedIdentifierBinder(MetadataBinder.QueryTokenVisitor bindMethod, BindingState state) : base(bindMethod, state) { } /// <summary> /// Binds a DottedIdentifierToken and it's parent node (if needed). /// </summary> /// <param name="dottedIdentifierToken">Token to bind to metadata.</param> /// <returns>A bound node representing the cast.</returns> internal QueryNode BindDottedIdentifier(DottedIdentifierToken dottedIdentifierToken) { ExceptionUtils.CheckArgumentNotNull(dottedIdentifierToken, "castToken"); ExceptionUtils.CheckArgumentNotNull(state, "state"); QueryNode parent = null; IEdmType parentType = null; if (state.ImplicitRangeVariable != null) { if (dottedIdentifierToken.NextToken == null) { parent = NodeFactory.CreateRangeVariableReferenceNode(state.ImplicitRangeVariable); parentType = state.ImplicitRangeVariable.TypeReference.Definition; } else { parent = this.bindMethod(dottedIdentifierToken.NextToken); parentType = parent.GetEdmType(); } } SingleEntityNode parentAsSingleValue = parent as SingleEntityNode; IEdmSchemaType childType = UriEdmHelpers.FindTypeFromModel(state.Model, dottedIdentifierToken.Identifier, this.Resolver); IEdmStructuredType childStructuredType = childType as IEdmStructuredType; if (childStructuredType == null) { FunctionCallBinder functionCallBinder = new FunctionCallBinder(bindMethod, state); QueryNode functionCallNode; if (functionCallBinder.TryBindDottedIdentifierAsFunctionCall(dottedIdentifierToken, parent as SingleValueNode, out functionCallNode)) { return functionCallNode; } else if ((!string.IsNullOrEmpty(dottedIdentifierToken.Identifier)) && (dottedIdentifierToken.Identifier[dottedIdentifierToken.Identifier.Length - 1] == '\'')) { // check if it is enum or not EnumBinder enumBinder = new EnumBinder(this.bindMethod); QueryNode enumNode; if (enumBinder.TryBindDottedIdentifierAsEnum(dottedIdentifierToken, parentAsSingleValue, state, out enumNode)) { return enumNode; } else { throw new ODataException(ODataErrorStrings.Binder_IsNotValidEnumConstant(dottedIdentifierToken.Identifier)); } } else { IEdmTypeReference edmTypeReference = UriEdmHelpers.FindTypeFromModel(state.Model, dottedIdentifierToken.Identifier, this.Resolver).ToTypeReference(); if (edmTypeReference is IEdmPrimitiveTypeReference || edmTypeReference is IEdmEnumTypeReference) { return new ConstantNode(dottedIdentifierToken.Identifier, dottedIdentifierToken.Identifier); } else { throw new ODataException(ODataErrorStrings.CastBinder_ChildTypeIsNotEntity(dottedIdentifierToken.Identifier)); } } } // Check whether childType is a derived type of the type of its parent node UriEdmHelpers.CheckRelatedTo(parentType, childType); IEdmEntityType childEntityType = childStructuredType as IEdmEntityType; if (childEntityType != null) { EntityCollectionNode parentAsCollection = parent as EntityCollectionNode; if (parentAsCollection != null) { return new EntityCollectionCastNode(parentAsCollection, childEntityType); } // parent can be null for casts on the implicit parameter; this is OK if (parent == null) { return new SingleEntityCastNode(null, childEntityType); } Debug.Assert(parentAsSingleValue != null, "If parent of the cast node was not collection, it should be a single value."); return new SingleEntityCastNode(parentAsSingleValue, childEntityType); } else { IEdmComplexType childComplexType = childStructuredType as IEdmComplexType; Debug.Assert(childComplexType != null, "If it is not entity type, it should be complex type"); CollectionPropertyAccessNode parentAsCollectionProperty = parent as CollectionPropertyAccessNode; if (parentAsCollectionProperty != null) { return new CollectionPropertyCastNode(parentAsCollectionProperty, childComplexType); } // parent can be null for casts on the implicit parameter; this is OK if (parent == null) { return new SingleValueCastNode(null, childComplexType); } SingleValueNode parentAsSingleValueNode = parent as SingleValueNode; Debug.Assert(parentAsSingleValueNode != null, "If parent of the cast node was not collection, it should be a single value."); return new SingleValueCastNode(parentAsSingleValueNode, childComplexType); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; using System.Web.WebPages; /* * CarrotCake CMS (MVC5) * http://www.carrotware.com/ * * Copyright 2015, Samantha Copeland * Dual licensed under the MIT or GPL Version 3 licenses. * * Date: August 2015 */ namespace Carrotware.Web.UI.Components { public abstract class CarrotWebGridBase : IHtmlString { protected HtmlHelper _htmlHelper; protected SortParm _sortDir; protected void StandardInit(HtmlHelper htmlHelper, PagedDataBase dp) { _htmlHelper = htmlHelper; this.FooterOuterTag = "ul"; this.FooterTag = "li"; this.FieldIdPrefix = String.Empty; this.FieldNamePrefix = String.Empty; this.SortDescIndicator = "&nbsp;&#9660;"; this.SortAscIndicator = "&nbsp;&#9650;"; this.HtmlClientId = "tblDataTable"; this.Columns = new List<ICarrotGridColumn>(); this.UseDataPage = true; this.PageSizeExternal = false; this.PagedDataBase = dp; } protected PagedDataBase PagedDataBase { get; set; } public List<ICarrotGridColumn> Columns { get; protected set; } public Func<Object, HelperResult> EmptyDataTemplate { get; set; } public string HtmlClientId { get; set; } public string HtmlFormId { get; set; } public string SortDescIndicator { get; set; } public string SortAscIndicator { get; set; } protected string FieldIdPrefix { get; set; } protected string FieldNamePrefix { get; set; } public int RowNumber { get; set; } public bool UseDataPage { get; set; } public bool PageSizeExternal { get; set; } public string FooterOuterTag { get; set; } public object htmlFootAttrib { get; set; } public string FooterTag { get; set; } public object htmlFootSel { get; set; } public object htmlFootNotSel { get; set; } public void ConfigName(IHtmlString name) { this.FieldNamePrefix = name.ToString(); if (String.IsNullOrEmpty(this.FieldNamePrefix)) { this.FieldNamePrefix = String.Empty; } else { this.FieldNamePrefix = String.Format("{0}.", this.FieldNamePrefix); } this.FieldIdPrefix = this.FieldNamePrefix.Replace(".", "_").Replace("]", "_").Replace("[", "_"); } public object TableAttributes { get; set; } public object THeadAttributes { get; set; } public object TBodyAttributes { get; set; } protected IDictionary<string, object> InitAttrib(object htmlAttribs) { IDictionary<string, object> tblAttrib = (IDictionary<string, object>)new RouteValueDictionary(); if (htmlAttribs != null) { tblAttrib = (IDictionary<string, object>)HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribs); } return tblAttrib; } protected void FormHelper(Expression<Func<PagedDataBase, object>> property, StringBuilder sb) { PropertyInfo propInfo = this.PagedDataBase.PropInfoFromExpression<PagedDataBase>(property); string columnName = ReflectionUtilities.BuildProp(property); Object val = propInfo.GetValue(this.PagedDataBase, null); string fldName = String.Format("{0}{1}", this.FieldNamePrefix, columnName); string str = val == null ? String.Empty : val.ToString(); sb.AppendLine(_htmlHelper.Hidden(fldName, str).ToString()); } protected StringBuilder BuildHeadScript(StringBuilder sb) { string frm = "form:first"; if (!String.IsNullOrEmpty(this.HtmlFormId)) { frm = String.Format("#{0}", this.HtmlFormId); } if (this.UseDataPage) { sb.AppendLine(String.Empty); sb.AppendLine(" <script type=\"text/javascript\">"); sb.AppendLine(" function __clickHead(fld) {"); sb.AppendLine(String.Format(" $('#{0}SortByNew').val(fld);", this.FieldIdPrefix)); sb.AppendLine(String.Format(" $('{0}')[0].submit();", frm)); sb.AppendLine(" }"); sb.AppendLine(String.Empty); sb.AppendLine(" function __clickPage(nbr, fld) {"); sb.AppendLine(" $('#' + fld).val(nbr);"); sb.AppendLine(" $('#' + fld).focus();"); sb.AppendLine(String.Format(" $('{0}')[0].submit();", frm)); sb.AppendLine(" }"); sb.AppendLine(" </script>"); sb.AppendLine(String.Empty); FormHelper(x => x.OrderBy, sb); FormHelper(x => x.SortByNew, sb); if (!this.PageSizeExternal) { FormHelper(x => x.PageSize, sb); } FormHelper(x => x.TotalRecords, sb); FormHelper(x => x.MaxPage, sb); FormHelper(x => x.PageNumber, sb); } return sb; } protected StringBuilder BuildTableHeadRow(StringBuilder sb) { using (new WrappedItem(sb, "thead", this.THeadAttributes)) { using (new WrappedItem(sb, "tr", null)) { foreach (var col in this.Columns) { using (new WrappedItem(sb, "th", col.HeadAttributes)) { if (col is ICarrotGridColumnExt) { var colExt = (ICarrotGridColumnExt)col; if (colExt.Sortable && this.UseDataPage) { string js = String.Format("javascript:__clickHead('{0}')", colExt.ColumnName); IDictionary<string, object> tagAttrib = InitAttrib(colExt.HeadLinkAttributes); tagAttrib.Add("href", js); using (new WrappedItem(sb, "a", tagAttrib)) { sb.Append(col.HeaderText); if (_sortDir.SortField.ToUpperInvariant() == colExt.ColumnName.ToUpperInvariant()) { if (_sortDir.SortDirection.ToUpperInvariant() == "ASC") { sb.Append(this.SortAscIndicator); } else { sb.Append(this.SortDescIndicator); } } } } else { sb.Append(col.HeaderText); } } else { sb.Append(col.HeaderText); } } } } } return sb; } protected virtual IHtmlString CreateBody() { return new HtmlString(String.Empty); } public virtual void SetupFooter(string outer, object outerAttrib, string inner, object selAttrib, object noselAttrib) { this.FooterOuterTag = String.IsNullOrEmpty(outer) ? "ul" : outer; this.htmlFootAttrib = outerAttrib; this.FooterTag = String.IsNullOrEmpty(inner) ? "li" : inner; this.htmlFootSel = selAttrib; this.htmlFootNotSel = noselAttrib; } public virtual IHtmlString OutputFooter() { StringBuilder sb = new StringBuilder(); if (this.PagedDataBase.TotalPages > 1) { using (new WrappedItem(sb, this.FooterOuterTag, this.htmlFootAttrib)) { foreach (var i in this.PagedDataBase.PageNumbers) { string clickFn = String.Format("javascript:__clickPage('{0}','{1}PageNumber')", i, this.FieldIdPrefix); using (new WrappedItem(_htmlHelper, sb, this.FooterTag, i, this.PagedDataBase.PageNumber, this.htmlFootSel, this.htmlFootNotSel)) { using (new WrappedItem(sb, "a", new { @href = clickFn })) { sb.Append(String.Format(" {0} ", i)); } } } } } return new HtmlString(sb.ToString()); } protected virtual IHtmlString EmptyTable() { this.PagedDataBase.TotalRecords = 0; this.PagedDataBase.PageNumber = 1; string cellContents = String.Empty; StringBuilder sb = new StringBuilder(); FormHelper(x => x.OrderBy, sb); FormHelper(x => x.SortByNew, sb); if (!this.PageSizeExternal) { FormHelper(x => x.PageSize, sb); } FormHelper(x => x.TotalRecords, sb); FormHelper(x => x.MaxPage, sb); FormHelper(x => x.PageNumber, sb); if ((!this.PagedDataBase.HasData) && this.EmptyDataTemplate != null) { cellContents = (new HelperResult(writer => { this.EmptyDataTemplate(new Object()).WriteTo(writer); })).ToHtmlString(); } sb.AppendLine(cellContents); return new HtmlString(sb.ToString()); } public virtual IHtmlString OutputHtmlBody() { if (this.PagedDataBase.HasData) { return CreateBody(); } else { return EmptyTable(); } } public string ToHtmlString() { StringBuilder sb = new StringBuilder(); //sb.AppendLine("<div>"); sb.AppendLine(this.OutputHtmlBody().ToString()); sb.AppendLine(this.OutputFooter().ToString()); //sb.AppendLine("</div>"); return sb.ToString(); } public IHtmlString Write() { return new HtmlString(ToHtmlString()); } } }
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; using System.Configuration; using Enyim.Caching.Configuration; using System.Net.Sockets; using System.Threading; using System.Collections.ObjectModel; using System.Net; namespace Enyim.Caching.Memcached { internal class ServerPool : IDisposable { private static MemcachedClientSection DefaultSettings = ConfigurationManager.GetSection("enyim.com/memcached") as MemcachedClientSection; // holds all dead servers which will be periodically rechecked and put back into the working servers if found alive List<MemcachedNode> deadServers = new List<MemcachedNode>(); // holds all of the currently working servers List<MemcachedNode> workingServers = new List<MemcachedNode>(); private ReadOnlyCollection<MemcachedNode> publicWorkingServers; // used to synchronize read/write accesses on the server lists private ReaderWriterLock serverAccessLock = new ReaderWriterLock(); private Timer isAliveTimer; private IMemcachedClientConfiguration configuration; private IKeyTransformer keyTransformer; private IMemcachedNodeLocator nodeLocator; private ITranscoder transcoder; public ServerPool() : this(ServerPool.DefaultSettings) { } public ServerPool(IMemcachedClientConfiguration configuration) { if (configuration == null) throw new ArgumentNullException("settings", "Invalid or missing pool configuration. Check if the enyim.com/memcached section or your custom section presents in the app/web.config."); this.configuration = configuration; this.isAliveTimer = new Timer(callback_isAliveTimer, null, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds, (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds); // create the key transformer instance Type t = this.configuration.KeyTransformer; this.keyTransformer = (t == null) ? new DefaultKeyTransformer() : (IKeyTransformer)Activator.CreateInstance(t); // create the item transcoder instance t = this.configuration.Transcoder; this.transcoder = (t == null) ? new DefaultTranscoder() : (ITranscoder)Activator.CreateInstance(t); // initialize the server list ISocketPoolConfiguration ispc = configuration.SocketPool; foreach (IPEndPoint ip in configuration.Servers) { this.workingServers.Add(new MemcachedNode(ip, ispc)); } // (re)creates the locator this.RebuildIndexes(); } private void RebuildIndexes() { this.serverAccessLock.AcquireWriterLock(Timeout.Infinite); try { Type ltype = this.configuration.NodeLocator; IMemcachedNodeLocator l = ltype == null ? new DefaultNodeLocator() : (IMemcachedNodeLocator)Enyim.Reflection.FastActivator.CreateInstance(ltype); l.Initialize(this.workingServers); this.nodeLocator = l; this.publicWorkingServers = null; } finally { this.serverAccessLock.ReleaseLock(); } } /// <summary> /// Checks if a dead node is working again. /// </summary> /// <param name="state"></param> private void callback_isAliveTimer(object state) { this.serverAccessLock.AcquireReaderLock(Timeout.Infinite); try { if (this.deadServers.Count == 0) return; List<MemcachedNode> resurrectList = this.deadServers.FindAll(delegate(MemcachedNode node) { return node.Ping(); }); if (resurrectList.Count > 0) { this.serverAccessLock.UpgradeToWriterLock(Timeout.Infinite); resurrectList.ForEach(delegate(MemcachedNode node) { // maybe it got removed while we were waiting for the writer lock upgrade? if (this.deadServers.Remove(node)) this.workingServers.Add(node); }); this.RebuildIndexes(); } } finally { this.serverAccessLock.ReleaseLock(); } } /// <summary> /// Marks a node as dead (unusable) /// - moves hte node to the "dead list" /// - recreates the locator based on the new list of still functioning servers /// </summary> /// <param name="node"></param> private void MarkAsDead(MemcachedNode node) { this.serverAccessLock.AcquireWriterLock(Timeout.Infinite); try { // server gained AoeREZ while AFK? if (!node.IsAlive) { this.workingServers.Remove(node); this.deadServers.Add(node); this.RebuildIndexes(); } } finally { this.serverAccessLock.ReleaseLock(); } } /// <summary> /// Returns the <see cref="t:IKeyTransformer"/> instance used by the pool /// </summary> public IKeyTransformer KeyTransformer { get { return this.keyTransformer; } } public IMemcachedNodeLocator NodeLocator { get { return this.nodeLocator; } } public ITranscoder Transcoder { get { return this.transcoder; } } /// <summary> /// Finds the <see cref="T:MemcachedNode"/> which is responsible for the specified item /// </summary> /// <param name="itemKey"></param> /// <returns></returns> private MemcachedNode LocateNode(string itemKey) { this.serverAccessLock.AcquireReaderLock(Timeout.Infinite); try { MemcachedNode node = this.NodeLocator.Locate(itemKey); if (node == null) return null; if (node.IsAlive) return node; this.MarkAsDead(node); return this.LocateNode(itemKey); } finally { this.serverAccessLock.ReleaseLock(); } } public PooledSocket Acquire(string itemKey) { if (this.serverAccessLock == null) throw new ObjectDisposedException("ServerPool"); MemcachedNode server = this.LocateNode(itemKey); if (server == null) return null; return server.Acquire(); } public ReadOnlyCollection<MemcachedNode> WorkingServers { get { if (this.publicWorkingServers == null) { this.serverAccessLock.AcquireReaderLock(Timeout.Infinite); try { if (this.publicWorkingServers == null) { this.publicWorkingServers = new ReadOnlyCollection<MemcachedNode>(this.workingServers.FindAll(delegate(MemcachedNode node) { return true; })); } } finally { this.serverAccessLock.ReleaseLock(); } } return this.publicWorkingServers; } } public IDictionary<MemcachedNode, IList<string>> SplitKeys(IEnumerable<string> keys) { Dictionary<MemcachedNode, IList<string>> keysByNode = new Dictionary<MemcachedNode, IList<string>>(new MemcachedNodeComparer()); IList<string> nodeKeys; MemcachedNode node; foreach (string key in keys) { node = this.LocateNode(key); if (!keysByNode.TryGetValue(node, out nodeKeys)) { nodeKeys = new List<string>(); keysByNode.Add(node, nodeKeys); } nodeKeys.Add(key); } return keysByNode; } #region [ IDisposable ] void IDisposable.Dispose() { ReaderWriterLock rwl = this.serverAccessLock; if (rwl == null) return; this.serverAccessLock = null; try { rwl.AcquireWriterLock(Timeout.Infinite); this.deadServers.ForEach(delegate(MemcachedNode node) { node.Dispose(); }); this.workingServers.ForEach(delegate(MemcachedNode node) { node.Dispose(); }); this.deadServers.Clear(); this.workingServers.Clear(); this.nodeLocator = null; this.isAliveTimer.Dispose(); this.isAliveTimer = null; } finally { rwl.ReleaseLock(); } } #endregion } } #region [ License information ] /* ************************************************************ * * Copyright (c) Attila Kiskó, enyim.com, 2007 * * This source code is subject to terms and conditions of * Microsoft Permissive License (Ms-PL). * * A copy of the license can be found in the License.html * file at the root of this distribution. If you can not * locate the License, please send an email to a@enyim.com * * By using this source code in any fashion, you are * agreeing to be bound by the terms of the Microsoft * Permissive License. * * You must not remove this notice, or any other, from this * software. * * ************************************************************/ #endregion
// The MIT License (MIT) // // Copyright (c) 2015 Xamarin // // 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; namespace XamarinCRM.Models.Local { public class WeeklySalesDataPoint { public WeeklySalesDataPoint() { DateStart = DateTime.MinValue; DateEnd = DateTime.MaxValue; Amount = 0; } public DateTime DateStart { get; set; } public DateTime DateEnd { get; set; } public double Amount { get; set; } public string DateStartString { get { return DateStart.ToString("M/dd"); } } public string DateEndString { get { return DateEnd.ToString("M/dd"); } } } }
using GongSolutions.Wpf.DragDrop; using Prism.Commands; using Prism.Mvvm; using System; using System.IO; using System.Linq; using System.Windows; namespace Quark.source.MWindow { class ViewModel : BindableBase, IDropTarget { readonly Model _model = new Model(); public ViewModel() { _model.PropertyChanged += (s, e) => { RaisePropertyChanged(e.PropertyName); }; _model.UserNameTitle = $"Main | {Globals.User["username"]} > {Globals.User["group"]}"; _model.StatusText = "Here is status bar"; ImportCodeCommand = new DelegateCommand(() => { Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); dialog.Filter = "CPP Code (*.cpp)|*.cpp|Text files (*.txt)|*.txt"; dialog.FilterIndex = 2; Nullable<bool> result = dialog.ShowDialog(); if (result == true) { string filename = dialog.FileName; if (File.Exists(filename)) UpdateCodeTab(filename); } }); } void IDropTarget.DragOver(IDropInfo dropInfo) { var dragFileList = ((DataObject)dropInfo.Data).GetFileDropList().Cast<string>(); dropInfo.Effects = dragFileList.Any(item => { var extension = Path.GetExtension(item); return extension != null && (extension.Equals(".cpp") || extension.Equals(".txt")); }) ? DragDropEffects.Copy : DragDropEffects.None; } void IDropTarget.Drop(IDropInfo dropInfo) { var dragFileList = ((DataObject)dropInfo.Data).GetFileDropList().Cast<string>(); dropInfo.Effects = dragFileList.Any(item => { var extension = Path.GetExtension(item); if (extension.Equals(".cpp") || extension.Equals(".txt") && extension != null) UpdateCodeTab(item); return extension != null && (extension.Equals(".cpp") || extension.Equals(".txt")); }) ? DragDropEffects.Copy : DragDropEffects.None; } public void UpdateCodeTab(string path) // Bad way to solve the problem. * REWRITE * { ((Application.Current.Windows[0]) as MainWindow).CodeEdit.Text = File.ReadAllText(path).Trim(); } public DelegateCommand ImportCodeCommand { get; } public string UserNameTitle => _model.UserNameTitle; public string StatusText => _model.StatusText; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Specialized; using System.Drawing; using System.Drawing.Imaging; using System.Reflection; using System.IO; using System.Net; using System.Web; using log4net; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; namespace OpenSim.Capabilities.Handlers { public class GetTextureRobustHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_assetService; public const string DefaultFormat = "x-j2c"; // TODO: Change this to a config option private string m_RedirectURL = null; public GetTextureRobustHandler(string path, IAssetService assService, string name, string description, string redirectURL) : base("GET", path, name, description) { m_assetService = assService; m_RedirectURL = redirectURL; if (m_RedirectURL != null && !m_RedirectURL.EndsWith("/")) m_RedirectURL += "/"; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); string format = query.GetOne("format"); //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return null; } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (!string.IsNullOrEmpty(format)) { formats = new string[1] { format.ToLower() }; } else { formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); if (formats.Length == 0) formats = new string[1] { DefaultFormat }; // default } // OK, we have an array with preferred formats, possibly with only one entry httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; foreach (string f in formats) { if (FetchTexture(httpRequest, httpResponse, textureID, f)) break; } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); return null; } /// <summary> /// /// </summary> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <param name="textureID"></param> /// <param name="format"></param> /// <returns>False for "caller try another codec"; true otherwise</returns> private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) { // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); if (!String.IsNullOrEmpty(m_RedirectURL)) { string textureUrl = m_RedirectURL + "?texture_id=" + textureID.ToString(); m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); httpResponse.StatusCode = (int)HttpStatusCode.Moved; httpResponse.AddHeader("Location:", textureUrl); return true; } // Fetch, Misses or invalid return a 404 AssetBase texture = m_assetService.Get(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } if (format == DefaultFormat) { WriteTextureData(httpRequest, httpResponse, texture, format); return true; } // need to convert format AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); newTexture.Data = ConvertTextureData(texture, format); if (newTexture.Data.Length == 0) return false; // !!! Caller try another codec, please! newTexture.Flags = AssetFlags.Collectable; newTexture.Temporary = true; newTexture.Local = true; WriteTextureData(httpRequest, httpResponse, newTexture, format); return true; } // not found // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) { string range = request.Headers.GetOne("Range"); if (!String.IsNullOrEmpty(range)) // JP2's only { // Range request int start, end; if (TryParseRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= texture.Data.Length) { // m_log.DebugFormat( // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", // texture.ID, start, texture.Data.Length); // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously // received a very small texture may attempt to fetch bytes from the server past the // range of data that it received originally. Whether this happens appears to depend on whether // the viewer's estimation of how large a request it needs to make for certain discard levels // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable // here will cause the viewer to treat the texture as bad and never display the full resolution // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); // response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentType = texture.Metadata.ContentType; } else { // Handle the case where no second range value was given. This is equivalent to requesting // the rest of the entity. if (end == -1) end = int.MaxValue; end = Utils.Clamp(end, 0, texture.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); // Always return PartialContent, even if the range covered the entire data length // We were accidentally sending back 404 before in this situation // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this. // // We also do not want to send back OK even if the whole range was satisfiable since this causes // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality. // if (end > maxEnd) // response.StatusCode = (int)System.Net.HttpStatusCode.OK; // else response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentLength = len; response.ContentType = texture.Metadata.ContentType; response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); response.RawBuffer = texture.Data; response.RawBufferStart = start; response.RawBufferLen = len; } } else { m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } } else // JP2's or other formats { // Full content request response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.ContentLength = texture.Data.Length; if (format == DefaultFormat) response.ContentType = texture.Metadata.ContentType; else response.ContentType = "image/" + format; response.RawBuffer = texture.Data; response.RawBufferStart = 0; response.RawBufferLen = texture.Data.Length; } // if (response.StatusCode < 200 || response.StatusCode > 299) // m_log.WarnFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // else // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); } /// <summary> /// Parse a range header. /// </summary> /// <remarks> /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-). /// Where there is no value, -1 is returned. /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1 /// for start.</remarks> /// <returns></returns> /// <param name='header'></param> /// <param name='start'>Start of the range. Undefined if this was not a number.</param> /// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param> private bool TryParseRange(string header, out int start, out int end) { start = end = 0; if (header.StartsWith("bytes=")) { string[] rangeValues = header.Substring(6).Split('-'); if (rangeValues.Length == 2) { if (!Int32.TryParse(rangeValues[0], out start)) return false; string rawEnd = rangeValues[1]; if (rawEnd == "") { end = -1; return true; } else if (Int32.TryParse(rawEnd, out end)) { return true; } } } start = end = 0; return false; } private byte[] ConvertTextureData(AssetBase texture, string format) { m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); byte[] data = new byte[0]; MemoryStream imgstream = new MemoryStream(); Bitmap mTexture = null; ManagedImage managedImage = null; Image image = null; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image) && image != null) { // Save to bitmap mTexture = new Bitmap(image); using (EncoderParameters myEncoderParameters = new EncoderParameters()) { myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream ImageCodecInfo codec = GetEncoderInfo("image/" + format); if (codec != null) { mTexture.Save(imgstream, codec, myEncoderParameters); // Write the stream to a byte array for output data = imgstream.ToArray(); } else m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); } } } catch (Exception e) { m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mTexture != null) mTexture.Dispose(); if (image != null) image.Dispose(); if (managedImage != null) managedImage.Clear(); if (imgstream != null) imgstream.Dispose(); } return data; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } } }
using System.Collections.Generic; using System.Threading.Tasks; using Ivvy.API.Event; namespace Ivvy.API { public partial interface IApiClient { /// <summary> /// Returns a specific event. /// </summary> /// <param name="id">The unique id of the event..</param> /// <returns></returns> Task<ResultOrError<Event.Event>> GetEventAsync(int id); /// <summary> /// Returns a collection of events. /// </summary> /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <param name="options">The options.</param> /// <returns></returns> Task<ResultOrError<ResultList<Event.Event>>> GetEventListAsync(int perPage, int start, Dictionary<string, object> filterRequest = null, Event.GetEventListOptions options = null); /// <summary> /// Returns a collection of event attendees. /// </summary> /// <param name="eventId">The event identifier.</param> /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<Event.Attendee>>> GetEventAttendeeListAsync( int eventId, int perPage, int start, Dictionary<string, object> filterRequest = null); /// <summary> /// Returns a collection of event attendees across many events in the account. /// </summary> /// <param name="perPage">The per page records.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<Event.Attendee>>> GetAttendeeListForAccountAsync( int perPage, int start, Dictionary<string, object> filterRequest = null); /// <summary> /// Gets the invited contact list for account. /// </summary> /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<InvitedContact>>> GetInvitedContactListForAccount( int perPage, int start, Dictionary<string, object> filterRequest = null); /// <summary> /// Gets the invited contact list. /// </summary> /// <param name="eventId">The event identifier.</param> /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<InvitedContact>>> GetInvitedContactList( int eventId, int perPage, int start, Dictionary<string, object> filterRequest = null); /// <summary> /// Returns a collection of event registrations. /// </summary> /// <param name="eventId">The event identifier.</param> /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<Event.Registration>>> GetEventRegistrationListAsync( int eventId, int perPage, int start, Dictionary<string, object> filterRequest = null); /// <param name="perPage">The per page.</param> /// <param name="start">The start.</param> /// <param name="filterRequest">The filter request.</param> /// <returns></returns> Task<ResultOrError<ResultList<Event.Registration>>> GetRegistrationListForAccountAsync( int perPage, int start, Dictionary<string, object> filterRequest = null); } }
using System.Web.Mvc; namespace FeatureSwitch.AspNet.Sample.Controllers { public class HomeController : Controller { public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Index() { return View(); } } }
using System; using System.IO; using System.Runtime.CompilerServices; namespace Excel.Core.BinaryFormat { /// <summary> /// Represents a BIFF stream /// </summary> internal class XlsBiffStream : XlsStream { private readonly ExcelBinaryReader reader; private readonly byte[] bytes; private readonly int m_size; private int m_offset; public XlsBiffStream(XlsHeader hdr, uint streamStart, bool isMini, XlsRootDirectory rootDir, ExcelBinaryReader reader) : base(hdr, streamStart, isMini, rootDir) { this.reader = reader; bytes = base.ReadStream(); m_size = bytes.Length; m_offset = 0; } /// <summary> /// Returns size of BIFF stream in bytes /// </summary> public int Size { get { return m_size; } } /// <summary> /// Returns current position in BIFF stream /// </summary> public int Position { get { return m_offset; } } //TODO:Remove ReadStream /// <summary> /// Always returns null, use biff-specific methods /// </summary> /// <returns></returns> [Obsolete("Use BIFF-specific methods for this stream")] public new byte[] ReadStream() { return bytes; } /// <summary> /// Sets stream pointer to the specified offset /// </summary> /// <param name="offset">Offset value</param> /// <param name="origin">Offset origin</param> [MethodImpl(MethodImplOptions.Synchronized)] public void Seek(int offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: m_offset = offset; break; case SeekOrigin.Current: m_offset += offset; break; case SeekOrigin.End: m_offset = m_size - offset; break; } if (m_offset < 0) throw new ArgumentOutOfRangeException(string.Format("{0} On offset={1}", Errors.ErrorBIFFIlegalBefore, offset)); if (m_offset > m_size) throw new ArgumentOutOfRangeException(string.Format("{0} On offset={1}", Errors.ErrorBIFFIlegalAfter, offset)); } /// <summary> /// Reads record under cursor and advances cursor position to next record /// </summary> /// <returns></returns> [MethodImpl(MethodImplOptions.Synchronized)] public XlsBiffRecord Read() { if ((uint)m_offset >= bytes.Length) return null; XlsBiffRecord rec = XlsBiffRecord.GetRecord(bytes, (uint)m_offset, reader); m_offset += rec.Size; if (m_offset > m_size) return null; return rec; } /// <summary> /// Reads record at specified offset, does not change cursor position /// </summary> /// <param name="offset"></param> /// <returns></returns> public XlsBiffRecord ReadAt(int offset) { if ((uint)offset >= bytes.Length) return null; XlsBiffRecord rec = XlsBiffRecord.GetRecord(bytes, (uint)offset, reader); //choose ReadOption.Loose to skip this check (e.g. sql reporting services) if (reader.ReadOption == ReadOption.Strict) { if (m_offset + rec.Size > m_size) return null; } return rec; } } }
using Microsoft.EntityFrameworkCore; using P01_StudentSystem.Data.Models; using ConnectionStringInfo; namespace P01_StudentSystem.Data { public class StudentSystemContext : DbContext { public StudentSystemContext() { } public StudentSystemContext(DbContextOptions options) :base(options) { } public DbSet<Course> Courses { get; set; } public DbSet<Homework> HomeworkSubmissions { get; set; } public DbSet<Resource> Resources { get; set; } public DbSet<Student> Students { get; set; } public DbSet<StudentCourse> StudentCourses { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(ConnectionStringInfo.ConnectionStringInfo.ConnectionString); } base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<StudentCourse>(x => { x.HasKey(x => new { x.CourseId, x.StudentId }); }); base.OnModelCreating(modelBuilder); } } }
// ***************************************************************************** // // © Component Factory Pty Ltd 2012. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy, // Seaford, Vic 3198, Australia and are supplied subject to licence terms. // // // ***************************************************************************** using System; using System.IO; using System.Xml; using System.Text; using System.Drawing; using System.Drawing.Design; using System.Reflection; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.Windows.Forms; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Runtime.InteropServices; using Microsoft.Win32; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Displays a message box that can contain text, buttons, and symbols that inform and instruct the user. /// </summary> [ToolboxItem(false)] [ToolboxBitmap(typeof(KryptonMessageBox), "ToolboxBitmaps.KryptonMessageBox.bmp")] [DesignerCategory("code")] [DesignTimeVisible(false)] public class KryptonMessageBox : KryptonForm { #region Types internal class HelpInfo { #region Instance Fields private string _helpFilePath; private string _keyword; private HelpNavigator _navigator; private object _param; #endregion #region Identity /// <summary> /// Initialize a new instance of the HelpInfo class. /// </summary> public HelpInfo() { } /// <summary> /// Initialize a new instance of the HelpInfo class. /// </summary> /// <param name="helpFilePath">Value for HelpFilePath.</param> public HelpInfo(string helpFilePath) { _helpFilePath = helpFilePath; } /// <summary> /// Initialize a new instance of the HelpInfo class. /// </summary> /// <param name="helpFilePath">Value for HelpFilePath.</param> /// <param name="keyword">Value for Keyword</param> public HelpInfo(string helpFilePath, string keyword) { _helpFilePath = helpFilePath; _keyword = keyword; } /// <summary> /// Initialize a new instance of the HelpInfo class. /// </summary> /// <param name="helpFilePath">Value for HelpFilePath.</param> /// <param name="navigator">Value for Navigator</param> public HelpInfo(string helpFilePath, HelpNavigator navigator) { _helpFilePath = helpFilePath; _navigator = navigator; } /// <summary> /// Initialize a new instance of the HelpInfo class. /// </summary> /// <param name="helpFilePath">Value for HelpFilePath.</param> /// <param name="navigator">Value for Navigator</param> /// <param name="param">Value for Param</param> public HelpInfo(string helpFilePath, HelpNavigator navigator, object param) { _helpFilePath = helpFilePath; _navigator = navigator; _param = param; } #endregion #region Properties /// <summary> /// Gets the HelpFilePath property. /// </summary> public string HelpFilePath { get { return _helpFilePath; } } /// <summary> /// Gets the Keyword property. /// </summary> public string Keyword { get { return _keyword; } } /// <summary> /// Gets the Navigator property. /// </summary> public HelpNavigator Navigator { get { return _navigator; } } /// <summary> /// Gets the Param property. /// </summary> public object Param { get { return _param; } } #endregion } [ToolboxItem(false)] internal class MessageButton : KryptonButton { #region Instance Fields private bool _ignoreAltF4; #endregion #region Identity /// <summary> /// Gets and sets the ignoring of Alt+F4 /// </summary> public bool IgnoreAltF4 { get { return _ignoreAltF4; } set { _ignoreAltF4 = value; } } #endregion #region Protected /// <summary> /// Processes Windows messages. /// </summary> /// <param name="m">The Windows Message to process. </param> protected override void WndProc(ref Message m) { switch (m.Msg) { case PI.WM_KEYDOWN: case PI.WM_SYSKEYDOWN: if (IgnoreAltF4) { // Extract the keys being pressed Keys keys = ((Keys)((int)m.WParam.ToInt64())); // If the user standard combination ALT + F4 if ((keys == Keys.F4) && ((Control.ModifierKeys & Keys.Alt) == Keys.Alt)) { // Eat the message, so standard window proc does not close the window return; } } break; } base.WndProc(ref m); } #endregion } #endregion #region Static Fields int GAP { get { return (int)( 13.0f * DpiHelper.Default.DpiScaleFactor ); } } int GAP2 { get { return (int)( 8.0f * DpiHelper.Default.DpiScaleFactor ); } } //private static readonly int GAP = 16;//10; //private static readonly int GAP2 = 10; private static int _osMajorVersion; #endregion #region Instance Fields private string _text; private string _caption; private MessageBoxButtons _buttons; private MessageBoxIcon _icon; private MessageBoxDefaultButton _defaultButton; private MessageBoxOptions _options; private KryptonPanel _panelMessage; private KryptonPanel _panelMessageText; private KryptonWrapLabel _messageText; private KryptonPanel _panelMessageIcon; private PictureBox _messageIcon; private KryptonPanel _panelButtons; private MessageButton _button1; private MessageButton _button2; private MessageButton _button3; private KryptonBorderEdge borderEdge; private HelpInfo _helpInfo; #endregion #region Identity static KryptonMessageBox() { _osMajorVersion = Environment.OSVersion.Version.Major; } private KryptonMessageBox(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, HelpInfo helpInfo) { // Store incoming values _text = text; _caption = caption; _buttons = buttons; _icon = icon; _defaultButton = defaultButton; _options = options; _helpInfo = helpInfo; // Create the form contents InitializeComponent(); // Update contents to match requirements UpdateText(); UpdateIcon(); UpdateButtons(); UpdateDefault(); UpdateHelp(); // Finally calculate and set form sizing UpdateSizing(); if( KryptonDarkThemeUtility.DarkTheme ) _messageText.StateCommon.TextColor = Color.FromArgb( 230, 230, 230 ); var color = KryptonDarkThemeUtility.DarkTheme ? Color.FromArgb( 40, 40, 40 ) : Color.FromArgb( 255, 255, 255 ); _panelMessage.StateCommon.Color1 = color; _panelMessageIcon.StateCommon.Color1 = color; _panelMessageText.StateCommon.Color1 = color; } /// <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) { } base.Dispose(disposing); } #endregion #region Public /// <summary> /// Displays a message box with specified text. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text) { return InternalShow(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text) { return InternalShow(owner, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box with specified text and caption. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption) { return InternalShow(null, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text and caption. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption) { return InternalShow(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box with specified text, caption, and buttons. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) { return InternalShow(null, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text, caption, and buttons. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { return InternalShow(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box with specified text, caption, buttons, and icon. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { return InternalShow(null, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text, caption, buttons, and icon. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon) { return InternalShow(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, 0, null); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, and default button. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { return InternalShow(null, text, caption, buttons, icon, defaultButton, 0, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text, caption, buttons, icon, and default button. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, 0, null); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, and options. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, null); } /// <summary> /// Displays a message box in front of the specified object and with the specified text, caption, buttons, icon, default button, and options. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, options, null); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="displayHelpButton">Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool displayHelpButton) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, displayHelpButton ? new HelpInfo() : null); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file and HelpNavigator. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="navigator">One of the System.Windows.Forms.HelpNavigator values.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, navigator)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file and Help keyword. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="keyword">The Help keyword to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, keyword)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file and HelpNavigator. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="navigator">One of the System.Windows.Forms.HelpNavigator values.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, navigator)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file and Help keyword. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="keyword">The Help keyword to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, string keyword) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, keyword)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file, HelpNavigator, and Help topic. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="navigator">One of the System.Windows.Forms.HelpNavigator values.</param> /// <param name="param">The numeric ID of the Help topic to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator, object param) { return InternalShow(null, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, navigator, param)); } /// <summary> /// Displays a message box with the specified text, caption, buttons, icon, default button, options, and Help button, using the specified Help file, HelpNavigator, and Help topic. /// </summary> /// <param name="owner">Owner of the modal dialog box.</param> /// <param name="text">The text to display in the message box.</param> /// <param name="caption">The text to display in the title bar of the message box.</param> /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param> /// <param name="options">One of the System.Windows.Forms.MessageBoxOptions values that specifies which display and association options will be used for the message box. You may pass in 0 if you wish to use the defaults.</param> /// <param name="helpFilePath">The path and name of the Help file to display when the user clicks the Help button.</param> /// <param name="navigator">One of the System.Windows.Forms.HelpNavigator values.</param> /// <param name="param">The numeric ID of the Help topic to display when the user clicks the Help button.</param> /// <returns>One of the System.Windows.Forms.DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, string helpFilePath, HelpNavigator navigator, object param) { return InternalShow(owner, text, caption, buttons, icon, defaultButton, options, new HelpInfo(helpFilePath, navigator, param)); } #endregion #region Implementation private static DialogResult InternalShow(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, HelpInfo helpInfo) { // Check if trying to show a message box from a non-interactive process, this is not possible if (!SystemInformation.UserInteractive && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0)) throw new InvalidOperationException("Cannot show modal dialog when non-interactive"); // Check if trying to show a message box from a service and the owner has been specified, this is not possible if ((owner != null) && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0)) throw new ArgumentException("Cannot show message box from a service with an owner specified", "options"); // Check if trying to show a message box from a service and help information is specified, this is not possible if ((helpInfo != null) && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0)) throw new ArgumentException("Cannot show message box from a service with help specified", "options"); // If help information provided or we are not a service/default desktop application then grab an owner for showing the message box IWin32Window showOwner = null; if ((helpInfo != null) || ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0)) { // If do not have an owner passed in then get the active window and use that instead if (owner == null) showOwner = Control.FromHandle(PI.GetActiveWindow()); else showOwner = owner; } // Show message box window as a modal dialog and then dispose of it afterwards using (KryptonMessageBox kmb = new KryptonMessageBox(text, caption, buttons, icon, defaultButton, options, helpInfo)) { if (showOwner == null) kmb.StartPosition = FormStartPosition.CenterScreen; else kmb.StartPosition = FormStartPosition.CenterParent; return kmb.ShowDialog(showOwner); } } private void UpdateText() { Text = _caption; _messageText.Text = _text; } static Image GetResized( Bitmap source ) { if( DpiHelper.Default.DpiScaleFactor != 1.0f ) { var newSize = new Size( (int)( 32.0f * DpiHelper.Default.DpiScaleFactor ), (int)( 32.0f * DpiHelper.Default.DpiScaleFactor ) ); return new Bitmap( source, newSize ); //Bitmap result = new Bitmap( source, newSize ); //using( Graphics g = Graphics.FromImage( result ) ) //{ // g.DrawImage( bmp, 0, 0, width, height ); //} } return source; } private void UpdateIcon() { switch (_icon) { case MessageBoxIcon.None: _panelMessageIcon.Visible = false; _panelMessageText.Left -= _messageIcon.Right; //// Windows XP and before will Beep, Vista and above do not! //if (_osMajorVersion < 6) // System.Media.SystemSounds.Beep.Play(); break; case MessageBoxIcon.Question: _messageIcon.Image = GetResized( Properties.Resources.help2 ); //System.Media.SystemSounds.Question.Play(); break; case MessageBoxIcon.Information: _messageIcon.Image = GetResized( Properties.Resources.information ); //System.Media.SystemSounds.Asterisk.Play(); break; case MessageBoxIcon.Warning: _messageIcon.Image = GetResized( Properties.Resources.sign_warning ); //System.Media.SystemSounds.Exclamation.Play(); break; case MessageBoxIcon.Error: _messageIcon.Image = GetResized( Properties.Resources.error ); //System.Media.SystemSounds.Hand.Play(); break; } } private void UpdateButtons() { switch (_buttons) { case MessageBoxButtons.OK: _button1.Text = KryptonManager.Strings.OK; _button1.DialogResult = DialogResult.OK; _button2.Visible = _button3.Visible = false; break; case MessageBoxButtons.OKCancel: _button1.Text = KryptonManager.Strings.OK; _button2.Text = KryptonManager.Strings.Cancel; _button1.DialogResult = DialogResult.OK; _button2.DialogResult = DialogResult.Cancel; _button3.Visible = false; break; case MessageBoxButtons.YesNo: _button1.Text = KryptonManager.Strings.Yes; _button2.Text = KryptonManager.Strings.No; _button1.DialogResult = DialogResult.Yes; _button2.DialogResult = DialogResult.No; _button3.Visible = false; ControlBox = false; break; case MessageBoxButtons.YesNoCancel: _button1.Text = KryptonManager.Strings.Yes; _button2.Text = KryptonManager.Strings.No; _button3.Text = KryptonManager.Strings.Cancel; _button1.DialogResult = DialogResult.Yes; _button2.DialogResult = DialogResult.No; _button3.DialogResult = DialogResult.Cancel; break; case MessageBoxButtons.RetryCancel: _button1.Text = KryptonManager.Strings.Retry; _button2.Text = KryptonManager.Strings.Cancel; _button1.DialogResult = DialogResult.Retry; _button2.DialogResult = DialogResult.Cancel; _button3.Visible = false; break; case MessageBoxButtons.AbortRetryIgnore: _button1.Text = KryptonManager.Strings.Abort; _button2.Text = KryptonManager.Strings.Retry; _button3.Text = KryptonManager.Strings.Ignore; _button1.DialogResult = DialogResult.Abort; _button2.DialogResult = DialogResult.Retry; _button3.DialogResult = DialogResult.Ignore; ControlBox = false; break; } // Do we ignore the Alt+F4 on the buttons? if (!ControlBox) { _button1.IgnoreAltF4 = true; _button2.IgnoreAltF4 = true; _button3.IgnoreAltF4 = true; } } private void UpdateDefault() { switch (_defaultButton) { case MessageBoxDefaultButton.Button2: _button2.Select(); break; case MessageBoxDefaultButton.Button3: _button3.Select(); break; } } private void UpdateHelp() { } private void UpdateSizing() { Size messageSizing = UpdateMessageSizing(); Size buttonsSizing = UpdateButtonsSizing(); // Size of window is calculated from the client area ClientSize = new Size(Math.Max(messageSizing.Width, buttonsSizing.Width), messageSizing.Height + buttonsSizing.Height); } private Size UpdateMessageSizing() { // Update size of the message label but with a maximum width using (Graphics g = CreateGraphics()) { // Find size of the label when it has a maximum length of 400 _messageText.UpdateFont(); Size messageSize = g.MeasureString(_text, _messageText.Font, 400).ToSize(); // Always add on ad extra 5 pixels as sometimes the measure size does not draw the last // character it contains, this ensures there is always definitely enough space for it all messageSize.Width += 12; // Work out DPI adjustment factor messageSize.Width = (int)(messageSize.Width * DpiHelper.Default.DpiScaleFactor); messageSize.Height += 10; //messageSize.Height = (int)(messageSize.Height * DpiHelper.Default.DpiScaleFactor); // Always add on ad extra 5 pixels as sometimes the measure size does not draw the last // character it contains, this ensures there is always definitely enough space for it all //messageSize.Width += 5; _messageText.Size = messageSize; } // Resize panel containing the message text Padding panelMessagePadding = _panelMessageText.Padding; _panelMessageText.Width = _messageText.Size.Width + panelMessagePadding.Horizontal; _panelMessageText.Height = _messageText.Size.Height + panelMessagePadding.Vertical; // Find size of icon area plus the text area added together Size panelSize = _panelMessageText.Size; if (_messageIcon.Image != null) { panelSize.Width += _panelMessageIcon.Width; panelSize.Height = Math.Max(panelSize.Height, _panelMessageIcon.Height); } // Enforce a minimum size for the message area panelSize = new Size(Math.Max(_panelMessage.Size.Width, panelSize.Width), Math.Max(_panelMessage.Size.Height, panelSize.Height)); // Note that the width will be ignored in this update, but that is fine as // it will be adjusted by the UpdateSizing method that is the caller. _panelMessage.Size = panelSize; return panelSize; } private Size UpdateButtonsSizing() { int numButtons = 1; // Button1 is always visible Size button1Size = new Size( 90/*117*/, 26/*32*/ );// _button1.GetPreferredSize(Size.Empty); Size maxButtonSize = new Size(button1Size.Width + GAP2, button1Size.Height); // If Button2 is visible switch (_buttons) { case MessageBoxButtons.OKCancel: case MessageBoxButtons.YesNo: case MessageBoxButtons.YesNoCancel: case MessageBoxButtons.RetryCancel: case MessageBoxButtons.AbortRetryIgnore: { numButtons++; Size button2Size = button1Size;//_button2.GetPreferredSize(Size.Empty); maxButtonSize.Width = Math.Max(maxButtonSize.Width, button2Size.Width + GAP2); maxButtonSize.Height = Math.Max(maxButtonSize.Height, button2Size.Height); } break; } // If Button3 is visible switch (_buttons) { case MessageBoxButtons.YesNoCancel: case MessageBoxButtons.AbortRetryIgnore: { numButtons++; Size button3Size = button1Size;// _button2.GetPreferredSize(Size.Empty); maxButtonSize.Width = Math.Max(maxButtonSize.Width, button3Size.Width + GAP2); maxButtonSize.Height = Math.Max(maxButtonSize.Height, button3Size.Height); } break; } // Start positioning buttons 10 pixels from right edge int right = _panelButtons.Right - GAP; // If Button3 is visible switch (_buttons) { case MessageBoxButtons.YesNoCancel: case MessageBoxButtons.AbortRetryIgnore: { _button3.Location = new Point(right - maxButtonSize.Width, GAP); _button3.Size = maxButtonSize; right -= maxButtonSize.Width + GAP2; } break; } // If Button2 is visible switch (_buttons) { case MessageBoxButtons.OKCancel: case MessageBoxButtons.YesNo: case MessageBoxButtons.YesNoCancel: case MessageBoxButtons.RetryCancel: case MessageBoxButtons.AbortRetryIgnore: { _button2.Location = new Point(right - maxButtonSize.Width, GAP); _button2.Size = maxButtonSize; right -= maxButtonSize.Width + GAP2; } break; } // Button1 is always visible _button1.Location = new Point(right - maxButtonSize.Width, GAP); _button1.Size = maxButtonSize; //!!!! int add = 0; if( DpiHelper.Default.DpiScaleFactor >= 1.5) add = (int)( 6.0f * DpiHelper.Default.DpiScaleFactor ); // Size the panel for the buttons _panelButtons.Size = new Size((maxButtonSize.Width * numButtons) + GAP * (numButtons + 1), maxButtonSize.Height + GAP * 2 + add ); // Button area is the number of buttons with gaps between them and 10 pixels around all edges return new Size((maxButtonSize.Width * numButtons) + GAP * (numButtons + 1), maxButtonSize.Height + GAP * 2 + add ); } private void button_keyDown(object sender, KeyEventArgs e) { // Escape key kills the dialog if we allow it to be closed if ((e.KeyCode == Keys.Escape) && ControlBox) Close(); else { // Pressing Ctrl+C should copy message text into the clipboard if ((e.Modifiers == Keys.Control) && (e.KeyCode == Keys.C)) { StringBuilder sb = new StringBuilder(); sb.AppendLine("---------------------------"); sb.AppendLine(_caption); sb.AppendLine("---------------------------"); sb.AppendLine(_text); sb.AppendLine("---------------------------"); sb.Append(_button1.Text); sb.Append(" "); if (_button2.Visible) { sb.Append(_button2.Text); sb.Append(" "); if (_button3.Visible) { sb.Append(_button3.Text); sb.Append(" "); } } sb.AppendLine(""); sb.AppendLine("---------------------------"); Clipboard.SetText(sb.ToString(), TextDataFormat.Text); } } } private void InitializeComponent() { this._panelMessage = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this._panelMessageText = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this._messageText = new ComponentFactory.Krypton.Toolkit.KryptonWrapLabel(); this._panelMessageIcon = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this._messageIcon = new System.Windows.Forms.PictureBox(); this._panelButtons = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.borderEdge = new ComponentFactory.Krypton.Toolkit.KryptonBorderEdge(); this._button3 = new ComponentFactory.Krypton.Toolkit.KryptonMessageBox.MessageButton(); this._button1 = new ComponentFactory.Krypton.Toolkit.KryptonMessageBox.MessageButton(); this._button2 = new ComponentFactory.Krypton.Toolkit.KryptonMessageBox.MessageButton(); ((System.ComponentModel.ISupportInitialize)(this._panelMessage)).BeginInit(); this._panelMessage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._panelMessageText)).BeginInit(); this._panelMessageText.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._panelMessageIcon)).BeginInit(); this._panelMessageIcon.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._messageIcon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._panelButtons)).BeginInit(); this._panelButtons.SuspendLayout(); this.SuspendLayout(); // // _panelMessage // this._panelMessage.AutoSize = true; this._panelMessage.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._panelMessage.Controls.Add(this._panelMessageText); this._panelMessage.Controls.Add(this._panelMessageIcon); this._panelMessage.Dock = System.Windows.Forms.DockStyle.Top; this._panelMessage.Location = new System.Drawing.Point(0, 0); this._panelMessage.Name = "_panelMessage"; this._panelMessage.Size = new System.Drawing.Size(156, 52); this._panelMessage.TabIndex = 0; // // _panelMessageText // this._panelMessageText.AutoSize = true; this._panelMessageText.Controls.Add(this._messageText); this._panelMessageText.Location = new System.Drawing.Point(52, 0); this._panelMessageText.Margin = new System.Windows.Forms.Padding(0); this._panelMessageText.Name = "_panelMessageText"; this._panelMessageText.Padding = new System.Windows.Forms.Padding(5, 17, 5, 17); this._panelMessageText.Size = new System.Drawing.Size(88, 52); this._panelMessageText.TabIndex = 1; // // _messageText // this._messageText.AutoSize = false; this._messageText.Font = new System.Drawing.Font("Segoe UI", 9F); this._messageText.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(57)))), ((int)(((byte)(91))))); this._messageText.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this._messageText.Location = new System.Drawing.Point(10, 22); this._messageText.Margin = new System.Windows.Forms.Padding(0); this._messageText.Name = "_messageText"; this._messageText.Size = new System.Drawing.Size(78, 15); this._messageText.Text = "Message Text"; // // _panelMessageIcon // this._panelMessageIcon.AutoSize = true; this._panelMessageIcon.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._panelMessageIcon.Controls.Add(this._messageIcon); this._panelMessageIcon.Location = new System.Drawing.Point(0, 0); this._panelMessageIcon.Margin = new System.Windows.Forms.Padding(0); this._panelMessageIcon.Name = "_panelMessageIcon"; this._panelMessageIcon.Padding = new System.Windows.Forms.Padding(10, 10, 0, 10); this._panelMessageIcon.Size = new System.Drawing.Size(42, 52); this._panelMessageIcon.TabIndex = 0; // // _messageIcon // this._messageIcon.BackColor = System.Drawing.Color.Transparent; this._messageIcon.Location = new System.Drawing.Point(16, 16); this._messageIcon.Margin = new System.Windows.Forms.Padding(0); this._messageIcon.Name = "_messageIcon"; this._messageIcon.Size = new System.Drawing.Size(32, 32); this._messageIcon.TabIndex = 0; this._messageIcon.TabStop = false; this._messageIcon.SizeMode = PictureBoxSizeMode.AutoSize; // // _panelButtons // this._panelButtons.Controls.Add(this.borderEdge); this._panelButtons.Controls.Add(this._button3); this._panelButtons.Controls.Add(this._button1); this._panelButtons.Controls.Add(this._button2); this._panelButtons.Dock = System.Windows.Forms.DockStyle.Top; this._panelButtons.Location = new System.Drawing.Point(0, 52); this._panelButtons.Margin = new System.Windows.Forms.Padding(0); this._panelButtons.Name = "_panelButtons"; this._panelButtons.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this._panelButtons.Size = new System.Drawing.Size(156, 26); this._panelButtons.TabIndex = 0; // // borderEdge // this.borderEdge.BorderStyle = ComponentFactory.Krypton.Toolkit.PaletteBorderStyle.HeaderPrimary; this.borderEdge.Dock = System.Windows.Forms.DockStyle.Top; this.borderEdge.Location = new System.Drawing.Point(0, 0); this.borderEdge.Name = "borderEdge"; this.borderEdge.Size = new System.Drawing.Size(156, 1); this.borderEdge.Text = "kryptonBorderEdge1"; // // _button3 // this._button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this._button3.AutoSize = true; this._button3.IgnoreAltF4 = false; this._button3.Location = new System.Drawing.Point(106, 0); this._button3.Margin = new System.Windows.Forms.Padding(0); this._button3.MinimumSize = new System.Drawing.Size(50, 26); this._button3.Name = "_button3"; this._button3.Size = new System.Drawing.Size(50, 26); this._button3.TabIndex = 2; this._button3.Values.Text = "B3"; this._button3.KeyDown += new System.Windows.Forms.KeyEventHandler(this.button_keyDown); // // _button1 // this._button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this._button1.AutoSize = true; this._button1.IgnoreAltF4 = false; this._button1.Location = new System.Drawing.Point(6, 0); this._button1.Margin = new System.Windows.Forms.Padding(0); this._button1.MinimumSize = new System.Drawing.Size(50, 26); this._button1.Name = "_button1"; this._button1.Size = new System.Drawing.Size(50, 26); this._button1.TabIndex = 0; this._button1.Values.Text = "B1"; this._button1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.button_keyDown); // // _button2 // this._button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this._button2.AutoSize = true; this._button2.IgnoreAltF4 = false; this._button2.Location = new System.Drawing.Point(56, 0); this._button2.Margin = new System.Windows.Forms.Padding(0); this._button2.MinimumSize = new System.Drawing.Size(50, 26); this._button2.Name = "_button2"; this._button2.Size = new System.Drawing.Size(50, 26); this._button2.TabIndex = 1; this._button2.Values.Text = "B2"; this._button2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.button_keyDown); // // KryptonMessageBox // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(156, 78); this.Controls.Add(this._panelButtons); this.Controls.Add(this._panelMessage); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "KryptonMessageBox"; this.ShowIcon = false; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.TopMost = false;//!!!!betauser = true; ((System.ComponentModel.ISupportInitialize)(this._panelMessage)).EndInit(); this._panelMessage.ResumeLayout(false); this._panelMessage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this._panelMessageText)).EndInit(); this._panelMessageText.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this._panelMessageIcon)).EndInit(); this._panelMessageIcon.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this._messageIcon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._panelButtons)).EndInit(); this._panelButtons.ResumeLayout(false); this._panelButtons.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected override CreateParams CreateParams { get { CreateParams handleParam = base.CreateParams; handleParam.ExStyle |= 0x02000000;//WS_EX_COMPOSITED return handleParam; } } } }
using System; using System.Linq; using STPLoader.Implementation.Parser; namespace STPLoader.Implementation.Model.Entity { /// <summary> /// /// </summary> public class Circle : Entity { /// <summary> /// /// </summary> public string Info; /// <summary> /// /// </summary> public long PointId; public double Radius; public override void Init() { Info = ParseHelper.Parse<string>(Data[0]); PointId = ParseHelper.ParseId(Data[1]); Radius = ParseHelper.Parse<double>(Data[2]); } public override string ToString() { return String.Format("<Circle({0}, {1}, {2})", Info, PointId, Radius); } } }
using UnityEngine; using System.Collections.Generic; using UMA; using System; /// <summary> /// Base class for UMA slot libraries. /// </summary> public abstract class SlotLibraryBase : MonoBehaviour { public virtual void AddSlotAsset(SlotDataAsset slot) { throw new NotFiniteNumberException(); } public virtual SlotDataAsset[] GetAllSlotAssets() { throw new NotFiniteNumberException(); } public abstract SlotData InstantiateSlot(string name); public abstract SlotData InstantiateSlot(int nameHash); public abstract SlotData InstantiateSlot(string name, List<OverlayData> overlayList); public abstract SlotData InstantiateSlot(int nameHash, List<OverlayData> overlayList); public abstract void UpdateDictionary(); public abstract void ValidateDictionary(); [Obsolete("SlotLibrary.AddSlot(SlotData slot) is obsolete use SlotLibrary.AddSlotAsset(SlotDataAsset slot) instead", false)] public virtual void AddSlot(SlotData slot) { throw new NotFiniteNumberException(); } [Obsolete("SlotLibrary.GetAllSlots() is obsolete use SlotLibrary.GetAllSlotAssets() instead", false)] public virtual SlotData[] GetAllSlots() { throw new NotFiniteNumberException(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Newtonsoft.Json; using Aliyun.Acs.Core; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class DescribeInstanceMonitorDataResponse : AcsResponse { private string requestId; private List<DescribeInstanceMonitorData_InstanceMonitorData> monitorData; public string RequestId { get { return requestId; } set { requestId = value; } } public List<DescribeInstanceMonitorData_InstanceMonitorData> MonitorData { get { return monitorData; } set { monitorData = value; } } public class DescribeInstanceMonitorData_InstanceMonitorData { private float? cPUCreditBalance; private int? bPSRead; private int? internetTX; private int? cPU; private float? cPUCreditUsage; private int? iOPSWrite; private int? intranetTX; private string instanceId; private int? bPSWrite; private float? cPUNotpaidSurplusCreditUsage; private float? cPUAdvanceCreditBalance; private int? iOPSRead; private int? internetBandwidth; private int? internetRX; private string timeStamp; private int? intranetRX; private int? intranetBandwidth; public float? CPUCreditBalance { get { return cPUCreditBalance; } set { cPUCreditBalance = value; } } public int? BPSRead { get { return bPSRead; } set { bPSRead = value; } } public int? InternetTX { get { return internetTX; } set { internetTX = value; } } public int? CPU { get { return cPU; } set { cPU = value; } } public float? CPUCreditUsage { get { return cPUCreditUsage; } set { cPUCreditUsage = value; } } public int? IOPSWrite { get { return iOPSWrite; } set { iOPSWrite = value; } } public int? IntranetTX { get { return intranetTX; } set { intranetTX = value; } } public string InstanceId { get { return instanceId; } set { instanceId = value; } } public int? BPSWrite { get { return bPSWrite; } set { bPSWrite = value; } } public float? CPUNotpaidSurplusCreditUsage { get { return cPUNotpaidSurplusCreditUsage; } set { cPUNotpaidSurplusCreditUsage = value; } } public float? CPUAdvanceCreditBalance { get { return cPUAdvanceCreditBalance; } set { cPUAdvanceCreditBalance = value; } } public int? IOPSRead { get { return iOPSRead; } set { iOPSRead = value; } } public int? InternetBandwidth { get { return internetBandwidth; } set { internetBandwidth = value; } } public int? InternetRX { get { return internetRX; } set { internetRX = value; } } public string TimeStamp { get { return timeStamp; } set { timeStamp = value; } } public int? IntranetRX { get { return intranetRX; } set { intranetRX = value; } } public int? IntranetBandwidth { get { return intranetBandwidth; } set { intranetBandwidth = value; } } } } }
using System; using Xunit; namespace GameboyAdvanced.Core.Tests; public class TestUtils { [Fact] public void TestReadWriteHalfWord() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteHalfWord(b, 0xFF, 0, 0x1122); Assert.Equal(0x22, b[0]); Assert.Equal(0x11, b[1]); Assert.Equal(0x1122, Utils.ReadHalfWord(b, 0, 0xFF)); } [Fact] public void TestReadWriteHalfWordUnaligned() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteHalfWord(b, 0xFF, 1, 0x1122); Assert.Equal(0x22, b[1]); Assert.Equal(0x11, b[2]); Assert.Equal(0x1122, Utils.ReadHalfWord(b, 1, 0xFF)); } [Fact] public void TestReadWriteHalfWordWrap() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteHalfWord(b, 0xFF, 0xFF, 0x1122); Assert.Equal(0x22, b[0xFF]); Assert.Equal(0x11, b[0x00]); Assert.Equal(0x1122, Utils.ReadHalfWord(b, 0xFF, 0xFF)); } [Fact] public void TestReadWriteWord() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteWord(b, 0xFF, 0, 0x11223344); Assert.Equal(0x44, b[0]); Assert.Equal(0x33, b[1]); Assert.Equal(0x22, b[2]); Assert.Equal(0x11, b[3]); Assert.Equal((uint)0x11223344, Utils.ReadWord(b, 0, 0xFF)); } [Fact] public void TestReadWriteWordUnaligned() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteWord(b, 0xFF, 1, 0x11223344); Assert.Equal(0x44, b[1]); Assert.Equal(0x33, b[2]); Assert.Equal(0x22, b[3]); Assert.Equal(0x11, b[4]); Assert.Equal((uint)0x11223344, Utils.ReadWord(b, 1, 0xFF)); } [Fact] public void TestReadWriteWordWrap() { var b = new byte[0x100]; new Random().NextBytes(b); Utils.WriteWord(b, 0xFF, 0xFE, 0x11223344); Assert.Equal(0x44, b[0xFE]); Assert.Equal(0x33, b[0xFF]); Assert.Equal(0x22, b[0x00]); Assert.Equal(0x11, b[0x01]); Assert.Equal((uint)0x11223344, Utils.ReadWord(b, 0xFE, 0xFF)); } }
//----------------------------------------------------------------------- // <copyright file="InstantPreviewManager.cs" company="Google"> // // Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using GoogleARCore; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SpatialTracking; #if UNITY_EDITOR using UnityEditor; #endif #if UNITY_IOS && !UNITY_EDITOR using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif /// <summary> /// Contains methods for managing communication to the Instant Preview /// plugin. /// </summary> public static class InstantPreviewManager { /// <summary> /// Name of the Instant Preview plugin library. /// </summary> public const string InstantPreviewNativeApi = "arcore_instant_preview_unity_plugin"; /// <summary> /// Location of the Instant Preview warning prefab. /// </summary> public const string InstantPreviewWarningPrefabPath = "Assets/GoogleARCore/SDK/InstantPreview/Prefabs/Instant Preview Touch Warning.prefab"; // Guid is taken from meta file and should never change. private const string k_ApkGuid = "cf7b10762fe921e40a18151a6c92a8a6"; private const string k_NoDevicesFoundAdbResult = "error: no devices/emulators found"; private const float k_MaxTolerableAspectRatioDifference = 0.1f; private const string k_MismatchedAspectRatioWarningFormatString = "The aspect ratio of your game window is different from the aspect ratio of your Instant Preview camera " + "texture. Please resize your game window's aspect ratio to match, or your preview will be distorted. " + "The camera texture resolution is {0}, {1}."; private static readonly WaitForEndOfFrame k_WaitForEndOfFrame = new WaitForEndOfFrame(); private static bool s_PauseWarned = false; // Throttle warnings to at most once every N seconds. private static ThrottledLogMessage s_DisableLightEstimationWarning = new ThrottledLogMessage(5f); private static ThrottledLogMessage s_DisablePlaneFindingWarning = new ThrottledLogMessage(5f); /// <summary> /// Coroutine method that communicates to the Instant Preview plugin /// every frame. /// /// If not running in the editor, this does nothing. /// </summary> /// <returns>Enumerator for a coroutine that updates Instant Preview /// every frame.</returns> public static IEnumerator InitializeIfNeeded() { // Terminates if not running in editor. if (!Application.isEditor) { yield break; } // User may have explicitly disabled Instant Preview. if (ARCoreProjectSettings.Instance != null && !ARCoreProjectSettings.Instance.IsInstantPreviewEnabled) { yield break; } #if UNITY_EDITOR // Determine if any augmented image databases need a rebuild. List<AugmentedImageDatabase> databases = new List<AugmentedImageDatabase>(); bool shouldRebuild = false; var augmentedImageDatabaseGuids = AssetDatabase.FindAssets("t:AugmentedImageDatabase"); foreach (var databaseGuid in augmentedImageDatabaseGuids) { var database = AssetDatabase.LoadAssetAtPath<AugmentedImageDatabase>( AssetDatabase.GUIDToAssetPath(databaseGuid)); databases.Add(database); shouldRebuild = shouldRebuild || database.IsBuildNeeded(); } // If the preference is to ask the user to rebuild, ask now. if (shouldRebuild && PromptToRebuildAugmentedImagesDatabase()) { foreach (var database in databases) { string error; database.BuildIfNeeded(out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning("Failed to rebuild augmented " + "image database: " + error); } } } #endif var adbPath = InstantPreviewManager.GetAdbPath(); if (adbPath == null) { Debug.LogError("Instant Preview requires your Unity Android SDK path to be set. " + "Please set it under 'Preferences > External Tools > Android'. " + "You may need to install the Android SDK first."); yield break; } else if (!File.Exists(adbPath)) { Debug.LogErrorFormat("adb not found at \"{0}\". Please verify that 'Preferences > " + "External Tools > Android' has the correct Android SDK path, " + "that the Android Platform Tools are installed, and that " + "\"{0}\" exists. You may need to install the Android SDK first.", adbPath); yield break; } string localVersion; if (!StartServer(adbPath, out localVersion)) { yield break; } yield return InstallApkAndRunIfConnected(adbPath, localVersion); yield return UpdateLoop(adbPath); } /// <summary> /// Uploads the latest camera video frame received from Instant Preview /// to the specified texture. The texture might be recreated if it is /// not the right size or null. /// </summary> /// <param name="backgroundTexture">Texture variable to store the latest /// Instant Preview video frame.</param> /// <returns>True if InstantPreview updated the background texture, /// false if it did not and the texture still needs updating.</returns> public static bool UpdateBackgroundTextureIfNeeded(ref Texture2D backgroundTexture) { if (!Application.isEditor) { return false; } IntPtr pixelBytes; int width; int height; if (NativeApi.LockCameraTexture(out pixelBytes, out width, out height)) { if (backgroundTexture == null || width != backgroundTexture.width || height != backgroundTexture.height) { backgroundTexture = new Texture2D(width, height, TextureFormat.BGRA32, false); } backgroundTexture.LoadRawTextureData(pixelBytes, width * height * 4); backgroundTexture.Apply(); NativeApi.UnlockCameraTexture(); } return true; } /// <summary> /// Handles Instant Preview logic when ARCore's EarlyUpdate method is called. /// </summary> public static void OnEarlyUpdate() { var session = LifecycleManager.Instance.SessionComponent; if (!Application.isEditor || session == null) { return; } if (!s_PauseWarned && !session.enabled) { Debug.LogWarning("Disabling ARCore session is not available in editor."); s_PauseWarned = true; } var config = session.SessionConfig; if (config == null) { return; } if (!config.EnableLightEstimation) { s_DisableLightEstimationWarning.ThrottledLogWarningFormat( "ARCore light estimation cannot be disabled in editor."); } if (config.PlaneFindingMode == DetectedPlaneFindingMode.Disabled) { s_DisablePlaneFindingWarning.ThrottledLogWarningFormat( "ARCore plane finding cannot be disabled in editor."); } } private static IEnumerator UpdateLoop(string adbPath) { var renderEventFunc = NativeApi.GetRenderEventFunc(); var shouldConvertToBgra = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11; var loggedAspectRatioWarning = false; // Waits until the end of the first frame until capturing the screen size, // because it might be incorrect when first querying it. yield return k_WaitForEndOfFrame; var currentWidth = 0; var currentHeight = 0; var needToStartActivity = true; var prevFrameLandscape = false; RenderTexture screenTexture = null; RenderTexture targetTexture = null; RenderTexture bgrTexture = null; #if UNITY_EDITOR // If enabled, instantiate dismissable warning message. InstantPreviewWarning prefab = AssetDatabase.LoadAssetAtPath<InstantPreviewWarning>(InstantPreviewWarningPrefabPath); if (prefab != null && prefab.ShowEditorWarning) { GameObject warningCanvas = GameObject.Instantiate(prefab.gameObject) as GameObject; GameObject.DontDestroyOnLoad(warningCanvas); } #endif // UNITY_EDITOR // Begins update loop. The coroutine will cease when the // ARCoreSession component it's called from is destroyed. for (;;) { yield return k_WaitForEndOfFrame; var curFrameLandscape = Screen.width > Screen.height; if (prevFrameLandscape != curFrameLandscape) { needToStartActivity = true; } prevFrameLandscape = curFrameLandscape; if (needToStartActivity) { string activityName = curFrameLandscape ? "InstantPreviewLandscapeActivity" : "InstantPreviewActivity"; string output; string errors; ShellHelper.RunCommand(adbPath, "shell am start -S -n com.google.ar.core.instantpreview/." + activityName, out output, out errors); needToStartActivity = false; } // Creates a target texture to capture the preview window onto. // Some video encoders prefer the dimensions to be a multiple of 16. var targetWidth = RoundUpToNearestMultipleOf16(Screen.width); var targetHeight = RoundUpToNearestMultipleOf16(Screen.height); if (targetWidth != currentWidth || targetHeight != currentHeight) { screenTexture = new RenderTexture(targetWidth, targetHeight, 0); targetTexture = screenTexture; if (shouldConvertToBgra) { bgrTexture = new RenderTexture(screenTexture.width, screenTexture.height, 0, RenderTextureFormat.BGRA32); targetTexture = bgrTexture; } currentWidth = targetWidth; currentHeight = targetHeight; } NativeApi.Update(); InstantPreviewInput.Update(); AddInstantPreviewTrackedPoseDriverWhenNeeded(); Graphics.Blit(null, screenTexture); if (shouldConvertToBgra) { Graphics.Blit(screenTexture, bgrTexture); } var cameraTexture = Frame.CameraImage.Texture; if (!loggedAspectRatioWarning && cameraTexture != null) { var sourceWidth = cameraTexture.width; var sourceHeight = cameraTexture.height; var sourceAspectRatio = (float)sourceWidth / sourceHeight; var destinationWidth = Screen.width; var destinationHeight = Screen.height; var destinationAspectRatio = (float)destinationWidth / destinationHeight; if (Mathf.Abs(sourceAspectRatio - destinationAspectRatio) > k_MaxTolerableAspectRatioDifference) { Debug.LogWarningFormat(k_MismatchedAspectRatioWarningFormatString, sourceWidth, sourceHeight); loggedAspectRatioWarning = true; } } NativeApi.SendFrame(targetTexture.GetNativeTexturePtr()); GL.IssuePluginEvent(renderEventFunc, 1); } } private static void AddInstantPreviewTrackedPoseDriverWhenNeeded() { foreach (var poseDriver in Component.FindObjectsOfType<TrackedPoseDriver>()) { poseDriver.enabled = false; var gameObject = poseDriver.gameObject; var hasInstantPreviewTrackedPoseDriver = gameObject.GetComponent<InstantPreviewTrackedPoseDriver>() != null; if (!hasInstantPreviewTrackedPoseDriver) { gameObject.AddComponent<InstantPreviewTrackedPoseDriver>(); } } } private static string GetAdbPath() { string sdkRoot = null; #if UNITY_EDITOR // Gets adb path and starts instant preview server. sdkRoot = UnityEditor.EditorPrefs.GetString("AndroidSdkRoot"); #endif // UNITY_EDITOR if (string.IsNullOrEmpty(sdkRoot)) { return null; } // Gets adb path from known directory. var adbPath = Path.Combine(Path.GetFullPath(sdkRoot), "platform-tools" + Path.DirectorySeparatorChar + "adb"); if (Application.platform == RuntimePlatform.WindowsEditor) { adbPath = Path.ChangeExtension(adbPath, "exe"); } return adbPath; } /// <summary> /// Tries to install and run the Instant Preview android app. /// </summary> /// <param name="adbPath">Path to adb to use for installing.</param> /// <param name="localVersion">Local version of Instant Preview plugin to compare installed APK against.</param> /// <returns>Enumerator for coroutine that handles installation if necessary.</returns> private static IEnumerator InstallApkAndRunIfConnected(string adbPath, string localVersion) { string apkPath = null; #if UNITY_EDITOR apkPath = UnityEditor.AssetDatabase.GUIDToAssetPath(k_ApkGuid); #endif // !UNITY_EDITOR // Early outs if set to install but the apk can't be found. if (!File.Exists(apkPath)) { Debug.LogErrorFormat("Trying to install Instant Preview APK but reference to InstantPreview.apk is " + "broken. Couldn't find an asset with .meta file guid={0}.", k_ApkGuid); yield break; } Result result = new Result(); Thread checkAdbThread = new Thread((object obj) => { Result res = (Result)obj; string output; string errors; // Gets version of installed apk. ShellHelper.RunCommand(adbPath, "shell dumpsys package com.google.ar.core.instantpreview | grep versionName", out output, out errors); string installedVersion = null; if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors)) { installedVersion = output.Substring(output.IndexOf('=') + 1); } // Early outs if no device is connected. if (string.Compare(errors, k_NoDevicesFoundAdbResult) == 0) { return; } // Prints errors and exits on failure. if (!string.IsNullOrEmpty(errors)) { Debug.LogError(errors); return; } if (installedVersion == null) { Debug.LogFormat( "Instant Preview app not installed on device.", apkPath); } else if (installedVersion != localVersion) { Debug.LogFormat( "Instant Preview installed version \"{0}\" does not match local version \"{1}\".", installedVersion, localVersion); } res.ShouldPromptForInstall = installedVersion != localVersion; }); checkAdbThread.Start(result); while (!checkAdbThread.Join(0)) { yield return 0; } if (result.ShouldPromptForInstall) { if (PromptToInstall()) { Thread installThread = new Thread(() => { string output; string errors; Debug.LogFormat( "Installing Instant Preview app version {0}.", localVersion); ShellHelper.RunCommand(adbPath, "uninstall com.google.ar.core.instantpreview", out output, out errors); ShellHelper.RunCommand(adbPath, string.Format("install \"{0}\"", apkPath), out output, out errors); // Prints any output from trying to install. if (!string.IsNullOrEmpty(output)) { Debug.LogFormat("Instant Preview installation:\n{0}", output); } if (!string.IsNullOrEmpty(errors) && errors != "Success") { Debug.LogErrorFormat("Failed to install Instant Preview app:\n{0}", errors); } }); installThread.Start(); while (!installThread.Join(0)) { yield return 0; } } else { yield break; } } } private static bool PromptToInstall() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog("Instant Preview", "To instantly reflect your changes on device, the " + "Instant Preview app will be installed on your " + "connected device.\n\nTo disable Instant Preview, " + "uncheck 'Instant Preview Enabled' under " + "'Edit > Project Settings > ARCore'.", "Okay", "Don't Install This Time"); #else return false; #endif } private static bool PromptToRebuildAugmentedImagesDatabase() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog("Augmented Images", "The Augmented Images database is out of date, " + "rebuild it now?", "Build", "Don't Build This Time"); #else return false; #endif } private static bool StartServer(string adbPath, out string version) { // Tries to start server. const int k_InstantPreviewVersionStringMaxLength = 64; var versionStringBuilder = new StringBuilder(k_InstantPreviewVersionStringMaxLength); var started = NativeApi.InitializeInstantPreview(adbPath, versionStringBuilder, versionStringBuilder.Capacity); if (!started) { Debug.LogErrorFormat("Couldn't start Instant Preview server with adb path \"{0}\".", adbPath); version = null; return false; } version = versionStringBuilder.ToString(); Debug.LogFormat("Instant Preview version {0}\n" + "To disable Instant Preview, uncheck " + "'Instant Preview Enabled' under 'Edit > Project Settings > ARCore'.", version); return true; } private static int RoundUpToNearestMultipleOf16(int value) { return (value + 15) & ~15; } private struct NativeApi { #pragma warning disable 626 [AndroidImport(InstantPreviewNativeApi)] public static extern bool InitializeInstantPreview( string adbPath, StringBuilder version, int versionStringLength); [AndroidImport(InstantPreviewNativeApi)] public static extern void Update(); [AndroidImport(InstantPreviewNativeApi)] public static extern IntPtr GetRenderEventFunc(); [AndroidImport(InstantPreviewNativeApi)] public static extern void SendFrame(IntPtr renderTexture); [AndroidImport(InstantPreviewNativeApi)] public static extern bool LockCameraTexture(out IntPtr pixelBytes, out int width, out int height); [AndroidImport(InstantPreviewNativeApi)] public static extern void UnlockCameraTexture(); [AndroidImport(InstantPreviewNativeApi)] public static extern bool IsConnected(); #pragma warning restore 626 } private class Result { public bool ShouldPromptForInstall = false; } } }
namespace TwitchLib.Models.API.v5.Users { #region using directives using System; using Newtonsoft.Json; #endregion public class UserBlock { #region Id [JsonProperty(PropertyName = "_id")] public long Id { get; protected set; } #endregion #region UpdatedAt [JsonProperty(PropertyName = "updated_at")] public DateTime UpdatedAt { get; protected set; } #endregion #region User [JsonProperty(PropertyName = "user")] public User User { get; protected set; } #endregion } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Web.LibraryManager.Contracts; using Microsoft.Web.LibraryManager.Providers.Unpkg; using Moq; namespace Microsoft.Web.LibraryManager.Test.Providers.Unpkg { [TestClass] public class NpmPackageSearchTest { [TestMethod] public async Task NpmPackageSearch_GetPackageNamesAsync_NullSearchItem_DoesNotMakeWebRequest() { var mockRequestHandler = new Mock<IWebRequestHandler>(); var sut = new NpmPackageSearch(mockRequestHandler.Object); IEnumerable<NpmPackageInfo> packages = await sut.GetPackageNamesAsync(null, CancellationToken.None); mockRequestHandler.Verify(x => x.GetStreamAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never); } [TestMethod] public async Task NpmPackageSearch_GetPackageNamesAsync_ResponseContainsNoObjects_ReturnEmptyListOfPackages() { string noHitsResponse = @"{""objects"":[],""total"":0}"; var mockRequestHandler = new Mock<IWebRequestHandler>(); mockRequestHandler.Setup(m => m.GetStreamAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Stream>(new MemoryStream(Encoding.Default.GetBytes(noHitsResponse)))); var sut = new NpmPackageSearch(mockRequestHandler.Object); IEnumerable<NpmPackageInfo> packages = await sut.GetPackageNamesAsync("searchTerm", CancellationToken.None); Assert.IsFalse(packages.Any()); } [TestMethod] public async Task NpmPackageSearch_GetPackageNamesAsync_UnScopedPackage() { // this is a mockup of the response from the NPM registry search string response = @"{ ""objects"": [ { ""package"": { ""name"": ""firstResult"", ""scope"": ""unscoped"", ""version"": ""1.0.1"", ""description"": ""a package"", } }, { ""package"": { ""name"": ""secondResult"", ""scope"": ""unscoped"", ""version"": ""2.2.0"", ""description"": ""another package"" } } ], ""total"": 2 }"; var mockRequestHandler = new Mock<IWebRequestHandler>(); mockRequestHandler.Setup(m => m.GetStreamAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Stream>(new MemoryStream(Encoding.Default.GetBytes(response)))); var sut = new NpmPackageSearch(mockRequestHandler.Object); IEnumerable<NpmPackageInfo> result = await sut.GetPackageNamesAsync("searchTerm", CancellationToken.None); CollectionAssert.AreEquivalent(new[] { "firstResult", "secondResult" }, result.Select(p => p.Name).ToList()); } [TestMethod] public async Task NpmPackageSearch_GetPackageNamesAsync_ScopedPackage() { // this is a mockup of the response from the npms.io search string response = @"{ ""results"": [ { ""package"": { ""name"": ""firstResult"", ""scope"": ""unscoped"", ""version"": ""1.0.1"", ""description"": ""a package"", } }, { ""package"": { ""name"": ""secondResult"", ""scope"": ""unscoped"", ""version"": ""2.2.0"", ""description"": ""another package"" } } ], ""total"": 2 }"; var mockRequestHandler = new Mock<IWebRequestHandler>(); mockRequestHandler.Setup(m => m.GetStreamAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Stream>(new MemoryStream(Encoding.Default.GetBytes(response)))); var sut = new NpmPackageSearch(mockRequestHandler.Object); IEnumerable<NpmPackageInfo> result = await sut.GetPackageNamesAsync("@searchTerm/", CancellationToken.None); CollectionAssert.AreEquivalent(new[] { "firstResult", "secondResult" }, result.Select(p => p.Name).ToList()); } } }
using NIntercept.Definition; using NIntercept.Helpers; using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace NIntercept.Builder { public class InterceptableMethodBuilder { private readonly CallbackMethodBuilder callbackMethodBuilder; public InterceptableMethodBuilder() { this.callbackMethodBuilder = new CallbackMethodBuilder(); } public virtual MethodBuilder CreateMethod(ProxyScope proxyScope, MethodDefinition methodDefinition, MemberInfo member, FieldBuilder memberField, FieldBuilder callerMethodField) { MethodInfo method = methodDefinition.Method; // callback method MethodBuilder callbackMethodBuilder = CreateCallbackMethod(proxyScope, methodDefinition.CallbackMethodDefinition); // invocation type Type invocationType = GetOrCreateInvocationType(proxyScope, methodDefinition, callbackMethodBuilder); // method MethodBuilder methodBuilder = proxyScope.DefineMethod(methodDefinition.Name, methodDefinition.MethodAttributes); methodBuilder.SetReturnType(methodDefinition.ReturnType); // parameters methodBuilder.DefineGenericParameters(methodDefinition.GenericArguments); if (methodDefinition.ParameterDefinitions.Length > 0) DefineParameters(methodBuilder, methodDefinition); // attributes DefineAttributes(methodBuilder, methodDefinition); // method body var il = methodBuilder.GetILGenerator(); // locals IInterceptorSelector interceptorSelector = proxyScope.TypeDefinition.Options?.InterceptorSelector; FieldBuilder interceptorSelectorField = null; FieldBuilder interceptorMethodField = null; if (interceptorSelector != null) { interceptorSelectorField = FindConstructorField(proxyScope, ProxyScope.InterceptorSelectorFieldName); interceptorMethodField = proxyScope.DefineField(methodDefinition.InterceptorSelectorFieldName, typeof(IInterceptor[]), FieldAttributes.Private); } var returnType = methodDefinition.ReturnType; Type targetType = methodDefinition.TypeDefinition.TargetType; Type localBuilderType = targetType != null ? targetType : typeof(object); LocalBuilder targetLocalBuilder = il.DeclareLocal(localBuilderType); // target LocalBuilder interceptorsLocalBuilder = il.DeclareLocal(typeof(IInterceptor[])); // interceptors LocalBuilder memberLocalBuilder = il.DeclareLocal(typeof(MemberInfo)); // MemberInfo LocalBuilder callerMethodLocalBuilder = il.DeclareLocal(typeof(MethodInfo)); // proxy method LocalBuilder proxyLocalBuilder = il.DeclareLocal(typeof(object)); // proxy LocalBuilder parametersLocalBuilder = il.DeclareLocal(typeof(object[])); // parameters LocalBuilder invocationLocalBuilder = il.DeclareLocal(invocationType); // invocation LocalBuilder returnValueLocalBuilder = null; if (returnType != typeof(void)) returnValueLocalBuilder = il.DeclareLocal(returnType); FieldBuilder interceptorsField = proxyScope.ConstructorFields[0]; if (targetType != null) { FieldBuilder targetField = FindConstructorField(proxyScope, methodDefinition.TypeDefinition.TargetFieldName); EmitHelper.StoreFieldToLocal(il, targetField, targetLocalBuilder); } EmitHelper.StoreFieldToLocal(il, memberField, memberLocalBuilder); EmitHelper.StoreFieldToLocal(il, callerMethodField, callerMethodLocalBuilder); EmitHelper.StoreThisToLocal(il, proxyLocalBuilder); if (interceptorSelector != null) { LocalBuilder isNullLocal = il.DeclareLocal(typeof(bool)); Label isNullLabel = il.DefineLabel(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, interceptorMethodField); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Stloc, isNullLocal); il.Emit(OpCodes.Ldloc, isNullLocal); il.Emit(OpCodes.Brfalse_S, isNullLabel); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, interceptorSelectorField); il.Emit(OpCodes.Ldtoken, member.DeclaringType); il.Emit(OpCodes.Call, Methods.GetTypeFromHandle); il.Emit(OpCodes.Ldloc, callerMethodLocalBuilder); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, interceptorsField); il.Emit(OpCodes.Callvirt, Methods.SelectInterceptorsMethod); il.Emit(OpCodes.Stfld, interceptorMethodField); il.MarkLabel(isNullLabel); EmitHelper.StoreFieldToLocal(il, interceptorMethodField, interceptorsLocalBuilder); } else EmitHelper.StoreFieldToLocal(il, interceptorsField, interceptorsLocalBuilder); StoreArgsToArray(il, methodDefinition.ParameterDefinitions, parametersLocalBuilder); EmitHelper.CreateInvocation(il, invocationType, targetLocalBuilder, interceptorsLocalBuilder, memberLocalBuilder, callerMethodLocalBuilder, proxyLocalBuilder, parametersLocalBuilder, invocationLocalBuilder); EmitHelper.CallProceed(il, invocationLocalBuilder); // set ref parameters values after Proceed called SetByRefArgs(il, methodDefinition.ParameterDefinitions, invocationLocalBuilder); EmitReturnValue(il, method, invocationLocalBuilder, returnValueLocalBuilder); if (method.DeclaringType.IsInterface) proxyScope.DefineMethodOverride(methodBuilder, method); return methodBuilder; } protected FieldBuilder FindConstructorField(ProxyScope proxyScope, string fieldName) { return proxyScope.ConstructorFields.First(p => p.Name == fieldName); } protected Type GetOrCreateInvocationType(ProxyScope proxyScope, MethodDefinition methodDefinition, MethodBuilder callbackMethodBuilder) { Type invocationType = proxyScope.ModuleScope.GetOrCreateInvocationType(methodDefinition.InvocationTypeDefinition, callbackMethodBuilder); if (invocationType.IsGenericType) invocationType = invocationType.MakeGenericType(methodDefinition.Method.GetGenericArguments()); return invocationType; } protected MethodBuilder CreateCallbackMethod(ProxyScope proxyScope, CallbackMethodDefinition callbackMethodDefinition) { return callbackMethodBuilder.CreateMethod(proxyScope, callbackMethodDefinition); } protected void DefineParameters(MethodBuilder methodBuilder, MethodDefinition methodDefinition) { methodBuilder.SetParameters(methodDefinition.ParameterDefinitions.Select(p => p.ParameterType).ToArray()); int index = 1; foreach (var parameterDefinition in methodDefinition.ParameterDefinitions) methodBuilder.DefineParameter(index++, parameterDefinition.Attributes, parameterDefinition.Name); } protected virtual bool ShouldAddInterceptionAttributes(MethodDefinition methodDefinition) { return methodDefinition.TypeDefinition.IsInterface && methodDefinition.InterceptorAttributes.Length > 0; } protected virtual void DefineAttributes(MethodBuilder methodBuilder, MethodDefinition methodDefinition) { if (ShouldAddInterceptionAttributes(methodDefinition)) AttributeHelper.AddInterceptorAttributes(methodBuilder, methodDefinition.InterceptorAttributes); } protected void StoreArgsToArray(ILGenerator il, ParameterDefinition[] parameterDefinitions, LocalBuilder localBuilder) { int length = parameterDefinitions.Length; il.EmitLdc_I4(length); il.Emit(OpCodes.Newarr, typeof(object)); foreach (var parameterDefinition in parameterDefinitions) { il.Emit(OpCodes.Dup); il.EmitLdc_I4(parameterDefinition.Index); il.EmitLdarg(parameterDefinition.Index + 1); if (parameterDefinition.IsByRef) { Type elementType = parameterDefinition.ElementType; il.Emit(OpCodes.Ldobj, elementType); if (elementType.IsValueType || elementType.IsGenericParameter) il.Emit(OpCodes.Box, elementType); } else if (parameterDefinition.ParameterType.IsValueType || parameterDefinition.ParameterType.ContainsGenericParameters) il.Emit(OpCodes.Box, parameterDefinition.ParameterType); il.Emit(OpCodes.Stelem_Ref); } il.Emit(OpCodes.Stloc, localBuilder); } protected void SetByRefArgs(ILGenerator il, ParameterDefinition[] parameterDefinitions, LocalBuilder invocationLocalBuilder) { foreach (var parameterDefinition in parameterDefinitions) { if (parameterDefinition.IsByRef) { il.EmitLdarg(parameterDefinition.Index + 1); il.Emit(OpCodes.Ldloc, invocationLocalBuilder); il.Emit(OpCodes.Call, InvocationMethods.get_ParametersMethod); il.EmitLdc_I4(parameterDefinition.Index); il.Emit(OpCodes.Ldelem_Ref); il.EmitUnboxOrCast(parameterDefinition.ElementType); il.EmitStindOrStobj(parameterDefinition.ElementType); } } } protected void EmitReturnValue(ILGenerator il, MethodInfo method, LocalBuilder invocationLocalBuilder, LocalBuilder returnValueLocalBuilder) { if (method.ReturnType != typeof(void)) { Label end = il.DefineLabel(); // return (string)invocation.ReturnValue; il.Emit(OpCodes.Ldloc, invocationLocalBuilder); il.Emit(OpCodes.Callvirt, InvocationMethods.get_ReturnValueMethod); il.EmitUnboxOrCast(method.ReturnType); il.Emit(OpCodes.Stloc, returnValueLocalBuilder); il.Emit(OpCodes.Br_S, end); il.MarkLabel(end); il.Emit(OpCodes.Ldloc, returnValueLocalBuilder); } il.Emit(OpCodes.Ret); } } }
namespace BatchToDoCLI.Models.Microsoft { public class TodoTaskListsResult { public List<TodoTaskList> value { get; set; } } }
using System; using CPUx86 = Cosmos.Assembler.x86; using Cosmos.IL2CPU.X86; using XSharp.Compiler; namespace Cosmos.IL2CPU.X86.IL { [Cosmos.IL2CPU.OpCode( ILOpCode.Code.Xor )] public class Xor : ILOp { public Xor( Cosmos.Assembler.Assembler aAsmblr ) : base( aAsmblr ) { } public override void Execute( MethodInfo aMethod, ILOpCode aOpCode ) { var xSize = Math.Max(SizeOfType(aOpCode.StackPopTypes[0]), SizeOfType(aOpCode.StackPopTypes[1])); XS.Pop(XSRegisters.EAX); XS.Pop(XSRegisters.EDX); XS.Xor(XSRegisters.EAX, XSRegisters.EDX); XS.Push(XSRegisters.EAX); } } }
namespace Towel.Mathematics { public static class Constant<T> { /// <summary>Zero [0]</summary> public static readonly T Zero = Compute.FromInt32<T>(0); /// <summary>One [1]</summary> public static readonly T One = Compute.FromInt32<T>(1); /// <summary>Two [2]</summary> public static readonly T Two = Compute.FromInt32<T>(2); /// <summary>Three [3]</summary> public static readonly T Three = Compute.FromInt32<T>(3); /// <summary>Four [4]</summary> public static readonly T Four = Compute.FromInt32<T>(4); /// <summary>Ten [10]</summary> public static readonly T Ten = Compute.FromInt32<T>(10); /// <summary>Negative One [-1]</summary> public static readonly T NegativeOne = Compute.FromInt32<T>(-1); /// <summary>π [3.14...]</summary> public static readonly T Pi = Compute.Pi<T>(); /// <summary>π [3.14...]</summary> public static readonly T π = Pi; /// <summary>2π [6.28...]</summary> public static readonly T Pi2 = Compute.Multiply(Two, Pi); /// <summary>2π [6.28...]</summary> public static readonly T π2 = Pi2; /// <summary>π / 2</summary> public static readonly T PiOver2 = Compute.Divide(Pi, Two); /// <summary>π / 2</summary> public static readonly T πOver2 = PiOver2; /// <summary>3π/2</summary> public static readonly T Pi3Over2 = Compute.Divide(Compute.Multiply(Three, Pi), Two); /// <summary>3π/2</summary> public static readonly T π3Over2 = Pi3Over2; /// <summary>4/(π^2)</summary> public static readonly T FourOverPiSquared = Compute.Divide(Compute.Multiply(Three, Pi), Two); /// <summary>4/(π^2)</summary> public static readonly T FourOverπSquared = FourOverPiSquared; /// <summary>-4/(π^2)</summary> public static readonly T Negative4OverPiSquared = Compute.Negate(FourOverPiSquared); /// <summary>-4/(π^2)</summary> public static readonly T Negative4OverπSquared = Negative4OverPiSquared; /// <summary>GoldenRatio [(1 + SquareRoot(5)) / 2]</summary> //public static readonly T GoldenRatio = Symbolics.ParseAndSimplifyToConstant<T>("(1 + SquareRoot(5)) / 2"); /// <summary>Epsilon (1.192092896...e-012f)</summary> //public static readonly T Epsilon = Compute.ComputeEpsilon<T>(); } #region Old Reference Code #region Mathematical Constants ///// <summary>The number e</summary> //public const double E = 2.7182818284590452353602874713526624977572470937000d; ///// <summary>The number ln(10)/20 - factor to convert from Power Decibel (dB) to Neper (Np). Use this version when the Decibel represent a power gain but the compared values are not powers (e.g. amplitude, current, voltage).</summary> //public const double PowerDecibel = 0.11512925464970228420089957273421821038005507443144d; ///// <summary>The number ln(10)/10 - factor to convert from Neutral Decibel (dB) to Neper (Np). Use this version when either both or neither of the Decibel and the compared values represent powers.</summary> //public const double NeutralDecibel = 0.23025850929940456840179914546843642076011014886288d; ///// <summary>The Catalan constant</summary> ///// <remarks>Sum(k=0 -> inf){ (-1)^k/(2*k + 1)2 }</remarks> //public const double Catalan = 0.9159655941772190150546035149323841107741493742816721342664981196217630197762547694794d; ///// <summary>The Euler-Mascheroni constant</summary> ///// <remarks>lim(n -> inf){ Sum(k=1 -> n) { 1/k - log(n) } }</remarks> //public const double EulerMascheroni = 0.5772156649015328606065120900824024310421593359399235988057672348849d; ///// <summary>The Glaisher constant</summary> ///// <remarks>e^(1/12 - Zeta(-1))</remarks> //public const double Glaisher = 1.2824271291006226368753425688697917277676889273250011920637400217404063088588264611297d; ///// <summary>The Khinchin constant</summary> ///// <remarks>prod(k=1 -> inf){1+1/(k*(k+2))^log(k,2)}</remarks> //public const double Khinchin = 2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011d; #endregion #region UNIVERSAL CONSTANTS ///// <summary>Speed of Light in Vacuum: c_0 = 2.99792458e8 [m s^-1] (defined, exact; 2007 CODATA)</summary> //public const double SpeedOfLight = 2.99792458e8; ///// <summary>Magnetic Permeability in Vacuum: mu_0 = 4*Pi * 10^-7 [N A^-2 = kg m A^-2 s^-2] (defined, exact; 2007 CODATA)</summary> //public const double MagneticPermeability = 1.2566370614359172953850573533118011536788677597500e-6; ///// <summary>Electric Permittivity in Vacuum: epsilon_0 = 1/(mu_0*c_0^2) [F m^-1 = A^2 s^4 kg^-1 m^-3] (defined, exact; 2007 CODATA)</summary> //public const double ElectricPermittivity = 8.8541878171937079244693661186959426889222899381429e-12; ///// <summary>Characteristic Impedance of Vacuum: Z_0 = mu_0*c_0 [Ohm = m^2 kg s^-3 A^-2] (defined, exact; 2007 CODATA)</summary> //public const double CharacteristicImpedanceVacuum = 376.73031346177065546819840042031930826862350835242; ///// <summary>Newtonian Constant of Gravitation: G = 6.67429e-11 [m^3 kg^-1 s^-2] (2007 CODATA)</summary> //public const double GravitationalConstant = 6.67429e-11; ///// <summary>Planck's constant: h = 6.62606896e-34 [J s = m^2 kg s^-1] (2007 CODATA)</summary> //public const double PlancksConstant = 6.62606896e-34; ///// <summary>Reduced Planck's constant: h_bar = h / (2*Pi) [J s = m^2 kg s^-1] (2007 CODATA)</summary> //public const double DiracsConstant = 1.054571629e-34; ///// <summary>Planck mass: m_p = (h_bar*c_0/G)^(1/2) [kg] (2007 CODATA)</summary> //public const double PlancksMass = 2.17644e-8; ///// <summary>Planck temperature: T_p = (h_bar*c_0^5/G)^(1/2)/k [K] (2007 CODATA)</summary> //public const double PlancksTemperature = 1.416786e32; ///// <summary>Planck length: l_p = h_bar/(m_p*c_0) [m] (2007 CODATA)</summary> //public const double PlancksLength = 1.616253e-35; ///// <summary>Planck time: t_p = l_p/c_0 [s] (2007 CODATA)</summary> //public const double PlancksTime = 5.39124e-44; #endregion #region ELECTROMAGNETIC CONSTANTS ///// <summary>Elementary Electron Charge: e = 1.602176487e-19 [C = A s] (2007 CODATA)</summary> //public const double ElementaryCharge = 1.602176487e-19; ///// <summary>Magnetic Flux Quantum: Towel_0 = h/(2*e) [Wb = m^2 kg s^-2 A^-1] (2007 CODATA)</summary> //public const double MagneticFluxQuantum = 2.067833668e-15; ///// <summary>Conductance Quantum: G_0 = 2*e^2/h [S = m^-2 kg^-1 s^3 A^2] (2007 CODATA)</summary> //public const double ConductanceQuantum = 7.7480917005e-5; ///// <summary>Josephson Constant: K_J = 2*e/h [Hz V^-1] (2007 CODATA)</summary> //public const double JosephsonConstant = 483597.891e9; ///// <summary>Von Klitzing Constant: R_K = h/e^2 [Ohm = m^2 kg s^-3 A^-2] (2007 CODATA)</summary> //public const double VonKlitzingConstant = 25812.807557; ///// <summary>Bohr Magneton: mu_B = e*h_bar/2*m_e [J T^-1] (2007 CODATA)</summary> //public const double BohrMagneton = 927.400915e-26; ///// <summary>Nuclear Magneton: mu_N = e*h_bar/2*m_p [J T^-1] (2007 CODATA)</summary> //public const double NuclearMagneton = 5.05078324e-27; #endregion #region ATOMIC AND NUCLEAR CONSTANTS ///// <summary>Fine Structure Constant: alpha = e^2/4*Pi*e_0*h_bar*c_0 [1] (2007 CODATA)</summary> //public const double FineStructureConstant = 7.2973525376e-3; ///// <summary>Rydberg Constant: R_infty = alpha^2*m_e*c_0/2*h [m^-1] (2007 CODATA)</summary> //public const double RydbergConstant = 10973731.568528; ///// <summary>Bor Radius: a_0 = alpha/4*Pi*R_infty [m] (2007 CODATA)</summary> //public const double BohrRadius = 0.52917720859e-10; ///// <summary>Hartree Energy: E_h = 2*R_infty*h*c_0 [J] (2007 CODATA)</summary> //public const double HartreeEnergy = 4.35974394e-18; ///// <summary>Quantum of Circulation: h/2*m_e [m^2 s^-1] (2007 CODATA)</summary> //public const double QuantumOfCirculation = 3.6369475199e-4; ///// <summary>Fermi Coupling Constant: G_F/(h_bar*c_0)^3 [GeV^-2] (2007 CODATA)</summary> //public const double FermiCouplingConstant = 1.16637e-5; ///// <summary>Weak Mixin Angle: sin^2(Towel_W) [1] (2007 CODATA)</summary> //public const double WeakMixingAngle = 0.22256; ///// <summary>Electron Mass: [kg] (2007 CODATA)</summary> //public const double ElectronMass = 9.10938215e-31; ///// <summary>Electron Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double ElectronMassEnergyEquivalent = 8.18710438e-14; ///// <summary>Electron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double ElectronMolarMass = 5.4857990943e-7; ///// <summary>Electron Compton Wavelength: [m] (2007 CODATA)</summary> //public const double ComptonWavelength = 2.4263102175e-12; ///// <summary>Classical Electron Radius: [m] (2007 CODATA)</summary> //public const double ClassicalElectronRadius = 2.8179402894e-15; ///// <summary>Tomson Cross Section: [m^2] (2002 CODATA)</summary> //public const double ThomsonCrossSection = 0.6652458558e-28; ///// <summary>Electron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double ElectronMagneticMoment = -928.476377e-26; ///// <summary>Electon G-Factor: [1] (2007 CODATA)</summary> //public const double ElectronGFactor = -2.0023193043622; ///// <summary>Muon Mass: [kg] (2007 CODATA)</summary> //public const double MuonMass = 1.88353130e-28; ///// <summary>Muon Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double MuonMassEnegryEquivalent = 1.692833511e-11; ///// <summary>Muon Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double MuonMolarMass = 0.1134289256e-3; ///// <summary>Muon Compton Wavelength: [m] (2007 CODATA)</summary> //public const double MuonComptonWavelength = 11.73444104e-15; ///// <summary>Muon Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double MuonMagneticMoment = -4.49044786e-26; ///// <summary>Muon G-Factor: [1] (2007 CODATA)</summary> //public const double MuonGFactor = -2.0023318414; ///// <summary>Tau Mass: [kg] (2007 CODATA)</summary> //public const double TauMass = 3.16777e-27; ///// <summary>Tau Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double TauMassEnergyEquivalent = 2.84705e-10; ///// <summary>Tau Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double TauMolarMass = 1.90768e-3; ///// <summary>Tau Compton Wavelength: [m] (2007 CODATA)</summary> //public const double TauComptonWavelength = 0.69772e-15; ///// <summary>Proton Mass: [kg] (2007 CODATA)</summary> //public const double ProtonMass = 1.672621637e-27; ///// <summary>Proton Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double ProtonMassEnergyEquivalent = 1.503277359e-10; ///// <summary>Proton Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double ProtonMolarMass = 1.00727646677e-3; ///// <summary>Proton Compton Wavelength: [m] (2007 CODATA)</summary> //public const double ProtonComptonWavelength = 1.3214098446e-15; ///// <summary>Proton Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double ProtonMagneticMoment = 1.410606662e-26; ///// <summary>Proton G-Factor: [1] (2007 CODATA)</summary> //public const double ProtonGFactor = 5.585694713; ///// <summary>Proton Shielded Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double ShieldedProtonMagneticMoment = 1.410570419e-26; ///// <summary>Proton Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> //public const double ProtonGyromagneticRatio = 2.675222099e8; ///// <summary>Proton Shielded Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> //public const double ShieldedProtonGyromagneticRatio = 2.675153362e8; ///// <summary>Neutron Mass: [kg] (2007 CODATA)</summary> //public const double NeutronMass = 1.674927212e-27; ///// <summary>Neutron Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double NeutronMassEnegryEquivalent = 1.505349506e-10; ///// <summary>Neutron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double NeutronMolarMass = 1.00866491597e-3; ///// <summary>Neuron Compton Wavelength: [m] (2007 CODATA)</summary> //public const double NeutronComptonWavelength = 1.3195908951e-1; ///// <summary>Neutron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double NeutronMagneticMoment = -0.96623641e-26; ///// <summary>Neutron G-Factor: [1] (2007 CODATA)</summary> //public const double NeutronGFactor = -3.82608545; ///// <summary>Neutron Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> //public const double NeutronGyromagneticRatio = 1.83247185e8; ///// <summary>Deuteron Mass: [kg] (2007 CODATA)</summary> //public const double DeuteronMass = 3.34358320e-27; ///// <summary>Deuteron Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double DeuteronMassEnegryEquivalent = 3.00506272e-10; ///// <summary>Deuteron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double DeuteronMolarMass = 2.013553212725e-3; ///// <summary>Deuteron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> //public const double DeuteronMagneticMoment = 0.433073465e-26; ///// <summary>Helion Mass: [kg] (2007 CODATA)</summary> //public const double HelionMass = 5.00641192e-27; ///// <summary>Helion Mass Energy Equivalent: [J] (2007 CODATA)</summary> //public const double HelionMassEnegryEquivalent = 4.49953864e-10; ///// <summary>Helion Molar Mass: [kg mol^-1] (2007 CODATA)</summary> //public const double HelionMolarMass = 3.0149322473e-3; ///// <summary>Avogadro constant: [mol^-1] (2010 CODATA)</summary> //public const double Avogadro = 6.0221412927e23; #endregion #endregion }
using System.Collections.Generic; using System.Threading.Tasks; using In.ProjectEKA.HipService.OpenMrs; using Moq; using Xunit; using OpenMrsPatient = Hl7.Fhir.Model.Patient; using OpenMrsPatientName = Hl7.Fhir.Model.HumanName; using OpenMrsGender = Hl7.Fhir.Model.AdministrativeGender; using FluentAssertions; using In.ProjectEKA.HipLibrary.Patient.Model; using In.ProjectEKA.HipLibrary.Patient; using System.Linq; namespace In.ProjectEKA.HipServiceTest.Link { [Collection("Patient Repository Tests")] public class PatientRepositoryTest { private Mock<IPatientDal> patientDal = new Mock<IPatientDal>(); private Mock<ICareContextRepository> careContextRepository = new Mock<ICareContextRepository>(); private Mock<IPhoneNumberRepository> phoneNumberRepository = new Mock<IPhoneNumberRepository>(); public PatientRepositoryTest() { var careContextRepresentations = new[] { new CareContextRepresentation("testReferrenceNumber1", "display1"), new CareContextRepresentation("testReferenceNumber2", "display2") }; var phoneNumber = "+91-9999999999"; patientDal.Setup(e => e.LoadPatientAsyncWithIndentifier(It.IsAny<string>())) .Returns(Task.FromResult( new OpenMrsPatient() { Name = new List<OpenMrsPatientName>{ new OpenMrsPatientName {GivenElement = new List<Hl7.Fhir.Model.FhirString>{ new Hl7.Fhir.Model.FhirString("test") }} }, Gender = OpenMrsGender.Female, BirthDate = "1981", Id = "someid" } )); careContextRepository.Setup(e => e.GetCareContexts(It.IsAny<string>())).Returns(Task.FromResult( new List<CareContextRepresentation>(careContextRepresentations).AsEnumerable() )); phoneNumberRepository.Setup(e => e.GetPhoneNumber(It.IsAny<string>())).ReturnsAsync(phoneNumber); } [Fact] private async void PatientRepositoryPatientWith_ReturnHIPPatient() { var patientIdentifier = "someidentifier"; var repo = new OpenMrsPatientRepository(patientDal.Object, careContextRepository.Object, phoneNumberRepository.Object); var patient = await repo.PatientWithAsync(patientIdentifier); var patientValue = patient.ValueOr(new Patient()); patientDal.Verify( x => x.LoadPatientAsyncWithIndentifier(patientIdentifier), Times.Once); careContextRepository.Verify(x => x.GetCareContexts(patientValue.Uuid), Times.Once); patientValue.Name.Should().Be("test"); patientValue.Gender.Should().Be(Gender.F); patientValue.YearOfBirth.Should().Be(1981); patientValue.CareContexts.First().ReferenceNumber.Should().Be("testReferrenceNumber1"); patientValue.CareContexts.Count().Should().Be(2); patientValue.PhoneNumber.Should().Be("+91-9999999999"); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebCoreEF { 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.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
@model EditRoleViewModel @{ ViewBag.Title = "编辑角色"; } <h1>编辑角色</h1> <form method="post" asp-action="EditRole"> <div class="form-group row"> <label asp-for="Id" class="col-sm-2 col-form-label "></label> <div class="col-sm-10"> <input asp-for="Id" class=" form-control" disabled /> </div> </div> <div class="form-group row"> <label asp-for="RoleName" class="col-sm-2 col-form-label "></label> <div class="col-sm-10"> <input asp-for="RoleName" class=" form-control" placeholder="请输入角色名称" /> <span asp-validation-for="RoleName" class="text-danger"></span> </div> </div> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group row" > <div class="col-sm-10"> <button type="submit" class="btn btn-primary">更新</button> <a class="btn btn-primary" asp-action="ListRoles">取消</a> </div> </div> <div class=" card"> <div class="card-header"> <h3>该角色中的用户</h3> </div> <div class="card-body"> @if (Model.Users.Any()) { foreach (var user in Model.Users) { <h5 class="card-title">@user</h5> } } else { <h5 class="card-title">目前没有信息</h5> } </div> <div class="card-footer"> <a asp-controller="Admin" asp-action="EditUsersInRole" asp-route-roleId="@Model.Id" class="btn btn-outline-primary" >从角色中添加或删除用户</a> </div> </div> </form>
#pragma checksum "D:\KodServer\VisualStudioProjeleri\AwesomeMusic\AwesomeMusic\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "37534F7186A5488381A956C7F05213CA" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; 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.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace AwesomeMusic { public partial class App : System.Windows.Application { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Awesome%20Music;component/App.xaml", System.UriKind.Relative)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Transactions { using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Transactions; /// <summary> /// Ignite transaction facade. /// </summary> internal sealed class Transaction : ITransaction { /** */ private readonly TransactionImpl _tx; /// <summary> /// Initializes a new instance of the <see cref="Transaction" /> class. /// </summary> /// <param name="tx">The tx to wrap.</param> public Transaction(TransactionImpl tx) { _tx = tx; } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] public void Dispose() { _tx.Dispose(); } /** <inheritDoc /> */ public Guid NodeId { get { return _tx.NodeId; } } /** <inheritDoc /> */ public long ThreadId { get { return _tx.ThreadId; } } /** <inheritDoc /> */ public DateTime StartTime { get { return _tx.StartTime; } } /** <inheritDoc /> */ public TransactionIsolation Isolation { get { return _tx.Isolation; } } /** <inheritDoc /> */ public TransactionConcurrency Concurrency { get { return _tx.Concurrency; } } /** <inheritDoc /> */ public TransactionState State { get { return _tx.State; } } /** <inheritDoc /> */ public TimeSpan Timeout { get { return _tx.Timeout; } } /** <inheritDoc /> */ public bool IsRollbackOnly { get { return _tx.IsRollbackOnly; } } /** <inheritDoc /> */ public bool SetRollbackonly() { return _tx.SetRollbackOnly(); } /** <inheritDoc /> */ public void Commit() { _tx.Commit(); } /** <inheritDoc /> */ public Task CommitAsync() { return _tx.GetTask(() => _tx.CommitAsync()); } /** <inheritDoc /> */ public void Rollback() { _tx.Rollback(); } /** <inheritDoc /> */ public Task RollbackAsync() { return _tx.GetTask(() => _tx.RollbackAsync()); } /** <inheritDoc /> */ public void AddMeta<TV>(string name, TV val) { _tx.AddMeta(name, val); } /** <inheritDoc /> */ public TV Meta<TV>(string name) { return _tx.Meta<TV>(name); } /** <inheritDoc /> */ public TV RemoveMeta<TV>(string name) { return _tx.RemoveMeta<TV>(name); } /// <summary> /// Executes prepare step of the two phase commit. /// </summary> public void Prepare() { _tx.Prepare(); } } }
// <auto-generated /> namespace FinalProject.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class NewStuff : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(NewStuff)); string IMigrationMetadata.Id { get { return "201804250644273_NewStuff"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// MybankCreditSupplychainTradeNettingRefundResponse. /// </summary> public class MybankCreditSupplychainTradeNettingRefundResponse : AlipayResponse { /// <summary> /// 业务事件受理的流水号,建议调用方保持此流水号,以方便后续业务处理 /// </summary> [JsonPropertyName("ev_seq_no")] public string EvSeqNo { get; set; } } }
/* * Copyright (c) 2008, DIaLOGIKa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of DIaLOGIKa nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY DIaLOGIKa ``AS IS AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL DIaLOGIKa BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace OdfConverter { /// <summary> /// COM Import and type declarations for Office Interop /// </summary> namespace Office { #region MSO Type Declarations public enum MsoControlType { msoControlCustom = 0, msoControlButton = 1, msoControlEdit = 2, msoControlDropdown = 3, msoControlComboBox = 4, msoControlButtonDropdown = 5, msoControlSplitDropdown = 6, msoControlOCXDropdown = 7, msoControlGenericDropdown = 8, msoControlGraphicDropdown = 9, msoControlPopup = 10, msoControlGraphicPopup = 11, msoControlButtonPopup = 12, msoControlSplitButtonPopup = 13, msoControlSplitButtonMRUPopup = 14, msoControlLabel = 15, msoControlExpandingGrid = 16, msoControlSplitExpandingGrid = 17, msoControlGrid = 18, msoControlGauge = 19, msoControlGraphicCombo = 20, msoControlPane = 21, msoControlActiveX = 22, msoControlSpinner = 23, msoControlLabelEx = 24, msoControlWorkPane = 25, msoControlAutoCompleteCombo = 26, } public enum MsoAppLanguageID { msoLanguageIDInstall = 1, msoLanguageIDUI = 2, msoLanguageIDHelp = 3, msoLanguageIDExeMode = 4, msoLanguageIDUIPrevious = 5, } public enum MsoFileDialogType { msoFileDialogOpen = 1, msoFileDialogSaveAs = 2, msoFileDialogFilePicker = 3, msoFileDialogFolderPicker = 4, } public enum WdCursorType { wdCursorWait = 0, wdCursorIBeam = 1, wdCursorNormal = 2, wdCursorNorthwestArrow = 3, } public enum WdSaveOptions { wdPromptToSaveChanges = -2, wdSaveChanges = -1, wdDoNotSaveChanges = 0, } public enum WdOriginalFormat { wdWordDocument = 0, wdOriginalDocumentFormat = 1, wdPromptUser = 2, } public enum XlSaveAsAccessMode { xlNoChange = 1, xlShared = 2, xlExclusive = 3, } public enum XlFileFormat { xlCurrentPlatformText = -4158, xlWorkbookNormal = -4143, xlSYLK = 2, xlWKS = 4, xlWK1 = 5, xlCSV = 6, xlDBF2 = 7, xlDBF3 = 8, xlDIF = 9, xlDBF4 = 11, xlWJ2WD1 = 14, xlWK3 = 15, xlExcel2 = 16, xlTemplate = 17, xlTemplate8 = 17, xlAddIn8 = 18, xlAddIn = 18, xlTextMac = 19, xlTextWindows = 20, xlTextMSDOS = 21, xlCSVMac = 22, xlCSVWindows = 23, xlCSVMSDOS = 24, xlIntlMacro = 25, xlIntlAddIn = 26, xlExcel2FarEast = 27, xlWorks2FarEast = 28, xlExcel3 = 29, xlWK1FMT = 30, xlWK1ALL = 31, xlWK3FM3 = 32, xlExcel4 = 33, xlWQ1 = 34, xlExcel4Workbook = 35, xlTextPrinter = 36, xlWK4 = 38, xlExcel7 = 39, xlExcel5 = 39, xlWJ3 = 40, xlWJ3FJ3 = 41, xlUnicodeText = 42, xlExcel9795 = 43, xlHtml = 44, xlWebArchive = 45, xlXMLSpreadsheet = 46, xlExcel12 = 50, xlOpenXMLWorkbook = 51, xlWorkbookDefault = 51, xlOpenXMLWorkbookMacroEnabled = 52, xlOpenXMLTemplateMacroEnabled = 53, xlOpenXMLTemplate = 54, xlOpenXMLAddIn = 55, xlExcel8 = 56, } public enum PpSaveAsFileType { ppSaveAsPresentation = 1, [TypeLibVar(64)] ppSaveAsPowerPoint7 = 2, [TypeLibVar(64)] ppSaveAsPowerPoint4 = 3, [TypeLibVar(64)] ppSaveAsPowerPoint3 = 4, ppSaveAsTemplate = 5, ppSaveAsRTF = 6, ppSaveAsShow = 7, ppSaveAsAddIn = 8, [TypeLibVar(64)] ppSaveAsPowerPoint4FarEast = 10, ppSaveAsDefault = 11, ppSaveAsHTML = 12, ppSaveAsHTMLv3 = 13, ppSaveAsHTMLDual = 14, ppSaveAsMetaFile = 15, ppSaveAsGIF = 16, ppSaveAsJPG = 17, ppSaveAsPNG = 18, ppSaveAsBMP = 19, ppSaveAsWebArchive = 20, ppSaveAsTIF = 21, [TypeLibVar(64)] ppSaveAsPresForReview = 22, ppSaveAsEMF = 23, ppSaveAsOpenXMLPresentation = 24, ppSaveAsOpenXMLPresentationMacroEnabled = 25, ppSaveAsOpenXMLTemplate = 26, ppSaveAsOpenXMLTemplateMacroEnabled = 27, ppSaveAsOpenXMLShow = 28, ppSaveAsOpenXMLShowMacroEnabled = 29, ppSaveAsOpenXMLAddin = 30, ppSaveAsOpenXMLTheme = 31, ppSaveAsPDF = 32, ppSaveAsXPS = 33, ppSaveAsXMLPresentation = 34, } public enum WdSaveFormat { wdFormatDocument = 0, wdFormatDocument97 = 0, wdFormatDocumentDefault = 0x10, wdFormatDOSText = 4, wdFormatDOSTextLineBreaks = 5, wdFormatEncodedText = 7, wdFormatFilteredHTML = 10, wdFormatFlatXML = 0x13, wdFormatFlatXMLMacroEnabled = 20, wdFormatFlatXMLTemplate = 0x15, wdFormatFlatXMLTemplateMacroEnabled = 0x16, wdFormatHTML = 8, wdFormatPDF = 0x11, wdFormatRTF = 6, wdFormatTemplate = 1, wdFormatTemplate97 = 1, wdFormatText = 2, wdFormatTextLineBreaks = 3, wdFormatUnicodeText = 7, wdFormatWebArchive = 9, wdFormatXML = 11, wdFormatXMLDocument = 12, wdFormatXMLDocumentMacroEnabled = 13, wdFormatXMLTemplate = 14, wdFormatXMLTemplateMacroEnabled = 15, wdFormatXPS = 0x12 } public enum MsoTriState { msoTriStateToggle = -3, msoTriStateMixed = -2, msoTrue = -1, msoFalse = 0, msoCTrue = 1, } #endregion [ComVisible(true), ClassInterface(ClassInterfaceType.None)] public sealed class CommandBarButtonEvents : ICommandBarButtonEvents { private List<CommandBarButtonEvents_ClickEventHandler> _sinks; public CommandBarButtonEvents() { _sinks = new List<CommandBarButtonEvents_ClickEventHandler>(); } public void Click(object ctrl, ref bool cancelDefault) { foreach (CommandBarButtonEvents_ClickEventHandler sink in _sinks) { sink.Invoke(ctrl, cancelDefault); } } public void Register(CommandBarButtonEvents_ClickEventHandler sink) { _sinks.Add(sink); } } [ComImport, Guid("000C0351-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ICommandBarButtonEvents { [DispId(1)] void Click([In, MarshalAs(UnmanagedType.Interface)] object ctrl, [In, Out] ref bool cancelDefault); } #region Ribbon [ComImport, Guid("000C0396-0000-0000-C000-000000000046"), TypeLibType((short)0x1040)] public interface IRibbonExtensibility { [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] string GetCustomUI([In, MarshalAs(UnmanagedType.BStr)] string RibbonID); } [ComImport, Guid("000C0395-0000-0000-C000-000000000046"), TypeLibType((short)0x1040)] public interface IRibbonControl { [DispId(1)] string Id { [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] get; } } #endregion public delegate void CommandBarButtonEvents_ClickEventHandler(object Ctrl, object CancelDefault); } namespace Extensibility { [ComImport, Guid("B65AD801-ABAF-11D0-BB8B-00A0C90F2744"), TypeLibType((short)0x1040)] public interface IDTExtensibility2 { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)] void OnConnection([In, MarshalAs(UnmanagedType.IDispatch)] object Application, [In] ext_ConnectMode ConnectMode, [In, MarshalAs(UnmanagedType.IDispatch)] object AddInInst, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array custom); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)] void OnDisconnection([In] ext_DisconnectMode RemoveMode, [In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array custom); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)] void OnAddInsUpdate([In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array custom); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)] void OnStartupComplete([In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array custom); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)] void OnBeginShutdown([In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array custom); } [Guid("289E9AF1-4973-11D1-AE81-00A0C90F26F4")] public enum ext_ConnectMode { ext_cm_AfterStartup = 0, ext_cm_Startup = 1, ext_cm_External = 2, ext_cm_CommandLine = 3, ext_cm_Solution = 4, ext_cm_UISetup = 5, } [Guid("289E9AF2-4973-11D1-AE81-00A0C90F26F4")] public enum ext_DisconnectMode { ext_dm_HostShutdown = 0, ext_dm_UserClosed = 1, ext_dm_UISetupComplete = 2, ext_dm_SolutionClosed = 3, } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.Net.Http; using System.Threading; using Microsoft.Azure.Portal.Configuration; using OpsLogix.WAP.RunPowerShell.ApiClient; using OpsLogix.WAP.Base; namespace OpsLogix.WAP.RunPowerShell.AdminExtension { public static class ClientFactory { //Get Service Management API endpoint private static Uri adminApiUri; private static BearerMessageProcessingHandler messageHandler; //This client is used to communicate with the Run PowerShell resource provider private static Lazy<RunPowerShellClient> runPowerShellRestClient = new Lazy<RunPowerShellClient>( () => new RunPowerShellClient(adminApiUri, messageHandler), LazyThreadSafetyMode.ExecutionAndPublication); //This client is used to communicate with the Admin API private static Lazy<AdminManagementClient> adminApiRestClient = new Lazy<AdminManagementClient>( () => new AdminManagementClient(adminApiUri, messageHandler), LazyThreadSafetyMode.ExecutionAndPublication); static ClientFactory() { adminApiUri = new Uri(OnPremPortalConfiguration.Instance.RdfeAdminUri); messageHandler = new BearerMessageProcessingHandler(new WebRequestHandler()); } public static RunPowerShellClient RunPowerShellClient { get { return runPowerShellRestClient.Value; } } public static AdminManagementClient AdminManagementClient { get { return adminApiRestClient.Value; } } } }
/* Problem 3. Check for a Play Card Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. */ using System; class CheckForCard { static void Main() { Console.Write("Check for a play card: "); string card = Console.ReadLine(); switch (card) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10": case "J": case "Q": case "K": case "A": Console.WriteLine("-->Yes"); break; default: Console.WriteLine("-->No"); break; } } }
using System.Collections.Generic; using ViennaNET.Orm.Repositories; namespace ViennaNET.TestUtils.Orm.Tests { public class SetEmptyLimitCardCommand : BaseCommand { public SetEmptyLimitCardCommand(CardEntity card) { Sql = "UPDATE cards SET limit = 0 WHERE card_id = :card_id"; Parameters = new Dictionary<string, TypeWrapper> { { "card_id", TypeWrapper.Create(card, c => c.Id) } }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace Gigableh { public static class CustomEditorExtensions { public static System.Type[] GetAllDerivedTypes(this System.AppDomain aAppDomain, System.Type aType) { var result = new List<System.Type>(); var assemblies = aAppDomain.GetAssemblies(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { if (type.IsSubclassOf(aType)) result.Add(type); } } return result.ToArray(); } public static Rect GetEditorMainWindowPos() { var containerWinType = System.AppDomain.CurrentDomain.GetAllDerivedTypes(typeof(ScriptableObject)).Where(t => t.Name == "ContainerWindow").FirstOrDefault(); if (containerWinType == null) throw new System.MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity"); var showModeField = containerWinType.GetField("m_ShowMode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var positionProperty = containerWinType.GetProperty("position", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if (showModeField == null || positionProperty == null) throw new System.MissingFieldException("Can't find internal fields 'm_ShowMode' or 'position'. Maybe something has changed inside Unity"); var windows = Resources.FindObjectsOfTypeAll(containerWinType); foreach (var win in windows) { var showmode = (int)showModeField.GetValue(win); if (showmode == 4) // main window { var pos = (Rect)positionProperty.GetValue(win, null); return pos; } } throw new System.NotSupportedException("Can't find internal main window. Maybe something has changed inside Unity"); } public static void CenterOnMainWin(this UnityEditor.EditorWindow aWin) { var main = GetEditorMainWindowPos(); var pos = aWin.position; float w = (main.width - pos.width)*0.5f; float h = (main.height - pos.height)*0.5f; pos.x = main.x + w; pos.y = main.y + h; aWin.position = pos; } } }
using System; using System.Collections.Generic; namespace PackageExplorer { public class ErrorFloodGate { private const double StopLoadingThreshold = 0.50; private const int SlidingExpirationInMinutes = 60; private const int MinFailuresCount = 5; private const int SecondsInOneTick = 5; private readonly DateTimeOffset _origin = DateTimeOffset.Now; private readonly Queue<int> _attempts = new Queue<int>(); private readonly Queue<int> _failures = new Queue<int>(); private DateTimeOffset _lastEvaluate = DateTimeOffset.Now; private bool _isOpen; public bool IsOpen { get { if (GetTicks(_lastEvaluate) > 1) { var discardOlderThan1Hour = GetTicks(DateTimeOffset.Now.AddMinutes(-SlidingExpirationInMinutes)); ExpireOlderValues(_attempts, discardOlderThan1Hour); ExpireOlderValues(_failures, discardOlderThan1Hour); var attemptsCount = _attempts.Count; var failuresCount = _failures.Count; _isOpen = attemptsCount > 0 && failuresCount > MinFailuresCount && ((double)failuresCount / attemptsCount) > StopLoadingThreshold; _lastEvaluate = DateTimeOffset.Now; } return _isOpen; } } private static void ExpireOlderValues(Queue<int> q, int expirationOffsetInTicks) { while (q.Count > 0 && q.Peek() < expirationOffsetInTicks) { q.Dequeue(); } } public void ReportAttempt() { var ticks = GetTicks(_origin); _attempts.Enqueue(ticks); } public void ReportError() { var ticks = GetTicks(_origin); _failures.Enqueue(ticks); } // Ticks here are of 5sec long private static int GetTicks(DateTimeOffset origin) { return (int)((DateTimeOffset.Now - origin).TotalSeconds / SecondsInOneTick); } } }
using System.Threading; using System.Threading.Tasks; using Xunit; using HotChocolate.StarWars; using HotChocolate.Execution; using HotChocolate.Execution.Processing; using Microsoft.Extensions.DependencyInjection; using Moq; namespace HotChocolate.AspNetCore.Subscriptions.Messages { public class DataStopMessageHandlerTests { [Fact] public void CanHandle_DataStartMessage_True() { // arrange var handler = new DataStopMessageHandler(); var message = new DataStopMessage("123"); // act var result = handler.CanHandle(message); // assert Assert.True(result); } [Fact] public void CanHandle_KeepAliveMessage_False() { // arrange var handler = new DataStopMessageHandler(); KeepConnectionAliveMessage message = KeepConnectionAliveMessage.Default; // act var result = handler.CanHandle(message); // assert Assert.False(result); } [Fact] public async Task Handle_Stop_Subscription() { // arrange var connection = new SocketConnectionMock(); var subscription = new Mock<ISubscription>(); IRequestExecutor executor = await new ServiceCollection() .AddGraphQL() .AddStarWarsTypes() .AddStarWarsRepositories() .AddInMemorySubscriptions() .Services .BuildServiceProvider() .GetRequiredService<IRequestExecutorResolver>() .GetRequestExecutorAsync(); var stream = (IResponseStream)await executor.ExecuteAsync( "subscription { onReview(episode: NEW_HOPE) { stars } }"); var subscriptionSession = new SubscriptionSession( new CancellationTokenSource(), connection, stream, subscription.Object, new NoopDiagnosticEvents(), "123"); connection.Subscriptions.Register(subscriptionSession); var handler = new DataStopMessageHandler(); var message = new DataStopMessage("123"); // act await handler.HandleAsync( connection, message, CancellationToken.None); // assert Assert.Empty(connection.Subscriptions); } } }
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Batch.V20200901 { /// <summary> /// Contains information about a pool. /// </summary> [AzureNextGenResourceType("azure-nextgen:batch/v20200901:Pool")] public partial class Pool : Pulumi.CustomResource { [Output("allocationState")] public Output<string> AllocationState { get; private set; } = null!; [Output("allocationStateTransitionTime")] public Output<string> AllocationStateTransitionTime { get; private set; } = null!; /// <summary> /// The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. /// </summary> [Output("applicationLicenses")] public Output<ImmutableArray<string>> ApplicationLicenses { get; private set; } = null!; /// <summary> /// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. /// </summary> [Output("applicationPackages")] public Output<ImmutableArray<Outputs.ApplicationPackageReferenceResponse>> ApplicationPackages { get; private set; } = null!; /// <summary> /// This property is set only if the pool automatically scales, i.e. autoScaleSettings are used. /// </summary> [Output("autoScaleRun")] public Output<Outputs.AutoScaleRunResponse> AutoScaleRun { get; private set; } = null!; /// <summary> /// For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. /// </summary> [Output("certificates")] public Output<ImmutableArray<Outputs.CertificateReferenceResponse>> Certificates { get; private set; } = null!; [Output("creationTime")] public Output<string> CreationTime { get; private set; } = null!; [Output("currentDedicatedNodes")] public Output<int> CurrentDedicatedNodes { get; private set; } = null!; [Output("currentLowPriorityNodes")] public Output<int> CurrentLowPriorityNodes { get; private set; } = null!; /// <summary> /// Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). /// </summary> [Output("deploymentConfiguration")] public Output<Outputs.DeploymentConfigurationResponse?> DeploymentConfiguration { get; private set; } = null!; /// <summary> /// The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. /// </summary> [Output("displayName")] public Output<string?> DisplayName { get; private set; } = null!; /// <summary> /// The ETag of the resource, used for concurrency statements. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. /// </summary> [Output("interNodeCommunication")] public Output<string?> InterNodeCommunication { get; private set; } = null!; /// <summary> /// This is the last time at which the pool level data, such as the targetDedicatedNodes or autoScaleSettings, changed. It does not factor in node-level changes such as a compute node changing state. /// </summary> [Output("lastModified")] public Output<string> LastModified { get; private set; } = null!; /// <summary> /// The Batch service does not assign any meaning to metadata; it is solely for the use of user code. /// </summary> [Output("metadata")] public Output<ImmutableArray<Outputs.MetadataItemResponse>> Metadata { get; private set; } = null!; /// <summary> /// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. /// </summary> [Output("mountConfiguration")] public Output<ImmutableArray<Outputs.MountConfigurationResponse>> MountConfiguration { get; private set; } = null!; /// <summary> /// The name of the resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The network configuration for a pool. /// </summary> [Output("networkConfiguration")] public Output<Outputs.NetworkConfigurationResponse?> NetworkConfiguration { get; private set; } = null!; [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; [Output("provisioningStateTransitionTime")] public Output<string> ProvisioningStateTransitionTime { get; private set; } = null!; /// <summary> /// Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady). /// </summary> [Output("resizeOperationStatus")] public Output<Outputs.ResizeOperationStatusResponse> ResizeOperationStatus { get; private set; } = null!; /// <summary> /// Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. /// </summary> [Output("scaleSettings")] public Output<Outputs.ScaleSettingsResponse?> ScaleSettings { get; private set; } = null!; /// <summary> /// In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. /// </summary> [Output("startTask")] public Output<Outputs.StartTaskResponse?> StartTask { get; private set; } = null!; /// <summary> /// If not specified, the default is spread. /// </summary> [Output("taskSchedulingPolicy")] public Output<Outputs.TaskSchedulingPolicyResponse?> TaskSchedulingPolicy { get; private set; } = null!; /// <summary> /// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. /// </summary> [Output("taskSlotsPerNode")] public Output<int?> TaskSlotsPerNode { get; private set; } = null!; /// <summary> /// The type of the resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; [Output("userAccounts")] public Output<ImmutableArray<Outputs.UserAccountResponse>> UserAccounts { get; private set; } = null!; /// <summary> /// For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). /// </summary> [Output("vmSize")] public Output<string?> VmSize { get; private set; } = null!; /// <summary> /// Create a Pool resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Pool(string name, PoolArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:batch/v20200901:Pool", name, args ?? new PoolArgs(), MakeResourceOptions(options, "")) { } private Pool(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:batch/v20200901:Pool", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:batch:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/latest:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20170901:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20181201:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20190401:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20190801:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20200301:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20200501:Pool"}, new Pulumi.Alias { Type = "azure-nextgen:batch/v20210101:Pool"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Pool resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Pool Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Pool(name, id, options); } } public sealed class PoolArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Batch account. /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; [Input("applicationLicenses")] private InputList<string>? _applicationLicenses; /// <summary> /// The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. /// </summary> public InputList<string> ApplicationLicenses { get => _applicationLicenses ?? (_applicationLicenses = new InputList<string>()); set => _applicationLicenses = value; } [Input("applicationPackages")] private InputList<Inputs.ApplicationPackageReferenceArgs>? _applicationPackages; /// <summary> /// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool. /// </summary> public InputList<Inputs.ApplicationPackageReferenceArgs> ApplicationPackages { get => _applicationPackages ?? (_applicationPackages = new InputList<Inputs.ApplicationPackageReferenceArgs>()); set => _applicationPackages = value; } [Input("certificates")] private InputList<Inputs.CertificateReferenceArgs>? _certificates; /// <summary> /// For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. /// </summary> public InputList<Inputs.CertificateReferenceArgs> Certificates { get => _certificates ?? (_certificates = new InputList<Inputs.CertificateReferenceArgs>()); set => _certificates = value; } /// <summary> /// Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). /// </summary> [Input("deploymentConfiguration")] public Input<Inputs.DeploymentConfigurationArgs>? DeploymentConfiguration { get; set; } /// <summary> /// The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. /// </summary> [Input("displayName")] public Input<string>? DisplayName { get; set; } /// <summary> /// This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. /// </summary> [Input("interNodeCommunication")] public Input<Pulumi.AzureNextGen.Batch.V20200901.InterNodeCommunicationState>? InterNodeCommunication { get; set; } [Input("metadata")] private InputList<Inputs.MetadataItemArgs>? _metadata; /// <summary> /// The Batch service does not assign any meaning to metadata; it is solely for the use of user code. /// </summary> public InputList<Inputs.MetadataItemArgs> Metadata { get => _metadata ?? (_metadata = new InputList<Inputs.MetadataItemArgs>()); set => _metadata = value; } [Input("mountConfiguration")] private InputList<Inputs.MountConfigurationArgs>? _mountConfiguration; /// <summary> /// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. /// </summary> public InputList<Inputs.MountConfigurationArgs> MountConfiguration { get => _mountConfiguration ?? (_mountConfiguration = new InputList<Inputs.MountConfigurationArgs>()); set => _mountConfiguration = value; } /// <summary> /// The network configuration for a pool. /// </summary> [Input("networkConfiguration")] public Input<Inputs.NetworkConfigurationArgs>? NetworkConfiguration { get; set; } /// <summary> /// The pool name. This must be unique within the account. /// </summary> [Input("poolName")] public Input<string>? PoolName { get; set; } /// <summary> /// The name of the resource group that contains the Batch account. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. /// </summary> [Input("scaleSettings")] public Input<Inputs.ScaleSettingsArgs>? ScaleSettings { get; set; } /// <summary> /// In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. /// </summary> [Input("startTask")] public Input<Inputs.StartTaskArgs>? StartTask { get; set; } /// <summary> /// If not specified, the default is spread. /// </summary> [Input("taskSchedulingPolicy")] public Input<Inputs.TaskSchedulingPolicyArgs>? TaskSchedulingPolicy { get; set; } /// <summary> /// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256. /// </summary> [Input("taskSlotsPerNode")] public Input<int>? TaskSlotsPerNode { get; set; } [Input("userAccounts")] private InputList<Inputs.UserAccountArgs>? _userAccounts; public InputList<Inputs.UserAccountArgs> UserAccounts { get => _userAccounts ?? (_userAccounts = new InputList<Inputs.UserAccountArgs>()); set => _userAccounts = value; } /// <summary> /// For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). /// </summary> [Input("vmSize")] public Input<string>? VmSize { get; set; } public PoolArgs() { } } }
/* * 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 acm-2015-12-08.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.CertificateManager.Model { /// <summary> /// Contains information about the status of ACM's <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html">managed /// renewal</a> for the certificate. This structure exists only when the certificate type /// is <code>AMAZON_ISSUED</code>. /// </summary> public partial class RenewalSummary { private List<DomainValidation> _domainValidationOptions = new List<DomainValidation>(); private RenewalStatus _renewalStatus; private FailureReason _renewalStatusReason; private DateTime? _updatedAt; /// <summary> /// Gets and sets the property DomainValidationOptions. /// <para> /// Contains information about the validation of each domain name in the certificate, /// as it pertains to ACM's <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html">managed /// renewal</a>. This is different from the initial validation that occurs as a result /// of the <a>RequestCertificate</a> request. This field exists only when the certificate /// type is <code>AMAZON_ISSUED</code>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1000)] public List<DomainValidation> DomainValidationOptions { get { return this._domainValidationOptions; } set { this._domainValidationOptions = value; } } // Check to see if DomainValidationOptions property is set internal bool IsSetDomainValidationOptions() { return this._domainValidationOptions != null && this._domainValidationOptions.Count > 0; } /// <summary> /// Gets and sets the property RenewalStatus. /// <para> /// The status of ACM's <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html">managed /// renewal</a> of the certificate. /// </para> /// </summary> [AWSProperty(Required=true)] public RenewalStatus RenewalStatus { get { return this._renewalStatus; } set { this._renewalStatus = value; } } // Check to see if RenewalStatus property is set internal bool IsSetRenewalStatus() { return this._renewalStatus != null; } /// <summary> /// Gets and sets the property RenewalStatusReason. /// <para> /// The reason that a renewal request was unsuccessful. /// </para> /// </summary> public FailureReason RenewalStatusReason { get { return this._renewalStatusReason; } set { this._renewalStatusReason = value; } } // Check to see if RenewalStatusReason property is set internal bool IsSetRenewalStatusReason() { return this._renewalStatusReason != null; } /// <summary> /// Gets and sets the property UpdatedAt. /// <para> /// The time at which the renewal summary was last updated. /// </para> /// </summary> [AWSProperty(Required=true)] public DateTime UpdatedAt { get { return this._updatedAt.GetValueOrDefault(); } set { this._updatedAt = value; } } // Check to see if UpdatedAt property is set internal bool IsSetUpdatedAt() { return this._updatedAt.HasValue; } } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("HelloUnoWorld.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HelloUnoWorld.Droid")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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")]
namespace Zygotine.WebExpo { internal class GTMeasure : UncensoredMeasure { internal GTMeasure(double a, string workerTag = null) : base(a, workerTag) { this.Censoring = MeasureType.GreaterThan; } internal GTMeasure(double a, Worker worker) : base(a, worker) { this.Censoring = MeasureType.GreaterThan; } internal override Measure Duplicate() { return new GTMeasure(A, Worker); } public override string ToString() { return ToString(MeasureList.FieldSeparator.Semicolon); } public override string ToString(MeasureList.FieldSeparator fs) { return ">" + base.ToString(fs); } } //class GTMeasure }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Uygulama { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
using System; using System.Collections.Generic; namespace Sio.Cms.Lib.Models.Cms { public partial class SioFile { public int Id { get; set; } public string Content { get; set; } public DateTime CreatedDateTime { get; set; } public string Extension { get; set; } public string FileFolder { get; set; } public string FileName { get; set; } public string FolderType { get; set; } public DateTime? LastModified { get; set; } public string ModifiedBy { get; set; } public int Priority { get; set; } public int Status { get; set; } public int? ThemeId { get; set; } public string ThemeName { get; set; } public SioTheme Theme { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeDiffLib.Changes { public class Change<T> { public T Before { private set; get; } public T After { private set; get; } public ChangeType ChangeType { private set; get; } public Change(T before, T after, ChangeType change) { Before = before; After = after; ChangeType = change; } } }
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.DAS.Models { public class AuthDasSmsRequest : TeaModel { // OAuth模式下的授权token [NameInMap("auth_token")] [Validation(Required=false)] public string AuthToken { get; set; } [NameInMap("product_instance_id")] [Validation(Required=false)] public string ProductInstanceId { get; set; } // 手机验证码 [NameInMap("verification_code")] [Validation(Required=true)] public string VerificationCode { get; set; } // 授权实例biz_uuid [NameInMap("auth_instance_biz_uuid")] [Validation(Required=true)] public string AuthInstanceBizUuid { get; set; } // 授权企业信息 [NameInMap("auth_person_enterprise_info")] [Validation(Required=false)] public AuthPersonEnterpriseInfo AuthPersonEnterpriseInfo { get; set; } // 授权人个人信息 [NameInMap("auth_person_individual_info")] [Validation(Required=false)] public AuthPersonIndividualInfo AuthPersonIndividualInfo { get; set; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt namespace Microsoft.Graph { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; /// <summary> /// The type WorkbookFunctionsValueRequestBody. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WorkbookFunctionsValueRequestBody { /// <summary> /// Gets or sets Text. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "text", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Text { get; set; } } }
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Security { /// <summary> /// API Version: 2020-01-01. /// </summary> [AzureNativeResourceType("azure-native:security:AdaptiveApplicationControl")] public partial class AdaptiveApplicationControl : Pulumi.CustomResource { /// <summary> /// The configuration status of the machines group or machine or rule /// </summary> [Output("configurationStatus")] public Output<string> ConfigurationStatus { get; private set; } = null!; /// <summary> /// The application control policy enforcement/protection mode of the machine group /// </summary> [Output("enforcementMode")] public Output<string?> EnforcementMode { get; private set; } = null!; [Output("issues")] public Output<ImmutableArray<Outputs.AdaptiveApplicationControlIssueSummaryResponse>> Issues { get; private set; } = null!; /// <summary> /// Location where the resource is stored /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("pathRecommendations")] public Output<ImmutableArray<Outputs.PathRecommendationResponse>> PathRecommendations { get; private set; } = null!; /// <summary> /// The protection mode of the collection/file types. Exe/Msi/Script are used for Windows, Executable is used for Linux. /// </summary> [Output("protectionMode")] public Output<Outputs.ProtectionModeResponse?> ProtectionMode { get; private set; } = null!; /// <summary> /// The initial recommendation status of the machine group or machine /// </summary> [Output("recommendationStatus")] public Output<string> RecommendationStatus { get; private set; } = null!; /// <summary> /// The source type of the machine group /// </summary> [Output("sourceSystem")] public Output<string> SourceSystem { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; [Output("vmRecommendations")] public Output<ImmutableArray<Outputs.VmRecommendationResponse>> VmRecommendations { get; private set; } = null!; /// <summary> /// Create a AdaptiveApplicationControl resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public AdaptiveApplicationControl(string name, AdaptiveApplicationControlArgs args, CustomResourceOptions? options = null) : base("azure-native:security:AdaptiveApplicationControl", name, args ?? new AdaptiveApplicationControlArgs(), MakeResourceOptions(options, "")) { } private AdaptiveApplicationControl(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:security:AdaptiveApplicationControl", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:security:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-native:security/latest:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-nextgen:security/latest:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-native:security/v20150601preview:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-nextgen:security/v20150601preview:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-native:security/v20200101:AdaptiveApplicationControl"}, new Pulumi.Alias { Type = "azure-nextgen:security/v20200101:AdaptiveApplicationControl"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing AdaptiveApplicationControl resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static AdaptiveApplicationControl Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new AdaptiveApplicationControl(name, id, options); } } public sealed class AdaptiveApplicationControlArgs : Pulumi.ResourceArgs { /// <summary> /// The location where ASC stores the data of the subscription. can be retrieved from Get locations /// </summary> [Input("ascLocation", required: true)] public Input<string> AscLocation { get; set; } = null!; /// <summary> /// The application control policy enforcement/protection mode of the machine group /// </summary> [Input("enforcementMode")] public Input<string>? EnforcementMode { get; set; } /// <summary> /// Name of an application control machine group /// </summary> [Input("groupName")] public Input<string>? GroupName { get; set; } [Input("pathRecommendations")] private InputList<Inputs.PathRecommendationArgs>? _pathRecommendations; public InputList<Inputs.PathRecommendationArgs> PathRecommendations { get => _pathRecommendations ?? (_pathRecommendations = new InputList<Inputs.PathRecommendationArgs>()); set => _pathRecommendations = value; } /// <summary> /// The protection mode of the collection/file types. Exe/Msi/Script are used for Windows, Executable is used for Linux. /// </summary> [Input("protectionMode")] public Input<Inputs.ProtectionModeArgs>? ProtectionMode { get; set; } [Input("vmRecommendations")] private InputList<Inputs.VmRecommendationArgs>? _vmRecommendations; public InputList<Inputs.VmRecommendationArgs> VmRecommendations { get => _vmRecommendations ?? (_vmRecommendations = new InputList<Inputs.VmRecommendationArgs>()); set => _vmRecommendations = value; } public AdaptiveApplicationControlArgs() { } } }
// TypeExpression.cs // Script#/Core/ScriptSharp // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Diagnostics; namespace ScriptSharp.ScriptModel { /// <summary> /// Represents a type which allows access to static members on the type /// Note that this does not represent a Type object itself (eg. typeof(x)); /// Instead that is represented by a LiteralExpression. /// </summary> internal sealed class TypeExpression : Expression { private TypeSymbol _associatedType; public TypeExpression(TypeSymbol associatedType, SymbolFilter memberMask) : base(ExpressionType.Type, associatedType, memberMask) { _associatedType = associatedType; } public TypeSymbol AssociatedType { get { return _associatedType; } } } }
@using MyFitnessApp.Data.Models @model AddFoodInputModel @{ this.ViewData["Title"] = "Add to food diary"; } <!-- Breadcrumb --> <nav aria-label="breadcrumb" class="main-breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="/">Home</a></li> <li class="breadcrumb-item"><a href="/Foods/All">All foods</a></li> <li class="breadcrumb-item active" aria-current="page"><strong>@this.ViewData["Title"]</strong></li> </ol> </nav> <!-- /Breadcrumb --> <div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2 col-xl-8 offset-xl-2 col-md-8 offset-md-2"> <form method="post"> <h3 class="text-center">@Model.Name</h3> <div> <div class="form-group"> <label asp-for="ServingSize"></label> <input asp-for="ServingSize" class="form-control"> <span asp-validation-for="ServingSize" class="small text-danger"></span> </div> <div class="form-group"> <label asp-for="MealName"></label> <select asp-for="MealName" class="form-control"> @foreach (int mealName in Enum.GetValues(typeof(MealName))) { <option value="@mealName">@Enum.GetName(typeof(MealName), mealName)</option> } </select> </div> </div> <div class="text-center pt-2"> <input class="btn btn-outline-secondary" type="submit" value="Add to food diary" /> </div> </form> </div> </div> </div>
using System; using System.Collections.Generic; using System.Linq; namespace Cocos2D { public enum TestCases { TEST_ACCELEROMRTER = 0, TEST_ACTION_MANAGER, TEST_EASE_ACTIONS, TEST_PROGRESS_ACTIONS, TEST_ACTIONS, TEST_BOX2D, TEST_BOX2DBED, TEST_BOX2DBED2, //TEST_BUGS, //TEST_CHIPMUNK, TEST_CLICK_AND_MOVE, TEST_CLIPPINGNODE, TEST_COCOSDENSHION, //TEST_CURL, //TEST_CURRENT_LANGUAGE, TEST_DIRECTOR, TEST_DRAW_PRIMITIVES, TEST_EFFECT_ADVANCE, TEST_EFFECTS, TEST_EXTENSIONS, TEST_FONTS, TEST_INTERVAL, //TEST_KEYPAD, TEST_LABEL, TEST_LAYER, TEST_MENU, TEST_MOTION_STREAK, TEST_MULTITOUCH, TEST_COCOSNODE, TEST_ORIENTATION, TEST_PARALLAX, TEST_PARTICLE, TEST_PERFORMANCE, TEST_RENDERTEXTURE, TEST_ROTATE_WORLD, TEST_SCENE, TEST_SCHEDULER, //TEST_SHADER, TEST_SPRITE, TEST_TEXT_INPUT, TEST_TEXTURE2D, //TEST_TEXTURECACHE, TEST_TILE_MAP, TEST_TOUCHES, TEST_TRANSITIONS, //TEST_USERDEFAULT, TEST_ZWOPTEX, #if IOS || MACOS || WINDOWSGL || WINDOWS || ANDROID || NETFX_CORE TEST_SYSTEM_FONTS, #endif TESTS_COUNT, }; public class Tests { public static string[] g_aTestNames = { "Accelerometer", "ActionManagerTest", "ActionsEaseTest", "ActionsProgressTest", "ActionsTest", "Box2dTest", "Box2dTestBed(Farseer)", "Box2dTestBed(Box2D)", //"BugsTest", //"ChipmunkTest", "ClickAndMoveTest", "ClippingNodeTest", "CocosDenshionTest", //"CurlTest", //"CurrentLanguageTest" "DirectorTest", "DrawPrimitivesTest", "EffectAdvancedTest", "EffectsTest", "ExtensionsTest", "FontTest", "IntervalTest", //"KeypadTest", "LabelTest", "LayerTest", "MenuTest", "MotionStreakTest", "MultiTouchTest", "NodeTest", "OrientationTest", "ParallaxTest", "ParticleTest", "PerformanceTest", "RenderTextureTest", "RotateWorldTest", "SceneTest", "SchedulerTest", //"ShaderTest", "SpriteTest", "TextInputTest", "Texture2DTest", //"TextureCacheTest", "TileMapTest", "TouchesTest", "TransitionsTest", //"UserDefaultTest", "ZwoptexTest", #if IOS || MACOS || WINDOWSGL || WINDOWS || (ANDROID && !OUYA) || NETFX_CORE "SystemFontTest", #endif }; } }
using System; using System.Threading.Tasks; using SFA.DAS.EmployerDemand.Domain.Demand; using SFA.DAS.EmployerDemand.Domain.Demand.Api.Requests; using SFA.DAS.EmployerDemand.Domain.Demand.Api.Responses; using SFA.DAS.EmployerDemand.Domain.Interfaces; namespace SFA.DAS.EmployerDemand.Application.Demand.Services { public class DemandService : IDemandService { private readonly IApiClient _apiClient; private readonly ICacheStorageService _cacheStorageService; public DemandService (IApiClient apiClient, ICacheStorageService cacheStorageService) { _apiClient = apiClient; _cacheStorageService = cacheStorageService; } public async Task<GetCreateCourseDemandResponse> GetCreateCourseDemand(int trainingCourseId, string locationName) { var result = await _apiClient.Get<GetCreateCourseDemandResponse>(new GetCreateDemandRequest(trainingCourseId, locationName)); return result; } public async Task CreateCacheCourseDemand(ICourseDemand item) { await _cacheStorageService.SaveToCache(item.Id.ToString(), item, TimeSpan.FromMinutes(30)); } public async Task<CourseDemandRequest> GetCachedCourseDemand(Guid itemKey) { var result = await _cacheStorageService.RetrieveFromCache<CourseDemandRequest>(itemKey.ToString()); return result; } public async Task CreateCourseDemand(Guid id) { var item = await _cacheStorageService.RetrieveFromCache<CourseDemandRequest>(id.ToString()); var data = new PostCreateDemandData(item); await _apiClient.Post<Guid, PostCreateDemandData>(new PostCreateDemandRequest(data)); } public async Task<GetProviderEmployerDemandResponse> GetProviderEmployerDemand( int ukprn, int? courseId, string location, string locationRadius) { var result = await _apiClient.Get<GetProviderEmployerDemandResponse>( new GetProviderEmployerDemandRequest(ukprn, courseId, location, locationRadius)); return result; } } }
/* * 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 servicediscovery-2017-03-14.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.ServiceDiscovery.Model { /// <summary> /// Container for the parameters to the CreatePublicDnsNamespace operation. /// Creates a public namespace based on DNS, which will be visible on the internet. The /// namespace defines your service naming scheme. For example, if you name your namespace /// <code>example.com</code> and name your service <code>backend</code>, the resulting /// DNS name for the service will be <code>backend.example.com</code>. You can associate /// more than one service with the same namespace. /// </summary> public partial class CreatePublicDnsNamespaceRequest : AmazonServiceDiscoveryRequest { private string _creatorRequestId; private string _description; private string _name; /// <summary> /// Gets and sets the property CreatorRequestId. /// <para> /// A unique string that identifies the request and that allows failed <code>CreatePublicDnsNamespace</code> /// requests to be retried without the risk of executing the operation twice. <code>CreatorRequestId</code> /// can be any unique string, for example, a date/time stamp. /// </para> /// </summary> public string CreatorRequestId { get { return this._creatorRequestId; } set { this._creatorRequestId = value; } } // Check to see if CreatorRequestId property is set internal bool IsSetCreatorRequestId() { return this._creatorRequestId != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// A description for the namespace. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name that you want to assign to this namespace. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
using UnityEngine; using System.Collections.Generic; namespace SceneExport{ [System.Serializable] public class JsonRendererData: IFastJsonValue{ //public bool hasRenderer = false; public bool receiveShadows = false; public string shadowCastingMode; public int lightmapIndex = -1; public Vector4 lightmapScaleOffset = new Vector4(1.0f, 1.0f, 0.0f, 0.0f); public List<ResId> materials = new List<ResId>(); public void writeRawJsonValue(FastJsonWriter writer){ writer.beginRawObject(); writer.writeKeyVal("lightmapIndex", lightmapIndex); writer.writeKeyVal("shadowCastingMode", shadowCastingMode); writer.writeKeyVal("lightmapScaleOffset", lightmapScaleOffset); writer.writeKeyVal("materials", materials); writer.writeKeyVal("receiveShadows", receiveShadows); writer.endObject(); } public static JsonRendererData[] makeRendererArray(Renderer r, ResourceMapper resMap){ if (!r) return null; var result = new JsonRendererData(r, resMap); return new JsonRendererData[]{result}; } public JsonRendererData(Renderer r, ResourceMapper resMap){ receiveShadows = r.receiveShadows; shadowCastingMode = r.shadowCastingMode.ToString(); lightmapIndex = r.lightmapIndex; lightmapScaleOffset = r.lightmapScaleOffset; foreach(var cur in r.sharedMaterials){ materials.Add(resMap.getMaterialId(cur)); } } }; }
@model IEnumerable<MovieLib.WebApp.Models.MovieViewModel> @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th> @Html.DisplayNameFor(model => model.Duration) </th> <th> @Html.DisplayNameFor(model => model.ReleaseYear) </th> <th> @Html.DisplayNameFor(model => model.Rating) </th> <th> @Html.DisplayNameFor(model => model.Genre) </th> <th> @Html.DisplayNameFor(model => model.IsClassic) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.Duration) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseYear) </td> <td> @Html.DisplayFor(modelItem => item.Rating) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.IsClassic) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </tbody> </table>
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; namespace Microsoft.EntityFrameworkCore.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public interface IModelValidator { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> void Validate([NotNull] IModel model); } }
using System; using System.Collections.Concurrent; using Consensus.FastBFT.Messages; using Consensus.FastBFT.Replicas; namespace Consensus.FastBFT.Handlers { public class TransactionHandler : Handler { public static int MinTransactionsCountInBlock = 100; public static void Handle( TransactionMessage message, PrimaryReplica primaryReplica, ref ConcurrentBag<int> block, ConcurrentQueue<int[]> blockExchange) { var transaction = message.Transaction; block.Add(transaction); var now = DateTime.Now; if (block.Count >= MinTransactionsCountInBlock) { var blockCopy = block.ToArray(); block = new ConcurrentBag<int>(); // publish block to start working on consensus blockExchange.Enqueue(blockCopy); Log(primaryReplica, $"New block arrived for consensus (TransactionCounts: {blockCopy.Length})."); } } } }
using System; using System.Reflection; using NBitcoin; using NBitcoin.Networks; using Newtonsoft.Json; namespace Stratis.Bitcoin.Utilities.JsonConverters { /// <summary> /// Converter used to convert the name of a network in JSON to the corresponding <see cref="Network"/>. /// </summary> /// <seealso cref="JsonConverter" /> public class NetworkJsonConverter : JsonConverter { /// <inheritdoc /> public override bool CanConvert(Type objectType) { return typeof(Network).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()); } /// <inheritdoc /> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; string networkName = (string)reader.Value; if (networkName == null) return null; if (networkName.Equals("MainNet", StringComparison.OrdinalIgnoreCase) || networkName.Equals("main", StringComparison.OrdinalIgnoreCase)) return NetworkRegistration.GetNetwork("MainNet"); if (networkName.Equals("TestNet", StringComparison.OrdinalIgnoreCase) || networkName.Equals("test", StringComparison.OrdinalIgnoreCase)) return NetworkRegistration.GetNetwork("TestNet"); if (networkName.Equals("RegTest", StringComparison.OrdinalIgnoreCase) || networkName.Equals("reg", StringComparison.OrdinalIgnoreCase)) return NetworkRegistration.GetNetwork("RegTest"); Network network = NetworkRegistration.GetNetwork(networkName); if (networkName != null) return networkName; throw new JsonObjectException("Unknown network (valid values : main, test, reg)", reader); } /// <inheritdoc /> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var network = (Network)value; string networkName = null; if (network == NetworkRegistration.GetNetwork("MainNet")) networkName = "MainNet"; else if (network == NetworkRegistration.GetNetwork("TestNet")) networkName = "TestNet"; else if (network == NetworkRegistration.GetNetwork("RegTest")) networkName = "RegTest"; else if (network != null) networkName = network.ToString(); if (networkName != null) writer.WriteValue(networkName); } } }
#region using System; using System.Collections.Generic; #endregion namespace LoESoft.GameServer.realm.entity.merchant { partial class Merchant { private const int BUY_NO_GOLD = 3; private const int BUY_NO_FAME = 6; private const int BUY_NO_FORTUNETOKENS = 9; private const int MERCHANT_SIZE = 100; private bool closing; private bool newMerchant; private int tickcount; #pragma warning disable CS0108 // 'Merchant.Random' hides inherited member 'Entity.Random'. Use the new keyword if hiding was intended. public static Random Random { get; private set; } #pragma warning restore CS0108 // 'Merchant.Random' hides inherited member 'Entity.Random'. Use the new keyword if hiding was intended. private static List<KeyValuePair<string, int>> AddedTypes { get; set; } public bool Custom { get; set; } public int MType { get; set; } public int MRemaining { get; set; } public int MTime { get; set; } public int Discount { get; set; } public static int[] region1list; public static int[] region2list; public static int[] region3list; public static int[] region4list; public static int[] region5list; public static int[] region6list; public static int[] region7list; public static int[] region8list; public static int[] region9list; public static int[] region10list; // public static int[] smallclothlist; // public static int[] accessorylist; // public static int[] largeclothlist; // public static int[] clothinglist; internal static readonly List<int> weaponSlotType = new List<int> { 1, 2, 3, 8, 17, 24 }; internal static readonly List<int> abilitySlotType = new List<int> { 4, 5, 11, 12, 13, 15, 16, 18, 19, 20, 21, 22, 23, 25 }; internal static readonly List<int> armorSlotType = new List<int> { 6, 7, 14 }; internal static readonly List<int> ringSlotType = new List<int> { 9 }; } }
namespace Going.Plaid.Entity; /// <summary> /// <para>This field is deprecated in favor of the <c>breakdown</c> object, which provides more granular institution health data.</para> /// </summary> public enum ProductStatusStatusEnum { /// <summary> /// <para>the majority of requests are successful</para> /// </summary> [EnumMember(Value = "HEALTHY")] Healthy, /// <summary> /// <para>only some requests are successful</para> /// </summary> [EnumMember(Value = "DEGRADED")] Degraded, /// <summary> /// <para>all requests are failing</para> /// </summary> [EnumMember(Value = "DOWN")] Down, /// <summary> /// <para>Catch-all for unknown values returned by Plaid. If you encounter this, please check if there is a later version of the Going.Plaid library.</para> /// </summary> [EnumMember(Value = "undefined")] Undefined, }
// <auto-generated /> using Kahla.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; namespace Kahla.Server.Migrations { [DbContext(typeof(KahlaDbContext))] [Migration("20200222061857_MarkEmailPublis")] partial class MarkEmailPublis { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.2") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Kahla.SDK.Models.At", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<Guid>("MessageId") .HasColumnType("uniqueidentifier"); b.Property<string>("TargetUserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("MessageId"); b.HasIndex("TargetUserId"); b.ToTable("Ats"); }); modelBuilder.Entity("Kahla.SDK.Models.Conversation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AESKey") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("ConversationCreateTime") .HasColumnType("datetime2"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int>("MaxLiveSeconds") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Conversations"); b.HasDiscriminator<string>("Discriminator").HasValue("Conversation"); }); modelBuilder.Entity("Kahla.SDK.Models.Device", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("AddTime") .HasColumnType("datetime2"); b.Property<string>("IPAddress") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("PushAuth") .HasColumnType("nvarchar(max)"); b.Property<string>("PushEndpoint") .HasColumnType("nvarchar(max)"); b.Property<string>("PushP256DH") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Devices"); }); modelBuilder.Entity("Kahla.SDK.Models.KahlaUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<DateTime>("AccountCreateTime") .HasColumnType("datetime2"); b.Property<string>("Bio") .HasColumnType("nvarchar(max)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("ConnectKey") .HasColumnType("nvarchar(max)"); b.Property<int>("CurrentChannel") .HasColumnType("int"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("EmailReasonInJson") .HasColumnType("nvarchar(max)"); b.Property<bool>("EnableEmailNotification") .HasColumnType("bit"); b.Property<bool>("EnableEnterToSendMessage") .HasColumnType("bit"); b.Property<bool>("EnableInvisiable") .HasColumnType("bit"); b.Property<string>("IconFilePath") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("LastEmailHimTime") .HasColumnType("datetime2"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<bool>("MarkEmailPublic") .HasColumnType("bit"); b.Property<string>("NickName") .HasColumnType("nvarchar(max)"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("PreferedLanguage") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Sex") .HasColumnType("nvarchar(max)"); b.Property<int>("ThemeId") .HasColumnType("int"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Kahla.SDK.Models.Message", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Content") .HasColumnType("nvarchar(max)"); b.Property<int>("ConversationId") .HasColumnType("int"); b.Property<bool>("GroupWithPrevious") .HasColumnType("bit"); b.Property<bool>("Read") .HasColumnType("bit"); b.Property<DateTime>("SendTime") .HasColumnType("datetime2"); b.Property<string>("SenderId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("ConversationId"); b.HasIndex("SenderId"); b.ToTable("Messages"); }); modelBuilder.Entity("Kahla.SDK.Models.Report", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Reason") .HasColumnType("nvarchar(max)"); b.Property<int>("Status") .HasColumnType("int"); b.Property<string>("TargetId") .HasColumnType("nvarchar(450)"); b.Property<string>("TriggerId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("TargetId"); b.HasIndex("TriggerId"); b.ToTable("Reports"); }); modelBuilder.Entity("Kahla.SDK.Models.Request", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("Completed") .HasColumnType("bit"); b.Property<DateTime>("CreateTime") .HasColumnType("datetime2"); b.Property<string>("CreatorId") .HasColumnType("nvarchar(450)"); b.Property<string>("TargetId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("CreatorId"); b.HasIndex("TargetId"); b.ToTable("Requests"); }); modelBuilder.Entity("Kahla.SDK.Models.UserGroupRelation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("GroupId") .HasColumnType("int"); b.Property<DateTime>("JoinTime") .HasColumnType("datetime2"); b.Property<bool>("Muted") .HasColumnType("bit"); b.Property<DateTime>("ReadTimeStamp") .HasColumnType("datetime2"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("GroupId"); b.HasIndex("UserId"); b.ToTable("UserGroupRelations"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Kahla.SDK.Models.GroupConversation", b => { b.HasBaseType("Kahla.SDK.Models.Conversation"); b.Property<string>("GroupImagePath") .HasColumnType("nvarchar(max)"); b.Property<string>("GroupName") .HasColumnType("nvarchar(max)"); b.Property<string>("JoinPassword") .HasColumnType("nvarchar(max)"); b.Property<string>("OwnerId") .HasColumnType("nvarchar(450)"); b.HasIndex("OwnerId"); b.HasDiscriminator().HasValue("GroupConversation"); }); modelBuilder.Entity("Kahla.SDK.Models.PrivateConversation", b => { b.HasBaseType("Kahla.SDK.Models.Conversation"); b.Property<string>("RequesterId") .HasColumnType("nvarchar(450)"); b.Property<string>("TargetId") .HasColumnType("nvarchar(450)"); b.HasIndex("RequesterId"); b.HasIndex("TargetId"); b.HasDiscriminator().HasValue("PrivateConversation"); }); modelBuilder.Entity("Kahla.SDK.Models.At", b => { b.HasOne("Kahla.SDK.Models.Message", "Message") .WithMany("Ats") .HasForeignKey("MessageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Kahla.SDK.Models.KahlaUser", "TargetUser") .WithMany("ByAts") .HasForeignKey("TargetUserId"); }); modelBuilder.Entity("Kahla.SDK.Models.Device", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", "KahlaUser") .WithMany("HisDevices") .HasForeignKey("UserId"); }); modelBuilder.Entity("Kahla.SDK.Models.Message", b => { b.HasOne("Kahla.SDK.Models.Conversation", "Conversation") .WithMany("Messages") .HasForeignKey("ConversationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Kahla.SDK.Models.KahlaUser", "Sender") .WithMany("MessagesSent") .HasForeignKey("SenderId"); }); modelBuilder.Entity("Kahla.SDK.Models.Report", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", "Target") .WithMany("ByReported") .HasForeignKey("TargetId"); b.HasOne("Kahla.SDK.Models.KahlaUser", "Trigger") .WithMany("Reported") .HasForeignKey("TriggerId"); }); modelBuilder.Entity("Kahla.SDK.Models.Request", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", "Creator") .WithMany() .HasForeignKey("CreatorId"); b.HasOne("Kahla.SDK.Models.KahlaUser", "Target") .WithMany() .HasForeignKey("TargetId"); }); modelBuilder.Entity("Kahla.SDK.Models.UserGroupRelation", b => { b.HasOne("Kahla.SDK.Models.GroupConversation", "Group") .WithMany("Users") .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Kahla.SDK.Models.KahlaUser", "User") .WithMany("GroupsJoined") .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Kahla.SDK.Models.KahlaUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Kahla.SDK.Models.GroupConversation", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", "Owner") .WithMany("GroupsOwned") .HasForeignKey("OwnerId"); }); modelBuilder.Entity("Kahla.SDK.Models.PrivateConversation", b => { b.HasOne("Kahla.SDK.Models.KahlaUser", "RequestUser") .WithMany("Friends") .HasForeignKey("RequesterId"); b.HasOne("Kahla.SDK.Models.KahlaUser", "TargetUser") .WithMany("OfFriends") .HasForeignKey("TargetId"); }); #pragma warning restore 612, 618 } } }
// <auto-generated /> using System; using Events.API.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace Events.API.Migrations.Event { [DbContext(typeof(EventContext))] [Migration("20210425160205_GroupWithChildGroups")] partial class GroupWithChildGroups { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.5") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); modelBuilder.Entity("Events.API.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int?>("CategoryId") .HasColumnType("integer"); b.Property<string>("CoverPath") .HasColumnType("text"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp without time zone"); b.Property<string>("Description") .HasColumnType("text"); b.Property<DateTime>("EndDate") .HasColumnType("timestamp without time zone"); b.Property<string>("Identifier") .IsRequired() .HasColumnType("text"); b.Property<DateTime>("ModifiedAt") .HasColumnType("timestamp without time zone"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<string>("Organizer") .HasColumnType("text"); b.Property<string>("ShortCoverPath") .HasColumnType("text"); b.Property<DateTime>("StartDate") .HasColumnType("timestamp without time zone"); b.Property<int?>("StatusId") .HasColumnType("integer"); b.Property<string>("Subtitle") .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.HasIndex("StatusId"); b.ToTable("Events"); }); modelBuilder.Entity("Events.API.Models.EventSocial", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("EventId") .HasColumnType("integer"); b.Property<int>("SocialId") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("SocialId"); b.HasIndex("EventId", "SocialId") .IsUnique(); b.ToTable("EventSocials"); }); modelBuilder.Entity("Events.API.Models.EventTag", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("EventId") .HasColumnType("integer"); b.Property<int>("TagId") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("TagId"); b.HasIndex("EventId", "TagId") .IsUnique(); b.ToTable("EventTags"); }); modelBuilder.Entity("Events.API.Models.Group", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<int?>("EventId") .HasColumnType("integer"); b.Property<int?>("GroupId") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("EventId"); b.HasIndex("GroupId"); b.ToTable("Groups"); }); modelBuilder.Entity("Events.API.Models.GroupItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("CoverPath") .HasColumnType("text"); b.Property<string>("Description") .HasColumnType("text"); b.Property<int?>("GroupId") .HasColumnType("integer"); b.Property<int?>("MetadataId") .HasColumnType("integer"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<int?>("Number") .HasColumnType("integer"); b.Property<int?>("TypeId") .HasColumnType("integer"); b.Property<long>("Votes") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("GroupId"); b.HasIndex("MetadataId"); b.HasIndex("TypeId"); b.ToTable("GroupItems"); }); modelBuilder.Entity("Events.API.Models.GroupItemMetadata", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Interpreter") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<string>("Productor") .HasColumnType("text"); b.Property<string>("Support") .HasColumnType("text"); b.HasKey("Id"); b.ToTable("GroupItemMetadatas"); }); modelBuilder.Entity("Events.API.Models.GroupItemSocialSocial", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("ItemId") .HasColumnType("integer"); b.Property<int>("SocialId") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("SocialId"); b.HasIndex("ItemId", "SocialId") .IsUnique(); b.ToTable("GroupItemSocialSocials"); }); modelBuilder.Entity("Events.API.Models.GroupItemType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.ToTable("GroupItemTypes"); }); modelBuilder.Entity("Events.API.Models.Interaction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int?>("EventId") .HasColumnType("integer"); b.Property<bool>("Like") .HasColumnType("boolean"); b.Property<bool>("Love") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("EventId"); b.ToTable("Interactions"); }); modelBuilder.Entity("Events.API.Models.NCategory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Categories"); }); modelBuilder.Entity("Events.API.Models.NEventStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("EventStatuses"); }); modelBuilder.Entity("Events.API.Models.NTag", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Description") .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Tags"); }); modelBuilder.Entity("Events.API.Models.Social", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int?>("PlatformTypeId") .HasColumnType("integer"); b.Property<string>("Url") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("PlatformTypeId"); b.ToTable("Socials"); }); modelBuilder.Entity("Events.API.Models.SocialPlatformType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<string>("Url") .IsRequired() .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("SocialPlatformTypes"); }); modelBuilder.Entity("Events.API.Models.Event", b => { b.HasOne("Events.API.Models.NCategory", "Category") .WithMany() .HasForeignKey("CategoryId"); b.HasOne("Events.API.Models.NEventStatus", "Status") .WithMany() .HasForeignKey("StatusId"); b.Navigation("Category"); b.Navigation("Status"); }); modelBuilder.Entity("Events.API.Models.EventSocial", b => { b.HasOne("Events.API.Models.Event", "Event") .WithMany("Socials") .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Events.API.Models.Social", "Social") .WithMany() .HasForeignKey("SocialId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Event"); b.Navigation("Social"); }); modelBuilder.Entity("Events.API.Models.EventTag", b => { b.HasOne("Events.API.Models.Event", "Event") .WithMany("Tags") .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Events.API.Models.NTag", "Tag") .WithMany() .HasForeignKey("TagId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Event"); b.Navigation("Tag"); }); modelBuilder.Entity("Events.API.Models.Group", b => { b.HasOne("Events.API.Models.Event", null) .WithMany("Groups") .HasForeignKey("EventId"); b.HasOne("Events.API.Models.Group", null) .WithMany("ChildGroups") .HasForeignKey("GroupId"); }); modelBuilder.Entity("Events.API.Models.GroupItem", b => { b.HasOne("Events.API.Models.Group", null) .WithMany("Items") .HasForeignKey("GroupId"); b.HasOne("Events.API.Models.GroupItemMetadata", "Metadata") .WithMany() .HasForeignKey("MetadataId"); b.HasOne("Events.API.Models.GroupItemType", "Type") .WithMany() .HasForeignKey("TypeId"); b.Navigation("Metadata"); b.Navigation("Type"); }); modelBuilder.Entity("Events.API.Models.GroupItemSocialSocial", b => { b.HasOne("Events.API.Models.GroupItem", "Item") .WithMany("Socials") .HasForeignKey("ItemId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Events.API.Models.Social", "Social") .WithMany() .HasForeignKey("SocialId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Item"); b.Navigation("Social"); }); modelBuilder.Entity("Events.API.Models.Interaction", b => { b.HasOne("Events.API.Models.Event", null) .WithMany("Interactions") .HasForeignKey("EventId"); }); modelBuilder.Entity("Events.API.Models.Social", b => { b.HasOne("Events.API.Models.SocialPlatformType", "PlatformType") .WithMany() .HasForeignKey("PlatformTypeId"); b.Navigation("PlatformType"); }); modelBuilder.Entity("Events.API.Models.Event", b => { b.Navigation("Groups"); b.Navigation("Interactions"); b.Navigation("Socials"); b.Navigation("Tags"); }); modelBuilder.Entity("Events.API.Models.Group", b => { b.Navigation("ChildGroups"); b.Navigation("Items"); }); modelBuilder.Entity("Events.API.Models.GroupItem", b => { b.Navigation("Socials"); }); #pragma warning restore 612, 618 } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SubtypeInduction { class RoslynUtils { /// <summary> /// Get the symbol of a given node. /// </summary> /// <param name="node"></param> /// <param name="semanticModel"></param> /// <returns></returns> public static ISymbol GetReferenceSymbol(SyntaxNode node, SemanticModel semanticModel) { ISymbol identifierSymbol = semanticModel.GetSymbolInfo(node).Symbol; if (identifierSymbol == null && node.Kind() == SyntaxKind.VariableDeclarator) { identifierSymbol = semanticModel.GetDeclaredSymbol(((VariableDeclaratorSyntax)node)); } else if (identifierSymbol == null && node.Kind() == SyntaxKind.ForEachStatement) { identifierSymbol = semanticModel.GetDeclaredSymbol(((ForEachStatementSyntax)node)); } else if (identifierSymbol != null) { identifierSymbol = identifierSymbol.OriginalDefinition; } return identifierSymbol; } /// <summary> /// Get the type symbol for a given variable. /// </summary> /// <param name="symbol"></param> /// <returns></returns> public static ITypeSymbol GetVariableTypeSymbol(ISymbol symbol) { ITypeSymbol type; if (symbol is ILocalSymbol) { type = ((ILocalSymbol)symbol).Type; } else if (symbol is IFieldSymbol) { type = ((IFieldSymbol)symbol).Type; } else if (symbol is IParameterSymbol) { type = ((IParameterSymbol)symbol).Type; } else if (symbol is IRangeVariableSymbol) { type = null; } else if (symbol is IPropertySymbol) { type = ((IPropertySymbol)symbol).Type; } else { return null; } return type; } public static bool IsVariableSymbol(ISymbol symbol) { var symbolKind = symbol.Kind; return (symbolKind == SymbolKind.Local || symbolKind == SymbolKind.Parameter || symbolKind == SymbolKind.Field || symbolKind == SymbolKind.Property); } } }
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class W3ReplacerWarningArea : CEntity { [Ordinal(1)] [RED("messageKey")] public CString MessageKey { get; set;} [Ordinal(2)] [RED("messageInterval")] public CFloat MessageInterval { get; set;} [Ordinal(3)] [RED("invertLogic")] public CBool InvertLogic { get; set;} [Ordinal(4)] [RED("isPlayerInArea")] public CBool IsPlayerInArea { get; set;} public W3ReplacerWarningArea(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3ReplacerWarningArea(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entity { /// <summary> /// Representa a resposta de uma operação de banco /// de dados que envolva Insert, Update, Delete. /// </summary> public class Response { public bool Sucesso { get; set; } public List<string> Erros { get; set; } public string GetErrorMessage() { StringBuilder builder = new StringBuilder(); //Lambda Expression //Erros.ForEach(erro => builder.AppendLine(erro)); foreach (string item in this.Erros) { builder.AppendLine(item); } return builder.ToString(); } public bool HasErrors() { return this.Erros.Count > 0; } public Response() { this.Erros = new List<string>(); } } }
/* --------------------------------------------------------------------------------------------------------------------------------------- * (C) 2019, Dr Warren Creemers. * This file is subject to the terms and conditions defined in the included file 'LICENSE.txt' * --------------------------------------------------------------------------------------------------------------------------------------- */
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace MyLife.Migrations { public partial class Upgrade_ABP_4_2_0 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "LastLoginTime", table: "AbpUsers"); migrationBuilder.DropColumn( name: "LastLoginTime", table: "AbpUserAccounts"); migrationBuilder.AddColumn<string>( name: "ReturnValue", table: "AbpAuditLogs", nullable: true); migrationBuilder.CreateTable( name: "AbpOrganizationUnitRoles", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CreationTime = table.Column<DateTime>(nullable: false), CreatorUserId = table.Column<long>(nullable: true), TenantId = table.Column<int>(nullable: true), RoleId = table.Column<int>(nullable: false), OrganizationUnitId = table.Column<long>(nullable: false), IsDeleted = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpOrganizationUnitRoles", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnitRoles_TenantId_OrganizationUnitId", table: "AbpOrganizationUnitRoles", columns: new[] { "TenantId", "OrganizationUnitId" }); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnitRoles_TenantId_RoleId", table: "AbpOrganizationUnitRoles", columns: new[] { "TenantId", "RoleId" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AbpOrganizationUnitRoles"); migrationBuilder.DropColumn( name: "ReturnValue", table: "AbpAuditLogs"); migrationBuilder.AddColumn<DateTime>( name: "LastLoginTime", table: "AbpUsers", nullable: true); migrationBuilder.AddColumn<DateTime>( name: "LastLoginTime", table: "AbpUserAccounts", nullable: true); } } }
namespace Capnp.Rpc { class RpcUnimplementedException : System.Exception { } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using Unity.Collections.LowLevel.Unsafe; using System.Collections.Generic; [assembly: InternalsVisibleTo("Unity.Entities.Tests")] namespace Unity.Entities { public static class FastEquality { internal static TypeInfo CreateTypeInfo(Type type) { var begin = 0; var end = 0; var hash = 0; var layouts = new List<Layout>(); CreateLayoutRecurse(type, 0, layouts, ref begin, ref end, ref hash); if (begin != end) layouts.Add(new Layout {offset = begin, count = end - begin, Aligned4 = false}); var layoutsArray = layouts.ToArray(); for (var i = 0; i != layoutsArray.Length; i++) if (layoutsArray[i].count % 4 == 0 && layoutsArray[i].offset % 4 == 0) { layoutsArray[i].count /= 4; layoutsArray[i].Aligned4 = true; } return new TypeInfo { Layouts = layoutsArray, Hash = hash }; } public struct Layout { public int offset; public int count; public bool Aligned4; public override string ToString() { return $"offset: {offset} count: {count} Aligned4: {Aligned4}"; } } public struct TypeInfo { public Layout[] Layouts; public int Hash; public static TypeInfo Null => new TypeInfo(); } private unsafe struct PointerSize { private void* pter; } struct FieldData { public int Offset; public FieldInfo Field; } static FixedBufferAttribute GetFixedBufferAttribute(FieldInfo field) { foreach (var attribute in field.GetCustomAttributes(typeof(FixedBufferAttribute))) { return (FixedBufferAttribute)attribute; } return null; } static void CombineHash(ref int hash, params int[] values) { foreach (var value in values) { hash *= FNV_32_PRIME; hash ^= value; } } private static void CreateLayoutRecurse(Type type, int baseOffset, List<Layout> layouts, ref int begin, ref int end, ref int typeHash) { var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var fieldsWithOffset = new FieldData[fields.Length]; for (int i = 0; i != fields.Length; i++) { fieldsWithOffset[i].Offset = UnsafeUtility.GetFieldOffset(fields[i]); fieldsWithOffset[i].Field = fields[i]; } Array.Sort(fieldsWithOffset, (a, b) => a.Offset - b.Offset); foreach (var fieldWithOffset in fieldsWithOffset) { var field = fieldWithOffset.Field; var fixedBuffer = GetFixedBufferAttribute(field); var offset = baseOffset + fieldWithOffset.Offset; if (fixedBuffer != null) { var stride = UnsafeUtility.SizeOf(fixedBuffer.ElementType); for (int i = 0; i < fixedBuffer.Length; ++i) { CreateLayoutRecurse(fixedBuffer.ElementType, offset + i * stride, layouts, ref begin, ref end, ref typeHash); } } else if (field.FieldType.IsPrimitive || field.FieldType.IsPointer || field.FieldType.IsClass || field.FieldType.IsEnum) { CombineHash(ref typeHash, offset, (int)Type.GetTypeCode(field.FieldType)); var sizeOf = -1; if (field.FieldType.IsPointer || field.FieldType.IsClass) sizeOf = UnsafeUtility.SizeOf<PointerSize>(); else if (field.FieldType.IsEnum) { //@TODO: Workaround IL2CPP bug // sizeOf = UnsafeUtility.SizeOf(field.FieldType); sizeOf = UnsafeUtility.SizeOf(field.FieldType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)[0].FieldType); } else sizeOf = UnsafeUtility.SizeOf(field.FieldType); if (end != offset) { layouts.Add(new Layout {offset = begin, count = end - begin, Aligned4 = false}); begin = offset; end = offset + sizeOf; } else { end += sizeOf; } } else { CreateLayoutRecurse(field.FieldType, offset, layouts, ref begin, ref end, ref typeHash); } } } private const int FNV_32_PRIME = 0x01000193; //@TODO: Encode type in hashcode... public static unsafe int GetHashCode<T>(T lhs, TypeInfo typeInfo) where T : struct { return GetHashCode(UnsafeUtility.AddressOf(ref lhs), typeInfo); } public static unsafe int GetHashCode<T>(ref T lhs, TypeInfo typeInfo) where T : struct { return GetHashCode(UnsafeUtility.AddressOf(ref lhs), typeInfo); } public static unsafe int GetHashCode(void* dataPtr, TypeInfo typeInfo) { var layout = typeInfo.Layouts; var data = (byte*) dataPtr; uint hash = 0; for (var k = 0; k != layout.Length; k++) if (layout[k].Aligned4) { var dataInt = (uint*) (data + layout[k].offset); var count = layout[k].count; for (var i = 0; i != count; i++) { hash *= FNV_32_PRIME; hash ^= dataInt[i]; } } else { var dataByte = data + layout[k].offset; var count = layout[k].count; for (var i = 0; i != count; i++) { hash *= FNV_32_PRIME; hash ^= dataByte[i]; } } return (int) hash; } public static unsafe bool Equals<T>(T lhs, T rhs, TypeInfo typeInfo) where T : struct { return Equals(UnsafeUtility.AddressOf(ref lhs), UnsafeUtility.AddressOf(ref rhs), typeInfo); } public static unsafe bool Equals<T>(ref T lhs, ref T rhs, TypeInfo typeInfo) where T : struct { return Equals(UnsafeUtility.AddressOf(ref lhs), UnsafeUtility.AddressOf(ref rhs), typeInfo); } public static unsafe bool Equals(void* lhsPtr, void* rhsPtr, TypeInfo typeInfo) { var layout = typeInfo.Layouts; var lhs = (byte*) lhsPtr; var rhs = (byte*) rhsPtr; var same = true; for (var k = 0; k != layout.Length; k++) if (layout[k].Aligned4) { var offset = layout[k].offset; var lhsInt = (uint*) (lhs + offset); var rhsInt = (uint*) (rhs + offset); var count = layout[k].count; for (var i = 0; i != count; i++) same &= lhsInt[i] == rhsInt[i]; } else { var offset = layout[k].offset; var lhsByte = lhs + offset; var rhsByte = rhs + offset; var count = layout[k].count; for (var i = 0; i != count; i++) same &= lhsByte[i] == rhsByte[i]; } return same; } } }
using System.IO; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.Xna.Framework; using MonoGame.Common; using Random = System.Random; public class BlobStorage : BaseStorage { public string BlockBlobContainerName = "democontainerblockblob"; public string PageBlobContainerName = "democontainerpageblob"; public BlobStorage(TextBox tb) : base(tb) { } public async void BlobStorageTest() { Running = true; ClearOutput(); WriteLine("-- Testing Blob Storage --"); await BasicStorageBlockBlobOperationsAsync(); await BasicStoragePageBlobOperationsAsync(); } private async Task BasicStorageBlockBlobOperationsAsync() { WriteLine("Testing BlockBlob"); const string ImageToUpload = "HelloWorld.png"; // Create a blob client for interacting with the blob service. CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); // Create a container for organizing blobs within the storage account. WriteLine("1. Creating Container"); CloudBlobContainer container = blobClient.GetContainerReference("democontainerblockblob"); try { await container.CreateIfNotExistsAsync(); } catch (StorageException) { WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample."); throw; } // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image // using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/democontainer/HelloWorld.png // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); // Upload a BlockBlob to the newly created container WriteLine("2. Uploading BlockBlob"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload); Stream s = TitleContainer.OpenStream(Path.Combine("Content", ImageToUpload)); await blockBlob.UploadFromStreamAsync(s); // List all the blobs in the container WriteLine("3. List Blobs in Container"); BlobContinuationToken token = null; BlobResultSegment list = await container.ListBlobsSegmentedAsync(token); foreach (IListBlobItem blob in list.Results) { // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type WriteLine(string.Format("- {0} (type: {1})", blob.Uri, blob.GetType())); } // Download a blob to your file system WriteLine(string.Format("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri)); OutputStream = new MemoryStream(); await blockBlob.DownloadToStreamAsync(OutputStream); WriteLine("File downloaded to in-memory stream"); // Clean up after the demo WriteLine("5. Delete block Blob"); await blockBlob.DeleteAsync(); // When you delete a container it could take several seconds before you can recreate a container with the same // name - hence to enable you to run the demo in quick succession the container is not deleted. If you want // to delete the container uncomment the line of code below. WriteLine("6. Delete Container -- Note that it will take a few seconds before you can recreate a container with the same name"); await container.DeleteAsync(); WriteLine("-- Test Complete --"); } private async Task BasicStoragePageBlobOperationsAsync() { WriteLine("-- Testing PageBlob --"); const string PageBlobName = "samplepageblob"; // Create a blob client for interacting with the blob service. CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient(); // Create a container for organizing blobs within the storage account. WriteLine("1. Creating Container"); CloudBlobContainer container = blobClient.GetContainerReference("democontainerpageblob"); await container.CreateIfNotExistsAsync(); // Create a page blob in the newly created container. WriteLine("2. Creating Page Blob"); CloudPageBlob pageBlob = container.GetPageBlobReference(PageBlobName); await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes // Write to a page blob WriteLine("2. Write to a Page Blob"); byte[] samplePagedata = new byte[512]; Random random = new Random(); random.NextBytes(samplePagedata); await pageBlob.UploadFromByteArrayAsync(samplePagedata, 0, samplePagedata.Length); // List all blobs in this container. Because a container can contain a large number of blobs the results // are returned in segments (pages) with a maximum of 5000 blobs per segment. You can define a smaller size // using the maxResults parameter on ListBlobsSegmentedAsync. WriteLine("3. List Blobs in Container"); BlobContinuationToken token = null; do { BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token); token = resultSegment.ContinuationToken; foreach (IListBlobItem blob in resultSegment.Results) { // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory WriteLine(string.Format("{0} (type: {1}", blob.Uri, blob.GetType())); } } while (token != null); // Read from a page blob WriteLine("4. Read from a Page Blob"); int bytesRead = await pageBlob.DownloadRangeToByteArrayAsync(samplePagedata, 0, 0, samplePagedata.Length); // Clean up after the demo WriteLine("5. Delete page Blob"); await pageBlob.DeleteAsync(); // When you delete a container it could take several seconds before you can recreate a container with the same // name - hence to enable you to run the demo in quick succession the container is not deleted. If you want // to delete the container uncomment the line of code below. WriteLine("6. Delete Container"); await container.DeleteAsync(); WriteLine("-- Test Complete --"); Running = false; } }
// System.Web.Services.Description.ServiceDescriptionCollection.ServiceDescriptionCollection() // System.Web.Services.Description.ServiceDescriptionCollection.Add() // System.Web.Services.Description.ServiceDescriptionCollection.Item(Int32) /* The following program demonstrates 'Constructor', 'Add' method and 'Item' property of 'ServiceDescriptionCollection' class. It creates an instance of 'ServiceDescriptionCollection' and adds 'ServiceDescription' objects to the collection. The Item property is used to display the TargetNamespace of elements in the collection. Note: This program requires 'DataTypes_CS.wsdl' and 'MathService_CS.wsdl' files to be placed in same directory as that of .exe for running. */ using System; using System.Web.Services.Description; class MyServiceDescriptionCollection { public static void Main() { try { ServiceDescription myServiceDescription1 = ServiceDescription.Read("DataTypes_CS.wsdl"); ServiceDescription myServiceDescription2 = ServiceDescription.Read("MathService_CS.wsdl"); // <Snippet11> // <Snippet12> // Create a ServiceDescriptionCollection. ServiceDescriptionCollection myCollection = new ServiceDescriptionCollection(); // Add the ServiceDescriptions to the collection. myCollection.Add(myServiceDescription1); myCollection.Add(myServiceDescription2); // </Snippet12> // </Snippet11> // <Snippet13> // Display element properties in the collection using the // Item property. for(int i = 0; i < myCollection.Count; i++) { Console.WriteLine(myCollection[i].TargetNamespace); } // </Snippet13> } catch(Exception e) { Console.WriteLine("The following exception was raised: {0}", e.Message); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(AudioSource))] public class FlyAway : MonoBehaviour { private float forcePower = 200f; public AudioClip[] audios; [HideInInspector] public AudioSource source; [HideInInspector] public Rigidbody rb; private void Start() { rb = GetComponent<Rigidbody>(); source = GetComponent<AudioSource>(); } private void OnCollisionStay(Collision other) { if (other.gameObject.name == "Train") { // Debug.Log("Hit"); rb.AddForce(forcePower * Random.rotation.eulerAngles.normalized); if (audios.Length > 0) { var clip = audios[Random.Range(0, audios.Length)]; source.clip = clip; source.Play(); } } } }
/* * Copyright 2017 Alastair Wyse (https://github.com/alastairwyse/MoreComplexDataStructures/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MoreComplexDataStructures { /// <summary> /// Provides a method to randomize the elements of a list with O(n) time complexity using the Fisher/Yates/Knuth algorithm. /// </summary> public class ListRandomizer { /// <summary>The random number generator to use for selecting indices from the source collection.</summary> protected IRandomIntegerGenerator randomGenerator; /// <summary> /// Initialises a new instance of the MoreComplexDataStructures.ListRandomizer class. /// </summary> public ListRandomizer() { randomGenerator = new DefaultRandomGenerator(); } /// <summary> /// Initialises a new instance of the MoreComplexDataStructures.ListRandomizer class. /// </summary> /// <param name="randomIntegerGenerator">An implementation of interface IRandomIntegerGenerator to use for selecting indices from the source collection.</param> public ListRandomizer(IRandomIntegerGenerator randomIntegerGenerator) : this() { randomGenerator = randomIntegerGenerator; } /// <summary> /// Randomizes the elements of the specified collection implementing interface IList&lt;T&gt;. /// </summary> /// <param name="inputCollection">The IList to randomize the elements of.</param> /// <exception cref="System.ArgumentException">The 'inputCollection' parameter contains a list exceeding the maximum supported size (Int32.MaxValue - 1 elements).</exception> public void Randomize(IList inputCollection) { // Need to throw an exception of the inputted collection contains Int32.MaxValue elements. // In this case we can never randomly select the last value in the list (as the IRandomIntegerGenerator.Next() 'maxValue' parameter is exclusive). if (inputCollection.Count == Int32.MaxValue) { throw new ArgumentException($"The maximum collection size supported by the ListRandomizer is {(Int32.MaxValue - 1)}.", nameof(inputCollection)); } Int32 randomizedPortionDividerIndex = inputCollection.Count; while (randomizedPortionDividerIndex > 0) { // Generate the index of the next element to move to the randomized portion of the list Int32 nextIndex = randomGenerator.Next(randomizedPortionDividerIndex); // Move the element to the randomized portion and swap with the existing object Object tempObject = inputCollection[nextIndex]; inputCollection[nextIndex] = inputCollection[randomizedPortionDividerIndex - 1]; inputCollection[randomizedPortionDividerIndex - 1] = tempObject; randomizedPortionDividerIndex--; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decorator.Sample { /// <summary> /// 「飾り枠」 /// 役割:Decorator(装飾者) /// </summary> abstract class Border : Display { /// <summary> /// この飾り枠がくるんでいる「中身」を指す。 /// </summary> protected Display display; /// <summary> /// コンストラクタ /// </summary> /// <param name="display">この飾り枠がくるんでいる「中身」</param> protected Border(Display display) { //インスタンス生成時に「中身」を引数で指定 this.display = display; } } }
using System; namespace Models.Domain { public class RefreshToken { public string Token { get; set; } public string JwtId { get; set; } public DateTime DateStart { get; set; } public DateTime DateEnd { get; set; } public bool Used { get; set; } public bool Invalidated { get; set; } public string UserId { get; set; } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; namespace OcelotServer01.Api.Controllers { //set ASPNETCORE_URLS = http://127.0.0.1:5001 [Produces("application/json")] [Route("api/[controller]")] //[Route("api/SMS")] public class SmsController : Controller { //"UpstreamPathTemplate": "/sms/{url}", 不适配/api/sms?msg=Hello //http://localhost:21422/api/sms?msg=Hello public string SendMsg(string msg) { string message = "SendMsg:发送短信:" + msg; Console.WriteLine(message); return message; } // Error //public string SendMsgs(string msg) //{ // string message = "SendMsgs:发送短信:" + msg; // Console.WriteLine(message); // return message; //} //OcelotServer01: http://localhost:806/sms/ReceiveMsg?msg=12345678910 [HttpGet("Send")] public IEnumerable<string> Send(string msg) { string message = "SendMsg:发送短信:" + msg; Console.WriteLine(message); string value = Request.Headers["X-Hello"]; Console.WriteLine($"x-hello={value}"); Console.WriteLine("发送短信" + msg); return new string[] { HttpContext.Request.Path, HttpContext.Request.Host.Value }; } //http://localhost:21422/api/sms/ReceiveMsg?msg=Hello // GET api/values [HttpGet("ReceiveMsg")] public bool ReceiveMsg(string msg) { Console.WriteLine("收到回复短信:" + msg); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TNBCSurvey.Models { public class SurveyExportAnswer { public int Client_SID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string GroupNumber { get; set; } public string Question_Period { get; set; } public string Question_Text { get; set; } public string Answer_Text { get; set; } } }
using System; using JulMar.Smpp.Utility; namespace JulMar.Smpp.Elements { /// <summary> /// The sm_default_msg_id parameter is used to specify the SMSC index of a pre-defined ("canned") /// message. /// </summary> public class sm_default_msg_id : SmppByte { /// <summary> /// Minimum index for a canned message. /// </summary> public const byte MIN_VALUE = 1; /// <summary> /// Maximum index for a message. /// </summary> public const byte MAX_VALUE = 254; /// <summary> /// Default constructor /// </summary> public sm_default_msg_id() : base(MIN_VALUE) { } /// <summary> /// Parameterized constructor /// </summary> public sm_default_msg_id(byte id) : base(id) { } /// <summary> /// Data validation support /// </summary> protected override void ValidateData() { if (Value != 0 && Value < MIN_VALUE || Value > MAX_VALUE) throw new System.ArgumentOutOfRangeException("The sm_default_msg_id is not valid."); } /// <summary> /// Override object.ToString /// </summary> /// <returns></returns> public override string ToString() { return string.Format("sm_default_msg_id: {0:X}", Value); } } }
// Copyright (c) 2020 .NET Foundation and Contributors. All rights reserved. // 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 full license information. using System.Windows.Forms; namespace ReactiveUI.Tests.Winforms { public class FakeView : IViewFor<FakeViewModel> { public FakeView() { TheTextBox = new TextBox(); ViewModel = new FakeViewModel(); } public TextBox TheTextBox { get; protected set; } object? IViewFor.ViewModel { get => ViewModel; set => ViewModel = (FakeViewModel?)value; } public FakeViewModel? ViewModel { get; set; } } }
using System.Text.Json; namespace StrawberryShake.Transport.Http; public interface IHttpConnection : IConnection<JsonDocument> { }
using UnityEngine; public class DestroyOnHit : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { Destroy(other.gameObject); } }
namespace InsanityBot; public partial class InsanityBot { public static void RegisterDatafixers() { } }
// Copyright © 2017 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Routing; using Newtonsoft.Json; using Platformus.Barebone; using Platformus.ECommerce.Data.Abstractions; using Platformus.ECommerce.Data.Entities; using Platformus.Routing.DataSources; namespace Platformus.ECommerce.Frontend.DataSources { public class ProductDataSource : DataSourceBase { public override string Description => "Loads current product by URL."; protected override dynamic GetData() { string url = string.Format("/{0}", this.requestHandler.HttpContext.GetRouteValue("url")); SerializedProduct serializedProduct = this.requestHandler.Storage.GetRepository<ISerializedProductRepository>().WithUrl(url); if (serializedProduct == null) throw new HttpException(404, "Not found."); IEnumerable<SerializedProduct.Attribute> serializedAttributes = JsonConvert.DeserializeObject<IEnumerable<SerializedProduct.Attribute>>(serializedProduct.SerializedAttributes); IEnumerable<SerializedProduct.Photo> serializedPhotos = JsonConvert.DeserializeObject<IEnumerable<SerializedProduct.Photo>>(serializedProduct.SerializedPhotos); SerializedProduct.Photo serializedCoverPhoto = serializedPhotos.FirstOrDefault(sph => sph.IsCover); return new ExpandoObjectBuilder() .AddProperty("Id", serializedProduct.ProductId) .AddProperty("Code", serializedProduct.Code) .AddProperty("Name", serializedProduct.Name) .AddProperty("Description", serializedProduct.Description) .AddProperty("Price", serializedProduct.Price) .AddProperty("Title", serializedProduct.Title) .AddProperty("MetaDescription", serializedProduct.MetaDescription) .AddProperty("MetaKeywords", serializedProduct.MetaKeywords) .AddProperty("Attributes", serializedAttributes.OrderBy(sa => sa.Feature.Position).Select(sa => this.CreateAttributeViewModel(sa))) .AddProperty("CoverPhoto", this.CreatePhotoViewModel(serializedCoverPhoto)) .AddProperty("Photos", serializedPhotos.OrderBy(sph => sph.Position).Select(sph => this.CreatePhotoViewModel(sph))) .Build(); } private dynamic CreateAttributeViewModel(SerializedProduct.Attribute serializedAttribute) { if (serializedAttribute == null) return null; return new ExpandoObjectBuilder() .AddProperty("Feature", this.CreateFeatureViewModel(serializedAttribute.Feature)) .AddProperty("Value", serializedAttribute.Value) .Build(); } private dynamic CreateFeatureViewModel(SerializedProduct.Feature serializedFeature) { if (serializedFeature == null) return null; return new ExpandoObjectBuilder() .AddProperty("Code", serializedFeature.Code) .AddProperty("Name", serializedFeature.Name) .Build(); } private dynamic CreatePhotoViewModel(SerializedProduct.Photo serializedPhoto) { if (serializedPhoto == null) return null; return new ExpandoObjectBuilder() .AddProperty("Filename", serializedPhoto.Filename) .Build(); } } }
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3d11.h(11007,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct D3D11_OMAC { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] Omac; } }
using System; using System.Drawing; namespace PluginCore.Helpers { public class DrawHelper { /// <summary> /// Measures the actual width of the text /// http://www.codeproject.com/KB/GDI-plus/measurestring.aspx /// </summary> public static Int32 MeasureDisplayStringWidth(Graphics graphics, String text, Font font) { try { System.Drawing.StringFormat format = new System.Drawing.StringFormat(); System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, 1000, 1000); System.Drawing.CharacterRange[] ranges = { new System.Drawing.CharacterRange(0, text.Length) }; System.Drawing.Region[] regions = new System.Drawing.Region[1]; format.SetMeasurableCharacterRanges(ranges); regions = graphics.MeasureCharacterRanges(text, font, rect, format); rect = regions[0].GetBounds(graphics); return (Int32)rect.Right; } catch (IndexOutOfRangeException) { return 0; } } } }
using System.ComponentModel.DataAnnotations; namespace BDSA2018.Lecture11.Shared { public class CharacterCreateUpdateDTO { public int Id { get; set; } public int? ActorId { get; set; } [Required] [StringLength(50)] public string Name { get; set; } [Required] [StringLength(50)] public string Species { get; set; } [StringLength(50)] public string Planet { get; set; } } }
using System.Threading.Tasks; using Market.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Market.Web.Areas.Identity.Pages.Account.Manage { public class PersonalDataModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<PersonalDataModel> _logger; public PersonalDataModel( UserManager<ApplicationUser> userManager, ILogger<PersonalDataModel> logger) { _userManager = userManager; _logger = logger; } public async Task<IActionResult> OnGet() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } return Page(); } } }
namespace Observer { public class WeatherData : Subject { public List<Observer> observers; private float temp; private float humidity; private float pressure; public WeatherData() { observers = new List<Observer>(); } public void RegisterObserver(Observer observer) { observers.Add(observer); } public void RemoveObserver(Observer observer) { observers.Remove(observer); } public void NotifyObservers() { foreach (var observer in observers) { observer.Update(temp, humidity, pressure); } } public void MeasurementsChanged() { NotifyObservers(); } public void SetMeasurements(float temp, float humidity, float pressure) { this.temp = temp; this.humidity = humidity; this.pressure = pressure; MeasurementsChanged(); } } }