content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> namespace AmplifyShaderEditor { [System.Serializable] [NodeAttributes( "Light Color", "Light", "Light Color, RGB value already contains light intensity while A only contains light intensity" )] public sealed class LightColorNode : ShaderVariablesNode { private const string m_lightColorValue = "_LightColor0"; protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); ChangeOutputProperties( 0, "RGBA", WirePortDataType.COLOR ); } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar ); return m_lightColorValue; } } }
34.916667
140
0.770883
[ "MIT" ]
kompyang/UnityGamePlayPocketLab
FPS/Assets/3rd/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/ShaderVariables/Lighting/LightColorNode.cs
838
C#
using System; namespace ColdBoi.CPU.Instructions { public class LdHN : Instruction { public const byte OPCODE = 0x26; public const string NAME = "ld"; public LdHN(Processor processor) : base(processor, OPCODE, 1, 8, NAME) { } public override void Execute(params byte[] operands) { var value = operands[0]; this.processor.Registers.HL.HigherByte = value; #if DEBUG Console.WriteLine($"{this.processor.Registers.PC.Value:X4}: {this.Name} h, {value:X2}"); #endif } } }
24.208333
100
0.590361
[ "MIT" ]
Myuujinn/ColdBoi
ColdBoi/CPU/Instructions/Ld/LdHN.cs
581
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// NumberFilter Marshaller /// </summary> public class NumberFilterMarshaller : IRequestMarshaller<NumberFilter, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(NumberFilter requestObject, JsonMarshallerContext context) { if(requestObject.IsSetEq()) { context.Writer.WritePropertyName("Eq"); context.Writer.Write(requestObject.Eq); } if(requestObject.IsSetGte()) { context.Writer.WritePropertyName("Gte"); context.Writer.Write(requestObject.Gte); } if(requestObject.IsSetLte()) { context.Writer.WritePropertyName("Lte"); context.Writer.Write(requestObject.Lte); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static NumberFilterMarshaller Instance = new NumberFilterMarshaller(); } }
32.121622
109
0.65082
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/NumberFilterMarshaller.cs
2,377
C#
using System.ComponentModel.DataAnnotations; using System.Windows.Input; using Param_RootNamespace.Core.Contracts.Services; using Param_RootNamespace.Core.Models; namespace Param_RootNamespace.ViewModels; public class Param_ItemNameViewModel : ObservableValidator { private readonly ISampleDataService _sampleDataService; private long _orderID; private DateTimeOffset _orderDate = DateTime.Now; private TimeSpan _orderTime = DateTime.Now.TimeOfDay; private string _company; private SampleSymbol _symbol; private string _orderTotal; private string _freight; private string _status; private string _shipperName; private string _shipperPhone; private string _shipTo; private ICommand _submitCommand; [Required] [Range(10000, 99999)] public long OrderID { get => _orderID; set => SetProperty(ref _orderID, value, true); } [Required] [DataType(DataType.Date)] public DateTimeOffset OrderDate { get => _orderDate; set => SetProperty(ref _orderDate, value, true); } [Required] [DataType(DataType.Time)] public TimeSpan OrderTime { get => _orderTime; set => SetProperty(ref _orderTime, value, true); } [Required] public string Company { get => _company; set => SetProperty(ref _company, value, true); } [Required] public SampleSymbol Symbol { get => _symbol; set => SetProperty(ref _symbol, value, true); } [Required] [CustomValidation(typeof(Param_ItemNameViewModel), "ValidateDoubleProperty")] public string OrderTotal { get => _orderTotal; set => SetProperty(ref _orderTotal, value, true); } [Required] [CustomValidation(typeof(Param_ItemNameViewModel), "ValidateDoubleProperty")] public string Freight { get => _freight; set => SetProperty(ref _freight, value, true); } [Required] public string Status { get => _status; set => SetProperty(ref _status, value, true); } [Required] public string ShipperName { get => _shipperName; set => SetProperty(ref _shipperName, value, true); } [Required] [Phone] public string ShipperPhone { get => _shipperPhone; set => SetProperty(ref _shipperPhone, value, true); } [Required] public string ShipTo { get => _shipTo; set => SetProperty(ref _shipTo, value, true); } public IEnumerable<string> StatusValues { get; } = new List<string>() { "New", "Shipped", "Closed" }; public IEnumerable<SampleSymbol> SymbolValues { get; } = new List<SampleSymbol> { new SampleSymbol() { Name = "Globe", Code = (char)57643 }, new SampleSymbol() { Name = "Audio", Code = (char)57737 }, new SampleSymbol() { Name = "Calendar", Code = (char)57699 }, new SampleSymbol() { Name = "Camera", Code = (char)57620 }, new SampleSymbol() { Name = "Clock", Code = (char)57633 }, new SampleSymbol() { Name = "Contact", Code = (char)57661 }, new SampleSymbol() { Name = "Favorite", Code = (char)57619 }, new SampleSymbol() { Name = "Home", Code = (char)57615 }, }; public ICommand SubmitCommand => _submitCommand ?? (_submitCommand = new RelayCommand(Submit)); public Param_ItemNameViewModel(ISampleDataService sampleDataService) { _sampleDataService = sampleDataService; Status = StatusValues.First(); Symbol = SymbolValues.First(); } private async void Submit() { ValidateAllProperties(); if (HasErrors) { return; } await _sampleDataService.SaveOrderAsync(new SampleOrder() { OrderID = OrderID, OrderDate = new DateTime(OrderDate.Year, OrderDate.Month, OrderDate.Day, OrderTime.Hours, OrderTime.Minutes, OrderTime.Seconds), ShipperName = ShipperName, ShipperPhone = ShipperPhone, Company = Company, ShipTo = ShipTo, OrderTotal = double.Parse(OrderTotal), Status = Status, Freight = double.Parse(Freight), SymbolCode = Symbol.Code, SymbolName = Symbol.Name, }); // Set default values OrderID = default; OrderDate = DateTime.Now; OrderTime = DateTime.Now.TimeOfDay; ShipperName = string.Empty; ShipperPhone = string.Empty; Company = string.Empty; ShipTo = string.Empty; OrderTotal = default; Freight = default; Status = StatusValues.First(); Symbol = SymbolValues.First(); ClearErrors(); } public static ValidationResult ValidateDoubleProperty(string property) => double.TryParse(property, out var result) ? ValidationResult.Success : new ValidationResult("Double property required"); }
29.044693
141
0.599154
[ "MIT" ]
Microsoft/WindowsTemplateStudio
code/TemplateStudioForWinUICs/Templates/Pg/Form/Param_ProjectName/ViewModels/Param_ItemNameViewModel.cs
5,023
C#
using System; namespace KaiHeiLa.Commands { // Cosmetic Summary, for Groups and Commands /// <summary> /// Attaches a summary to your command. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class SummaryAttribute : Attribute { public string Text { get; } public SummaryAttribute(string text) { Text = text; } } }
25.35
140
0.635108
[ "MIT" ]
gehongyan/KaiHeiLa.Net
src/KaiHeiLa.Net.Commands/Attributes/SummaryAttribute.cs
507
C#
#if UNITY_EDITOR using UnityEditor; #endif using System; namespace UnityEngine.Rendering { /// <summary> /// Data-Driven Lens Flare can be added on any gameobeject /// </summary> [ExecuteAlways] [AddComponentMenu("Rendering/Lens Flare (SRP)")] public sealed class LensFlareComponentSRP : MonoBehaviour { [SerializeField] private LensFlareDataSRP m_LensFlareData = null; /// <summary> /// Lens flare asset used on this component /// </summary> public LensFlareDataSRP lensFlareData { get { return m_LensFlareData; } set { m_LensFlareData = value; OnValidate(); } } /// <summary> /// Intensity /// </summary> [Min(0.0f)] public float intensity = 1.0f; /// <summary> /// Distance used to scale the Distance Attenuation Curve /// </summary> [Min(1e-5f)] public float maxAttenuationDistance = 100.0f; /// <summary> /// Distance used to scale the Scale Attenuation Curve /// </summary> [Min(1e-5f)] public float maxAttenuationScale = 100.0f; /// <summary> /// Attenuation by distance /// </summary> public AnimationCurve distanceAttenuationCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 0.0f)); /// <summary> /// Scale by distance, use the same distance as distanceAttenuationCurve /// </summary> public AnimationCurve scaleByDistanceCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 0.0f)); /// <summary> /// If component attached to a light, attenuation the lens flare per light type /// </summary> public bool attenuationByLightShape = true; /// <summary> /// Attenuation used radially, which allow for instance to enable flare only on the edge of the screen /// </summary> public AnimationCurve radialScreenAttenuationCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f)); /// <summary> /// Enable Occlusion feature /// </summary> public bool useOcclusion = false; /// <summary> /// Radius around the light used to occlude the flare (value in world space) /// </summary> [Min(0.0f)] public float occlusionRadius = 0.1f; /// <summary> /// Random Samples Count used inside the disk with 'occlusionRadius' /// </summary> [Range(1, 64)] public uint sampleCount = 32; /// <summary> /// Z Occlusion Offset allow us to offset the plane where the disc of occlusion is place (closer to camera), value on world space. /// Useful for instance to sample occlusion outside a light bulb if we place a flare inside the light bulb /// </summary> public float occlusionOffset = 0.05f; /// <summary> /// Global Scale /// </summary> [Min(0.0f)] public float scale = 1.0f; /// <summary> /// If allowOffScreen is true then If the lens flare is outside the screen we still emit the flare on screen /// </summary> public bool allowOffScreen = false; /// Our default celestial body will have an angular radius of 3.3 degrees. This is an arbitrary number, but must be kept constant /// so the occlusion radius for direct lights is consistent regardless of near / far clip plane configuration. private static float sCelestialAngularRadius = 3.3f * Mathf.PI / 180.0f; /// <summary> /// Retrieves the projected occlusion radius from a particular celestial in the infinity plane with an angular radius. /// This is used for directional lights which require to have consistent occlusion radius regardless of the near/farplane configuration. /// <param name="mainCam">The camera utilized to calculate the occlusion radius</param> /// <return>The value, in world units, of the occlusion angular radius.</return> /// </summary> public float celestialProjectedOcclusionRadius(Camera mainCam) { float projectedRadius = (float)Math.Tan(sCelestialAngularRadius) * mainCam.farClipPlane; return occlusionRadius * projectedRadius; } /// <summary> /// Add or remove the lens flare to the queue of PostProcess /// </summary> void OnEnable() { if (lensFlareData) LensFlareCommonSRP.Instance.AddData(this); else LensFlareCommonSRP.Instance.RemoveData(this); } /// <summary> /// Remove the lens flare from the queue of PostProcess /// </summary> void OnDisable() { LensFlareCommonSRP.Instance.RemoveData(this); } /// <summary> /// Add or remove the lens flare from the queue of PostProcess /// </summary> void OnValidate() { if (isActiveAndEnabled && lensFlareData != null) { LensFlareCommonSRP.Instance.AddData(this); } else { LensFlareCommonSRP.Instance.RemoveData(this); } } #if UNITY_EDITOR private float sDebugClippingSafePercentage = 0.9f; //for debug gizmo, only push 90% further so we avoid clipping of debug lines. void OnDrawGizmosSelected() { Camera mainCam = Camera.current; if (mainCam != null && useOcclusion) { Vector3 positionWS; float adjustedOcclusionRadius = occlusionRadius; Light light = GetComponent<Light>(); if (light != null && light.type == LightType.Directional) { positionWS = -transform.forward * (mainCam.farClipPlane * sDebugClippingSafePercentage) + mainCam.transform.position; adjustedOcclusionRadius = celestialProjectedOcclusionRadius(mainCam); } else { positionWS = transform.position; } Color previousH = Handles.color; Color previousG = Gizmos.color; Handles.color = Color.red; Gizmos.color = Color.red; Vector3 dir = (mainCam.transform.position - positionWS).normalized; Handles.DrawWireDisc(positionWS + dir * occlusionOffset, dir, adjustedOcclusionRadius, 1.0f); Gizmos.DrawWireSphere(positionWS, occlusionOffset); Gizmos.color = previousG; Handles.color = previousH; } } #endif } }
38.405556
144
0.580934
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.core@12.1.3/Runtime/PostProcessing/LensFlareComponentSRP.cs
6,913
C#
using System; using UltimaOnline.Items; using UltimaOnline.Engines.MLQuests.Items; namespace UltimaOnline.Items { public class BoneMachete : ElvenMachete, ITicket { public override WeaponAbility PrimaryAbility { get { return null; } } public override WeaponAbility SecondaryAbility { get { return null; } } public override int PhysicalResistance { get { return 1; } } public override int FireResistance { get { return 1; } } public override int ColdResistance { get { return 1; } } public override int PoisonResistance { get { return 1; } } public override int EnergyResistance { get { return 1; } } public override int InitMinHits { get { return 5; } } public override int InitMaxHits { get { return 5; } } [Constructable] public BoneMachete() { ItemID = 0x20E; } public BoneMachete( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } #region ITicket Members public void OnTicketUsed( Mobile from ) { if ( Utility.RandomDouble() < 0.25 ) { from.SendLocalizedMessage( 1075007 ); // Your bone handled machete snaps in half as you force your way through the poisonous undergrowth. Delete(); } else { from.SendLocalizedMessage( 1075008 ); // Your bone handled machete has grown dull but you still manage to force your way past the venomous branches. } } #endregion } }
26.328125
153
0.672997
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Weapons/Swords/BoneMachete.cs
1,685
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers * for more information concerning the license and the contributors participating to this project. */ using System; using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.AspNetCore.Http; using static AspNet.Security.OAuth.Salesforce.SalesforceAuthenticationConstants; namespace AspNet.Security.OAuth.Salesforce { /// <summary> /// Defines a set of options used by <see cref="SalesforceAuthenticationHandler"/>. /// </summary> public class SalesforceAuthenticationOptions : OAuthOptions { public SalesforceAuthenticationOptions() { ClaimsIssuer = SalesforceAuthenticationDefaults.Issuer; CallbackPath = new PathString(SalesforceAuthenticationDefaults.CallbackPath); Environment = SalesforceAuthenticationDefaults.Environment; ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "user_id"); ClaimActions.MapJsonKey(ClaimTypes.Name, "username"); ClaimActions.MapJsonKey(Claims.Email, "email"); ClaimActions.MapJsonKey(Claims.UtcOffset, "utcOffset"); ClaimActions.MapJsonSubKey(Claims.RestUrl, "urls", "rest"); ClaimActions.MapJsonSubKey(Claims.ThumbnailPhoto, "photos", "thumbnail"); } public SalesforceAuthenticationEnvironment Environment { set { switch (value) { case SalesforceAuthenticationEnvironment.Production: AuthorizationEndpoint = SalesforceAuthenticationDefaults.Production.AuthorizationEndpoint; TokenEndpoint = SalesforceAuthenticationDefaults.Production.TokenEndpoint; break; case SalesforceAuthenticationEnvironment.Test: AuthorizationEndpoint = SalesforceAuthenticationDefaults.Test.AuthorizationEndpoint; TokenEndpoint = SalesforceAuthenticationDefaults.Test.TokenEndpoint; break; default: throw new ArgumentOutOfRangeException(nameof(value), value, "Unsupported Salesforce environment"); } } } } }
41.166667
122
0.666397
[ "Apache-2.0" ]
dealarconjose/AspNet.Security.OAuth.Providers
src/AspNet.Security.OAuth.Salesforce/SalesforceAuthenticationOptions.cs
2,470
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="GetNodeProtocolInfoResponse.cs" company="Martin Karlsson"> // Copyright (c) Martin Karlsson. All rights reserved. // </copyright> // ------------------------------------------------------------------------------------------------- namespace ZWaveSerialApi.Functions.ZWave { public record GetNodeProtocolInfoResponse(bool Listening); }
46.3
101
0.436285
[ "MIT" ]
martin-repo/zwaveserialapi
src/ZWaveSerialApi/Functions/ZWave/GetNodeProtocolInfoResponse.cs
465
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using BellDetectWpf.Enums; using BellDetectWpf.Repository; namespace BellDetectWpf.ViewModels { public partial class ButterworthVM : INotifyPropertyChanged { // Events public event PropertyChangedEventHandler PropertyChanged; // Observable properties public string WavFilePathName { get { return Repo.WavFilePathName; } set { if (Repo.WavFilePathName != value) { Repo.WavFilePathName = value; NotifyPropertyChanged(); } } } public FilterButterworthEnum FilterButterworth { get { return Repo.FilterButterworth; } set { if (Repo.FilterButterworth != value) { Repo.FilterButterworth = value; NotifyPropertyChanged(); } } } public string ButterworthFilePathName { get { return Repo.ButterworthFilePathName; } set { if (Repo.ButterworthFilePathName != value) { Repo.ButterworthFilePathName = value; NotifyPropertyChanged(); } } } public string ButterworthStatus { get { return Repo.ButterworthStatus; } set { if (Repo.ButterworthStatus != value) { Repo.ButterworthStatus = value; NotifyPropertyChanged(); } } } // Notification method public void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
24.354839
86
0.483444
[ "MIT" ]
tjbarnes23/BellDetectWpf
BellDetectWpf/ViewModels/Butterworth/ButterworthVM.cs
2,267
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 04.07.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.DateOnly.NullableDateOnly{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.DateOnly; using T_DATA2 =System.Nullable<System.DateOnly>; using T_DATA1_U=System.DateOnly; using T_DATA2_U=System.DateOnly; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__02__VN public static class TestSet_001__fields__02__VN { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_TYPE_DATE"; private const string c_NameOf__COL_DATA2 ="COL2_TYPE_DATE"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 c_value1=new T_DATA1_U(2021,05,11); System.Int64? testID=Helper__InsertRow(db,c_value1,null); var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (null, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 c_value1=new T_DATA1_U(2021,05,11); System.Int64? testID=Helper__InsertRow(db,c_value1,null); var recs=db.testTable.Where(r => !(((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r //! \todo [2021-05-16] I think, query may be better (without col2 is not null): "(col1=col2) and test_id=?" db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" = ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t",c_NameOf__COL_DATA2).IS_NOT_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__02__VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.DateOnly.NullableDateOnly
31.255319
205
0.567903
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete2__objs/DateOnly/NullableDateOnly/TestSet_001__fields__02__VN.cs
5,878
C#
using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; namespace LeptonicaSharp { public partial class _All { // textops.c (115, 1) // pixAddSingleTextblock(pixs, bmf, textstr, val, location, poverflow) as Pix // pixAddSingleTextblock(PIX *, L_BMF *, const char *, l_uint32, l_int32, l_int32 *) as PIX * /// <summary> /// (1) This function paints a set of lines of text over an image. /// If %location is L_ADD_ABOVE or L_ADD_BELOW, the pix size /// is expanded with a border and rendered over the border.<para/> /// /// (2) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc.<para/> /// /// (3) If textstr == NULL, use the text field in the pix.<para/> /// /// (4) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it.<para/> /// /// (5) Typical usage is for labelling a pix with some text data. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixAddSingleTextblock/*"/> /// <param name="pixs">[in] - input pix colormap ok</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="textstr">[in][optional] - text string to be added</param> /// <param name="val">[in] - color to set the text</param> /// <param name="location">[in] - L_ADD_ABOVE, L_ADD_AT_TOP, L_ADD_AT_BOT, L_ADD_BELOW</param> /// <param name="poverflow">[out][optional] - 1 if text overflows allocated region and is clipped 0 otherwise</param> /// <returns>pixd new pix with rendered text, or either a copy or NULL on error</returns> public static Pix pixAddSingleTextblock( Pix pixs, L_Bmf bmf, String textstr, uint val, int location, out int poverflow) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} IntPtr _Result = Natives.pixAddSingleTextblock(pixs.Pointer, bmf.Pointer, textstr, val, location, out poverflow); if (_Result == IntPtr.Zero) {return null;} return new Pix(_Result); } // textops.c (270, 1) // pixAddTextlines(pixs, bmf, textstr, val, location) as Pix // pixAddTextlines(PIX *, L_BMF *, const char *, l_uint32, l_int32) as PIX * /// <summary> /// (1) This function expands an image as required to paint one or /// more lines of text adjacent to the image. If %bmf == NULL, /// this returns a copy. If above or below, the lines are /// centered with respect to the image if left or right, they /// are left justified.<para/> /// /// (2) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc.<para/> /// /// (3) If textstr == NULL, use the text field in the pix. The /// text field contains one or most "lines" of text, where newlines /// are used as line separators.<para/> /// /// (4) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it.<para/> /// /// (5) Typical usage is for labelling a pix with some text data. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixAddTextlines/*"/> /// <param name="pixs">[in] - input pix colormap ok</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="textstr">[in][optional] - text string to be added</param> /// <param name="val">[in] - color to set the text</param> /// <param name="location">[in] - L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT</param> /// <returns>pixd new pix with rendered text, or either a copy or NULL on error</returns> public static Pix pixAddTextlines( Pix pixs, L_Bmf bmf, String textstr, uint val, int location) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} IntPtr _Result = Natives.pixAddTextlines(pixs.Pointer, bmf.Pointer, textstr, val, location); if (_Result == IntPtr.Zero) {return null;} return new Pix(_Result); } // textops.c (431, 1) // pixSetTextblock(pixs, bmf, textstr, val, x0, y0, wtext, firstindent, poverflow) as int // pixSetTextblock(PIX *, L_BMF *, const char *, l_uint32, l_int32, l_int32, l_int32, l_int32, l_int32 *) as l_ok /// <summary> /// (1) This function paints a set of lines of text over an image.<para/> /// /// (2) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc. /// The last two hex digits are 00 (byte value 0), assigned to /// the A component. Note that, as usual, RGBA proceeds from /// left to right in the order from MSB to LSB (see pix.h /// for details).<para/> /// /// (3) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixSetTextblock/*"/> /// <param name="pixs">[in] - input image</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="textstr">[in] - block text string to be set</param> /// <param name="val">[in] - color to set the text</param> /// <param name="x0">[in] - left edge for each line of text</param> /// <param name="y0">[in] - baseline location for the first text line</param> /// <param name="wtext">[in] - max width of each line of generated text</param> /// <param name="firstindent">[in] - indentation of first line, in x-widths</param> /// <param name="poverflow">[out][optional] - 0 if text is contained in input pix 1 if it is clipped</param> /// <returns>0 if OK, 1 on error</returns> public static int pixSetTextblock( Pix pixs, L_Bmf bmf, String textstr, uint val, int x0, int y0, int wtext, int firstindent, out int poverflow) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} int _Result = Natives.pixSetTextblock(pixs.Pointer, bmf.Pointer, textstr, val, x0, y0, wtext, firstindent, out poverflow); return _Result; } // textops.c (544, 1) // pixSetTextline(pixs, bmf, textstr, val, x0, y0, pwidth, poverflow) as int // pixSetTextline(PIX *, L_BMF *, const char *, l_uint32, l_int32, l_int32, l_int32 *, l_int32 *) as l_ok /// <summary> /// (1) This function paints a line of text over an image.<para/> /// /// (2) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc. /// The last two hex digits are 00 (byte value 0), assigned to /// the A component. Note that, as usual, RGBA proceeds from /// left to right in the order from MSB to LSB (see pix.h /// for details).<para/> /// /// (3) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixSetTextline/*"/> /// <param name="pixs">[in] - input image</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="textstr">[in] - text string to be set on the line</param> /// <param name="val">[in] - color to set the text</param> /// <param name="x0">[in] - left edge for first char</param> /// <param name="y0">[in] - baseline location for all text on line</param> /// <param name="pwidth">[out][optional] - width of generated text</param> /// <param name="poverflow">[out][optional] - 0 if text is contained in input pix 1 if it is clipped</param> /// <returns>0 if OK, 1 on error</returns> public static int pixSetTextline( Pix pixs, L_Bmf bmf, String textstr, uint val, int x0, int y0, out int pwidth, out int poverflow) { if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} int _Result = Natives.pixSetTextline(pixs.Pointer, bmf.Pointer, textstr, val, x0, y0, out pwidth, out poverflow); return _Result; } // textops.c (641, 1) // pixaAddTextNumber(pixas, bmf, na, val, location) as Pixa // pixaAddTextNumber(PIXA *, L_BMF *, NUMA *, l_uint32, l_int32) as PIXA * /// <summary> /// (1) Typical usage is for labelling each pix in a pixa with a number.<para/> /// /// (2) This function paints numbers external to each pix, in a position /// given by %location. In all cases, the pix is expanded on /// on side and the number is painted over white in the added region.<para/> /// /// (3) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc.<para/> /// /// (4) If na == NULL, number each pix sequentially, starting with 1.<para/> /// /// (5) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixaAddTextNumber/*"/> /// <param name="pixas">[in] - input pixa colormap ok</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="na">[in][optional] - number array use 1 ... n if null</param> /// <param name="val">[in] - color to set the text</param> /// <param name="location">[in] - L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT</param> /// <returns>pixad new pixa with rendered numbers, or NULL on error</returns> public static Pixa pixaAddTextNumber( Pixa pixas, L_Bmf bmf, Numa na, uint val, int location) { if (pixas == null) {throw new ArgumentNullException ("pixas cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} IntPtr naPtr = IntPtr.Zero; if (na != null) {naPtr = na.Pointer;} IntPtr _Result = Natives.pixaAddTextNumber(pixas.Pointer, bmf.Pointer, naPtr, val, location); if (_Result == IntPtr.Zero) {return null;} return new Pixa(_Result); } // textops.c (710, 1) // pixaAddTextlines(pixas, bmf, sa, val, location) as Pixa // pixaAddTextlines(PIXA *, L_BMF *, SARRAY *, l_uint32, l_int32) as PIXA * /// <summary> /// (1) This function adds one or more lines of text externally to /// each pix, in a position given by %location. In all cases, /// the pix is expanded as necessary to accommodate the text.<para/> /// /// (2) %val is the pixel value to be painted through the font mask. /// It should be chosen to agree with the depth of pixs. /// If it is out of bounds, an intermediate value is chosen. /// For RGB, use hex notation: 0xRRGGBB00, where RR is the /// hex representation of the red intensity, etc.<para/> /// /// (3) If sa == NULL, use the text embedded in each pix. In all /// cases, newlines in the text string are used to separate the /// lines of text that are added to the pix.<para/> /// /// (4) If sa has a smaller count than pixa, issue a warning /// and do not use any embedded text.<para/> /// /// (5) If there is a colormap, this does the best it can to use /// the requested color, or something similar to it. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixaAddTextlines/*"/> /// <param name="pixas">[in] - input pixa colormap ok</param> /// <param name="bmf">[in] - bitmap font data</param> /// <param name="sa">[in][optional] - sarray use text embedded in each pix if null</param> /// <param name="val">[in] - color to set the text</param> /// <param name="location">[in] - L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT</param> /// <returns>pixad new pixa with rendered text, or NULL on error</returns> public static Pixa pixaAddTextlines( Pixa pixas, L_Bmf bmf, Sarray sa, uint val, int location) { if (pixas == null) {throw new ArgumentNullException ("pixas cannot be Nothing");} if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} IntPtr saPtr = IntPtr.Zero; if (sa != null) {saPtr = sa.Pointer;} IntPtr _Result = Natives.pixaAddTextlines(pixas.Pointer, bmf.Pointer, saPtr, val, location); if (_Result == IntPtr.Zero) {return null;} return new Pixa(_Result); } // textops.c (780, 1) // pixaAddPixWithText(pixa, pixs, reduction, bmf, textstr, val, location) as int // pixaAddPixWithText(PIXA *, PIX *, l_int32, L_BMF *, const char *, l_uint32, l_int32) as l_ok /// <summary> /// (1) This function generates a new pix with added text, and adds /// it by insertion into the pixa.<para/> /// /// (2) If the input pixs is not cmapped and not 32 bpp, it is /// converted to 32 bpp rgb. %val is a standard 32 bpp pixel, /// expressed as 0xrrggbb00. If there is a colormap, this does /// the best it can to use the requested color, or something close.<para/> /// /// (3) if %bmf == NULL, generate an 8 pt font this takes about 5 msec.<para/> /// /// (4) If %textstr == NULL, use the text field in the pix.<para/> /// /// (5) In general, the text string can be written in multiple lines /// use newlines as the separators.<para/> /// /// (6) Typical usage is for debugging, where the pixa of labeled images /// is used to generate a pdf. Suggest using 1.0 for scalefactor. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/pixaAddPixWithText/*"/> /// <param name="pixa">[in] - </param> /// <param name="pixs">[in] - any depth, colormap ok</param> /// <param name="reduction">[in] - integer subsampling factor</param> /// <param name="bmf">[in][optional] - bitmap font data</param> /// <param name="textstr">[in][optional] - text string to be added</param> /// <param name="val">[in] - color to set the text</param> /// <param name="location">[in] - L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT</param> /// <returns>0 if OK, 1 on error.</returns> public static int pixaAddPixWithText( Pixa pixa, Pix pixs, int reduction, L_Bmf bmf, String textstr, uint val, int location) { if (pixa == null) {throw new ArgumentNullException ("pixa cannot be Nothing");} if (pixs == null) {throw new ArgumentNullException ("pixs cannot be Nothing");} if (reduction < 2 || reduction > 16) { throw new ArgumentException ("integer subsampling factor");} IntPtr bmfPtr = IntPtr.Zero; if (bmf != null) {bmfPtr = bmf.Pointer;} int _Result = Natives.pixaAddPixWithText(pixa.Pointer, pixs.Pointer, reduction, bmfPtr, textstr, val, location); return _Result; } // textops.c (862, 1) // bmfGetLineStrings(bmf, textstr, maxw, firstindent, ph) as Sarray // bmfGetLineStrings(L_BMF *, const char *, l_int32, l_int32, l_int32 *) as SARRAY * /// <summary> /// (1) Divides the input text string into an array of text strings, /// each of which will fit within maxw bits of width. /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/bmfGetLineStrings/*"/> /// <param name="bmf">[in] - </param> /// <param name="textstr">[in] - </param> /// <param name="maxw">[in] - max width of a text line in pixels</param> /// <param name="firstindent">[in] - indentation of first line, in x-widths</param> /// <param name="ph">[out] - height required to hold text bitmap</param> /// <returns>sarray of text strings for each line, or NULL on error</returns> public static Sarray bmfGetLineStrings( L_Bmf bmf, String textstr, int maxw, int firstindent, out int ph) { if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} IntPtr _Result = Natives.bmfGetLineStrings(bmf.Pointer, textstr, maxw, firstindent, out ph); if (_Result == IntPtr.Zero) {return null;} return new Sarray(_Result); } // textops.c (938, 1) // bmfGetWordWidths(bmf, textstr, sa) as Numa // bmfGetWordWidths(L_BMF *, const char *, SARRAY *) as NUMA * /// <summary> /// bmfGetWordWidths() /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/bmfGetWordWidths/*"/> /// <param name="bmf">[in] - </param> /// <param name="textstr">[in] - </param> /// <param name="sa">[in] - of individual words</param> /// <returns>numa of word lengths in pixels for the font represented by the bmf, or NULL on error</returns> public static Numa bmfGetWordWidths( L_Bmf bmf, String textstr, Sarray sa) { if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} if (sa == null) {throw new ArgumentNullException ("sa cannot be Nothing");} IntPtr _Result = Natives.bmfGetWordWidths(bmf.Pointer, textstr, sa.Pointer); if (_Result == IntPtr.Zero) {return null;} return new Numa(_Result); } // textops.c (979, 1) // bmfGetStringWidth(bmf, textstr, pw) as int // bmfGetStringWidth(L_BMF *, const char *, l_int32 *) as l_ok /// <summary> /// bmfGetStringWidth() /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/bmfGetStringWidth/*"/> /// <param name="bmf">[in] - </param> /// <param name="textstr">[in] - </param> /// <param name="pw">[out] - width of text string, in pixels for the font represented by the bmf</param> /// <returns>0 if OK, 1 on error</returns> public static int bmfGetStringWidth( L_Bmf bmf, String textstr, out int pw) { if (bmf == null) {throw new ArgumentNullException ("bmf cannot be Nothing");} if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} int _Result = Natives.bmfGetStringWidth(bmf.Pointer, textstr, out pw); return _Result; } // textops.c (1023, 1) // splitStringToParagraphs(textstr, splitflag) as Sarray // splitStringToParagraphs(char *, l_int32) as SARRAY * /// <summary> /// splitStringToParagraphs() /// </summary> /// <remarks> /// </remarks> /// <include file="..\CHM_Help\IncludeComments.xml" path="Comments/splitStringToParagraphs/*"/> /// <param name="textstr">[in] - text string</param> /// <param name="splitflag">[in] - see enum in bmf.h valid values in {1,2,3}</param> /// <returns>sarray where each string is a paragraph of the input, or NULL on error.</returns> public static Sarray splitStringToParagraphs( String textstr, int splitflag) { if (textstr == null) {throw new ArgumentNullException ("textstr cannot be Nothing");} IntPtr _Result = Natives.splitStringToParagraphs( textstr, splitflag); if (_Result == IntPtr.Zero) {return null;} return new Sarray(_Result); } } }
42.197556
138
0.646798
[ "BSD-2-Clause" ]
VLunev/LeptonicaSharp
LeptonicaSharp/Functions/textops.cs
20,719
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Bicep.Core.Parsing; using Bicep.Core.Resources; using Bicep.Core.TypeSystem; namespace Bicep.Core { public static class LanguageConstants { public const string LanguageId = "bicep"; public const string LanguageFileExtension = ".bicep"; public const string JsonLanguageId = "json"; public const string JsoncLanguageId = "jsonc"; public const string ArmTemplateLanguageId = "arm-template"; // Provided by the ARM Tools VSCode extension. public const string JsonFileExtension = ".json"; public const string JsoncFileExtension = ".jsonc"; public const string ArmTemplateFileExtension = ".arm"; public const string Build = "build"; public const int MaxParameterCount = 256; public const int MaxIdentifierLength = 255; public const int MaxLiteralCharacterLimit = 131072; public const string ErrorName = "<error>"; public const string MissingName = "<missing>"; public const string TargetScopeKeyword = "targetScope"; public const string ParameterKeyword = "param"; public const string OutputKeyword = "output"; public const string VariableKeyword = "var"; public const string ResourceKeyword = "resource"; public const string ModuleKeyword = "module"; public const string ExistingKeyword = "existing"; public const string ImportKeyword = "import"; public const string FromKeyword = "from"; public const string IfKeyword = "if"; public const string ForKeyword = "for"; public const string InKeyword = "in"; public const string TargetScopeTypeTenant = "tenant"; public const string TargetScopeTypeManagementGroup = "managementGroup"; public const string TargetScopeTypeSubscription = "subscription"; public const string TargetScopeTypeResourceGroup = "resourceGroup"; public const string BicepConfigurationFileName = "bicepconfig.json"; public const string DisableNextLineDiagnosticsKeyword = "disable-next-line"; public static readonly Regex ArmTemplateSchemaRegex = new(@"https?:\/\/schema\.management\.azure\.com\/schemas\/([^""\/]+\/[a-zA-Z]*[dD]eploymentTemplate\.json)#?"); public static readonly ImmutableSortedSet<string> DeclarationKeywords = new[] { ParameterKeyword, VariableKeyword, ResourceKeyword, OutputKeyword, ModuleKeyword }.ToImmutableSortedSet(StringComparer.Ordinal); public static readonly ImmutableSortedSet<string> ContextualKeywords = DeclarationKeywords .Add(TargetScopeKeyword) .Add(IfKeyword) .Add(ForKeyword) .Add(InKeyword); public const string TrueKeyword = "true"; public const string FalseKeyword = "false"; public const string NullKeyword = "null"; public static readonly ImmutableDictionary<string, TokenType> Keywords = new Dictionary<string, TokenType>(StringComparer.Ordinal) { [TrueKeyword] = TokenType.TrueKeyword, [FalseKeyword] = TokenType.FalseKeyword, [NullKeyword] = TokenType.NullKeyword }.ToImmutableDictionary(); // Decorators public const string ParameterAllowedPropertyName = "allowed"; public const string ParameterSecurePropertyName = "secure"; public const string ParameterMinValuePropertyName = "minValue"; public const string ParameterMaxValuePropertyName = "maxValue"; public const string ParameterMinLengthPropertyName = "minLength"; public const string ParameterMaxLengthPropertyName = "maxLength"; public const string ParameterMetadataPropertyName = "metadata"; public const string MetadataDescriptionPropertyName = "description"; public const string BatchSizePropertyName = "batchSize"; // module properties public const string ModuleParamsPropertyName = "params"; public const string ModuleOutputsPropertyName = "outputs"; public const string ModuleNamePropertyName = "name"; // resource properties public const string ResourceScopePropertyName = "scope"; public const string ResourceParentPropertyName = "parent"; public const string ResourceDependsOnPropertyName = "dependsOn"; public const string ResourcePropertiesPropertyName = "properties"; // types public const string TypeNameString = "string"; public const string TypeNameModule = "module"; public static readonly StringComparer IdentifierComparer = StringComparer.Ordinal; public static readonly StringComparison IdentifierComparison = StringComparison.Ordinal; public static readonly StringComparer ResourceTypeComparer = StringComparer.OrdinalIgnoreCase; public static readonly StringComparison ResourceTypeComparison = StringComparison.OrdinalIgnoreCase; public const string StringDelimiter = "'"; public const string StringHoleOpen = "${"; public const string StringHoleClose = "}"; public const string AnyFunction = "any"; public static readonly TypeSymbol Any = new AnyType(); public static readonly TypeSymbol Never = new UnionType("never", ImmutableArray<ITypeReference>.Empty); public static readonly TypeSymbol ResourceRef = CreateResourceScopeReference(ResourceScope.Module | ResourceScope.Resource); // type used for the item type in the dependsOn array type public static readonly TypeSymbol ResourceOrResourceCollectionRefItem = TypeHelper.CreateTypeUnion( ResourceRef, new TypedArrayType(CreateResourceScopeReference(ResourceScope.Module), TypeSymbolValidationFlags.Default), new TypedArrayType(CreateResourceScopeReference(ResourceScope.Resource), TypeSymbolValidationFlags.Default)); // the type of the dependsOn property in module and resource bodies public static readonly TypeSymbol ResourceOrResourceCollectionRefArray = new TypedArrayType(ResourceOrResourceCollectionRefItem, TypeSymbolValidationFlags.Default); public static readonly TypeSymbol String = new PrimitiveType(TypeNameString, TypeSymbolValidationFlags.Default); // LooseString should be regarded as equal to the 'string' type, but with different validation behavior public static readonly TypeSymbol LooseString = new PrimitiveType(TypeNameString, TypeSymbolValidationFlags.AllowLooseStringAssignment); // SecureString should be regarded as equal to the 'string' type, but with different validation behavior public static readonly TypeSymbol SecureString = new PrimitiveType(TypeNameString, TypeSymbolValidationFlags.AllowLooseStringAssignment | TypeSymbolValidationFlags.IsSecure); public static readonly TypeSymbol Object = new ObjectType("object", TypeSymbolValidationFlags.Default, Enumerable.Empty<TypeProperty>(), LanguageConstants.Any); public static readonly TypeSymbol SecureObject = new ObjectType("object", TypeSymbolValidationFlags.Default | TypeSymbolValidationFlags.IsSecure, Enumerable.Empty<TypeProperty>(), LanguageConstants.Any); public static readonly TypeSymbol Int = new PrimitiveType("int", TypeSymbolValidationFlags.Default); public static readonly TypeSymbol Bool = new PrimitiveType("bool", TypeSymbolValidationFlags.Default); public static readonly TypeSymbol Null = new PrimitiveType(NullKeyword, TypeSymbolValidationFlags.Default); public static readonly TypeSymbol Array = new ArrayType("array"); //Type for available loadTextContent encoding public static readonly ImmutableArray<(string name, Encoding encoding)> SupportedEncodings = new[]{ ("us-ascii", Encoding.ASCII), ("iso-8859-1", Encoding.GetEncoding("iso-8859-1")), ("utf-8", Encoding.UTF8), ("utf-16BE", Encoding.BigEndianUnicode), ("utf-16", Encoding.Unicode) }.ToImmutableArray(); public static readonly TypeSymbol LoadTextContentEncodings = TypeHelper.CreateTypeUnion(SupportedEncodings.Select(s => new StringLiteralType(s.name))); // declares the description property but also allows any other property of any type public static readonly TypeSymbol ParameterModifierMetadata = new ObjectType(nameof(ParameterModifierMetadata), TypeSymbolValidationFlags.Default, CreateParameterModifierMetadataProperties(), Any, TypePropertyFlags.Constant); // types allowed to use in output and parameter declarations public static readonly ImmutableSortedDictionary<string, TypeSymbol> DeclarationTypes = new[] { String, Object, Int, Bool, Array }.ToImmutableSortedDictionary(type => type.Name, type => type, StringComparer.Ordinal); public static TypeSymbol? TryGetDeclarationType(string? typeName) { if (typeName != null && DeclarationTypes.TryGetValue(typeName, out var primitiveType)) { return primitiveType; } return null; } private static IEnumerable<TypeProperty> CreateParameterModifierMetadataProperties() { yield return new TypeProperty("description", String, TypePropertyFlags.Constant); } public static IEnumerable<string> GetResourceScopeDescriptions(ResourceScope resourceScope) { if (resourceScope == ResourceScope.None) { yield return "none"; } if (resourceScope.HasFlag(ResourceScope.Resource)) { yield return "resource"; } if (resourceScope.HasFlag(ResourceScope.Module)) { yield return "module"; } if (resourceScope.HasFlag(ResourceScope.Tenant)) { yield return "tenant"; } if (resourceScope.HasFlag(ResourceScope.ManagementGroup)) { yield return "managementGroup"; } if (resourceScope.HasFlag(ResourceScope.Subscription)) { yield return "subscription"; } if (resourceScope.HasFlag(ResourceScope.ResourceGroup)) { yield return "resourceGroup"; } } public static ResourceScopeType CreateResourceScopeReference(ResourceScope resourceScope) { var scopeDescriptions = string.Join(" | ", GetResourceScopeDescriptions(resourceScope)); return new ResourceScopeType(scopeDescriptions, resourceScope); } public static TypeSymbol CreateModuleType(IEnumerable<TypeProperty> paramsProperties, IEnumerable<TypeProperty> outputProperties, ResourceScope moduleScope, ResourceScope containingScope, string typeName) { var paramsType = new ObjectType(ModuleParamsPropertyName, TypeSymbolValidationFlags.Default, paramsProperties, null); // If none of the params are reqired, we can allow the 'params' declaration to be omitted entirely var paramsRequiredFlag = paramsProperties.Any(x => x.Flags.HasFlag(TypePropertyFlags.Required)) ? TypePropertyFlags.Required : TypePropertyFlags.None; var outputsType = new ObjectType(ModuleOutputsPropertyName, TypeSymbolValidationFlags.Default, outputProperties, null); var scopePropertyFlags = TypePropertyFlags.WriteOnly | TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.DisallowAny | TypePropertyFlags.LoopVariant; if (moduleScope != containingScope) { // If the module scope matches the parent scope, we can safely omit the scope property scopePropertyFlags |= TypePropertyFlags.Required; } var moduleBody = new ObjectType( typeName, TypeSymbolValidationFlags.Default, new[] { new TypeProperty(ModuleNamePropertyName, LanguageConstants.String, TypePropertyFlags.Required | TypePropertyFlags.DeployTimeConstant | TypePropertyFlags.ReadableAtDeployTime | TypePropertyFlags.LoopVariant), new TypeProperty(ResourceScopePropertyName, CreateResourceScopeReference(moduleScope), scopePropertyFlags), new TypeProperty(ModuleParamsPropertyName, paramsType, paramsRequiredFlag | TypePropertyFlags.WriteOnly), new TypeProperty(ModuleOutputsPropertyName, outputsType, TypePropertyFlags.ReadOnly), new TypeProperty(ResourceDependsOnPropertyName, ResourceOrResourceCollectionRefArray, TypePropertyFlags.WriteOnly | TypePropertyFlags.DisallowAny), }, null); return new ModuleType(typeName, moduleScope, moduleBody); } } }
52.903226
233
0.703506
[ "MIT" ]
AzureMentor/bicep
src/Bicep.Core/LanguageConstants.cs
13,120
C#
// Mozilla Public License 2.0 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // Copyright (C) LibreHardwareMonitor and Contributors // All Rights Reserved using System.Drawing; using System.IO; using System.Reflection; namespace LibreHardwareMonitor.Utilities { public class EmbeddedResources { public static Image GetImage(string name) { name = "LibreHardwareMonitor.Resources." + name; string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(names[i])) { // "You must keep the stream open for the lifetime of the Image." Image image = Image.FromStream(stream); // so we just create a copy of the image Bitmap bitmap = new Bitmap(image); // and dispose it right here image.Dispose(); return bitmap; } } } return new Bitmap(1, 1); } public static Icon GetIcon(string name) { name = "LibreHardwareMonitor.Resources." + name; string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames(); for (int i = 0; i < names.Length; i++) { if (names[i].Replace('\\', '.') == name) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(names[i])) { return new Icon(stream); } } } return null; } } }
33.316667
111
0.503752
[ "MPL-2.0" ]
Vargson/LibreHardwareMonitor
LibreHardwareMonitor/Utilities/EmbeddedResources.cs
1,999
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; [Serializable] public class InputVar{ public string name; public string varType; public string var; } [Serializable] public class Rule{ public string detectModuleType; [NonSerialized] public AIDetectModule detector; public InputVar[] vars; public string var1; public string ruleOperator; public string var2; public int nextModule; } [Serializable] public class ModulePacket{ public string moduleType; [NonSerialized] public AIModule mainScript; public InputVar[] vars; public Rule[] rules; } public class AI : MonoBehaviour { public ModulePacket[] modules; ModulePacket moduleRunning; void Start(){ setUpForModuleRunning(new ModulePacket(), modules[0]); } void Update(){ foreach(Rule rule in moduleRunning.rules){ ifWithString(rule.ruleOperator, rule.detector.vars[rule.var1], rule.detector.vars[rule.var2], rule.nextModule); } } void setUpForModuleRunning(ModulePacket oldModule, ModulePacket newModule){ if(oldModule.mainScript != null){ foreach(Rule rule in oldModule.rules){ Destroy(rule.detector); } Destroy(oldModule.mainScript); } moduleRunning = newModule; for(int i = 0; i < moduleRunning.rules.Length; i++){ moduleRunning.rules[i].detector = gameObject.AddComponent(Type.GetType(moduleRunning.rules[i].detectModuleType)) as AIDetectModule; foreach(InputVar inputVar in moduleRunning.rules[i].vars){ moduleRunning.rules[i].detector.vars.Add(inputVar.name, Convert.ChangeType(inputVar.var, Type.GetType(inputVar.varType))); } } moduleRunning.mainScript = gameObject.AddComponent(Type.GetType(moduleRunning.moduleType)) as AIModule; foreach(InputVar inputVar in moduleRunning.vars){ moduleRunning.mainScript.vars.Add(inputVar.name, Convert.ChangeType(inputVar.var, Type.GetType(inputVar.varType))); } } void ifWithString(string ruleOperator, dynamic var1, dynamic var2, int nextModule){ if(ruleOperator == "=="){ if(var1 == var2){ setUpForModuleRunning(moduleRunning, modules[nextModule]); } return; } if(ruleOperator == "<="){ if(var1 <= var2){ setUpForModuleRunning(moduleRunning, modules[nextModule]); } return; } if(ruleOperator == ">="){ if(var1 >= var2){ setUpForModuleRunning(moduleRunning, modules[nextModule]); } return; } if(ruleOperator == ">"){ if(var1 > var2){ setUpForModuleRunning(moduleRunning, modules[nextModule]); } return; } if(ruleOperator == "<"){ if(var1 < var2){ setUpForModuleRunning(moduleRunning, modules[nextModule]); } return; } throw new System.ArgumentException("Rule operator doesn't contain ==, <=, =>, <, or >", "Llarence's cool errors"); } }
30.719626
143
0.613021
[ "MIT" ]
Llarence/Cooked-Game
Assets/Scripts/AI.cs
3,289
C#
namespace AdminUI.STS.Identity.ViewModels.Manage { public class ShowRecoveryCodesViewModel { public string[] RecoveryCodes { get; set; } } }
12
51
0.660714
[ "MIT" ]
vbjay/IDS4-Sample
src/AdminUI/src/AdminUI.STS.Identity/ViewModels/Manage/ShowRecoveryCodesViewModel.cs
170
C#
using System; using System.Diagnostics; namespace _07._Water_Overflow { class Program { static void Main(string[] args) { int numberOfOperations = int.Parse(Console.ReadLine()); short littresWater = 0; for (int i = 0; i < numberOfOperations; i++) { short litres = short.Parse(Console.ReadLine()); bool isTankFull = littresWater + litres > 255; if(isTankFull) { Console.WriteLine("Insufficient capacity!"); } else { littresWater += litres ; } } Console.WriteLine(littresWater); } } }
24.612903
67
0.465269
[ "MIT" ]
ErsanYashar/SoftUni-C--Fundamentals
Data Types and Variables - Exercise/07. Water Overflow/Program.cs
765
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.AzureStack.Management.StorageAdmin; using Microsoft.AzureStack.Management.StorageAdmin.Models; using System.Management.Automation; namespace Microsoft.AzureStack.Commands.StorageAdmin { /// <summary> /// /// </summary> [Cmdlet(VerbsCommon.Set, Nouns.AdminManagementService, SupportsShouldProcess = true)] public sealed class SetManagementService : AdminCmdlet { /// <summary> /// Farm Identifier /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 4)] [ValidateNotNull] public string FarmName { get; set; } /// <summary> /// WacContainerGcFullScanIntervalInSeconds /// </summary> [Parameter] [SettingField] public int? WacContainerGcFullScanIntervalInSeconds { get; set; } /// <summary> /// WacAccountGcFullScanIntervalInSeconds /// </summary> [Parameter] [SettingField] public int? WacAccountGcFullScanIntervalInSeconds { get; set; } protected override void Execute() { string confirmString; ManagementServiceWritableSettings settings = Tools.ToSettingsObject<SetManagementService, ManagementServiceWritableSettings>(this, out confirmString); if (ShouldProcess( Resources.SetServiceDescription.FormatInvariantCulture(Resources.ManagementService, confirmString), Resources.SetServiceWarning.FormatInvariantCulture(Resources.ManagementService, confirmString), Resources.ShouldProcessCaption)) { ManagementServiceGetResponse result = Client.ManagementService.Patch(ResourceGroupName, FarmName, new ManagementServicePatchParameters { ManagementService = new ManagementServiceRequest { Settings = settings } }); WriteObject(new ManagementServiceResponse(result.Resource)); } } } }
43.072464
163
0.599596
[ "MIT" ]
hchungmsft/azure-powershell
src/ResourceManager/AzureStackStorage/Commands.AzureStackStorage/Service/SetManagementService.cs
2,904
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ApiManagement { /// <summary> /// Gateway hostname configuration details. /// API Version: 2019-12-01. /// </summary> [AzureNextGenResourceType("azure-nextgen:apimanagement:GatewayHostnameConfiguration")] public partial class GatewayHostnameConfiguration : Pulumi.CustomResource { /// <summary> /// Identifier of Certificate entity that will be used for TLS connection establishment /// </summary> [Output("certificateId")] public Output<string?> CertificateId { get; private set; } = null!; /// <summary> /// Hostname value. Supports valid domain name, partial or full wildcard /// </summary> [Output("hostname")] public Output<string?> Hostname { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Determines whether gateway requests client certificate /// </summary> [Output("negotiateClientCertificate")] public Output<bool?> NegotiateClientCertificate { get; private set; } = null!; /// <summary> /// Resource type for API Management resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a GatewayHostnameConfiguration 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 GatewayHostnameConfiguration(string name, GatewayHostnameConfigurationArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement:GatewayHostnameConfiguration", name, args ?? new GatewayHostnameConfigurationArgs(), MakeResourceOptions(options, "")) { } private GatewayHostnameConfiguration(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement:GatewayHostnameConfiguration", 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:apimanagement/latest:GatewayHostnameConfiguration"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201:GatewayHostnameConfiguration"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201preview:GatewayHostnameConfiguration"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20200601preview:GatewayHostnameConfiguration"}, }, }; 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 GatewayHostnameConfiguration 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 GatewayHostnameConfiguration Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new GatewayHostnameConfiguration(name, id, options); } } public sealed class GatewayHostnameConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// Identifier of Certificate entity that will be used for TLS connection establishment /// </summary> [Input("certificateId")] public Input<string>? CertificateId { get; set; } /// <summary> /// Gateway entity identifier. Must be unique in the current API Management service instance. Must not have value 'managed' /// </summary> [Input("gatewayId", required: true)] public Input<string> GatewayId { get; set; } = null!; /// <summary> /// Gateway hostname configuration identifier. Must be unique in the scope of parent Gateway entity. /// </summary> [Input("hcId")] public Input<string>? HcId { get; set; } /// <summary> /// Hostname value. Supports valid domain name, partial or full wildcard /// </summary> [Input("hostname")] public Input<string>? Hostname { get; set; } /// <summary> /// Determines whether gateway requests client certificate /// </summary> [Input("negotiateClientCertificate")] public Input<bool>? NegotiateClientCertificate { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public Input<string> ServiceName { get; set; } = null!; public GatewayHostnameConfigurationArgs() { } } }
42.385135
166
0.6249
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/GatewayHostnameConfiguration.cs
6,273
C#
using System; using System.Linq; using System.IO; using System.Reflection; using RoslynIntellisense; using Microsoft.CodeAnalysis; namespace Syntaxer { public class Test { public static void All() { var trigegr_loadig_var = csscript.Cscs_asm; // Test.SuggestUsings(); return; // Test.SignatureHelp(); return; // Test.Resolving(); // Test.AssignmentCompletion(); return; // Test.Renaming(); Test.CodeMapVSCode(); // Test.Format(); // Test.Project(); // Test.Tooltip(); // Test.CSSCompletion(); // Test.CSSResolving(); // Test.CSSResolving2(); // Test.CSSTooltipResolving(); } public static void Format() { Output.WriteLine("---"); Output.Write("Formatting: "); // $safeprojectname$ try { // var dummyWorkspace = MSBuildWorkspace.Create(); // SyntaxTree tree = CSharpSyntaxTree.ParseText(SyntaxProvider.testCode.Trim()); // SyntaxNode root = Microsoft.CodeAnalysis.Formatting.Formatter.Format(tree.GetRoot(), dummyWorkspace); RoslynIntellisense.Formatter.FormatHybrid(SyntaxProvider.testFreestyleCode, "code.cs"); Output.WriteLine("OK"); } catch (Exception e) { Output.WriteLine("failed"); Output.WriteLine(e); } } public static void CodeMapVSCode() { var script = Path.GetTempFileName(); Output.WriteLine("---"); Output.Write("CodeMap-VSCode: "); try { var code = @"//css_autoclass using System; void main() { void ttt() { } } //css_ac_end static class Extensions { static public void Convert(this string text) { } }"; File.WriteAllText(script, code); var map = SyntaxProvider.CodeMap(script, false, true); Output.WriteLine("OK"); } catch (Exception e) { Output.WriteLine("failed"); Output.WriteLine(e); } finally { try { File.Delete(script); } catch { } } } static void TestScript(Action<string> action, bool local = false) { var script = Path.GetTempFileName(); if (local) { var localFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) .PathJoin(Path.GetFileName(script)); File.Move(script, localFile); script = localFile; } try { var currDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var cscs = Path.Combine(currDir, "cscs.exe"); if (File.Exists(cscs)) csscript.cscs_path = cscs; else { cscs = Path.Combine(Path.GetDirectoryName(currDir), "cscs.exe"); if (File.Exists(cscs)) csscript.cscs_path = cscs; else csscript.cscs_path = "./cscs.exe"; } action(script); } catch (Exception e) { Output.WriteLine("failed"); Output.WriteLine(e); } finally { try { File.Delete(script); } catch { } } } public static void Project() { TestScript(script => { Output.WriteLine("---"); Output.WriteLine("Generating project: "); Project project = CSScriptHelper.GenerateProjectFor(new SourceInfo(script)); project.Files.ToList().ForEach(x => Output.WriteLine(" file: " + x)); project.Refs.ToList().ForEach(x => Output.WriteLine(" ref: " + x)); project.SearchDirs.ToList().ForEach(x => Output.WriteLine(" searchDir: " + x)); Output.WriteLine("OK - " + project.Files.Concat(project.Refs).Concat(project.SearchDirs).Count() + " project item(s)"); }); } public static void Completion() { TestScript(script => { Output.WriteLine("---"); Console.Write("Autocompletion: "); string code = SyntaxProvider.testCode7b; File.WriteAllText(script, code); var caret = code.IndexOf("info.ver") + "info.ver".Length; string word = code.WordAt(caret); var completions = TestServices.GetCompletion(script, caret); Output.WriteLine("OK - " + completions.Count() + " completion item(s)..."); Output.WriteLine(" '" + completions.GetLines().FirstOrDefault(x => x.StartsWith(word)) + "'"); }); } public static void AssignmentCompletion() { TestScript(script => { Output.WriteLine("---"); Console.Write("AssignmentCompletion: "); string code = SyntaxProvider.testCode7b; // System.IO.StreamReader file = File.WriteAllText(script, code); var pattern = "System.IO.StreamReader file ="; pattern = "f.DialogResult ="; pattern = "Form form ="; pattern = "Form form = new"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var completions = TestServices.GetCompletion(script, caret); Output.WriteLine("OK - " + completions.Count() + " completion item(s)..."); Output.WriteLine(" '" + completions.GetLines().FirstOrDefault(x => x.StartsWith(word)) + "'"); }); } public static void CSSCompletion() { TestScript(script => { Console.Write("CS-Script Autocompletion: "); File.WriteAllText(script, " //css_inc test.cs"); var caret = 5; var completions = SyntaxProvider.GetCompletion(script, caret); Output.WriteLine("OK"); caret = 12; completions = SyntaxProvider.GetCompletion(script, caret); File.WriteAllText(script, " //css_inc cmd.cs"); caret = 12; completions = SyntaxProvider.GetCompletion(script, caret); caret = 15; completions = SyntaxProvider.GetCompletion(script, caret); // Console.WriteLine(" '" + completions.Split('\n').FirstOrDefault(x => x.StartsWith(word)) + "'"); }, local: true); } // static void TestCSSCompletion2() // { // TestScript(script => // { // Console.Write("CS-Script 'Include' Autocompletion: "); // string code = " //css_inc test.cs"; // File.WriteAllText(script, code); // var caret = 12; // var completions = SyntaxProvider.GetCompletion(script, caret); // Console.WriteLine("OK"); // caret = 12; // var word = code.WordAt(caret, true); // var line = code.LineAt(caret); // completions = SyntaxProvider.GetCompletion(script, caret); // // Console.WriteLine(" '" + completions.Split('\n').FirstOrDefault(x => x.StartsWith(word)) + "'"); // }); // } public static void CSSResolving() { TestScript(script => { Output.Write("Resolve CS-Script symbol: "); string code = " //css_ref test.dll;"; File.WriteAllText(script, code); var caret = 5; var info = TestServices.Resolve(script, caret); Output.WriteLine("OK"); }); } public static void CSSResolving2() { TestScript(script => { Output.Write("Resolve CS-Script symbol: "); string code = "//css_inc cmd.cs;"; // string code = "//css_ref cmd.dll;"; File.WriteAllText(script, code); var caret = 13; var info = TestServices.Resolve(script, caret); Output.WriteLine(info); Output.WriteLine("OK"); }); } public static void CSSTooltipResolving() { TestScript(script => { Output.Write("Resolve CS-Script symbol to tooltip: "); // string code = " //css_ref test.dll;"; string code = " //css_inc cmd.cs;"; File.WriteAllText(script, code); var caret = 13; // var caret = 5; string info = TestServices.GetTooltip(script, caret, null, true); Output.WriteLine(info); Output.WriteLine("OK"); }); } public static void Resolving() { TestScript(script => { Output.WriteLine("---"); Output.Write("Resolve symbol: "); string code = SyntaxProvider.testCode7b; File.WriteAllText(script, code); var pattern = "Console.Write"; // pattern = "info.ver"; pattern = "System.IO.StreamReader fi"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var region = TestServices.Resolve(script, caret); Output.WriteLine("OK - " + 1 + " symbol info item(s)..."); Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'"); }); } public static void Renaming() { TestScript(script => { Output.WriteLine("---"); Output.Write("Generate renaming info: "); string code = SyntaxProvider.testCodeClass; File.WriteAllText(script, code); var pattern = "class Scr"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var region = TestServices.FindRefreneces(script, caret, "all"); Output.WriteLine("OK - " + 1 + " symbol info item(s)..."); Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'"); }); } public static void SignatureHelp() { TestScript(script => { Output.WriteLine("---"); Output.Write("Generate signature help: "); string code = @"using System; class Program { static void Main(string[] args) { Console.WriteLine(22 // Console.WriteLine(5.ToString(), 33, } }"; // Console.WriteLine(22, File.WriteAllText(script, code); // var pattern = "WriteLine("; var pattern = "22"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var region = TestServices.GetSignatureHelp(script, caret); Output.WriteLine("OK - " + 1 + " symbol info item(s)..."); Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'"); }); } public static void SuggestUsings() { TestScript(script => { Output.WriteLine("---"); Output.Write("SuggestUsings: "); string code = @"using System; class Program { static void Main(string[] args) { File } }"; File.WriteAllText(script, code); var pattern = "File"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var region = TestServices.FindUsings(script, "File"); Output.WriteLine("OK - " + 1 + " symbol info item(s)..."); Output.WriteLine(" '" + region.GetLines().FirstOrDefault() + "'"); }); } public static void Tooltip() { TestScript(script => { Output.WriteLine("---"); Output.Write("Get tooltip: "); string code = SyntaxProvider.testCode7b; File.WriteAllText(script, code); var pattern = "Console.Write"; // pattern = "info.ver"; var caret = code.IndexOf(pattern) + pattern.Length; string word = code.WordAt(caret); var tooltip = TestServices.GetTooltip(script, caret, null, true); Output.WriteLine("OK"); Output.WriteLine(" '" + tooltip.GetLines().FirstOrDefault() + "'"); }); } } }
30.874429
135
0.47911
[ "MIT" ]
oleg-shilo/syntaxer
Test.cs
13,523
C#
// MIT License - Copyright (c) Callum McGing // This file is subject to the terms and conditions defined in // LICENSE, which is part of this source code package using System; using System.Numerics; using ImGuiNET; using LibreLancer; using LibreLancer.Interface; using LibreLancer.GameData; using LibreLancer.ImUI; namespace SystemViewer { public class SystemMap { private UiContext ctx; private Navmap navmap; private MainWindow win; public void CreateContext(MainWindow window) { var uidata = new UiData(); uidata.FileSystem = window.GameData.VFS; uidata.Fonts = window.GetService<FontManager>(); uidata.ResourceManager = window.Resources; ctx = new UiContext(uidata); ctx.RenderState = window.RenderState; ctx.Renderer2D = window.Renderer2D; navmap = new Navmap(); navmap.Width = 480; navmap.Height = 480; navmap.LetterMargin = true; navmap.MapBorder = true; ctx.SetWidget(navmap); this.win = window; } public void SetObjects(StarSystem sys) { navmap.PopulateIcons(ctx, sys); } private RenderTarget2D rtarget; private int rw = -1, rh = -1, rt = -1; public void Draw(int width, int height) { //Set viewport height -= 30; if (width <= 0) width = 1; if (height <= 0) height = 1; if (width != rw || height != rh) { if (rtarget != null) { ImGuiHelper.DeregisterTexture(rtarget.Texture); rtarget.Dispose(); } rtarget = new RenderTarget2D(width, height); rw = width; rh = height; rt = ImGuiHelper.RegisterTexture(rtarget.Texture); } //Draw win.Viewport.Push(0, 0, width, height); ctx.ViewportWidth = width; ctx.ViewportHeight = height; ctx.RenderState.RenderTarget = rtarget; ctx.RenderState.ClearColor = Color4.TransparentBlack; ctx.RenderState.ClearAll(); ctx.RenderWidget(); ctx.RenderState.RenderTarget = null; win.Viewport.Pop(); //ImGui ImGui.Button("x##a"); ImGui.SameLine(); ImGui.Button("x##b"); var cpos = ImGui.GetCursorPos(); ImGui.Image((IntPtr)rt, new Vector2(width, height), new Vector2(0,1), new Vector2(1,0), Color4.White); ImGui.SetCursorPos(cpos); ImGui.InvisibleButton("##navmap", new Vector2(width, height)); } } }
33.578313
99
0.54503
[ "MIT" ]
HaydnTrigg/Librelancer
src/Editor/SystemViewer/SystemMap.cs
2,787
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2022 Senparc 文件名:ResponseMessagetTransfer_Customer_Service.cs 文件功能描述:响应回复多客服消息 创建标识:Senparc - 20150211 修改标识:Senparc - 20180924 修改描述:从 Senparc.Weixi.MP 移植并修改 ----------------------------------------------------------------*/ using Senparc.NeuChar; using Senparc.NeuChar.Entities; namespace Senparc.Weixin.WxOpen.Entities { /// <summary> /// 响应回复多客服消息 /// </summary> public class ResponseMessageTransfer_Customer_Service : ResponseMessageBase, IResponseMessageTransfer_Customer_Service { public ResponseMessageTransfer_Customer_Service() { } public override ResponseMsgType MsgType { get { return ResponseMsgType.Transfer_Customer_Service; } } } }
30.636364
119
0.642136
[ "Apache-2.0" ]
AaronWu666/WeiXinMPSDK
src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Entities/Response/ResponseMessagetTransfer_Customer_Service.cs
1,787
C#
//------------------------------------------------------------------------------ // <copyright file="ContractReference.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Discovery { using System; using System.Net; using System.Xml.Serialization; using System.Web.Services.Description; using System.IO; using System.Xml; using System.Xml.Schema; using System.Web.Services.Protocols; using System.Text; using System.Collections; using System.Threading; using System.Diagnostics; using System.Web.Services.Diagnostics; /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlRoot("contractRef", Namespace = ContractReference.Namespace)] public class ContractReference : DiscoveryReference { /// <include file='doc\contractreference.uex' path='docs/doc[@for="contractreference.namespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string Namespace = "http://schemas.xmlsoap.org/disco/scl/"; private string docRef; private string reference; /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.ContractReference"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ContractReference() { } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.ContractReference1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ContractReference(string href) { Ref = href; } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.ContractReference2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ContractReference(string href, string docRef) { Ref = href; DocRef = docRef; } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.Ref"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("ref")] public string Ref { get { return reference; } set { reference = value; } } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.DocRef"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("docRef")] public string DocRef { get { return docRef; } set { docRef = value; } } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.Url"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public override string Url { get { return Ref; } set { Ref = value; } } internal override void LoadExternals(Hashtable loadedExternals) { ServiceDescription contract = null; try { contract = Contract; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } // don't let the exception out - keep going. Just add it to the list of errors. ClientProtocol.Errors[Url] = e; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "LoadExternals", e); } if (contract != null) { foreach (XmlSchema schema in Contract.Types.Schemas) { SchemaReference.LoadExternals(schema, Url, ClientProtocol, loadedExternals); } } } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.Contract"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public ServiceDescription Contract { get { if (ClientProtocol == null) throw new InvalidOperationException(Res.GetString(Res.WebMissingClientProtocol)); object document = ClientProtocol.Documents[Url]; if (document == null) { Resolve(); document = ClientProtocol.Documents[Url]; } ServiceDescription contract = document as ServiceDescription; if (contract == null) { throw new InvalidOperationException(Res.GetString(Res.WebInvalidDocType, typeof(ServiceDescription).FullName, document == null ? string.Empty : document.GetType().FullName, Url)); } return contract; } } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.DefaultFilename"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public override string DefaultFilename { get { string fileName = MakeValidFilename(Contract.Name); if (fileName == null || fileName.Length == 0) fileName = FilenameFromUrl(Url); return Path.ChangeExtension(fileName, ".wsdl"); } } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.WriteDocument"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override void WriteDocument(object document, Stream stream) { ((ServiceDescription) document).Write(new StreamWriter(stream, new UTF8Encoding(false))); } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.ReadDocument"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override object ReadDocument(Stream stream) { return ServiceDescription.Read(stream, true); } /// <include file='doc\ContractReference.uex' path='docs/doc[@for="ContractReference.Resolve"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected internal override void Resolve(string contentType, Stream stream) { if (ContentType.IsHtml(contentType)) throw new InvalidContentTypeException(Res.GetString(Res.WebInvalidContentType, contentType), contentType); ServiceDescription serviceDescription = ClientProtocol.Documents[Url] as ServiceDescription; if ( serviceDescription == null ) { serviceDescription = ServiceDescription.Read(stream, true); serviceDescription.RetrievalUrl = Url; ClientProtocol.Documents[Url] = serviceDescription; } ClientProtocol.References[Url] = this; ArrayList importUrls = new ArrayList(); foreach (Import import in serviceDescription.Imports) if (import.Location != null) importUrls.Add(import.Location); foreach (XmlSchema schema in serviceDescription.Types.Schemas) { foreach (XmlSchemaExternal external in schema.Includes) { if (external.SchemaLocation != null && external.SchemaLocation.Length > 0) { importUrls.Add(external.SchemaLocation); } } } foreach (string urlFromImport in importUrls) { // make the (possibly) relative Uri in the contract fully qualified with respect to the contract URL string importUrl = UriToString(Url, urlFromImport); if ( ClientProtocol.Documents[importUrl] != null ) { continue; } string oldUrl = importUrl; try { stream = ClientProtocol.Download(ref importUrl, ref contentType); try { //Proceed only if not been here before if ( ClientProtocol.Documents[importUrl] == null ) { XmlTextReader reader = new XmlTextReader(new StreamReader(stream, RequestResponseUtils.GetEncoding(contentType))); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.XmlResolver = null; reader.DtdProcessing = DtdProcessing.Prohibit; //Resolve on WSDL and XSD will go recursivelly if (ServiceDescription.CanRead(reader)) { ServiceDescription doc = ServiceDescription.Read(reader, true); doc.RetrievalUrl = importUrl; ClientProtocol.Documents[importUrl] = doc; ContractReference contractReference = new ContractReference(importUrl, null); contractReference.ClientProtocol = ClientProtocol; try { contractReference.Resolve(contentType, stream); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } contractReference.Url = oldUrl; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "Resolve", e); } } else if (reader.IsStartElement("schema", XmlSchema.Namespace)) { ClientProtocol.Documents[importUrl] = XmlSchema.Read(reader, null); SchemaReference schemaReference = new SchemaReference(importUrl); schemaReference.ClientProtocol = ClientProtocol; try { schemaReference.Resolve(contentType, stream); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } schemaReference.Url = oldUrl; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "Resolve", e); } } // If it's not XML, or we don't know what kind of XML it is, skip the file. The user // will have to download the dependent file(s) manually, but at least we will continue // to discover files instead of throwing an exception. } } finally { stream.Close(); } } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } throw new InvalidDocumentContentsException(Res.GetString(Res.TheWSDLDocumentContainsLinksThatCouldNotBeResolved, importUrl), e); } } } } }
45.190647
148
0.503065
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/NetFx20/System.Web.Services/System/Web/Services/Discovery/ContractReference.cs
12,563
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20190801 { /// <summary> /// Virtual Network resource. /// </summary> [AzureNextGenResourceType("azure-nextgen:network/v20190801:VirtualNetwork")] public partial class VirtualNetwork : Pulumi.CustomResource { /// <summary> /// The AddressSpace that contains an array of IP address ranges that can be used by subnets. /// </summary> [Output("addressSpace")] public Output<Outputs.AddressSpaceResponse?> AddressSpace { get; private set; } = null!; /// <summary> /// Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET. /// </summary> [Output("bgpCommunities")] public Output<Outputs.VirtualNetworkBgpCommunitiesResponse?> BgpCommunities { get; private set; } = null!; /// <summary> /// The DDoS protection plan associated with the virtual network. /// </summary> [Output("ddosProtectionPlan")] public Output<Outputs.SubResourceResponse?> DdosProtectionPlan { get; private set; } = null!; /// <summary> /// The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. /// </summary> [Output("dhcpOptions")] public Output<Outputs.DhcpOptionsResponse?> DhcpOptions { get; private set; } = null!; /// <summary> /// Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. /// </summary> [Output("enableDdosProtection")] public Output<bool?> EnableDdosProtection { get; private set; } = null!; /// <summary> /// Indicates if VM protection is enabled for all the subnets in the virtual network. /// </summary> [Output("enableVmProtection")] public Output<bool?> EnableVmProtection { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// Resource location. /// </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!; /// <summary> /// The provisioning state of the virtual network resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The resourceGuid property of the Virtual Network resource. /// </summary> [Output("resourceGuid")] public Output<string?> ResourceGuid { get; private set; } = null!; /// <summary> /// A list of subnets in a Virtual Network. /// </summary> [Output("subnets")] public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// A list of peerings in a Virtual Network. /// </summary> [Output("virtualNetworkPeerings")] public Output<ImmutableArray<Outputs.VirtualNetworkPeeringResponse>> VirtualNetworkPeerings { get; private set; } = null!; /// <summary> /// Create a VirtualNetwork 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 VirtualNetwork(string name, VirtualNetworkArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20190801:VirtualNetwork", name, args ?? new VirtualNetworkArgs(), MakeResourceOptions(options, "")) { } private VirtualNetwork(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20190801:VirtualNetwork", 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:network:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/latest:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:VirtualNetwork"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:VirtualNetwork"}, }, }; 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 VirtualNetwork 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 VirtualNetwork Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new VirtualNetwork(name, id, options); } } public sealed class VirtualNetworkArgs : Pulumi.ResourceArgs { /// <summary> /// The AddressSpace that contains an array of IP address ranges that can be used by subnets. /// </summary> [Input("addressSpace")] public Input<Inputs.AddressSpaceArgs>? AddressSpace { get; set; } /// <summary> /// Bgp Communities sent over ExpressRoute with each route corresponding to a prefix in this VNET. /// </summary> [Input("bgpCommunities")] public Input<Inputs.VirtualNetworkBgpCommunitiesArgs>? BgpCommunities { get; set; } /// <summary> /// The DDoS protection plan associated with the virtual network. /// </summary> [Input("ddosProtectionPlan")] public Input<Inputs.SubResourceArgs>? DdosProtectionPlan { get; set; } /// <summary> /// The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network. /// </summary> [Input("dhcpOptions")] public Input<Inputs.DhcpOptionsArgs>? DhcpOptions { get; set; } /// <summary> /// Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource. /// </summary> [Input("enableDdosProtection")] public Input<bool>? EnableDdosProtection { get; set; } /// <summary> /// Indicates if VM protection is enabled for all the subnets in the virtual network. /// </summary> [Input("enableVmProtection")] public Input<bool>? EnableVmProtection { get; set; } /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The resourceGuid property of the Virtual Network resource. /// </summary> [Input("resourceGuid")] public Input<string>? ResourceGuid { get; set; } [Input("subnets")] private InputList<Inputs.SubnetArgs>? _subnets; /// <summary> /// A list of subnets in a Virtual Network. /// </summary> public InputList<Inputs.SubnetArgs> Subnets { get => _subnets ?? (_subnets = new InputList<Inputs.SubnetArgs>()); set => _subnets = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// The name of the virtual network. /// </summary> [Input("virtualNetworkName")] public Input<string>? VirtualNetworkName { get; set; } [Input("virtualNetworkPeerings")] private InputList<Inputs.VirtualNetworkPeeringArgs>? _virtualNetworkPeerings; /// <summary> /// A list of peerings in a Virtual Network. /// </summary> public InputList<Inputs.VirtualNetworkPeeringArgs> VirtualNetworkPeerings { get => _virtualNetworkPeerings ?? (_virtualNetworkPeerings = new InputList<Inputs.VirtualNetworkPeeringArgs>()); set => _virtualNetworkPeerings = value; } public VirtualNetworkArgs() { EnableDdosProtection = false; EnableVmProtection = false; } } }
45.394137
172
0.60333
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20190801/VirtualNetwork.cs
13,936
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerDummy : MovingObject { // Use this for initialization void Start () { InitializePosition(); } }
16.615385
41
0.703704
[ "MIT" ]
Graygzou/Brain-Control
Assets/Dossiers Personnels/Greg/PlaceHolder/PlayerDummy.cs
218
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glue-2017-03-31.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.Glue.Model { /// <summary> /// The encryption-at-rest settings of the transform that apply to accessing user data. /// </summary> public partial class MLUserDataEncryption { private string _kmsKeyId; private MLUserDataEncryptionModeString _mlUserDataEncryptionMode; /// <summary> /// Gets and sets the property KmsKeyId. /// <para> /// The ID for the customer-provided KMS key. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } // Check to see if KmsKeyId property is set internal bool IsSetKmsKeyId() { return this._kmsKeyId != null; } /// <summary> /// Gets and sets the property MlUserDataEncryptionMode. /// <para> /// The encryption mode applied to user data. Valid values are: /// </para> /// <ul> <li> /// <para> /// DISABLED: encryption is disabled /// </para> /// </li> <li> /// <para> /// SSEKMS: use of server-side encryption with Key Management Service (SSE-KMS) for user /// data stored in Amazon S3. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public MLUserDataEncryptionModeString MlUserDataEncryptionMode { get { return this._mlUserDataEncryptionMode; } set { this._mlUserDataEncryptionMode = value; } } // Check to see if MlUserDataEncryptionMode property is set internal bool IsSetMlUserDataEncryptionMode() { return this._mlUserDataEncryptionMode != null; } } }
31
102
0.615469
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/MLUserDataEncryption.cs
2,728
C#
using JetBrains.Rd.Tasks; using JetBrains.Rider.FSharp.TypeProviders.Protocol.Server; namespace JetBrains.ReSharper.Plugins.FSharp.TypeProviders.Host.Hosts { internal class ProvidedAssemblyHost : IOutOfProcessHost<RdProvidedAssemblyProcessModel> { private readonly TypeProvidersContext myTypeProvidersContext; public ProvidedAssemblyHost(TypeProvidersContext typeProvidersContext) => myTypeProvidersContext = typeProvidersContext; public void Initialize(RdProvidedAssemblyProcessModel model) { model.GetProvidedAssembly.Set(GetProvidedAssembly); model.GetManifestModuleContents.Set(GetManifestModuleContents); } private RdProvidedAssembly GetProvidedAssembly(int entityId) { var (providedAssembly, typeProviderId) = myTypeProvidersContext.ProvidedAssembliesCache.Get(entityId); return myTypeProvidersContext.ProvidedAssemblyRdModelsCreator.CreateRdModel(providedAssembly, typeProviderId); } private byte[] GetManifestModuleContents(int entityId) { var (providedAssembly, typeProviderId) = myTypeProvidersContext.ProvidedAssembliesCache.Get(entityId); var typeProvider = myTypeProvidersContext.TypeProvidersCache.Get(typeProviderId); return typeProvider.GetGeneratedAssemblyContents(providedAssembly.Handle); } } }
39.939394
116
0.805008
[ "Apache-2.0" ]
JetBrains/fsharp-support
ReSharper.FSharp/src/FSharp.TypeProviders.Host/src/Hosts/ProvidedAssemblyHost.cs
1,320
C#
using System; using System.Collections.Generic; using System.Net; using Microsoft.Extensions.Logging; namespace Adeotek.MicroWebServer.Example { class Program { static ILogger _logger; static void Main(string[] args) { ConsoleKeyInfo cki; var loggerFactory = LoggerFactory.Create(builder => { builder .SetMinimumLevel(LogLevel.Debug) .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddConsole(); }); _logger = loggerFactory.CreateLogger<Program>(); _logger.LogInformation("Preparing the MicroWebServer..."); var microWebServer = new MicroHttpServer( requestResponderMethod: ProcessWebRequest, routes: new List<string>() { "hello/" }, host: "localhost", port: 8080, responseType: ResponseTypes.Text, utf8: true, allowedOrigin: "*", logger: _logger ); microWebServer.Start(); while (true) { Console.WriteLine("\nCTRL+C to stop the MicroWebServer and exit."); cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.C) { break; } } } static string ProcessWebRequest(HttpListenerRequest request) { _logger.LogInformation("Request received: {url}", request.RawUrl); return "Hello world!"; } } }
30.232143
83
0.508565
[ "MIT" ]
adeotek/DotNet.MicroWebServer
src/Adeotek.MicroWebServer.Example/Program.cs
1,695
C#
#if THUNDERKIT_CONFIGURED namespace PassivePicasso.ThunderKit.Proxy { public partial class NGSS_Local : global::NGSS_Local {} } #endif
19.857143
59
0.791367
[ "MIT" ]
Jarlyk/Rain-of-Stages
Assets/RainOfStages/RoR2/GeneratedProxies/NGSS_Local.cs
139
C#
// // Copyright 2018-2020 Dynatrace LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.Generic; using System.IO; using System.IO.Compression; using System.Text; using Dynatrace.OpenKit.API; using Dynatrace.OpenKit.Core.Configuration; using Dynatrace.OpenKit.Core.Util; using Dynatrace.OpenKit.Util; using NSubstitute; using NUnit.Framework; namespace Dynatrace.OpenKit.Protocol { public class HttpClientTest { private StubHttpClient spyClient; private const string BaseUrl = "https://localhost"; private const int ServerId = 1; private const string ApplicationId = "ApplicationID"; private IAdditionalQueryParameters mockAdditionalParameters; private static readonly string MonitorUrl = BaseUrl + $"?{HttpClient.RequestTypeMobile}" + $"&{HttpClient.QueryKeyServerId}={ServerId}" + $"&{HttpClient.QueryKeyApplication}={ApplicationId}" + $"&{HttpClient.QueryKeyVersion}={ProtocolConstants.OpenKitVersion}" + $"&{HttpClient.QueryKeyPlatformType}={ProtocolConstants.PlatformTypeOpenKit}" + $"&{HttpClient.QueryKeyAgentTechnologyType}={ProtocolConstants.AgentTechnologyType}" + $"&{HttpClient.QueryKeyResponseType}={ProtocolConstants.ResponseType}"; private static readonly string NewSessionUrl = MonitorUrl + $"&{HttpClient.QueryKeyNewSession}=1"; private static readonly HttpClient.HttpResponse StatusResponse = new HttpClient.HttpResponse { ResponseCode = 200, Response = HttpClient.RequestTypeMobile, Headers = new Dictionary<string, List<string>>() }; private static readonly HttpClient.HttpResponse InvalidStatusResponseShort = new HttpClient.HttpResponse { ResponseCode = 200, Response = "type=mts", Headers = new Dictionary<string, List<string>>() }; private static readonly HttpClient.HttpResponse InvalidStatusResponseLong = new HttpClient.HttpResponse { ResponseCode = 200, Response = "type=mts&t1=-1&t2=-1", Headers = new Dictionary<string, List<string>>() }; [SetUp] public void SetUp() { // mock logger var mockLogger = Substitute.For<ILogger>(); mockLogger.IsDebugEnabled.Returns(true); mockLogger.IsInfoEnabled.Returns(true); mockLogger.IsWarnEnabled.Returns(true); mockLogger.IsErrorEnabled.Returns(true); // mock trust manager var trustManager = Substitute.For<ISSLTrustManager>(); var openKitConfig = Substitute.For<IOpenKitConfiguration>(); openKitConfig.EndpointUrl.Returns(BaseUrl); openKitConfig.DefaultServerId.Returns(ServerId); openKitConfig.ApplicationId.Returns(ApplicationId); openKitConfig.TrustManager.Returns(trustManager); var threadSuspender = Substitute.For<IInterruptibleThreadSuspender>(); // HTTPClient spy var httpConfiguration = HttpClientConfiguration.From(openKitConfig); spyClient = Substitute.ForPartsOf<StubHttpClient>(mockLogger, httpConfiguration, threadSuspender); mockAdditionalParameters = Substitute.For<IAdditionalQueryParameters>(); } [Test] public void SendStatusRequestSendsOneHttpGetRequest() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendStatusRequestSendRequestToMonitorUrl() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoGetRequest(MonitorUrl, null); } [Test] public void SendStatusRequestWorksIfResponseIsNull() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 200, Headers = headers, Response = null}); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendStatusRequestReturnsErrorCode() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 400, Headers = headers, Response = null}); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(400)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendStatusRequestIsRetriedThreeTimesBeforeGivingUp() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)) .Do(x => throw new Exception("dummy")); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(3).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendStatusRequestReturnsAnUnknownErrorResponseForWrongHttpResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); // when spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(InvalidStatusResponseShort); var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); // and when spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(InvalidStatusResponseLong); obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(2).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendStatusRequestReturnsAnUnknownErrorResponseForUnparseableStatusResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs( new HttpClient.HttpResponse { ResponseCode = 200, Headers = new Dictionary<string, List<string>>(), Response = StatusResponse.Response + "&cp=a" }); // when var obtained = target.SendStatusRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestSendsOneHttpGetRequest() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestSendRequestToNewSessionUrl() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoGetRequest(NewSessionUrl, null); } [Test] public void SendNewSessionRequestWorksIfResponseIsNull() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 200, Headers = headers, Response = null}); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestReturnsErrorCode() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 400, Headers = headers, Response = null}); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(400)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestIsRetriedThreeTimesBeforeGivingUp() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)) .Throw(new Exception("dummy")); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(3).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestReturnsAnUnknownErrorResponseForWrongHttpResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); // when spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(InvalidStatusResponseShort); var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); // and when spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs(InvalidStatusResponseLong); obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(2).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendNewSessionRequestReturnsAnUnknownErrorResponseForUnparseableStatusResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoGetRequest(string.Empty, string.Empty)).DoNotCallBase(); spyClient.DoGetRequest(string.Empty, string.Empty).ReturnsForAnyArgs( new HttpClient.HttpResponse { ResponseCode = 200, Headers = new Dictionary<string, List<string>>(), Response = StatusResponse.Response + "&cp=a" }); // when var obtained = target.SendNewSessionRequest(null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(1).DoGetRequest(string.Empty, string.Empty); } [Test] public void SendBeaconRequestSendsOneHttpPostRequest() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendBeaconRequest("175.45.176.1", new byte[] {0xba, 0xad, 0xbe, 0xef}, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.ReceivedWithAnyArgs(1).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendBeaconRequestSendsNullDataIfNullWasGiven() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendBeaconRequest("175.45.176.1", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoPostRequest(Arg.Is<string>(x => !string.IsNullOrEmpty(x)), Arg.Is<string>(x => !string.IsNullOrEmpty(x)), null); } [Test] public void SendBeaconRequestSendsGzipCompressedDataIfNonNullDataWasGiven() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendBeaconRequest("175.45.176.1", Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog"), null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoPostRequest(Arg.Is<string>(x => !string.IsNullOrEmpty(x)), Arg.Is<string>(x => !string.IsNullOrEmpty(x)), Arg.Is<byte[]>(x => Encoding.UTF8.GetString(Unzip(x)) == "The quick brown fox jumps over the lazy dog")); } [Test] public void SendBeaconRequestSendsRequestToMonitorUrl() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendBeaconRequest("192.168.0.1", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoPostRequest(Arg.Is<string>(x => x == MonitorUrl), Arg.Is<string>(x => !string.IsNullOrEmpty(x)), null); } [Test] public void SendBeaconRequestForwardsClientIp() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(StatusResponse); // when var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); spyClient.Received(1).DoPostRequest(Arg.Is<string>(x => !string.IsNullOrEmpty(x)), Arg.Is<string>(x => x == "156.33.241.5"), null); } [Test] public void SendBeaconRequestWorksIfResponseIsNull() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 200, Headers = headers, Response = null}); // when var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(200)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendBeaconRequestReturnsErrorCode() { // given var headers = new Dictionary<string, List<string>> { {"Content-Length", new List<string> {"42"} }, {"Content-Type", new List<string> { "application/json" } } }; HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(new HttpClient.HttpResponse {ResponseCode = 400, Headers = headers, Response = null}); // when var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(400)); Assert.That(((StatusResponse)obtained).Headers, Is.EqualTo(headers)); spyClient.ReceivedWithAnyArgs(1).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendBeaconRequestIsRetriedThreeTimesBeforeGivingUp() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)) .Throw(new Exception("dummy")); // when var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(3).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendBeaconRequestReturnsAnUnknownErrorResponseForWrongHttpResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); // when spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(InvalidStatusResponseShort); var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); // and when spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs(InvalidStatusResponseLong); obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(2).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendBeaconRequestReturnsAnUnknownErrorResponseForUnparseableStatusResponse() { // given HttpClient target = spyClient; spyClient.WhenForAnyArgs(x => x.DoPostRequest(string.Empty, string.Empty, null)).DoNotCallBase(); spyClient.DoPostRequest(string.Empty, string.Empty, null).ReturnsForAnyArgs( new HttpClient.HttpResponse { ResponseCode = 200, Headers = new Dictionary<string, List<string>>(), Response = StatusResponse.Response + "&cp=a" }); // when var obtained = target.SendBeaconRequest("156.33.241.5", null, null); // then Assert.That(obtained, Is.Not.Null); Assert.That(obtained.ResponseCode, Is.EqualTo(int.MaxValue)); Assert.That(((StatusResponse)obtained).Headers, Is.Empty); spyClient.ReceivedWithAnyArgs(1).DoPostRequest(string.Empty, string.Empty, null); } [Test] public void SendStatusRequestDoesNotAppendIfAdditionalQueryParametersAreNull() { // given string capturedUrl = null; spyClient.DoGetRequest(Arg.Do<string>(x => capturedUrl = x), Arg.Any<string>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendStatusRequest(null); // then var expectedUrl = InitializeBaseUrl(); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } [Test] public void SendStatusRequestAppendsAdditionalQueryParameters() { // given const long timestamp = 1234; string capturedUrl = null; mockAdditionalParameters.ConfigurationTimestamp.Returns(timestamp); spyClient.DoGetRequest(Arg.Do<string>(u => capturedUrl = u), Arg.Any<string>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendStatusRequest(mockAdditionalParameters); // then var expectedUrl = InitializeBaseUrl(); AppendUrlParameter(expectedUrl, "cts", timestamp.ToString()); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } [Test] public void SendNewSessionRequestDoesNotAppendIfAdditionalQueryParametersAreNull() { // given string capturedUrl = null; spyClient.DoGetRequest(Arg.Do<string>(u => capturedUrl = u), Arg.Any<string>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendNewSessionRequest(null); // then var expectedUrl = InitializeBaseUrl(); AppendUrlParameter(expectedUrl, "ns", "1"); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } [Test] public void SendNewSessionRequestAppendsAdditionalQueryParameters() { // given const long timestamp = 1234; mockAdditionalParameters.ConfigurationTimestamp.Returns(timestamp); string capturedUrl = null; spyClient.DoGetRequest(Arg.Do<string>(u => capturedUrl = u), Arg.Any<string>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendNewSessionRequest(mockAdditionalParameters); // then var expectedUrl = InitializeBaseUrl(); AppendUrlParameter(expectedUrl, "ns", "1"); AppendUrlParameter(expectedUrl, "cts", timestamp.ToString()); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } [Test] public void SendBeaconRequestDoesNotAppendIfAdditionalQueryParametersAreNull() { // given string capturedUrl = null; spyClient.DoPostRequest(Arg.Do<string>(u => capturedUrl = u), Arg.Any<string>(), Arg.Any<byte[]>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendBeaconRequest(null, null, null); // then var expectedUrl = InitializeBaseUrl(); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } [Test] public void SendBeaconRequestAppendsAdditionalQueryParameters() { // given const long timestamp = 1234; mockAdditionalParameters.ConfigurationTimestamp.Returns(timestamp); string capturedUrl = null; spyClient.DoPostRequest(Arg.Do<string>(u => capturedUrl = u), Arg.Any<string>(), Arg.Any<byte[]>()) .Returns(CreateSuccessHttpResponse()); // when spyClient.SendBeaconRequest(null, null, mockAdditionalParameters); // then var expectedUrl = InitializeBaseUrl(); AppendUrlParameter(expectedUrl, "cts", timestamp.ToString()); Assert.That(capturedUrl, Is.EqualTo(expectedUrl.ToString())); } private StringBuilder InitializeBaseUrl() { var builder = new StringBuilder(); builder.Append(BaseUrl).Append("?type=m"); AppendUrlParameter(builder, "srvid", ServerId.ToString()); AppendUrlParameter(builder, "app", ApplicationId); AppendUrlParameter(builder, "va", ProtocolConstants.OpenKitVersion); AppendUrlParameter(builder, "pt", ProtocolConstants.PlatformTypeOpenKit.ToString()); AppendUrlParameter(builder, "tt", ProtocolConstants.AgentTechnologyType); AppendUrlParameter(builder, "resp", ProtocolConstants.ResponseType); return builder; } private void AppendUrlParameter(StringBuilder builder, string key, string value) { builder.Append("&").Append(key).Append("=").Append(value); } private HttpClient.HttpResponse CreateSuccessHttpResponse() { return new HttpClient.HttpResponse {ResponseCode = 200, Headers = new Dictionary<string, List<string>>(), Response = null}; } /// <summary> /// Stub class for NSubstitute to work. /// </summary> public class StubHttpClient : HttpClient { public StubHttpClient(ILogger logger, IHttpClientConfiguration configuration, IInterruptibleThreadSuspender threadSuspender) : base(logger, configuration, threadSuspender) { } public virtual HttpResponse DoGetRequest(string url, string clientIpAddress) { throw new NotImplementedException(); } protected override HttpResponse GetRequest(string url, string clientIpAddress) { return DoGetRequest(url, clientIpAddress); } public virtual HttpResponse DoPostRequest(string url, string clientIpAddress, byte[] gzippedPayload) { throw new NotImplementedException(); } protected override HttpResponse PostRequest(string url, string clientIpAddress, byte[] gzippedPayload) { return DoPostRequest(url, clientIpAddress, gzippedPayload); } } private static byte[] Unzip(byte[] data) { byte[] result; using (var inputStream = new MemoryStream(data)) { using (var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress, true)) { using (var outputStream = new MemoryStream()) { gzipStream.CopyTo(outputStream); result = outputStream.ToArray(); } } } return result; } } }
40.291063
153
0.603789
[ "Apache-2.0" ]
stefaneberl/openkit-dotnet
tests/Dynatrace.OpenKit.Tests/Protocol/HttpClientTest.cs
33,363
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2019 // // 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. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// Structure specifying parameters of a newly created fence. /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct FenceCreateInfo { /// <summary> /// flags defines the initial state and behavior of the fence. Bits /// which can be set include: + -- /// </summary> public SharpVk.FenceCreateFlags? Flags { get; set; } /// <summary> /// /// </summary> internal unsafe void MarshalTo(SharpVk.Interop.FenceCreateInfo* pointer) { pointer->SType = StructureType.FenceCreateInfo; pointer->Next = null; if (this.Flags != null) { pointer->Flags = this.Flags.Value; } else { pointer->Flags = default(SharpVk.FenceCreateFlags); } } } }
35.40625
81
0.652251
[ "MIT" ]
Y-Less/SharpVk
src/SharpVk/FenceCreateInfo.gen.cs
2,266
C#
using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace DotNext.Numerics; /// <summary> /// Allows to convert bit vectors to scalar values. /// </summary> public static class BitVector { private interface IValueBuilder<TResult> where TResult : unmanaged { void SetBit(int position, bool bit); TResult Result { get; } } [StructLayout(LayoutKind.Auto)] private struct UInt32Builder : IValueBuilder<uint> { private uint result; void IValueBuilder<uint>.SetBit(int position, bool bit) => result |= (uint)bit.ToByte() << position; readonly uint IValueBuilder<uint>.Result => result; } [StructLayout(LayoutKind.Auto)] private struct UInt64Builder : IValueBuilder<ulong> { private ulong result; void IValueBuilder<ulong>.SetBit(int position, bool bit) => result |= (ulong)bit.ToByte() << position; readonly ulong IValueBuilder<ulong>.Result => result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TResult VectorToScalar<TResult, TBuilder>(ReadOnlySpan<bool> bits) where TResult : unmanaged where TBuilder : struct, IValueBuilder<TResult> { var result = new TBuilder(); ref var first = ref MemoryMarshal.GetReference(bits); for (var position = 0; position < bits.Length; position++) result.SetBit(position, Unsafe.Add(ref first, position)); return result.Result; } /// <summary> /// Converts bit vector to 8-bit unsigned integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>8-bit unsigned integer reconstructed from the bits.</returns> public static byte ToByte(ReadOnlySpan<bool> bits) => (byte)VectorToScalar<uint, UInt32Builder>(bits.TrimLength(8)); /// <summary> /// Converts bit vector to 16-bit signed integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>16-bit signed integer reconstructed from the bits.</returns> public static short ToInt16(ReadOnlySpan<bool> bits) => (short)VectorToScalar<uint, UInt32Builder>(bits.TrimLength(16)); /// <summary> /// Converts bit vector to 16-bit unsigned integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>16-bit unsigned integer reconstructed from the bits.</returns> [CLSCompliant(false)] public static ushort ToUInt16(ReadOnlySpan<bool> bits) => (ushort)VectorToScalar<uint, UInt32Builder>(bits.TrimLength(16)); /// <summary> /// Converts bit vector to 32-bit signed integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>32-bit signed integer reconstructed from the bits.</returns> public static int ToInt32(ReadOnlySpan<bool> bits) => (int)VectorToScalar<uint, UInt32Builder>(bits.TrimLength(32)); /// <summary> /// Converts bit vector to 32-bit unsigned integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>32-bit unsigned integer reconstructed from the bits.</returns> [CLSCompliant(false)] public static uint ToUInt32(ReadOnlySpan<bool> bits) => VectorToScalar<uint, UInt32Builder>(bits.TrimLength(32)); /// <summary> /// Converts bit vector to 64-bit signed integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>64-bit signed integer reconstructed from the bits.</returns> public static long ToInt64(ReadOnlySpan<bool> bits) => (long)VectorToScalar<ulong, UInt64Builder>(bits.TrimLength(64)); /// <summary> /// Converts bit vector to 64-bit unsigned integer. /// </summary> /// <param name="bits">A sequence of bits.</param> /// <returns>64-bit unsigned integer reconstructed from the bits.</returns> [CLSCompliant(false)] public static ulong ToUInt64(ReadOnlySpan<bool> bits) => VectorToScalar<ulong, UInt64Builder>(bits.TrimLength(64)); }
37.571429
111
0.64615
[ "MIT" ]
ranma42/dotNext
src/DotNext/Numerics/BitVector.cs
4,208
C#
using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.Linq; using System; // Arktoon-Shaders // // Copyright (c) 2018 synqark // // This code and repos(https://github.com/synqark/Arktoon-Shader) is under MIT licence, see LICENSE // // 本コードおよびリポジトリ(https://github.com/synqark/Arktoon-Shader) は MIT License を使用して公開しています。 // 詳細はLICENSEか、https://opensource.org/licenses/mit-license.php を参照してください。 namespace ArktoonShaders { public class ArktoonInspector : ShaderGUI { #region MaterialProperties MaterialProperty BaseTexture; MaterialProperty BaseColor; MaterialProperty Normalmap; MaterialProperty BumpScale; MaterialProperty EmissionMap; MaterialProperty EmissionColor; MaterialProperty AlphaMask; MaterialProperty BaseTextureSecondary; MaterialProperty BaseColorSecondary; MaterialProperty NormalmapSecondary; MaterialProperty BumpScaleSecondary; MaterialProperty EmissionMapSecondary; MaterialProperty EmissionColorSecondary; MaterialProperty UseEmissionParallax; MaterialProperty EmissionParallaxColor; MaterialProperty EmissionParallaxTex; MaterialProperty EmissionParallaxMask; MaterialProperty EmissionParallaxDepth; MaterialProperty EmissionParallaxDepthMask; MaterialProperty EmissionParallaxDepthMaskInvert; MaterialProperty Shadowborder; MaterialProperty ShadowborderBlur; MaterialProperty ShadowborderBlurMask; MaterialProperty ShadowStrength; MaterialProperty ShadowStrengthMask; MaterialProperty ShadowIndirectIntensity; MaterialProperty ShadowUseStep; MaterialProperty ShadowSteps; MaterialProperty PointAddIntensity; MaterialProperty PointShadowStrength; MaterialProperty PointShadowborder; MaterialProperty PointShadowborderBlur; MaterialProperty PointShadowborderBlurMask; MaterialProperty PointShadowUseStep; MaterialProperty PointShadowSteps; MaterialProperty CutoutCutoutAdjust; MaterialProperty ShadowPlanBUsePlanB; MaterialProperty ShadowPlanBDefaultShadowMix; MaterialProperty ShadowPlanBUseCustomShadowTexture; MaterialProperty ShadowPlanBHueShiftFromBase; MaterialProperty ShadowPlanBSaturationFromBase; MaterialProperty ShadowPlanBValueFromBase; MaterialProperty ShadowPlanBCustomShadowTexture; MaterialProperty ShadowPlanBCustomShadowTextureRGB; MaterialProperty CustomShadow2nd; MaterialProperty ShadowPlanB2border; MaterialProperty ShadowPlanB2borderBlur; MaterialProperty ShadowPlanB2HueShiftFromBase; MaterialProperty ShadowPlanB2SaturationFromBase; MaterialProperty ShadowPlanB2ValueFromBase; MaterialProperty ShadowPlanB2UseCustomShadowTexture; MaterialProperty ShadowPlanB2CustomShadowTexture; MaterialProperty ShadowPlanB2CustomShadowTextureRGB; MaterialProperty UseGloss; MaterialProperty GlossBlend; MaterialProperty GlossBlendMask; MaterialProperty GlossPower; MaterialProperty GlossColor; MaterialProperty UseOutline; MaterialProperty OutlineWidth; MaterialProperty OutlineMask; MaterialProperty OutlineCutoffRange; MaterialProperty OutlineColor; MaterialProperty OutlineTexture; MaterialProperty OutlineShadeMix; MaterialProperty OutlineTextureColorRate; MaterialProperty OutlineWidthMask; MaterialProperty OutlineUseColorShift; MaterialProperty OutlineHueShiftFromBase; MaterialProperty OutlineSaturationFromBase; MaterialProperty OutlineValueFromBase; MaterialProperty MatcapBlendMode; MaterialProperty MatcapBlend; MaterialProperty MatcapTexture; MaterialProperty MatcapColor; MaterialProperty MatcapBlendMask; MaterialProperty MatcapNormalMix; MaterialProperty MatcapShadeMix; MaterialProperty UseReflection; MaterialProperty UseReflectionProbe; MaterialProperty ReflectionReflectionPower; MaterialProperty ReflectionReflectionMask; MaterialProperty ReflectionNormalMix; MaterialProperty ReflectionShadeMix; MaterialProperty ReflectionCubemap; MaterialProperty ReflectionSuppressBaseColorValue; MaterialProperty RefractionFresnelExp; MaterialProperty RefractionStrength; MaterialProperty UseRim; MaterialProperty RimBlend; MaterialProperty RimBlendMask; MaterialProperty RimShadeMix; MaterialProperty RimFresnelPower; MaterialProperty RimUpperSideWidth; MaterialProperty RimColor; MaterialProperty RimTexture; MaterialProperty RimUseBaseTexture; MaterialProperty ShadowCapBlendMode; MaterialProperty ShadowCapBlend; MaterialProperty ShadowCapBlendMask; MaterialProperty ShadowCapNormalMix; MaterialProperty ShadowCapTexture; MaterialProperty StencilNumber; MaterialProperty StencilCompareAction; MaterialProperty StencilNumberSecondary; MaterialProperty StencilCompareActionSecondary; MaterialProperty StencilMaskTex; MaterialProperty StencilMaskAdjust; MaterialProperty StencilMaskAlphaDither; MaterialProperty UseDoubleSided; MaterialProperty DoubleSidedFlipBackfaceNormal; MaterialProperty DoubleSidedBackfaceLightIntensity; MaterialProperty DoubleSidedBackfaceUseColorShift; MaterialProperty DoubleSidedBackfaceHueShiftFromBase; MaterialProperty DoubleSidedBackfaceSaturationFromBase; MaterialProperty DoubleSidedBackfaceValueFromBase; MaterialProperty ShadowCasterCulling; MaterialProperty ZWrite; MaterialProperty VertexColorBlendDiffuse; MaterialProperty VertexColorBlendEmissive; MaterialProperty OtherShadowBorderSharpness; MaterialProperty OtherShadowAdjust; MaterialProperty UseVertexLight; MaterialProperty BackfaceColorMultiply; MaterialProperty LightSampling; MaterialProperty UsePositionRelatedCalc; MaterialProperty EmissiveFreak1Tex; MaterialProperty EmissiveFreak1Mask; MaterialProperty EmissiveFreak1Color; MaterialProperty EmissiveFreak1U; MaterialProperty EmissiveFreak1V; MaterialProperty EmissiveFreak1Depth; MaterialProperty EmissiveFreak1DepthMask; MaterialProperty EmissiveFreak1DepthMaskInvert; MaterialProperty EmissiveFreak1Breathing; MaterialProperty EmissiveFreak1BreathingMix; MaterialProperty EmissiveFreak1BlinkOut; MaterialProperty EmissiveFreak1BlinkOutMix; MaterialProperty EmissiveFreak1BlinkIn; MaterialProperty EmissiveFreak1BlinkInMix; MaterialProperty EmissiveFreak1HueShift; MaterialProperty EmissiveFreak2Tex; MaterialProperty EmissiveFreak2Mask; MaterialProperty EmissiveFreak2Color; MaterialProperty EmissiveFreak2U; MaterialProperty EmissiveFreak2V; MaterialProperty EmissiveFreak2Depth; MaterialProperty EmissiveFreak2DepthMask; MaterialProperty EmissiveFreak2DepthMaskInvert; MaterialProperty EmissiveFreak2Breathing; MaterialProperty EmissiveFreak2BreathingMix; MaterialProperty EmissiveFreak2BlinkOut; MaterialProperty EmissiveFreak2BlinkOutMix; MaterialProperty EmissiveFreak2BlinkIn; MaterialProperty EmissiveFreak2BlinkInMix; MaterialProperty EmissiveFreak2HueShift; // TODO: そろそろShaderUtil.GetPropertiesで一括処理したい。 // ただ、その場合は、カスタムインスペクタで定義していない追加のプロパティを、このファイルを弄らずに動的に表示できるようにしてあげたい(改変の負荷軽減のため) #endregion static bool IsShowAdvanced = false; static bool IsShowAlphaMask = false; GUIStyle style = new GUIStyle(); public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { Material material = materialEditor.target as Material; // バージョンを逐一確認して、アセットバージョンが高い場合はマテリアルをマイグレーション if( material.GetInt("_Version") < ArktoonManager.AssetVersionInt) { ArktoonMigrator.MigrateArktoonMaterial(material); } Shader shader = material.shader; // shader.nameによって調整可能なプロパティを制御する。 bool isOpaque = shader.name.Contains("Opaque"); bool isFade = shader.name.Contains("Fade"); bool isCutout = shader.name.Contains("Cutout"); bool isStencilWriter = shader.name.Contains("Stencil/Writer") || shader.name.Contains("StencilWriter"); bool isStencilReader = shader.name.Contains("Stencil/Reader") || shader.name.Contains("StencilReader"); bool isStencilReaderDouble = shader.name.Contains("Stencil/Reader/Double"); bool isStencilWriterMask = shader.name.Contains("Stencil/WriterMask"); bool isRefracted = shader.name.Contains("Refracted"); bool isEmissiveFreak = shader.name.Contains("/EmissiveFreak/"); // FindProperties BaseTexture = FindProperty("_MainTex", props, false); BaseColor = FindProperty("_Color", props, false); Normalmap = FindProperty("_BumpMap", props, false); BumpScale = FindProperty("_BumpScale", props, false); EmissionMap = FindProperty("_EmissionMap", props, false); EmissionColor = FindProperty("_EmissionColor", props, false); AlphaMask = FindProperty("_AlphaMask", props, false); BaseTextureSecondary = FindProperty("_MainTexSecondary", props, false); BaseColorSecondary = FindProperty("_ColorSecondary", props, false); NormalmapSecondary = FindProperty("_BumpMapSecondary", props, false); BumpScaleSecondary = FindProperty("_BumpScaleSecondary", props, false); EmissionMapSecondary = FindProperty("_EmissionMapSecondary", props, false); EmissionColorSecondary = FindProperty("_EmissionColorSecondary", props, false); UseEmissionParallax = FindProperty("_UseEmissionParallax", props, false); EmissionParallaxColor = FindProperty("_EmissionParallaxColor", props, false); EmissionParallaxTex = FindProperty("_EmissionParallaxTex", props, false); EmissionParallaxMask = FindProperty("_EmissionParallaxMask", props, false); EmissionParallaxDepth = FindProperty("_EmissionParallaxDepth", props, false); EmissionParallaxDepthMask = FindProperty("_EmissionParallaxDepthMask", props, false); EmissionParallaxDepthMaskInvert = FindProperty("_EmissionParallaxDepthMaskInvert", props, false); CutoutCutoutAdjust = FindProperty("_CutoutCutoutAdjust", props, false); Shadowborder = FindProperty("_Shadowborder", props, false); ShadowborderBlur = FindProperty("_ShadowborderBlur", props, false); ShadowborderBlurMask = FindProperty("_ShadowborderBlurMask", props, false); ShadowStrength = FindProperty("_ShadowStrength", props, false); ShadowStrengthMask = FindProperty("_ShadowStrengthMask", props, false); ShadowIndirectIntensity = FindProperty("_ShadowIndirectIntensity", props, false); ShadowUseStep = FindProperty("_ShadowUseStep", props, false); ShadowSteps = FindProperty("_ShadowSteps", props, false); PointAddIntensity = FindProperty("_PointAddIntensity", props, false); PointShadowStrength = FindProperty("_PointShadowStrength", props, false); PointShadowborder = FindProperty("_PointShadowborder", props, false); PointShadowborderBlur = FindProperty("_PointShadowborderBlur", props, false); PointShadowborderBlurMask= FindProperty("_PointShadowborderBlurMask", props, false); PointShadowUseStep = FindProperty("_PointShadowUseStep", props, false); PointShadowSteps = FindProperty("_PointShadowSteps", props, false); ShadowPlanBUsePlanB = FindProperty("_ShadowPlanBUsePlanB", props, false); ShadowPlanBDefaultShadowMix = FindProperty("_ShadowPlanBDefaultShadowMix", props, false); ShadowPlanBUseCustomShadowTexture = FindProperty("_ShadowPlanBUseCustomShadowTexture", props, false); ShadowPlanBHueShiftFromBase = FindProperty("_ShadowPlanBHueShiftFromBase", props, false); ShadowPlanBSaturationFromBase = FindProperty("_ShadowPlanBSaturationFromBase", props, false); ShadowPlanBValueFromBase = FindProperty("_ShadowPlanBValueFromBase", props, false); ShadowPlanBCustomShadowTexture = FindProperty("_ShadowPlanBCustomShadowTexture", props, false); ShadowPlanBCustomShadowTextureRGB = FindProperty("_ShadowPlanBCustomShadowTextureRGB", props, false); CustomShadow2nd = FindProperty("_CustomShadow2nd", props, false); ShadowPlanB2border = FindProperty("_ShadowPlanB2border", props, false); ShadowPlanB2borderBlur = FindProperty("_ShadowPlanB2borderBlur", props, false); ShadowPlanB2HueShiftFromBase = FindProperty("_ShadowPlanB2HueShiftFromBase", props, false); ShadowPlanB2SaturationFromBase = FindProperty("_ShadowPlanB2SaturationFromBase", props, false); ShadowPlanB2ValueFromBase = FindProperty("_ShadowPlanB2ValueFromBase", props, false); ShadowPlanB2UseCustomShadowTexture = FindProperty("_ShadowPlanB2UseCustomShadowTexture", props, false); ShadowPlanB2CustomShadowTexture = FindProperty("_ShadowPlanB2CustomShadowTexture", props, false); ShadowPlanB2CustomShadowTextureRGB = FindProperty("_ShadowPlanB2CustomShadowTextureRGB", props, false); UseGloss = FindProperty("_UseGloss", props, false); GlossBlend = FindProperty("_GlossBlend", props, false); GlossBlendMask = FindProperty("_GlossBlendMask", props, false); GlossPower = FindProperty("_GlossPower", props, false); GlossColor = FindProperty("_GlossColor", props, false); UseOutline = FindProperty("_UseOutline", props, false); OutlineWidth = FindProperty("_OutlineWidth", props, false); OutlineMask = FindProperty("_OutlineMask", props, false); OutlineCutoffRange = FindProperty("_OutlineCutoffRange", props, false); OutlineColor = FindProperty("_OutlineColor", props, false); OutlineTexture = FindProperty("_OutlineTexture", props, false); OutlineShadeMix = FindProperty("_OutlineShadeMix", props, false); OutlineTextureColorRate = FindProperty("_OutlineTextureColorRate", props, false); OutlineWidthMask = FindProperty("_OutlineWidthMask", props, false); OutlineUseColorShift = FindProperty("_OutlineUseColorShift", props, false); OutlineHueShiftFromBase = FindProperty("_OutlineHueShiftFromBase", props, false); OutlineSaturationFromBase = FindProperty("_OutlineSaturationFromBase", props, false); OutlineValueFromBase = FindProperty("_OutlineValueFromBase", props, false); MatcapBlendMode = FindProperty("_MatcapBlendMode", props, false); MatcapBlend = FindProperty("_MatcapBlend", props, false); MatcapTexture = FindProperty("_MatcapTexture", props, false); MatcapColor = FindProperty("_MatcapColor", props, false); MatcapBlendMask = FindProperty("_MatcapBlendMask", props, false); MatcapNormalMix = FindProperty("_MatcapNormalMix", props, false); MatcapShadeMix = FindProperty("_MatcapShadeMix", props, false); UseReflection = FindProperty("_UseReflection", props, false); UseReflectionProbe = FindProperty("_UseReflectionProbe", props, false); ReflectionReflectionPower = FindProperty("_ReflectionReflectionPower", props, false); ReflectionReflectionMask = FindProperty("_ReflectionReflectionMask", props, false); ReflectionNormalMix = FindProperty("_ReflectionNormalMix", props, false); ReflectionShadeMix = FindProperty("_ReflectionShadeMix", props, false); ReflectionCubemap = FindProperty("_ReflectionCubemap", props, false); ReflectionSuppressBaseColorValue = FindProperty("_ReflectionSuppressBaseColorValue", props, false); RefractionFresnelExp = FindProperty("_RefractionFresnelExp", props, false); RefractionStrength = FindProperty("_RefractionStrength", props, false); UseRim = FindProperty("_UseRim", props, false); RimBlend = FindProperty("_RimBlend", props, false); RimBlendMask = FindProperty("_RimBlendMask", props, false); RimShadeMix = FindProperty("_RimShadeMix", props, false); RimFresnelPower = FindProperty("_RimFresnelPower", props, false); RimUpperSideWidth = FindProperty("_RimUpperSideWidth", props, false); RimColor = FindProperty("_RimColor", props, false); RimTexture = FindProperty("_RimTexture", props, false); RimUseBaseTexture = FindProperty("_RimUseBaseTexture", props, false); ShadowCapBlendMode = FindProperty("_ShadowCapBlendMode", props, false); ShadowCapBlend = FindProperty("_ShadowCapBlend", props, false); ShadowCapBlendMask = FindProperty("_ShadowCapBlendMask", props, false); ShadowCapNormalMix = FindProperty("_ShadowCapNormalMix", props, false); ShadowCapTexture = FindProperty("_ShadowCapTexture", props, false); StencilNumber = FindProperty("_StencilNumber", props, false); StencilMaskTex = FindProperty("_StencilMaskTex", props, false); StencilMaskAdjust = FindProperty("_StencilMaskAdjust", props, false); StencilMaskAlphaDither = FindProperty("_StencilMaskAlphaDither", props, false); StencilCompareAction = FindProperty("_StencilCompareAction", props, false); StencilNumberSecondary = FindProperty("_StencilNumberSecondary", props, false); StencilCompareActionSecondary = FindProperty("_StencilCompareActionSecondary", props, false); UseDoubleSided = FindProperty("_UseDoubleSided", props, false); DoubleSidedFlipBackfaceNormal = FindProperty("_DoubleSidedFlipBackfaceNormal", props, false); DoubleSidedBackfaceLightIntensity = FindProperty("_DoubleSidedBackfaceLightIntensity", props, false); DoubleSidedBackfaceUseColorShift = FindProperty("_DoubleSidedBackfaceUseColorShift", props, false); DoubleSidedBackfaceHueShiftFromBase = FindProperty("_DoubleSidedBackfaceHueShiftFromBase", props, false); DoubleSidedBackfaceSaturationFromBase = FindProperty("_DoubleSidedBackfaceSaturationFromBase", props, false); DoubleSidedBackfaceValueFromBase = FindProperty("_DoubleSidedBackfaceValueFromBase", props, false); ShadowCasterCulling = FindProperty("_ShadowCasterCulling", props, false); VertexColorBlendDiffuse = FindProperty("_VertexColorBlendDiffuse", props, false); VertexColorBlendEmissive = FindProperty("_VertexColorBlendEmissive", props, false); OtherShadowBorderSharpness = FindProperty("_OtherShadowBorderSharpness", props, false); OtherShadowAdjust = FindProperty("_OtherShadowAdjust", props, false); UseVertexLight = FindProperty("_UseVertexLight", props, false); LightSampling = FindProperty("_LightSampling", props, false); UsePositionRelatedCalc = FindProperty("_UsePositionRelatedCalc", props, false); ZWrite = FindProperty("_ZWrite", props, false); EmissiveFreak1Tex = FindProperty("_EmissiveFreak1Tex", props, false); EmissiveFreak1Mask = FindProperty("_EmissiveFreak1Mask", props, false); EmissiveFreak1Color = FindProperty("_EmissiveFreak1Color", props, false); EmissiveFreak1U = FindProperty("_EmissiveFreak1U", props, false); EmissiveFreak1V = FindProperty("_EmissiveFreak1V", props, false); EmissiveFreak1Depth = FindProperty("_EmissiveFreak1Depth", props, false); EmissiveFreak1DepthMask = FindProperty("_EmissiveFreak1DepthMask", props, false); EmissiveFreak1DepthMaskInvert = FindProperty("_EmissiveFreak1DepthMaskInvert", props, false); EmissiveFreak1Breathing = FindProperty("_EmissiveFreak1Breathing", props, false); EmissiveFreak1BreathingMix = FindProperty("_EmissiveFreak1BreathingMix", props, false); EmissiveFreak1BlinkOut = FindProperty("_EmissiveFreak1BlinkOut", props, false); EmissiveFreak1BlinkOutMix = FindProperty("_EmissiveFreak1BlinkOutMix", props, false); EmissiveFreak1BlinkIn = FindProperty("_EmissiveFreak1BlinkIn", props, false); EmissiveFreak1BlinkInMix = FindProperty("_EmissiveFreak1BlinkInMix", props, false); EmissiveFreak1HueShift = FindProperty("_EmissiveFreak1HueShift", props, false); EmissiveFreak2Tex = FindProperty("_EmissiveFreak2Tex", props, false); EmissiveFreak2Mask = FindProperty("_EmissiveFreak2Mask", props, false); EmissiveFreak2Color = FindProperty("_EmissiveFreak2Color", props, false); EmissiveFreak2U = FindProperty("_EmissiveFreak2U", props, false); EmissiveFreak2V = FindProperty("_EmissiveFreak2V", props, false); EmissiveFreak2Depth = FindProperty("_EmissiveFreak2Depth", props, false); EmissiveFreak2DepthMask = FindProperty("_EmissiveFreak2DepthMask", props, false); EmissiveFreak2DepthMaskInvert = FindProperty("_EmissiveFreak2DepthMaskInvert", props, false); EmissiveFreak2Breathing = FindProperty("_EmissiveFreak2Breathing", props, false); EmissiveFreak2BreathingMix = FindProperty("_EmissiveFreak2BreathingMix", props, false); EmissiveFreak2BlinkOut = FindProperty("_EmissiveFreak2BlinkOut", props, false); EmissiveFreak2BlinkOutMix = FindProperty("_EmissiveFreak2BlinkOutMix", props, false); EmissiveFreak2BlinkIn = FindProperty("_EmissiveFreak2BlinkIn", props, false); EmissiveFreak2BlinkInMix = FindProperty("_EmissiveFreak2BlinkInMix", props, false); EmissiveFreak2HueShift = FindProperty("_EmissiveFreak2HueShift", props, false); EditorGUIUtility.labelWidth = 0f; EditorGUI.BeginChangeCheck(); { // Common UIHelper.ShurikenHeader("Common"); UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Main Texture", "Base Color Texture (RGB)"), BaseTexture, BaseColor); materialEditor.TextureScaleOffsetPropertyIndent(BaseTexture); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Normal Map", "Normal Map (RGB)"), Normalmap, BumpScale); materialEditor.TextureScaleOffsetPropertyIndent(Normalmap); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Emission", "Emission (RGB)"), EmissionMap, EmissionColor); materialEditor.TextureScaleOffsetPropertyIndent(EmissionMap); }); // materialEditor.ShaderProperty(Cull, "Cull"); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(UseDoubleSided, "Is Double Sided"); var doublesided = UseDoubleSided.floatValue; if(doublesided > 0){ ShadowCasterCulling.floatValue = 0; EditorGUI.indentLevel ++; materialEditor.ShaderProperty(DoubleSidedFlipBackfaceNormal, "Flip backface normal"); materialEditor.ShaderProperty(DoubleSidedBackfaceLightIntensity, "Backface Light Intensity"); materialEditor.ShaderProperty(DoubleSidedBackfaceUseColorShift, "Use Backface Color Shift"); var backfaceColorShift = DoubleSidedBackfaceUseColorShift.floatValue; if(backfaceColorShift > 0) { EditorGUI.indentLevel ++; materialEditor.ShaderProperty(DoubleSidedBackfaceHueShiftFromBase, "Hue Shift"); materialEditor.ShaderProperty(DoubleSidedBackfaceSaturationFromBase, "Saturation"); materialEditor.ShaderProperty(DoubleSidedBackfaceValueFromBase, "Value"); EditorGUI.indentLevel --; } EditorGUI.indentLevel --; } else { ShadowCasterCulling.floatValue = 2; } if(isFade) materialEditor.ShaderProperty(ZWrite, "ZWrite"); }); }); // Secondary Common if(isStencilReaderDouble) { UIHelper.ShurikenHeader("Secondary Common"); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Main Texture", "Base Color Texture (RGB)"), BaseTextureSecondary, BaseColorSecondary); materialEditor.TexturePropertySingleLine(new GUIContent("Normal Map", "Normal Map (RGB)"), NormalmapSecondary, BumpScaleSecondary); materialEditor.TexturePropertySingleLine(new GUIContent("Emission", "Emission (RGB)"), EmissionMapSecondary, EmissionColorSecondary); }); } // AlphaMask if(isFade){ IsShowAlphaMask = UIHelper.ShurikenFoldout("AlphaMask", IsShowAlphaMask); if (IsShowAlphaMask) { UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(AlphaMask, "Alpha Mask"); }); } } // Refraction if(isRefracted){ UIHelper.ShurikenHeader("Refraction"); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(RefractionFresnelExp, "Fresnel Exp"); materialEditor.ShaderProperty(RefractionStrength, "Strength"); }); } // Alpha Cutout if(isCutout){ UIHelper.ShurikenHeader("Alpha Cutout"); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(CutoutCutoutAdjust, "Cutoff Adjust"); }); } // Shadow UIHelper.ShurikenHeader("Shadow"); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(Shadowborder, "Border"); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Strength & Mask", "Strength and Mask Texture"), ShadowStrengthMask, ShadowStrength); materialEditor.TextureScaleOffsetPropertyIndent(ShadowStrengthMask); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Blur & Mask", "Blur and Mask Texture"), ShadowborderBlurMask, ShadowborderBlur); materialEditor.TextureScaleOffsetPropertyIndent(ShadowborderBlurMask); }); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(ShadowUseStep, "Use Steps"); var useStep = ShadowUseStep.floatValue; if(useStep > 0) { EditorGUI.indentLevel ++; ShadowSteps.floatValue = EditorGUILayout.IntSlider( new GUIContent("Steps"), (int)ShadowSteps.floatValue, (int)ShadowSteps.rangeLimits.x, (int)ShadowSteps.rangeLimits.y) ; EditorGUI.indentLevel --; } }); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(ShadowPlanBUsePlanB, "Use Custom Shade"); var usePlanB = ShadowPlanBUsePlanB.floatValue; if(usePlanB > 0) { EditorGUILayout.HelpBox( "[Strength] max is recommended for using custom shade." + Environment.NewLine + "Custom Shadeの使用時は[Strength]を最大値に設定することを推奨", MessageType.Info); materialEditor.ShaderProperty(ShadowPlanBDefaultShadowMix, "Mix Default Shade"); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("1st shade", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(ShadowPlanBUseCustomShadowTexture, "Use Shade Texture"); var useShadeTexture = ShadowPlanBUseCustomShadowTexture.floatValue; if(useShadeTexture > 0) { materialEditor.ShaderProperty(ShadowPlanBCustomShadowTexture, "Shade Texture"); materialEditor.ShaderProperty(ShadowPlanBCustomShadowTextureRGB, "Shade Texture RGB"); } else { materialEditor.ShaderProperty(ShadowPlanBHueShiftFromBase, "Hue Shift"); materialEditor.ShaderProperty(ShadowPlanBSaturationFromBase, "Saturation"); materialEditor.ShaderProperty(ShadowPlanBValueFromBase, "Value"); } EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("2nd shade", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(CustomShadow2nd, "Use"); var customshadow2nd = CustomShadow2nd.floatValue; if(customshadow2nd > 0) { materialEditor.ShaderProperty(ShadowPlanB2border, "Border"); materialEditor.ShaderProperty(ShadowPlanB2borderBlur, "Blur"); materialEditor.ShaderProperty(ShadowPlanB2UseCustomShadowTexture, "Use Shade Texture"); var useShadeTexture2 = ShadowPlanB2UseCustomShadowTexture.floatValue; if(useShadeTexture2 > 0) { materialEditor.ShaderProperty(ShadowPlanB2CustomShadowTexture, "Shade Texture"); materialEditor.ShaderProperty(ShadowPlanB2CustomShadowTextureRGB, "Shade Texture RGB"); }else{ materialEditor.ShaderProperty(ShadowPlanB2HueShiftFromBase, "Hue Shift"); materialEditor.ShaderProperty(ShadowPlanB2SaturationFromBase, "Saturation"); materialEditor.ShaderProperty(ShadowPlanB2ValueFromBase, "Value"); } } EditorGUI.indentLevel --; }); } }); }); // Gloss UIHelper.ShurikenHeader("Gloss"); materialEditor.DrawShaderPropertySameLIne(UseGloss); var isEnabledGloss = UseGloss.floatValue; if(isEnabledGloss > 0) { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Smoothness & Mask", "Smoothness and Mask Texture"), GlossBlendMask, GlossBlend); materialEditor.TextureScaleOffsetPropertyIndent(GlossBlendMask); }); materialEditor.ShaderProperty(GlossPower, "Metallic"); materialEditor.ShaderProperty(GlossColor, "Color"); }); } // Outline if(!isRefracted) { UIHelper.ShurikenHeader("Outline"); materialEditor.DrawShaderPropertySameLIne(UseOutline); var useOutline = UseOutline.floatValue; if(useOutline > 0) { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Width & Mask", "Width and Mask Texture"), OutlineWidthMask, OutlineWidth); materialEditor.TextureScaleOffsetPropertyIndent(OutlineWidthMask); }); UIHelper.DrawWithGroup(() => { if(!isOpaque) { materialEditor.TexturePropertySingleLine(new GUIContent("Cutoff Mask & Range", "Cutoff Mask Texture & Range"), OutlineMask, OutlineCutoffRange); materialEditor.TextureScaleOffsetPropertyIndent(OutlineMask); }else{ EditorGUILayout.LabelField("Cutoff Mask & Range","Unavailable in Opaque", EditorStyles.centeredGreyMiniLabel); } }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Texture and Color"), OutlineTexture, OutlineColor); materialEditor.TextureScaleOffsetPropertyIndent(OutlineTexture); materialEditor.ShaderProperty(OutlineTextureColorRate,"Base Color Mix"); materialEditor.ShaderProperty(OutlineUseColorShift, "Use Color Shift"); var isEnabledOutlineColorShift = OutlineUseColorShift.floatValue; if(isEnabledOutlineColorShift > 0) { EditorGUI.indentLevel ++; materialEditor.ShaderProperty(OutlineHueShiftFromBase, "Hue Shift"); materialEditor.ShaderProperty(OutlineSaturationFromBase, "Saturation"); materialEditor.ShaderProperty(OutlineValueFromBase, "Value"); EditorGUI.indentLevel --; } }); materialEditor.ShaderProperty(OutlineShadeMix,"Shadow mix"); }); } } // MatCap UIHelper.ShurikenHeader("MatCap"); materialEditor.DrawShaderPropertySameLIne(MatcapBlendMode); var useMatcap = MatcapBlendMode.floatValue; if(useMatcap != 3) // Not 'Unused' { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Blend & Mask", "Blend and Mask Texture"), MatcapBlendMask, MatcapBlend); materialEditor.TextureScaleOffsetPropertyIndent(MatcapBlendMask); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Color and Texture"), MatcapTexture, MatcapColor); materialEditor.TextureScaleOffsetPropertyIndent(MatcapTexture); }); materialEditor.ShaderProperty(MatcapNormalMix, "Normal Map mix"); materialEditor.ShaderProperty(MatcapShadeMix,"Shadow mix"); }); } // Reflection UIHelper.ShurikenHeader("Reflection"); materialEditor.DrawShaderPropertySameLIne(UseReflection); var useReflection = UseReflection.floatValue; if(useReflection > 0) { UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(UseReflectionProbe,"Use Reflection Probe"); var useProbe = UseReflectionProbe.floatValue; UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Smoothness & Mask", "Smoothness and Mask Texture"), ReflectionReflectionMask, ReflectionReflectionPower); materialEditor.TextureScaleOffsetPropertyIndent(ReflectionReflectionMask); }); UIHelper.DrawWithGroup(() => { var cubemapLabel = "Cubemap"; if(useProbe > 0) { cubemapLabel += "(fallback)"; } materialEditor.TexturePropertySingleLine(new GUIContent(cubemapLabel, cubemapLabel), ReflectionCubemap); materialEditor.TextureScaleOffsetPropertyIndent(ReflectionCubemap); }); materialEditor.ShaderProperty(ReflectionNormalMix,"Normal Map mix"); materialEditor.ShaderProperty(ReflectionShadeMix, "Shadow mix"); materialEditor.ShaderProperty(ReflectionSuppressBaseColorValue,"Suppress Base Color"); }); } // Rim Light UIHelper.ShurikenHeader("Rim"); materialEditor.DrawShaderPropertySameLIne(UseRim); var useRim = UseRim.floatValue; if(useRim > 0) { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Blend & Mask", "Blend and Mask Texture"), RimBlendMask, RimBlend); materialEditor.TextureScaleOffsetPropertyIndent(RimBlendMask); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Texture and Color"), RimTexture, RimColor); materialEditor.TextureScaleOffsetPropertyIndent(RimTexture); materialEditor.ShaderProperty(RimUseBaseTexture,"Use Base Color"); }); materialEditor.ShaderProperty(RimShadeMix,"Shadow mix"); materialEditor.ShaderProperty(RimFresnelPower,"Fresnel Power"); materialEditor.ShaderProperty(RimUpperSideWidth,"Upper side width"); }); } // Shade Cap UIHelper.ShurikenHeader("Shade Cap"); materialEditor.DrawShaderPropertySameLIne(ShadowCapBlendMode); var useShadowCap = ShadowCapBlendMode.floatValue; if(useShadowCap != 3) // Not 'Unused' { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Blend & Mask", "Blend and Mask Texture"), ShadowCapBlendMask, ShadowCapBlend); materialEditor.TextureScaleOffsetPropertyIndent(ShadowCapBlendMask); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture", "Texture"), ShadowCapTexture); materialEditor.TextureScaleOffsetPropertyIndent(ShadowCapTexture); }); materialEditor.ShaderProperty(ShadowCapNormalMix,"Normal Map mix"); }); } // Stencil Writer if(isStencilWriter) { UIHelper.ShurikenHeader("Stencil Writer"); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(StencilNumber,"Stencil Number"); if(isStencilWriterMask) { materialEditor.TexturePropertySingleLine(new GUIContent("Stencil Mask & Range", "Stencil Mask and Range"), StencilMaskTex, StencilMaskAdjust); materialEditor.TextureScaleOffsetPropertyIndent(StencilMaskTex); } if(isStencilWriterMask) materialEditor.ShaderProperty(StencilMaskAlphaDither, "Alpha(Dither)"); }); } // Stencil Reader if(isStencilReader) { UIHelper.ShurikenHeader("Stencil Reader"); if(isStencilReaderDouble) { UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Primary", EditorStyles.boldLabel); EditorGUI.indentLevel++; materialEditor.ShaderProperty(StencilNumber,"Number"); materialEditor.ShaderProperty(StencilCompareAction,"Compare Action"); EditorGUI.indentLevel--; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Secondary", EditorStyles.boldLabel); EditorGUI.indentLevel++; materialEditor.ShaderProperty(StencilNumberSecondary,"Number"); materialEditor.ShaderProperty(StencilCompareActionSecondary,"Compare Action"); EditorGUI.indentLevel--; }); }); } else { UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(StencilNumber,"Number"); materialEditor.ShaderProperty(StencilCompareAction,"Compare Action"); }); } } // Parallax Emission UIHelper.ShurikenHeader("Parallaxed Emission"); materialEditor.DrawShaderPropertySameLIne(UseEmissionParallax); var useEmissionPara = UseEmissionParallax.floatValue; if(useEmissionPara > 0){ UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Texture and Color"), EmissionParallaxTex, EmissionParallaxColor); materialEditor.TextureScaleOffsetPropertyIndent(EmissionParallaxTex); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("TexCol Mask", "Texture and Color Mask"), EmissionParallaxMask); materialEditor.TextureScaleOffsetPropertyIndent(EmissionParallaxMask); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Depth & Mask", "Depth and Mask Texture"), EmissionParallaxDepthMask, EmissionParallaxDepth); materialEditor.TextureScaleOffsetPropertyIndent(EmissionParallaxDepthMask); materialEditor.ShaderProperty(EmissionParallaxDepthMaskInvert, "Invert Depth Mask"); }); }); } // Scrolled Emission if(isEmissiveFreak) { UIHelper.ShurikenHeader("Emissive Freak"); UIHelper.DrawWithGroup(() => { UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("1st", EditorStyles.boldLabel); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Texture and Color"), EmissiveFreak1Tex, EmissiveFreak1Color); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak1Tex); materialEditor.TexturePropertySingleLine(new GUIContent("TexCol Mask", "Texture and Color Mask"), EmissiveFreak1Mask); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak1Mask); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(EmissiveFreak1U, "Scroll U"); materialEditor.ShaderProperty(EmissiveFreak1V, "Scroll V"); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Depth & Mask", "Depth and Mask Texture"), EmissiveFreak1DepthMask, EmissiveFreak1Depth); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak1DepthMask); materialEditor.ShaderProperty(EmissiveFreak1DepthMaskInvert, "Invert Depth Mask"); }); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(EmissiveFreak1Breathing, "Breathing"); materialEditor.ShaderProperty(EmissiveFreak1BreathingMix, "Breathing Mix"); materialEditor.ShaderProperty(EmissiveFreak1BlinkOut, "Blink Out"); materialEditor.ShaderProperty(EmissiveFreak1BlinkOutMix, "Blink Out Mix"); materialEditor.ShaderProperty(EmissiveFreak1BlinkIn, "Blink In"); materialEditor.ShaderProperty(EmissiveFreak1BlinkInMix, "Blink In Mix"); materialEditor.ShaderProperty(EmissiveFreak1HueShift, "Hue Shift"); }); }); }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("2nd", EditorStyles.boldLabel); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Texture & Color", "Texture and Color"), EmissiveFreak2Tex, EmissiveFreak2Color); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak2Tex); materialEditor.TexturePropertySingleLine(new GUIContent("TexCol Mask", "Texture and Color Mask"), EmissiveFreak2Mask); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak2Mask); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(EmissiveFreak2U, "Scroll U"); materialEditor.ShaderProperty(EmissiveFreak2V, "Scroll V"); }); UIHelper.DrawWithGroup(() => { materialEditor.TexturePropertySingleLine(new GUIContent("Depth & Mask", "Depth and Mask Texture"), EmissiveFreak2DepthMask, EmissiveFreak2Depth); materialEditor.TextureScaleOffsetPropertyIndent(EmissiveFreak2DepthMask); materialEditor.ShaderProperty(EmissiveFreak2DepthMaskInvert, "Invert Depth Mask"); }); UIHelper.DrawWithGroup(() => { materialEditor.ShaderProperty(EmissiveFreak2Breathing, "Breathing"); materialEditor.ShaderProperty(EmissiveFreak2BreathingMix, "Breathing Mix"); materialEditor.ShaderProperty(EmissiveFreak2BlinkOut, "Blink Out"); materialEditor.ShaderProperty(EmissiveFreak2BlinkOutMix, "Blink Out Mix"); materialEditor.ShaderProperty(EmissiveFreak2BlinkIn, "Blink In"); materialEditor.ShaderProperty(EmissiveFreak2BlinkInMix, "Blink In Mix"); materialEditor.ShaderProperty(EmissiveFreak2HueShift, "Hue Shift"); }); }); }); }); } // Advanced / Experimental IsShowAdvanced = UIHelper.ShurikenFoldout("Advanced / Experimental (Click to Open)", IsShowAdvanced); if (IsShowAdvanced) { UIHelper.DrawWithGroup(() => { EditorGUILayout.HelpBox("These are some shade tweaking. no need to change usually." + Environment.NewLine + "ほとんどのケースで触る必要のないやつら。",MessageType.Info); if (GUILayout.Button("Revert advanced params.")){ PointAddIntensity.floatValue = 1f; PointShadowStrength.floatValue = 0.5f; PointShadowborder.floatValue = 0.5f; PointShadowborderBlur.floatValue = 0.01f; PointShadowborderBlurMask.textureValue = null; OtherShadowAdjust.floatValue = -0.1f; OtherShadowBorderSharpness.floatValue = 3; PointShadowUseStep.floatValue = 0; PointShadowSteps.floatValue = 2; ShadowIndirectIntensity.floatValue = 0.25f; VertexColorBlendDiffuse.floatValue = 0f; VertexColorBlendEmissive.floatValue = 0f; UseVertexLight.floatValue = 1f; LightSampling.floatValue = 0f; UsePositionRelatedCalc.floatValue = 0f; } UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Lights", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(LightSampling, "Sampling Style (def:arktoon)"); EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Directional Shadow", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(ShadowIndirectIntensity, "Indirect face Intensity (0.25)"); EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Vertex Colors", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(VertexColorBlendDiffuse, "Color blend to diffuse (def:0) "); materialEditor.ShaderProperty(VertexColorBlendEmissive, "Color blend to emissive (def:0) "); EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("PointLights", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(PointAddIntensity, "Intensity (def:1)"); materialEditor.ShaderProperty(PointShadowStrength, "Shadow Strength (def:0.5)"); materialEditor.ShaderProperty(PointShadowborder, "Shadow Border (def:0.5)"); materialEditor.ShaderProperty(PointShadowborderBlur, "Shadow Border blur (def:0.01)"); materialEditor.ShaderProperty(PointShadowborderBlurMask, "Shadow Border blur Mask(def:none)"); materialEditor.ShaderProperty(PointShadowUseStep, "Use Shadow Steps"); var usePointStep = PointShadowUseStep.floatValue; if(usePointStep > 0) { materialEditor.ShaderProperty(PointShadowSteps, " "); } materialEditor.ShaderProperty(UseVertexLight, "Use Per-vertex Light"); EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("Shade from other meshes", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(OtherShadowAdjust, "Adjust (def:-0.1)"); materialEditor.ShaderProperty(OtherShadowBorderSharpness, "Sharpness(def:3)"); EditorGUI.indentLevel --; }); UIHelper.DrawWithGroup(() => { EditorGUILayout.LabelField("MatCap / ShadeCap", EditorStyles.boldLabel); EditorGUI.indentLevel ++; materialEditor.ShaderProperty(UsePositionRelatedCalc, "Use Position Related Calc(def: no)"); EditorGUI.indentLevel --; }); }); } // Arktoon version info string localVersion = EditorUserSettings.GetConfigValue ("arktoon_version_local"); string remoteVersion = EditorUserSettings.GetConfigValue ("arktoon_version_remote"); UIHelper.ShurikenHeader("Arktoon-Shaders"); style.alignment = TextAnchor.MiddleRight; style.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black; EditorGUILayout.LabelField("Your Version : " + localVersion, style); if (!string.IsNullOrEmpty(remoteVersion)) { Version local_v = new Version(localVersion); Version remote_v = new Version(remoteVersion); if(remote_v > local_v) { style.normal.textColor = EditorGUIUtility.isProSkin ? Color.cyan : Color.blue; EditorGUILayout.LabelField("Remote Version : " + remoteVersion, style); EditorGUILayout.BeginHorizontal( GUI.skin.box ); { style.alignment = TextAnchor.MiddleLeft; EditorGUILayout.LabelField("New version available : ", style); if(GUILayout.Button("Open download page.")) { System.Diagnostics.Process.Start("https://github.com/synqark/Arktoon-Shaders/releases"); } } GUILayout.EndHorizontal(); } else { EditorGUILayout.LabelField("Remote Version : " + remoteVersion, style); } } // Docs UIHelper.DrawWithGroupHorizontal(() => { if(GUILayout.Button("How to use (Japanese)")) { System.Diagnostics.Process.Start("https://synqark.github.io/Arktoon-Shaders-Doc/"); } if(GUILayout.Button("README.md (English)")) { System.Diagnostics.Process.Start("https://github.com/synqark/Arktoon-Shaders/blob/master/README.md"); } }); } EditorGUI.EndChangeCheck(); } } static class UIHelper { static int HEADER_HEIGHT = 22; public static void DrawShaderPropertySameLIne(this MaterialEditor editor, MaterialProperty property) { Rect r = EditorGUILayout.GetControlRect(true,0,EditorStyles.layerMaskField); r.y -= HEADER_HEIGHT; r.height = MaterialEditor.GetDefaultPropertyHeight(property); editor.ShaderProperty(r, property, " "); } private static Rect DrawShuriken(string title, Vector2 contentOffset) { var style = new GUIStyle("ShurikenModuleTitle"); style.margin = new RectOffset(0, 0, 8, 0); style.font = new GUIStyle(EditorStyles.boldLabel).font; style.border = new RectOffset(15, 7, 4, 4); style.fixedHeight = HEADER_HEIGHT; style.contentOffset = contentOffset; var rect = GUILayoutUtility.GetRect(16f, HEADER_HEIGHT, style); GUI.Box(rect, title, style); return rect; } public static void ShurikenHeader(string title) { DrawShuriken(title,new Vector2(6f, -2f)); } public static bool ShurikenFoldout(string title, bool display) { var rect = DrawShuriken(title,new Vector2(20f, -2f)); var e = Event.current; var toggleRect = new Rect(rect.x + 4f, rect.y + 2f, 13f, 13f); if (e.type == EventType.Repaint) { EditorStyles.foldout.Draw(toggleRect, false, false, display, false); } if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) { display = !display; e.Use(); } return display; } public static void Vector2Property(MaterialProperty property, string name) { EditorGUI.BeginChangeCheck(); Vector2 vector2 = EditorGUILayout.Vector2Field(name,new Vector2(property.vectorValue.x, property.vectorValue.y),null); if (EditorGUI.EndChangeCheck()) property.vectorValue = new Vector4(vector2.x, vector2.y); } public static void Vector4Property(MaterialProperty property, string name) { EditorGUI.BeginChangeCheck(); Vector4 vector4 = EditorGUILayout.Vector2Field(name,property.vectorValue,null); if (EditorGUI.EndChangeCheck()) property.vectorValue = vector4; } public static void Vector2PropertyZW(MaterialProperty property, string name) { EditorGUI.BeginChangeCheck(); Vector2 vector2 = EditorGUILayout.Vector2Field(name,new Vector2(property.vectorValue.x, property.vectorValue.y),null); if (EditorGUI.EndChangeCheck()) property.vectorValue = new Vector4(vector2.x, vector2.y); } public static void TextureScaleOffsetPropertyIndent(this MaterialEditor editor, MaterialProperty property) { EditorGUI.indentLevel ++; editor.TextureScaleOffsetProperty(property); EditorGUI.indentLevel --; } public static void DrawWithGroup(Action action) { EditorGUILayout.BeginVertical( GUI.skin.box ); action(); EditorGUILayout.EndVertical(); } public static void DrawWithGroupHorizontal(Action action) { EditorGUILayout.BeginHorizontal( GUI.skin.box ); action(); EditorGUILayout.EndHorizontal(); } } // シェーダーキーワードを作らないToggle (Unity 2018.2以降で存在するUIToggleと同じ。) internal class MaterialATSToggleDrawer : MaterialPropertyDrawer { public MaterialATSToggleDrawer() { } public MaterialATSToggleDrawer(string keyword) { } protected virtual void SetKeyword(MaterialProperty prop, bool on) { } static bool IsPropertyTypeSuitable(MaterialProperty prop) { return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range; } public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) { return base.GetPropertyHeight(prop, label, editor); } public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor) { EditorGUI.BeginChangeCheck(); bool value = (Math.Abs(prop.floatValue) > 0.001f); EditorGUI.showMixedValue = prop.hasMixedValue; value = EditorGUI.Toggle(position, label, value); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { prop.floatValue = value ? 1.0f : 0.0f; SetKeyword(prop, value); } } public override void Apply(MaterialProperty prop) { base.Apply(prop); if (!IsPropertyTypeSuitable(prop)) return; if (prop.hasMixedValue) return; SetKeyword(prop, (Math.Abs(prop.floatValue) > 0.001f)); } } }
59.66385
190
0.591923
[ "MIT" ]
RamType-0/Arktoon-Shaders
Assets/arktoon Shaders/Editor/ArktoonInspector.cs
64,064
C#
using CupCake.DefaultCommands.Commands.User; namespace CupCake.DefaultCommands { public sealed class UserCommandsMuffin : CupCakeMuffin<UserCommandsMuffin> { public KickCommand KickCommand { get; private set; } public KillCommand KillCommand { get; private set; } public TeleportCommand TeleportCommand { get; private set; } public GiveEditCommand GiveEditCommand { get; private set; } public RemoveEditCommand RemoveEditCommand { get; private set; } public MuteCommand MuteCommand { get; private set; } public UnmuteCommand UnmuteCommand { get; private set; } public ReportAbuseCommand ReportAbuseCommand { get; private set; } protected override void Enable() { this.KickCommand = this.EnablePart<KickCommand>(); this.KillCommand = this.EnablePart<KillCommand>(); this.TeleportCommand = this.EnablePart<TeleportCommand>(); this.GiveEditCommand = this.EnablePart<GiveEditCommand>(); this.RemoveEditCommand = this.EnablePart<RemoveEditCommand>(); this.MuteCommand = this.EnablePart<MuteCommand>(); this.UnmuteCommand = this.EnablePart<UnmuteCommand>(); this.ReportAbuseCommand = this.EnablePart<ReportAbuseCommand>(); } } }
47.178571
78
0.683573
[ "MIT" ]
KylerM/CupCake
CupCake.DefaultCommands/UserCommandsMuffin.cs
1,323
C#
using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate; using System.Threading.Tasks; namespace Microsoft.eShopWeb.ApplicationCore.Interfaces { public interface IOrderReserver { Task ReserveOrderAsync(Order order); } }
22.818182
66
0.776892
[ "MIT" ]
spriazhkin/eShopOnWeb
src/ApplicationCore/Interfaces/IOrderReserver.cs
253
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type AuthorizationPolicyDefaultUserRoleOverridesCollectionRequest. /// </summary> public partial class AuthorizationPolicyDefaultUserRoleOverridesCollectionRequest : BaseRequest, IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest { /// <summary> /// Constructs a new AuthorizationPolicyDefaultUserRoleOverridesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public AuthorizationPolicyDefaultUserRoleOverridesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified DefaultUserRoleOverride to the collection via POST. /// </summary> /// <param name="defaultUserRoleOverride">The DefaultUserRoleOverride to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DefaultUserRoleOverride.</returns> public System.Threading.Tasks.Task<DefaultUserRoleOverride> AddAsync(DefaultUserRoleOverride defaultUserRoleOverride, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsync<DefaultUserRoleOverride>(defaultUserRoleOverride, cancellationToken); } /// <summary> /// Adds the specified DefaultUserRoleOverride to the collection via POST and returns a <see cref="GraphResponse{DefaultUserRoleOverride}"/> object of the request. /// </summary> /// <param name="defaultUserRoleOverride">The DefaultUserRoleOverride to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DefaultUserRoleOverride}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<DefaultUserRoleOverride>> AddResponseAsync(DefaultUserRoleOverride defaultUserRoleOverride, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<DefaultUserRoleOverride>(defaultUserRoleOverride, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IAuthorizationPolicyDefaultUserRoleOverridesCollectionPage> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var response = await this.SendAsync<AuthorizationPolicyDefaultUserRoleOverridesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response?.Value?.CurrentPage != null) { response.Value.InitializeNextPageRequest(this.Client, response.NextLink); // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; return response.Value; } return null; } /// <summary> /// Gets the collection page and returns a <see cref="GraphResponse{AuthorizationPolicyDefaultUserRoleOverridesCollectionResponse}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{AuthorizationPolicyDefaultUserRoleOverridesCollectionResponse}"/> object.</returns> public System.Threading.Tasks.Task<GraphResponse<AuthorizationPolicyDefaultUserRoleOverridesCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<AuthorizationPolicyDefaultUserRoleOverridesCollectionResponse>(null, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Expand(Expression<Func<DefaultUserRoleOverride, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Select(Expression<Func<DefaultUserRoleOverride, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IAuthorizationPolicyDefaultUserRoleOverridesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
47.210526
195
0.63687
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/AuthorizationPolicyDefaultUserRoleOverridesCollectionRequest.cs
9,867
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Lightsail.Model { /// <summary> /// Container for the parameters to the CreateLoadBalancer operation. /// Creates a Lightsail load balancer. To learn more about deciding whether to load balance /// your application, see <a href="https://lightsail.aws.amazon.com/ls/docs/how-to/article/configure-lightsail-instances-for-load-balancing">Configure /// your Lightsail instances for load balancing</a>. You can create up to 5 load balancers /// per AWS Region in your account. /// /// /// <para> /// When you create a load balancer, you can specify a unique name and port settings. /// To change additional load balancer settings, use the <code>UpdateLoadBalancerAttribute</code> /// operation. /// </para> /// /// <para> /// The <code>create load balancer</code> operation supports tag-based access control /// via request tags. For more information, see the <a href="https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags">Lightsail /// Dev Guide</a>. /// </para> /// </summary> public partial class CreateLoadBalancerRequest : AmazonLightsailRequest { private List<string> _certificateAlternativeNames = new List<string>(); private string _certificateDomainName; private string _certificateName; private string _healthCheckPath; private int? _instancePort; private string _loadBalancerName; private List<Tag> _tags = new List<Tag>(); /// <summary> /// Gets and sets the property CertificateAlternativeNames. /// <para> /// The optional alternative domains and subdomains to use with your SSL/TLS certificate /// (e.g., <code>www.example.com</code>, <code>example.com</code>, <code>m.example.com</code>, /// <code>blog.example.com</code>). /// </para> /// </summary> public List<string> CertificateAlternativeNames { get { return this._certificateAlternativeNames; } set { this._certificateAlternativeNames = value; } } // Check to see if CertificateAlternativeNames property is set internal bool IsSetCertificateAlternativeNames() { return this._certificateAlternativeNames != null && this._certificateAlternativeNames.Count > 0; } /// <summary> /// Gets and sets the property CertificateDomainName. /// <para> /// The domain name with which your certificate is associated (e.g., <code>example.com</code>). /// </para> /// /// <para> /// If you specify <code>certificateDomainName</code>, then <code>certificateName</code> /// is required (and vice-versa). /// </para> /// </summary> public string CertificateDomainName { get { return this._certificateDomainName; } set { this._certificateDomainName = value; } } // Check to see if CertificateDomainName property is set internal bool IsSetCertificateDomainName() { return this._certificateDomainName != null; } /// <summary> /// Gets and sets the property CertificateName. /// <para> /// The name of the SSL/TLS certificate. /// </para> /// /// <para> /// If you specify <code>certificateName</code>, then <code>certificateDomainName</code> /// is required (and vice-versa). /// </para> /// </summary> public string CertificateName { get { return this._certificateName; } set { this._certificateName = value; } } // Check to see if CertificateName property is set internal bool IsSetCertificateName() { return this._certificateName != null; } /// <summary> /// Gets and sets the property HealthCheckPath. /// <para> /// The path you provided to perform the load balancer health check. If you didn't specify /// a health check path, Lightsail uses the root path of your website (e.g., <code>"/"</code>). /// </para> /// /// <para> /// You may want to specify a custom health check path other than the root of your application /// if your home page loads slowly or has a lot of media or scripting on it. /// </para> /// </summary> public string HealthCheckPath { get { return this._healthCheckPath; } set { this._healthCheckPath = value; } } // Check to see if HealthCheckPath property is set internal bool IsSetHealthCheckPath() { return this._healthCheckPath != null; } /// <summary> /// Gets and sets the property InstancePort. /// <para> /// The instance port where you're creating your load balancer. /// </para> /// </summary> [AWSProperty(Required=true, Min=0, Max=65535)] public int InstancePort { get { return this._instancePort.GetValueOrDefault(); } set { this._instancePort = value; } } // Check to see if InstancePort property is set internal bool IsSetInstancePort() { return this._instancePort.HasValue; } /// <summary> /// Gets and sets the property LoadBalancerName. /// <para> /// The name of your load balancer. /// </para> /// </summary> [AWSProperty(Required=true)] public string LoadBalancerName { get { return this._loadBalancerName; } set { this._loadBalancerName = value; } } // Check to see if LoadBalancerName property is set internal bool IsSetLoadBalancerName() { return this._loadBalancerName != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tag keys and optional values to add to the resource during create. /// </para> /// /// <para> /// To tag a resource after it has been created, see the <code>tag resource</code> operation. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
35.853081
175
0.598414
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/CreateLoadBalancerRequest.cs
7,565
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Lightsail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Lightsail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for StartRelationalDatabase operation /// </summary> public class StartRelationalDatabaseResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { StartRelationalDatabaseResponse response = new StartRelationalDatabaseResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("operations", targetDepth)) { var unmarshaller = new ListUnmarshaller<Operation, OperationUnmarshaller>(OperationUnmarshaller.Instance); response.Operations = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("AccountSetupInProgressException")) { return AccountSetupInProgressExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("OperationFailureException")) { return OperationFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException")) { return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthenticatedException")) { return UnauthenticatedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonLightsailException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static StartRelationalDatabaseResponseUnmarshaller _instance = new StartRelationalDatabaseResponseUnmarshaller(); internal static StartRelationalDatabaseResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StartRelationalDatabaseResponseUnmarshaller Instance { get { return _instance; } } } }
42.238806
192
0.643993
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/StartRelationalDatabaseResponseUnmarshaller.cs
5,660
C#
// <auto-generated /> using ImageServer.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; namespace ImageServer.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 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.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); 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<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); 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("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(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); 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(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); 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("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", 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("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.65942
125
0.468251
[ "MIT" ]
itIsEazy/ImageServer
ImageServer/Data/Migrations/ApplicationDbContextModelSnapshot.cs
10,394
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dataflow.V1Beta3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedSnapshotsV1Beta3ClientTest { [xunit::FactAttribute] public void GetSnapshotRequestObject() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); GetSnapshotRequest request = new GetSnapshotRequest { ProjectId = "project_id43ad98b0", SnapshotId = "snapshot_id3456a275", Location = "locatione09d18d5", }; Snapshot expectedResponse = new Snapshot { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", SourceJobId = "source_job_id1406915d", CreationTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), State = SnapshotState.UnknownSnapshotState, PubsubMetadata = { new PubsubSnapshotMetadata(), }, Description = "description2cf9da67", DiskSizeBytes = -5516951742914183668L, Region = "regionedb20d96", }; mockGrpcClient.Setup(x => x.GetSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); Snapshot response = client.GetSnapshot(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSnapshotRequestObjectAsync() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); GetSnapshotRequest request = new GetSnapshotRequest { ProjectId = "project_id43ad98b0", SnapshotId = "snapshot_id3456a275", Location = "locatione09d18d5", }; Snapshot expectedResponse = new Snapshot { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", SourceJobId = "source_job_id1406915d", CreationTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), State = SnapshotState.UnknownSnapshotState, PubsubMetadata = { new PubsubSnapshotMetadata(), }, Description = "description2cf9da67", DiskSizeBytes = -5516951742914183668L, Region = "regionedb20d96", }; mockGrpcClient.Setup(x => x.GetSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); Snapshot responseCallSettings = await client.GetSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Snapshot responseCancellationToken = await client.GetSnapshotAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSnapshotRequestObject() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); DeleteSnapshotRequest request = new DeleteSnapshotRequest { ProjectId = "project_id43ad98b0", SnapshotId = "snapshot_id3456a275", Location = "locatione09d18d5", }; DeleteSnapshotResponse expectedResponse = new DeleteSnapshotResponse { }; mockGrpcClient.Setup(x => x.DeleteSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); DeleteSnapshotResponse response = client.DeleteSnapshot(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSnapshotRequestObjectAsync() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); DeleteSnapshotRequest request = new DeleteSnapshotRequest { ProjectId = "project_id43ad98b0", SnapshotId = "snapshot_id3456a275", Location = "locatione09d18d5", }; DeleteSnapshotResponse expectedResponse = new DeleteSnapshotResponse { }; mockGrpcClient.Setup(x => x.DeleteSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DeleteSnapshotResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); DeleteSnapshotResponse responseCallSettings = await client.DeleteSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); DeleteSnapshotResponse responseCancellationToken = await client.DeleteSnapshotAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ListSnapshotsRequestObject() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectId = "project_id43ad98b0", Location = "locatione09d18d5", JobId = "job_id38ea97d6", }; ListSnapshotsResponse expectedResponse = new ListSnapshotsResponse { Snapshots = { new Snapshot(), }, }; mockGrpcClient.Setup(x => x.ListSnapshots(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); ListSnapshotsResponse response = client.ListSnapshots(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListSnapshotsRequestObjectAsync() { moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client> mockGrpcClient = new moq::Mock<SnapshotsV1Beta3.SnapshotsV1Beta3Client>(moq::MockBehavior.Strict); ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectId = "project_id43ad98b0", Location = "locatione09d18d5", JobId = "job_id38ea97d6", }; ListSnapshotsResponse expectedResponse = new ListSnapshotsResponse { Snapshots = { new Snapshot(), }, }; mockGrpcClient.Setup(x => x.ListSnapshotsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListSnapshotsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SnapshotsV1Beta3Client client = new SnapshotsV1Beta3ClientImpl(mockGrpcClient.Object, null); ListSnapshotsResponse responseCallSettings = await client.ListSnapshotsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ListSnapshotsResponse responseCancellationToken = await client.ListSnapshotsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
52.745856
236
0.655494
[ "Apache-2.0" ]
Mattlk13/google-cloud-dotnet
apis/Google.Cloud.Dataflow.V1Beta3/Google.Cloud.Dataflow.V1Beta3.Tests/SnapshotsV1Beta3ClientTest.g.cs
9,547
C#
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Trusthub.V1; namespace Twilio.Tests.Rest.Trusthub.V1 { [TestFixture] public class EndUserTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Trusthub, "/v1/EndUsers", "" ); request.AddPostParam("FriendlyName", Serialize("friendly_name")); request.AddPostParam("Type", Serialize("type")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { EndUserResource.Create("friendly_name", "type", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"date_updated\": \"2021-02-16T20:40:57Z\",\"sid\": \"ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"auth_rep_1\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-16T20:40:57Z\",\"attributes\": {\"phone_number\": \"+11234567890\",\"job_position\": \"CEO\",\"first_name\": \"rep1\",\"last_name\": \"test\",\"business_title\": \"ceo\",\"email\": \"foobar@test.com\"},\"type\": \"authorized_representative_1\"}" )); var response = EndUserResource.Create("friendly_name", "type", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Trusthub, "/v1/EndUsers", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { EndUserResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"results\": [],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/EndUsers?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/EndUsers?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}" )); var response = EndUserResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"results\": [{\"date_updated\": \"2021-02-16T20:40:57Z\",\"sid\": \"ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"auth_rep_1\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-16T20:40:57Z\",\"attributes\": {\"phone_number\": \"+11234567890\",\"job_position\": \"CEO\",\"first_name\": \"rep1\",\"last_name\": \"test\",\"business_title\": \"ceo\",\"email\": \"foobar@test.com\"},\"type\": \"authorized_representative_1\"}],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/EndUsers?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/EndUsers?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}" )); var response = EndUserResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Trusthub, "/v1/EndUsers/ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { EndUserResource.Fetch("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"date_updated\": \"2021-02-16T20:40:57Z\",\"sid\": \"ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"auth_rep_1\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-16T20:40:57Z\",\"attributes\": {\"phone_number\": \"+11234567890\",\"job_position\": \"CEO\",\"first_name\": \"rep1\",\"last_name\": \"test\",\"business_title\": \"ceo\",\"email\": \"foobar@test.com\"},\"type\": \"authorized_representative_1\"}" )); var response = EndUserResource.Fetch("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Trusthub, "/v1/EndUsers/ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { EndUserResource.Update("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"date_updated\": \"2021-02-16T20:40:57Z\",\"sid\": \"ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/EndUsers/ITaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-16T20:40:57Z\",\"attributes\": {\"phone_number\": \"+11234567890\",\"job_position\": \"CEO\",\"first_name\": \"rep1\",\"last_name\": \"test\",\"business_title\": \"ceo\",\"email\": \"foobar@test.com\"},\"type\": \"authorized_representative_1\"}" )); var response = EndUserResource.Update("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Trusthub, "/v1/EndUsers/ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { EndUserResource.Delete("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = EndUserResource.Delete("ITXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } } }
49.877828
872
0.569355
[ "MIT" ]
BrimmingDev/twilio-csharp
test/Twilio.Test/Rest/Trusthub/V1/EndUserResourceTest.cs
11,023
C#
namespace BinaryDataSerialization.Test { public class Ingredients { [FieldOrder(0)] public byte MainIngredientIndicator { get; set; } [FieldOrder(1)] [Subtype(nameof(MainIngredientIndicator), 1, typeof(CalciumCarbonate))] [Subtype(nameof(MainIngredientIndicator), 2, typeof(Iron))] [Subtype(nameof(MainIngredientIndicator), 3, typeof(Zinc))] public Chemical MainIngredient { get; set; } } }
30.733333
79
0.663774
[ "MIT" ]
jackwakefield/BinaryDataSerializer
BinaryDataSerializer.Test/Ingredients.cs
463
C#
using UniRx; namespace ReMotion { public class ObservableEasing { const float DefaultOvershoot = 1.70158f; const float DefaultAmplitude = 1.70158f; const float DefaultPeriod = 0.0f; public static IObservable<float> Create(EasingFunction easing, float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(easing, duration, ignoreTimeScale); } public static IObservable<float> Linear(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.Linear, duration, ignoreTimeScale); } public static IObservable<float> EaseInSine(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInSine, duration, ignoreTimeScale); } public static IObservable<float> EaseOutSine(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutSine, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutSine(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutSine, duration, ignoreTimeScale); } public static IObservable<float> EaseInQuad(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInQuad, duration, ignoreTimeScale); } public static IObservable<float> EaseOutQuad(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutQuad, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutQuad(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutQuad, duration, ignoreTimeScale); } public static IObservable<float> EaseInCubic(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInCubic, duration, ignoreTimeScale); } public static IObservable<float> EaseOutCubic(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutCubic, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutCubic(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutCubic, duration, ignoreTimeScale); } public static IObservable<float> EaseInQuart(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInQuart, duration, ignoreTimeScale); } public static IObservable<float> EaseOutQuart(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutQuart, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutQuart(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutQuart, duration, ignoreTimeScale); } public static IObservable<float> EaseInQuint(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInQuint, duration, ignoreTimeScale); } public static IObservable<float> EaseOutQuint(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutQuint, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutQuint(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutQuint, duration, ignoreTimeScale); } public static IObservable<float> EaseInExpo(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInExpo, duration, ignoreTimeScale); } public static IObservable<float> EaseOutExpo(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutExpo, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutExpo(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutExpo, duration, ignoreTimeScale); } public static IObservable<float> EaseInCirc(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInCirc, duration, ignoreTimeScale); } public static IObservable<float> EaseOutCirc(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutCirc, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutCirc(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutCirc, duration, ignoreTimeScale); } public static IObservable<float> EaseInBack(float duration, float overshoot = DefaultOvershoot, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInBack(overshoot), duration, ignoreTimeScale); } public static IObservable<float> EaseOutBack(float duration, float overshoot = DefaultOvershoot, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutBack(overshoot), duration, ignoreTimeScale); } public static IObservable<float> EaseInOutBack(float duration, float overshoot = DefaultOvershoot, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutBack(overshoot), duration, ignoreTimeScale); } public static IObservable<float> EaseInElastic(float duration, float amplitude = DefaultAmplitude, float period = DefaultPeriod, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInElastic(amplitude, period), duration, ignoreTimeScale); } public static IObservable<float> EaseOutElastic(float duration, float amplitude = DefaultAmplitude, float period = DefaultPeriod, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutElastic(amplitude, period), duration, ignoreTimeScale); } public static IObservable<float> EaseInOutElastic(float duration, float amplitude = DefaultAmplitude, float period = DefaultPeriod, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutElastic(amplitude, period), duration, ignoreTimeScale); } public static IObservable<float> EaseInBounce(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInBounce, duration, ignoreTimeScale); } public static IObservable<float> EaseOutBounce(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseOutBounce, duration, ignoreTimeScale); } public static IObservable<float> EaseInOutBounce(float duration, bool ignoreTimeScale = false) { return ObservableTween.CreateObservable(EasingFunctions.EaseInOutBounce, duration, ignoreTimeScale); } class ObservableTween : ITween { readonly IObserver<float> observer; readonly BooleanDisposable cancellation; readonly EasingFunction easing; readonly bool ignoreTimeScale; readonly float duration; float currentTime = 0; ObservableTween(IObserver<float> observer, BooleanDisposable cancellation, EasingFunction easing, float duration, bool ignoreTimeScale) { this.observer = observer; this.cancellation = cancellation; this.easing = easing; this.ignoreTimeScale = ignoreTimeScale; this.duration = duration; } public static IObservable<float> CreateObservable(EasingFunction easing, float duration, bool ignoreTimeScale) { return Observable.CreateSafe<float>(observer => { observer.OnNext(default(float)); // push initial value on subscribe. var cancellation = new BooleanDisposable(); var tween = new ObservableTween(observer, cancellation, easing, duration, ignoreTimeScale); TweenEngine.AddTween(tween); return cancellation; }, false); } public bool MoveNext(ref float deltaTime, ref float unscaledDeltaTime) { if (cancellation.IsDisposed) return false; var delta = (ignoreTimeScale) ? unscaledDeltaTime : deltaTime; if (delta == 0) return true; currentTime += delta; bool isCompleted = false; if (currentTime >= duration) { currentTime = duration; isCompleted = true; } observer.OnNext(easing(currentTime, duration)); if (isCompleted) { observer.OnCompleted(); return false; } return true; } } } }
44.043478
169
0.673149
[ "MIT" ]
HagamosVideojuegos/ReMotion
Assets/Scripts/ObservableEasing.cs
10,132
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class movement : MonoBehaviour { private Animator Anim; public GameObject parachute; // Start is called before the first frame update void Start() { Anim = gameObject.GetComponent<Animator> (); Anim.SetBool("isLanding",false); } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.W)) { Anim.SetBool("isWalking", true); } else if( Input.GetKeyUp (KeyCode.W)) { Anim.SetBool("isWalking",false); } if(Input.GetKeyDown(KeyCode.Space)) { Anim.SetBool("isJumping",true); } else if (Input.GetKeyUp(KeyCode.Space)) { Anim.SetBool("isJumping",false); } //joystick if(Input.GetButtonDown("Jump")||Input.GetButtonDown("Fire2")) { Anim.SetBool("isJumping",true); } else if (Input.GetButtonUp("Jump")||Input.GetButtonUp("Fire2")) { Anim.SetBool("isJumping",false); } Debug.Log(PlayerMovement.isGrounded); if(!PlayerMovement.isGrounded) { Anim.SetBool("isFlying",true); } if(PlayerMovement.isGrounded) { Anim.SetBool("isFlying",false); Anim.SetBool("isWalking",false); Anim.SetBool("isLanding",true); } //Dhruv Parachute if(Input.GetButton("Fire1")) { parachute.SetActive(true); } } }
24.507463
71
0.537759
[ "MIT" ]
TheCodeCrush/Sky-Diving
Assets/Script/movement.cs
1,644
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.Leaderboards; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using Realms; namespace osu.Game.Screens.Select.Leaderboards { public class BeatmapLeaderboard : Leaderboard<BeatmapLeaderboardScope, ScoreInfo> { public Action<ScoreInfo> ScoreSelected; [Resolved] private RulesetStore rulesets { get; set; } [Resolved] private RealmContextFactory realmFactory { get; set; } private BeatmapInfo beatmapInfo; public BeatmapInfo BeatmapInfo { get => beatmapInfo; set { if (beatmapInfo?.Equals(value) == true) return; beatmapInfo = value; Scores = null; UpdateScores(); if (IsLoaded) refreshRealmSubscription(); } } private bool filterMods; /// <summary> /// Whether to apply the game's currently selected mods as a filter when retrieving scores. /// </summary> public bool FilterMods { get => filterMods; set { if (value == filterMods) return; filterMods = value; UpdateScores(); } } [Resolved] private ScoreManager scoreManager { get; set; } [Resolved] private IBindable<RulesetInfo> ruleset { get; set; } [Resolved] private IBindable<IReadOnlyList<Mod>> mods { get; set; } [Resolved] private IAPIProvider api { get; set; } [BackgroundDependencyLoader] private void load() { ruleset.ValueChanged += _ => UpdateScores(); mods.ValueChanged += _ => { if (filterMods) UpdateScores(); }; } protected override void LoadComplete() { base.LoadComplete(); refreshRealmSubscription(); } private IDisposable scoreSubscription; private void refreshRealmSubscription() { scoreSubscription?.Dispose(); scoreSubscription = null; if (beatmapInfo == null) return; scoreSubscription = realmFactory.Context.All<ScoreInfo>() .Filter($"{nameof(ScoreInfo.BeatmapInfo)}.{nameof(BeatmapInfo.ID)} = $0", beatmapInfo.ID) .QueryAsyncWithNotifications((_, changes, ___) => { if (changes == null) return; RefreshScores(); }); } protected override void Reset() { base.Reset(); TopScore = null; } protected override bool IsOnlineScope => Scope != BeatmapLeaderboardScope.Local; private CancellationTokenSource loadCancellationSource; protected override APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback) { loadCancellationSource?.Cancel(); loadCancellationSource = new CancellationTokenSource(); var cancellationToken = loadCancellationSource.Token; var fetchBeatmapInfo = BeatmapInfo; if (fetchBeatmapInfo == null) { PlaceholderState = PlaceholderState.NoneSelected; return null; } if (Scope == BeatmapLeaderboardScope.Local) { using (var realm = realmFactory.CreateContext()) { var scores = realm.All<ScoreInfo>() .AsEnumerable() // TODO: update to use a realm filter directly (or at least figure out the beatmap part to reduce scope). .Where(s => !s.DeletePending && s.BeatmapInfo.ID == fetchBeatmapInfo.ID && s.Ruleset.OnlineID == ruleset.Value.ID); if (filterMods && !mods.Value.Any()) { // we need to filter out all scores that have any mods to get all local nomod scores scores = scores.Where(s => !s.Mods.Any()); } else if (filterMods) { // otherwise find all the scores that have *any* of the currently selected mods (similar to how web applies mod filters) // we're creating and using a string list representation of selected mods so that it can be translated into the DB query itself var selectedMods = mods.Value.Select(m => m.Acronym); scores = scores.Where(s => s.Mods.Any(m => selectedMods.Contains(m.Acronym))); } scores = scores.Detach(); scoreManager.OrderByTotalScoreAsync(scores.ToArray(), cancellationToken) .ContinueWith(ordered => scoresCallback?.Invoke(ordered.GetResultSafely()), TaskContinuationOptions.OnlyOnRanToCompletion); return null; } } if (api?.IsLoggedIn != true) { PlaceholderState = PlaceholderState.NotLoggedIn; return null; } if (fetchBeatmapInfo.OnlineID <= 0 || fetchBeatmapInfo.Status <= BeatmapOnlineStatus.Pending) { PlaceholderState = PlaceholderState.Unavailable; return null; } if (!api.LocalUser.Value.IsSupporter && (Scope != BeatmapLeaderboardScope.Global || filterMods)) { PlaceholderState = PlaceholderState.NotSupporter; return null; } IReadOnlyList<Mod> requestMods = null; if (filterMods && !mods.Value.Any()) // add nomod for the request requestMods = new Mod[] { new ModNoMod() }; else if (filterMods) requestMods = mods.Value; var req = new GetScoresRequest(fetchBeatmapInfo, ruleset.Value ?? fetchBeatmapInfo.Ruleset, Scope, requestMods); req.Success += r => { scoreManager.OrderByTotalScoreAsync(r.Scores.Select(s => s.CreateScoreInfo(rulesets, fetchBeatmapInfo)).ToArray(), cancellationToken) .ContinueWith(task => Schedule(() => { if (cancellationToken.IsCancellationRequested) return; scoresCallback?.Invoke(task.GetResultSafely()); TopScore = r.UserScore?.CreateScoreInfo(rulesets, fetchBeatmapInfo); }), TaskContinuationOptions.OnlyOnRanToCompletion); }; return req; } protected override LeaderboardScore CreateDrawableScore(ScoreInfo model, int index) => new LeaderboardScore(model, index, IsOnlineScope) { Action = () => ScoreSelected?.Invoke(model) }; protected override LeaderboardScore CreateDrawableTopScore(ScoreInfo model) => new LeaderboardScore(model, model.Position, false) { Action = () => ScoreSelected?.Invoke(model) }; protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); scoreSubscription?.Dispose(); } } }
35.543568
156
0.517044
[ "MIT" ]
apollo-dw/osu
osu.Game/Screens/Select/Leaderboards/BeatmapLeaderboard.cs
8,326
C#
using System; using System.Globalization; using System.Text; namespace Poker.Deck { internal static class CardFormat { private const string DefaultCardMaskFormat = "ia"; internal static string Format(CardMask cardMask, string format, CardFormatInfo cardFormatInfo) { if (string.IsNullOrEmpty(format)) { format = DefaultCardMaskFormat; } return FormatCustomized(cardMask, format, cardFormatInfo); } private static string FormatCustomized(CardMask cardMask, string format, CardFormatInfo cardFormatInfo) { var deck = cardFormatInfo.Deck; var sb = new StringBuilder(128); var index1 = 0; var isOnePatternAlreadyProcessed = false; while (index1 < format.Length) { var num1 = 1; var patternChar = format[index1]; if (patternChar == 'n') { if (isOnePatternAlreadyProcessed) { sb.Append(cardFormatInfo.PatternSeparator); } sb.Append(((long) cardMask).ToString(CultureInfo.CurrentCulture)); isOnePatternAlreadyProcessed = true; } if (patternChar == 'i' || patternChar == 'a' || patternChar == 'c' || patternChar == 'r' || patternChar == 'R' || patternChar == 's' || patternChar == 'S') { var patternChar2 = ParseNextChar(format, index1); if (((patternChar == 'r' && patternChar2 == 's') || (patternChar == 's' && patternChar2 == 'r')) || ((patternChar == 'R' && patternChar2 == 'S') || (patternChar == 'S' && patternChar2 == 'R'))) { num1 = 2; } FormatAllCards(cardMask, cardFormatInfo, isOnePatternAlreadyProcessed, sb, deck, patternChar, num1); isOnePatternAlreadyProcessed = true; } index1 += num1; } return sb.ToString(); } private static void FormatAllCards(CardMask cardMask, CardFormatInfo cardFormatInfo, bool isOnePatternAlreadyProcessed, StringBuilder sb, IDeck deck, char patternChar, int num1) { var cardIndexes = cardFormatInfo.Deck.ToCardIndexes(cardMask); var i = 0; foreach (var cardIndex in cardIndexes) { if (i == 0 && isOnePatternAlreadyProcessed) { sb.Append(cardFormatInfo.PatternSeparator); } var rankIndex = deck.ToRankIndex(cardIndex); var suitIndex = deck.ToSuitIndex(cardIndex); switch (patternChar) { case 'i': if (i != 0) { sb.Append(cardFormatInfo.CardIndexesSeparator); } sb.Append(cardIndex.ToString(CultureInfo.CurrentCulture)); break; case 'a': FormatAbbreviatedName(cardFormatInfo, i, sb, rankIndex, suitIndex); break; case 'c': FormatName(cardFormatInfo, i, sb, rankIndex, suitIndex); break; case 'r': case 's': FormatAbbreviatedName2(cardFormatInfo, i, sb, patternChar, rankIndex, suitIndex, num1); break; case 'R': case 'S': FormatName2(cardFormatInfo, i, sb, patternChar, rankIndex, suitIndex, num1); break; default: throw new ArgumentException(patternChar.ToString()); } ++i; } } private static void FormatName2(CardFormatInfo cardFormatInfo, int i, StringBuilder sb, char patternChar, int rankIndex, int suitIndex, int num1) { if (i != 0) { sb.Append(cardFormatInfo.CardNamesSeparator); } sb.Append(patternChar == 'R' ? cardFormatInfo.GetRankName(rankIndex) : cardFormatInfo.GetSuitName(suitIndex, (cardFormatInfo.FormatSettings & CardFormatSettings.UseGenitiveSuit) != CardFormatSettings.None)); if (num1 != 2) { return; } sb.Append(cardFormatInfo.CardNamePartsSeparator); sb.Append(patternChar == 'R' ? cardFormatInfo.GetSuitName(suitIndex, (cardFormatInfo.FormatSettings & CardFormatSettings.UseGenitiveSuit) != CardFormatSettings.None) : cardFormatInfo.GetRankName(rankIndex)); } private static void FormatAbbreviatedName2(CardFormatInfo cardFormatInfo, int i, StringBuilder sb, char patternChar, int rankIndex, int suitIndex, int num1) { if (i != 0) { sb.Append(cardFormatInfo.CardAbbreviationsSeparator); } sb.Append(patternChar == 'r' ? cardFormatInfo.GetAbbreviatedRankName(rankIndex) : cardFormatInfo.GetAbbreviatedSuitName(suitIndex)); if (num1 != 2) { return; } sb.Append(cardFormatInfo.CardAbbreviationPartsSeparator); sb.Append(patternChar == 'r' ? cardFormatInfo.GetAbbreviatedSuitName(suitIndex) : cardFormatInfo.GetAbbreviatedRankName(rankIndex)); } private static void FormatName(CardFormatInfo cardFormatInfo, int i, StringBuilder sb, int rankIndex, int suitIndex) { if (i != 0) { sb.Append(cardFormatInfo.CardNamesSeparator); } sb.Append((cardFormatInfo.FormatSettings & CardFormatSettings.UseSuitFirst) == CardFormatSettings.None ? cardFormatInfo.GetRankName(rankIndex) : cardFormatInfo.GetSuitName(suitIndex, (cardFormatInfo.FormatSettings & CardFormatSettings.UseGenitiveSuit) != CardFormatSettings.None)); sb.Append(cardFormatInfo.CardNamePartsSeparator); sb.Append((cardFormatInfo.FormatSettings & CardFormatSettings.UseSuitFirst) == CardFormatSettings.None ? cardFormatInfo.GetSuitName(suitIndex, (cardFormatInfo.FormatSettings & CardFormatSettings.UseGenitiveSuit) != CardFormatSettings.None) : cardFormatInfo.GetRankName(rankIndex)); } private static void FormatAbbreviatedName(CardFormatInfo cardFormatInfo, int i, StringBuilder sb, int rankIndex, int suitIndex) { if (i != 0) { sb.Append(cardFormatInfo.CardAbbreviationsSeparator); } sb.Append((cardFormatInfo.FormatSettings & CardFormatSettings.UseSuitFirst) == CardFormatSettings.None ? cardFormatInfo.GetAbbreviatedRankName(rankIndex) : cardFormatInfo.GetAbbreviatedSuitName(suitIndex)); sb.Append(cardFormatInfo.CardAbbreviationPartsSeparator); sb.Append((cardFormatInfo.FormatSettings & CardFormatSettings.UseSuitFirst) == CardFormatSettings.None ? cardFormatInfo.GetAbbreviatedSuitName(suitIndex) : cardFormatInfo.GetAbbreviatedRankName(rankIndex)); } private static char ParseNextChar(string format, int pos) => pos >= format.Length - 1 ? char.MinValue : format[pos + 1]; } }
37.108597
120
0.525058
[ "MIT" ]
Pulsatrix/Poker
Poker/Deck/CardFormat.cs
8,203
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wingdi.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='EMRSETWORLDTRANSFORM.xml' path='doc/member[@name="EMRSETWORLDTRANSFORM"]/*' /> public partial struct EMRSETWORLDTRANSFORM { /// <include file='EMRSETWORLDTRANSFORM.xml' path='doc/member[@name="EMRSETWORLDTRANSFORM.emr"]/*' /> public EMR emr; /// <include file='EMRSETWORLDTRANSFORM.xml' path='doc/member[@name="EMRSETWORLDTRANSFORM.xform"]/*' /> public XFORM xform; }
42.647059
145
0.74069
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/wingdi/EMRSETWORLDTRANSFORM.cs
727
C#
using System.Collections.Generic; using System.Threading.Tasks; using SFA.DAS.Events.Api.Types; namespace SFA.DAS.Data.Worker.Events.EventsCollectors { public interface IEventsCollector<T> { Task<ICollection<T>> GetEvents(); } }
20.916667
53
0.729084
[ "MIT" ]
SkillsFundingAgency/das-data
src/SFA.DAS.Data.Worker/Events/EventsCollectors/IEventsCollector.cs
253
C#
using System; namespace Apocalypse.Any.Core.Model.Damage { /// <summary> /// A dynamic damage that can be lazy loaded or its implementation can be changed at runtime /// </summary> /// <typeparam name="TDamageValueType"></typeparam> public sealed class DynamicDamage<TDamageValueType> : Damage<TDamageValueType> where TDamageValueType : struct { private Func<TDamageValueType> InternalDamageFn { get; set; } public override TDamageValueType GetDamage() => InternalDamageFn == null ? throw new ArgumentNullException("No default declaration for dynamic damage") : InternalDamageFn(); public DynamicDamage(Func<TDamageValueType> internalDamageFn) { InternalDamageFn = internalDamageFn ?? throw new ArgumentNullException("No default declaration for dynamic damage"); } } }
39.454545
136
0.701613
[ "MIT" ]
inidibininging/apocalypse_netcore
Apocalypse.Any.Core/Model/Damage/DynamicDamage.cs
870
C#
using Agridea.Diagnostics.Contracts; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; namespace Agridea.Web.Mvc.Grid { public static class GridHelper { public static string GetDefaultOrderProperty<T>() { Asserts<ArgumentException>.IsTrue(typeof(T).GetProperty(GridParameters.DefaultPropertyName) != null, string.Format("If you don't define any ordering, {0} should have a property {1}", typeof(T).Name, GridParameters.DefaultPropertyName)); return GridParameters.DefaultPropertyName; } public static string BuildUrl<T>(this ControllerContext context, T item, RouteValueDictionary routeValues, IList<IGridDataKey<T>> dataKeys) { foreach (var dataKey in dataKeys.Where(dataKey => routeValues.ContainsKey(dataKey.Name))) { routeValues[dataKey.Name] = dataKey.GetValue(item); } return context.BuildUrl(routeValues); } public static string BuildUrl(this ControllerContext context, RouteValueDictionary routeValues, IEnumerable<IGridDataKey> dataKeys) { foreach (var dataKey in dataKeys) { if (routeValues.ContainsKey(dataKey.Name)) { var queryString = context.HttpContext.Request.QueryString; if (queryString.HasKeys() && queryString[dataKey.Name] != null) { routeValues[dataKey.Name] = queryString[dataKey.Name]; } } } return context.BuildUrl(routeValues); } private static string BuildUrl(this ControllerContext context, RouteValueDictionary routeValues) { return UrlHelper.GenerateUrl(null, null, null, routeValues, RouteTable.Routes, context.RequestContext, true); } public static IDictionary<string, object> DictionaryParse(this object withProperties) { return TypeDescriptor.GetProperties(withProperties) .Cast<PropertyDescriptor>() .ToDictionary(property => property.Name, property => property.GetValue(withProperties)); } public static RouteValueDictionary GetRouteValueDictionary(this ControllerContext context, string methodName, bool usePostAction) { var routeValues = new RouteValueDictionary(); var controller = context.Controller; var controllerName = MvcExpressionHelper.GetControllerName(controller.GetType()); routeValues.Add(GridParameters.ControllerKey, controllerName); routeValues.Add(GridParameters.ActionKey, methodName); var methods = controller.GetType().GetMethods().Where(m => m.Name == methodName); MethodInfo methodInfo; if (methods.Count() == 1) methodInfo = methods.First(); else methodInfo = methods.First(x => usePostAction ? x.GetCustomAttributes(true).OfType<HttpPostAttribute>().Any() : !x.GetCustomAttributes(true).OfType<HttpPostAttribute>().Any()); Requires<ArgumentException>.IsNotNull(methodInfo, string.Format("There's no method {0} in controller {1}", methodName, controllerName)); foreach (var parameter in methodInfo.GetParameters()) routeValues.Add(parameter.Name, parameter.ParameterType.IsValueType ? Activator.CreateInstance(parameter.ParameterType) : null); return routeValues; } } }
45.433735
151
0.631663
[ "MIT" ]
ni11c/AkkaJobs
AgrideaCore/Web/Mvc/Grid/Extensions/GridHelper.cs
3,773
C#
using System; using System.Threading; using Xunit; namespace DelimitedDataParser { public partial class ParserTest { [Fact] public void Can_Cancel_Parse() { var cts = new CancellationTokenSource(); cts.Cancel(); var parser = new Parser { UseFirstRowAsColumnHeaders = false }; Assert.Throws<OperationCanceledException>(() => parser.Parse(GetTextReader("R1C1"), cts.Token)); } [Fact] public void Can_Cancel_ParseReader_Read() { var input = @"One" + Environment.NewLine + @"Two"; var cts = new CancellationTokenSource(); var parser = new Parser { UseFirstRowAsColumnHeaders = false }; using (var reader = parser.ParseReader(GetTextReader(input), cts.Token)) { reader.Read(); cts.Cancel(); Assert.Throws<OperationCanceledException>(() => reader.Read()); } } [Fact] public void Can_Cancel_ParseReader_ReadAsync() { var cts = new CancellationTokenSource(); cts.Cancel(); var parser = new Parser { UseFirstRowAsColumnHeaders = false }; using (var reader = parser.ParseReader(GetTextReader("R1C1"))) { Assert.ThrowsAsync<OperationCanceledException>(() => reader.ReadAsync(cts.Token)); } } } }
26.147541
108
0.51348
[ "MIT" ]
EnableSoftware/DelimitedDataParser
test/DelimitedDataParser.Test/ParserTest.CancellationToken.cs
1,597
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2019 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2020 Senparc 文件名:GetApplyProtocolJsonResult.cs 文件功能描述:卡券开放类目查询的返回结果 创建标识:Senparc - 20160520 修改标识:Senparc - 20160520 修改描述:整理接口 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Senparc.Weixin.Entities; namespace Senparc.Weixin.MP.AdvancedAPIs.Card { /// <summary> /// 卡券开放类目查询的返回结果 /// </summary> public class GetApplyProtocolJsonResult : WxJsonResult { public List<GetApplyProtocol_Category> category { get; set; } } public class GetApplyProtocol_Category { /// <summary> /// 一级目录id /// </summary> public int primary_category_id { get; set; } /// <summary> /// /// </summary> public string category_name { get; set; } /// <summary> /// 二级目录id /// </summary> public List<GetApplyProtocol_Secondary_Category> secondary_category { get; set; } } public class GetApplyProtocol_Secondary_Category { /// <summary> /// secondary_category_id /// </summary> public int secondary_category_id { get; set; } /// <summary> /// category_name /// </summary> public string category_name { get; set; } /// <summary> /// need_qualification_stuffs /// </summary> public List<string> need_qualification_stuffs { get; set; } /// <summary> /// can_choose_prepaid_card /// </summary> public int can_choose_prepaid_card { get; set; } /// <summary> /// can_choose_payment_card /// </summary> public int can_choose_payment_card { get; set; } } }
29.870968
90
0.586393
[ "Apache-2.0" ]
Frunck8206/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Card/Submerchat/GetApplyProtocolJsonResult.cs
2,908
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("hacbuild")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("hacbuild")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("423bc4fd-36ba-4356-aa31-84269d80d36b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.540541
84
0.743701
[ "MIT" ]
LucaCorigliano/hacbuild
hacbuild/Properties/AssemblyInfo.cs
1,392
C#
namespace StripeTests { using Newtonsoft.Json; using Stripe; using Xunit; public class CustomerBalanceTransactionTest : BaseStripeTest { public CustomerBalanceTransactionTest(StripeMockFixture stripeMockFixture) : base(stripeMockFixture) { } [Fact] public void Deserialize() { string json = this.GetFixture("/v1/customers/cus_123/balance_transactions/cbtxn_123"); var transaction = JsonConvert.DeserializeObject<CustomerBalanceTransaction>(json); Assert.NotNull(transaction); Assert.IsType<CustomerBalanceTransaction>(transaction); Assert.NotNull(transaction.Id); Assert.Equal("customer_balance_transaction", transaction.Object); } [Fact] public void DeserializeWithExpansions() { string[] expansions = { "credit_note", "customer", "invoice", }; string json = this.GetFixture("/v1/customers/cus_123/balance_transactions/cbtxn_123", expansions); var transaction = JsonConvert.DeserializeObject<CustomerBalanceTransaction>(json); Assert.NotNull(transaction); Assert.IsType<CustomerBalanceTransaction>(transaction); Assert.NotNull(transaction.Id); Assert.Equal("customer_balance_transaction", transaction.Object); Assert.NotNull(transaction.CreditNote); Assert.Equal("credit_note", transaction.CreditNote.Object); Assert.NotNull(transaction.Customer); Assert.Equal("customer", transaction.Customer.Object); Assert.NotNull(transaction.Invoice); Assert.Equal("invoice", transaction.Invoice.Object); } } }
34.433962
110
0.630137
[ "Apache-2.0" ]
Furysoft/stripe-dotnet
src/StripeTests/Entities/CustomerBalanceTransactions/CustomerBalanceTransactionTest.cs
1,825
C#
using MMBackend.MapEditor; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace CTF.MapEditor { public class DeleteButton : MonoBehaviour { public EditorJudgementHolder judgementHolder; public Timer timer; void Start() { GetComponent<Button>().onClick.AddListener(Remove); } /// <summary> /// Removes a judgement. /// Used to remove an index from judgementHolder list and sets the timer to index - 1. /// </summary> void Remove() { int active = timer.GetActiveJudgement(); judgementHolder.RemoveJudgement(active); if (active != 0) timer.SetActiveJudgement(active - 1); else timer.SetActiveJudgement(active); } } }
26.375
94
0.616114
[ "MIT" ]
2haus/MateMatirun
Assets/Scripts/MapEditor/DeleteButton.cs
846
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TFSUpgradeTeamProjectFeatures { class TextWriterDebug : TextWriter { public override Encoding Encoding { get { return Encoding.Default; } } public override void Close() { Debug.Close(); base.Close(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } public override void Flush() { Debug.Flush(); base.Flush(); } public override void Write(bool value) { Debug.Write(value); } public override void Write(char value) { Debug.Write(value); } public override void Write(char[] buffer) { Debug.Write(buffer); } public override void Write(decimal value) { Debug.Write(value); } public override void Write(double value) { Debug.Write(value); } public override void Write(float value) { Debug.Write(value); } public override void Write(int value) { Debug.Write(value); } public override void Write(long value) { Debug.Write(value); } public override void Write(object value) { Debug.Write(value); } public override void Write(string value) { Debug.Write(value); } public override void Write(uint value) { Debug.Write(value); } public override void Write(ulong value) { Debug.Write(value); } public override void Write(string format, object arg0) { Debug.Write(string.Format(format, arg0)); } public override void Write(string format, params object[] arg) { Debug.Write(string.Format(format, arg)); } public override void Write(char[] buffer, int index, int count) { string x = new string(buffer, index, count); Debug.Write(x); } public override void Write(string format, object arg0, object arg1) { Debug.Write(string.Format(format, arg0, arg1)); } public override void Write(string format, object arg0, object arg1, object arg2) { Debug.Write(string.Format(format, arg0, arg1, arg2)); } public override void WriteLine() { Debug.WriteLine(string.Empty); } public override void WriteLine(bool value) { Debug.WriteLine(value); } public override void WriteLine(char value) { Debug.WriteLine(value); } public override void WriteLine(char[] buffer) { Debug.WriteLine(buffer); } public override void WriteLine(decimal value) { Debug.WriteLine(value); } public override void WriteLine(double value) { Debug.WriteLine(value); } public override void WriteLine(float value) { Debug.WriteLine(value); } public override void WriteLine(int value) { Debug.WriteLine(value); } public override void WriteLine(long value) { Debug.WriteLine(value); } public override void WriteLine(object value) { Debug.WriteLine(value); } public override void WriteLine(string value) { Debug.WriteLine(value); } public override void WriteLine(uint value) { Debug.WriteLine(value); } public override void WriteLine(ulong value) { Debug.WriteLine(value); } public override void WriteLine(string format, object arg0) { Debug.WriteLine(string.Format(format, arg0)); } public override void WriteLine(string format, params object[] arg) { Debug.WriteLine(string.Format(format, arg)); } public override void WriteLine(char[] buffer, int index, int count) { string x = new string(buffer, index, count); Debug.WriteLine(x); } public override void WriteLine(string format, object arg0, object arg1) { Debug.WriteLine(string.Format(format, arg0, arg1)); } public override void WriteLine(string format, object arg0, object arg1, object arg2) { Debug.WriteLine(string.Format(format, arg0, arg1, arg2)); } } }
23.060465
92
0.530254
[ "MIT" ]
kszicsillag/TFSUpgradeTeamProjectFeatures
TFSUpgradeTeamProjectFeatures/DebugWriter.cs
4,960
C#
namespace DigitRecognizerBot.Services { public class MLStudioDigitRecognizerConfiguration { /// <summary> /// URL of the MLStudioDigitRecognizer service. /// </summary> public string ServiceUrl { get; set; } /// <summary> /// API Key used for authentication with the MLStudioDigitRecognizer service. /// </summary> public string ApiKey { get; set; } } }
27
85
0.611111
[ "MIT" ]
Bhawk90/digit-recognizer-bot
digit-recognizer-bot/Services/MLStudioDigitRecognizerConfiguration.cs
434
C#
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Thrift; using Thrift.Collections; using System.Runtime.Serialization; using Thrift.Protocol; using Thrift.Transport; namespace Net.Thrift { #if !SILVERLIGHT [Serializable] #endif public partial class ResponseUserLogin : TBase { private string _gameserver; /// <summary> /// /// <seealso cref="LoginCode"/> /// </summary> public LoginCode Code { get; set; } public string Msg { get; set; } public int Uid { get; set; } public string Passport { get; set; } public string SecureKey { get; set; } public string Gameserver { get { return _gameserver; } set { __isset.gameserver = true; this._gameserver = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool gameserver; } public ResponseUserLogin() { } public ResponseUserLogin(LoginCode code, string msg, int uid, string passport, string secureKey) : this() { this.Code = code; this.Msg = msg; this.Uid = uid; this.Passport = passport; this.SecureKey = secureKey; } public void Read (TProtocol iprot) { bool isset_code = false; bool isset_msg = false; bool isset_uid = false; bool isset_passport = false; bool isset_secureKey = false; TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.I32) { Code = (LoginCode)iprot.ReadI32(); isset_code = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.String) { Msg = iprot.ReadString(); isset_msg = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I32) { Uid = iprot.ReadI32(); isset_uid = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.String) { Passport = iprot.ReadString(); isset_passport = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.String) { SecureKey = iprot.ReadString(); isset_secureKey = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 6: if (field.Type == TType.String) { Gameserver = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); if (!isset_code) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_msg) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_uid) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_passport) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_secureKey) throw new TProtocolException(TProtocolException.INVALID_DATA); } public void Write(TProtocol oprot) { TStruct struc = new TStruct("ResponseUserLogin"); oprot.WriteStructBegin(struc); TField field = new TField(); field.Name = "code"; field.Type = TType.I32; field.ID = 1; oprot.WriteFieldBegin(field); oprot.WriteI32((int)Code); oprot.WriteFieldEnd(); field.Name = "msg"; field.Type = TType.String; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteString(Msg); oprot.WriteFieldEnd(); field.Name = "uid"; field.Type = TType.I32; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI32(Uid); oprot.WriteFieldEnd(); field.Name = "passport"; field.Type = TType.String; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteString(Passport); oprot.WriteFieldEnd(); field.Name = "secureKey"; field.Type = TType.String; field.ID = 5; oprot.WriteFieldBegin(field); oprot.WriteString(SecureKey); oprot.WriteFieldEnd(); if (Gameserver != null && __isset.gameserver) { field.Name = "gameserver"; field.Type = TType.String; field.ID = 6; oprot.WriteFieldBegin(field); oprot.WriteString(Gameserver); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } public override string ToString() { StringBuilder __sb = new StringBuilder("ResponseUserLogin("); __sb.Append(", Code: "); __sb.Append(Code); __sb.Append(", Msg: "); __sb.Append(Msg); __sb.Append(", Uid: "); __sb.Append(Uid); __sb.Append(", Passport: "); __sb.Append(Passport); __sb.Append(", SecureKey: "); __sb.Append(SecureKey); if (Gameserver != null && __isset.gameserver) { __sb.Append(", Gameserver: "); __sb.Append(Gameserver); } __sb.Append(")"); return __sb.ToString(); } } }
26.264317
111
0.556692
[ "Apache-2.0" ]
live106/TetrisClone
Assets/Scripts/Net/Thrift/ResponseUserLogin.cs
5,962
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Localisation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Input.Events; using osu.Game.Audio; using osu.Game.Beatmaps.Drawables.Cards; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.Containers; using osu.Game.Overlays.BeatmapListing; using osu.Game.Resources.Localisation.Web; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays { public class BeatmapListingOverlay : OnlineOverlay<BeatmapListingHeader> { [Resolved] private PreviewTrackManager previewTrackManager { get; set; } private Drawable currentContent; private Container panelTarget; private FillFlowContainer<BeatmapCard> foundContent; private NotFoundDrawable notFoundContent; private SupporterRequiredDrawable supporterRequiredContent; private BeatmapListingFilterControl filterControl; public BeatmapListingOverlay() : base(OverlayColourScheme.Blue) { } [BackgroundDependencyLoader] private void load() { Child = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { filterControl = new BeatmapListingFilterControl { TypingStarted = onTypingStarted, SearchStarted = onSearchStarted, SearchFinished = onSearchFinished, }, new Container { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = ColourProvider.Background5, }, panelTarget = new Container { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Masking = true, Padding = new MarginPadding { Horizontal = 20 }, Children = new Drawable[] { foundContent = new FillFlowContainer<BeatmapCard>(), notFoundContent = new NotFoundDrawable(), supporterRequiredContent = new SupporterRequiredDrawable(), } } }, }, } }; } public void ShowWithSearch(string query) { filterControl.Search(query); Show(); } protected override BeatmapListingHeader CreateHeader() => new BeatmapListingHeader(); protected override Color4 BackgroundColour => ColourProvider.Background6; private void onTypingStarted() { // temporary until the textbox/header is updated to always stay on screen. ScrollFlow.ScrollToStart(); } protected override void OnFocus(FocusEvent e) { base.OnFocus(e); filterControl.TakeFocus(); } private CancellationTokenSource cancellationToken; private void onSearchStarted() { cancellationToken?.Cancel(); previewTrackManager.StopAnyPlaying(this); if (panelTarget.Any()) Loading.Show(); } private Task panelLoadDelegate; private void onSearchFinished(BeatmapListingFilterControl.SearchResult searchResult) { if (searchResult.Type == BeatmapListingFilterControl.SearchResultType.SupporterOnlyFilters) { supporterRequiredContent.UpdateText(searchResult.SupporterOnlyFiltersUsed); addContentToPlaceholder(supporterRequiredContent); return; } var newPanels = searchResult.Results.Select(b => new BeatmapCard(b) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }); if (filterControl.CurrentPage == 0) { //No matches case if (!newPanels.Any()) { addContentToPlaceholder(notFoundContent); return; } // spawn new children with the contained so we only clear old content at the last moment. var content = new FillFlowContainer<BeatmapCard> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10), Alpha = 0, Margin = new MarginPadding { Vertical = 15 }, ChildrenEnumerable = newPanels }; panelLoadDelegate = LoadComponentAsync(foundContent = content, addContentToPlaceholder, (cancellationToken = new CancellationTokenSource()).Token); } else { panelLoadDelegate = LoadComponentsAsync(newPanels, loaded => { lastFetchDisplayedTime = Time.Current; foundContent.AddRange(loaded); loaded.ForEach(p => p.FadeIn(200, Easing.OutQuint)); }); } } private void addContentToPlaceholder(Drawable content) { Loading.Hide(); lastFetchDisplayedTime = Time.Current; if (content == currentContent) return; var lastContent = currentContent; if (lastContent != null) { lastContent.FadeOut(100, Easing.OutQuint); // Consider the case when the new content is smaller than the last content. // If the auto-size computation is delayed until fade out completes, the background remain high for too long making the resulting transition to the smaller height look weird. // At the same time, if the last content's height is bypassed immediately, there is a period where the new content is at Alpha = 0 when the auto-sized height will be 0. // To resolve both of these issues, the bypass is delayed until a point when the content transitions (fade-in and fade-out) overlap and it looks good to do so. var sequence = lastContent.Delay(25).Schedule(() => lastContent.BypassAutoSizeAxes = Axes.Y); if (lastContent != notFoundContent && lastContent != supporterRequiredContent) sequence.Then().Schedule(() => lastContent.Expire()); } if (!content.IsAlive) panelTarget.Add(content); content.FadeInFromZero(200, Easing.OutQuint); currentContent = content; // currentContent may be one of the placeholders, and still have BypassAutoSizeAxes set to Y from the last fade-out. // restore to the initial state. currentContent.BypassAutoSizeAxes = Axes.None; } protected override void Dispose(bool isDisposing) { cancellationToken?.Cancel(); base.Dispose(isDisposing); } public class NotFoundDrawable : CompositeDrawable { public NotFoundDrawable() { RelativeSizeAxes = Axes.X; Height = 250; Alpha = 0; Margin = new MarginPadding { Top = 15 }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { AddInternal(new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, AutoSizeAxes = Axes.X, Direction = FillDirection.Horizontal, Spacing = new Vector2(10, 0), Children = new Drawable[] { new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, Texture = textures.Get(@"Online/not-found") }, new OsuSpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = BeatmapsStrings.ListingSearchNotFoundQuote, } } }); } } // TODO: localisation requires Text/LinkFlowContainer support for localising strings with links inside // (https://github.com/ppy/osu-framework/issues/4530) public class SupporterRequiredDrawable : CompositeDrawable { private LinkFlowContainer supporterRequiredText; public SupporterRequiredDrawable() { RelativeSizeAxes = Axes.X; Height = 225; Alpha = 0; } [BackgroundDependencyLoader] private void load(TextureStore textures) { AddInternal(new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, AutoSizeAxes = Axes.X, Direction = FillDirection.Horizontal, Children = new Drawable[] { new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, Texture = textures.Get(@"Online/supporter-required"), }, supporterRequiredText = new LinkFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Margin = new MarginPadding { Bottom = 10 }, }, } }); } public void UpdateText(List<LocalisableString> filters) { supporterRequiredText.Clear(); supporterRequiredText.AddText( BeatmapsStrings.ListingSearchSupporterFilterQuoteDefault(string.Join(" and ", filters), "").ToString(), t => { t.Font = OsuFont.GetFont(size: 16); t.Colour = Colour4.White; } ); supporterRequiredText.AddLink(BeatmapsStrings.ListingSearchSupporterFilterQuoteLinkText.ToString(), @"/store/products/supporter-tag"); } } private const double time_between_fetches = 500; private double lastFetchDisplayedTime; protected override void Update() { base.Update(); const int pagination_scroll_distance = 500; bool shouldShowMore = panelLoadDelegate?.IsCompleted != false && Time.Current - lastFetchDisplayedTime > time_between_fetches && (ScrollFlow.ScrollableExtent > 0 && ScrollFlow.IsScrolledToEnd(pagination_scroll_distance)); if (shouldShowMore) filterControl.FetchNextPage(); } } }
38.740413
191
0.503617
[ "MIT" ]
MBmasher/osu
osu.Game/Overlays/BeatmapListingOverlay.cs
12,797
C#
// // System.Net.Mail.SmtpPermission // // Authors: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Security; using System.Security.Permissions; namespace System.Net.Mail { [Serializable] public sealed class SmtpPermission : CodeAccessPermission, IUnrestrictedPermission { private const int version = 1; private bool unrestricted; private SmtpAccess access; public SmtpPermission (bool unrestricted) : base () { this.unrestricted = unrestricted; access = unrestricted ? SmtpAccess.ConnectToUnrestrictedPort : SmtpAccess.None; } public SmtpPermission (PermissionState state) : base () { unrestricted = (state == PermissionState.Unrestricted); access = unrestricted ? SmtpAccess.ConnectToUnrestrictedPort : SmtpAccess.None; } public SmtpPermission (SmtpAccess access) : base () { // this ctor can accept invalid enum values this.access = access; } public SmtpAccess Access { get { return access; } } public void AddPermission (SmtpAccess access) { if (!unrestricted && (access > this.access)) { this.access = access; } } public override IPermission Copy () { if (unrestricted) { return new SmtpPermission (true); } else { return new SmtpPermission (access); } } public override IPermission Intersect (IPermission target) { SmtpPermission sp = Cast (target); if (sp == null) return null; if (unrestricted && sp.unrestricted) return new SmtpPermission (true); else if (access > sp.access) return new SmtpPermission (sp.access); else return new SmtpPermission (access); } public override bool IsSubsetOf (IPermission target) { SmtpPermission sp = Cast (target); if (sp == null) return IsEmpty (); if (unrestricted) { return sp.unrestricted; } else { return (access <= sp.access); } } public bool IsUnrestricted () { return unrestricted; } public override SecurityElement ToXml () { SecurityElement se = PermissionHelper.Element (typeof (SmtpPermission), version); if (unrestricted) { se.AddAttribute ("Unrestricted", "true"); } else { switch (access) { case SmtpAccess.ConnectToUnrestrictedPort: se.AddAttribute ("Access", "ConnectToUnrestrictedPort"); break; case SmtpAccess.Connect: se.AddAttribute ("Access", "Connect"); break; // note: SmtpAccess.None and invalid values aren't serialized to XML } } return se; } public override void FromXml (SecurityElement securityElement) { PermissionHelper.CheckSecurityElement (securityElement, "securityElement", version, version); // LAMESPEC: it says to throw an ArgumentNullException in this case if (securityElement.Tag != "IPermission") throw new ArgumentException ("securityElement"); if (PermissionHelper.IsUnrestricted (securityElement)) access = SmtpAccess.Connect; else access = SmtpAccess.None; } public override IPermission Union (IPermission target) { SmtpPermission sp = Cast (target); if (sp == null) return Copy (); if (unrestricted || sp.unrestricted) return new SmtpPermission (true); else if (access > sp.access) return new SmtpPermission (access); else return new SmtpPermission (sp.access); } // Internal helpers methods private bool IsEmpty () { return (!unrestricted && (access == SmtpAccess.None)); } private SmtpPermission Cast (IPermission target) { if (target == null) return null; SmtpPermission sp = (target as SmtpPermission); if (sp == null) { PermissionHelper.ThrowInvalidPermission (target, typeof (SmtpPermission)); } return sp; } } } #endif
26.073684
96
0.688938
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/class/System/System.Net.Mail/SmtpPermission.cs
4,954
C#
using System; using System.Threading.Tasks; using Cosmos.Debug.Kernel; using Cosmos.TestRunner; namespace Cosmos.Compiler.Tests.Bcl.System { public static class StringTest { public static void Execute() { Assert.IsTrue(("a" + "b") == "ab", "concatting 2 string using + doesn't work"); Assert.IsTrue(("a" + 'b') == "ab", "concatting 1 string and 1 character doesn't work"); string a = "a"; string b = "b"; string result = a + b; Assert.IsTrue(result == "ab", "concatting 2 string (not optimizable) using + doesn't work"); // Fails char x = 'a'; string y = "a"; Assert.IsTrue(x.ToString() == y, "String == operator "); string str = "Cosmos is awesome!"; string expected = "Cosmos"; string substr = str.Substring(0, 6); Assert.IsTrue((substr == expected), "Substring is not equal to the expected result, result should be \"Cosmos\". Substrings are broken or MichaelTheShifter made an off-by-one error."); int value1 = 1; string value2 = "4"; string expected_res = "1 + 3 = 4"; Assert.IsTrue(($"{value1} + 3 = {value2}" == expected_res), "String $ operator does not work."); string split_in = "ABC"; var xResultArray = split_in.Split('B'); Assert.IsTrue(xResultArray.Length == 2, "String.Split(char[]) doesn't work."); xResultArray = split_in.Split(new[] { "B" }, StringSplitOptions.None); Assert.IsTrue(xResultArray.Length == 2, "String.Split(string[], StringSplitOptions) doesn't work."); string test = "This is a test string."; Assert.IsTrue(test.Contains("test"), "string.Contains(string) doesn't find a substring that actually exists."); Assert.IsFalse(test.Contains("cosmos"), "string.Contains(string) found a substring that didn't actually exist in a string."); //Assert.IsTrue(test.EndsWith("string."), "string.EndsWith(string) is not reporting false even though the string actually does end with the substring."); //Assert.IsFalse(test.EndsWith("sentence."), "string.EndsWith(string) is not reporting true even though the string actually doesn't end with the substring."); Assert.IsTrue(test.StartsWith("This"), "string.StartsWith(string) is reporting false even though the string does start with the supplied substring."); Assert.IsFalse(test.StartsWith("That"), "string.StartsWith(string) is reporting true even though the string doesn't start with the supplied substring."); string lower_expected = "this is a test string."; string upper_expected = "THIS IS A TEST STRING."; Assert.IsTrue((test.ToLower() == lower_expected), "string.ToLower() does not work."); Assert.IsTrue((test.ToUpper() == upper_expected), "string.ToUpper() does not work."); string replace_test = "That is a test string."; Assert.IsTrue((test.Replace("This", "That") == replace_test), "string.Replace(string, string) does not work."); string char_array_test = "char"; char[] char_array_expected = { 'c', 'h', 'a', 'r' }; Assert.IsTrue((char_array_test.ToCharArray().Length == 4), "string.ToCharArray() does not work."); } } }
50.955224
196
0.613943
[ "BSD-3-Clause" ]
ERamaM/Cosmos
Tests/Cosmos.Compiler.Tests.Bcl/System/StringTest.cs
3,416
C#
using AutoMapper; using MediatR; using Ordering.Application.Contracts.Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ordering.Application.Features.Orders.Queries.GetOrderList { public class GetOrdersListQueryHandler : IRequestHandler<GetOrdersListQuery, List<OrderViewModel>> { private readonly IOrderRepository _orderRepository; private readonly IMapper _mapper; public GetOrdersListQueryHandler(IOrderRepository orderRepository, IMapper mapper) { _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } public async Task<List<OrderViewModel>> Handle(GetOrdersListQuery request, CancellationToken cancellationToken) { var orderList = await _orderRepository.GetOrdersByUserName(request.UserName); return _mapper.Map<List<OrderViewModel>>(orderList); } } }
35.15625
107
0.736
[ "MIT" ]
andguto/AspNetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Queries/GetOrderList/GetOrdersListQueryHandler.cs
1,127
C#
using System; using System.Runtime.InteropServices; namespace hds { public class AttributeClass2625 :GameObject { public Attribute Orientation = new Attribute(16, "Orientation"); public Attribute Position = new Attribute(24, "Position"); public Attribute HalfExtents = new Attribute(12, "HalfExtents"); public AttributeClass2625(string name,UInt16 _goid) : base(3, 0, name, _goid, 0xFFFFFFFF) { AddAttribute(ref Orientation, 0, -1); AddAttribute(ref Position, 1, -1); AddAttribute(ref HalfExtents, 2, -1); } } }
24.166667
68
0.677586
[ "MIT" ]
hdneo/mxo-hd
hds/resources/gameobjects/definitions/AttributeClasses/AttributeClass2625.cs
580
C#
using System; using System.Collections.Generic; using System.Linq; using TriggersTools.SharpUtils.Collections; namespace TriggersTools.SharpUtils.IO { /// <summary> /// Extension methods for the <see cref="IDisposable"/> interface. /// </summary> public static class IDisposableExtensions { #region ToDisposableCollection /// <summary> /// Takes the source collection and adds it to a disposable collection. /// </summary> /// <typeparam name="T">The element type of the collection.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A new disposable collection containing the elements from the source collection.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is null. /// </exception> public static DisposableCollection<T> ToDisposableCollection<T>(this IEnumerable<T> source) where T : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); return new DisposableCollection<T>(source.ToList()); } #endregion #region ToDisposableArray /// <summary> /// Takes the source collection and adds it to a disposable array. /// </summary> /// <typeparam name="T">The element type of the collection.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A new disposable array containing the elements from the source collection.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is null. /// </exception> public static DisposableArray<T> ToDisposableArray<T>(this IEnumerable<T> source) where T : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); return new DisposableArray<T>(source.ToArray()); } /// <summary> /// Takes the source collection and adds it to a disposable array. /// </summary> /// <typeparam name="T">The element type of the collection.</typeparam> /// <param name="source">The source collection.</param> /// <returns>A new disposable array containing the elements from the source collection.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is null. /// </exception> public static DisposableArray<T> ToDisposableArray<T>(this ICollection<T> source) where T : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); T[] newSource = new T[source.Count]; source.CopyTo(newSource, 0); return new DisposableArray<T>(newSource); } /// <summary> /// Takes the source collection and adds it to a disposable array. /// </summary> /// <typeparam name="T">The element type of the array.</typeparam> /// <param name="source">The source array.</param> /// <returns>A new disposable array containing the elements from the source array.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is null. /// </exception> public static DisposableArray<T> ToDisposableArray<T>(this T[] source) where T : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); T[] newSource = new T[source.Length]; Array.Copy(source, newSource, source.Length); return new DisposableArray<T>(newSource); } #endregion } }
35.351064
104
0.692447
[ "MIT" ]
trigger-death/TriggersTools.SharpUtils
src/TriggersTools.SharpUtils/IO/IDisposableExtensions.cs
3,325
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Management.Automation; using Hyak.Common; using Microsoft.Azure.Commands.Insights.Properties; using Microsoft.Azure.Management.Insights.Models; namespace Microsoft.Azure.Commands.Insights.Alerts { /// <summary> /// Add an Alert rule /// </summary> [Cmdlet(VerbsCommon.Add, "AlertRule"), OutputType(typeof(List<PSObject>))] public class AddAlertRuleCommand : AddAlertRuleCommandBase { #region Cmdlet parameters for Event and Metric alert rules /// <summary> /// Gets or sets the rule condition operator /// </summary> [Parameter(ParameterSetName = AddMetricAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule condition operator")] [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The rule condition operator")] public ConditionOperator Operator { get; set; } /// <summary> /// Gets or sets the rule threshold /// </summary> [Parameter(ParameterSetName = AddMetricAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The threshold for rule condition")] [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The threshold for rule condition")] public double Threshold { get; set; } /// <summary> /// Gets or sets the ResourceId parameter /// </summary> [Parameter(ParameterSetName = AddMetricAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource id for rule")] [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource id for rule")] [ValidateNotNullOrEmpty] public string ResourceId { get; set; } #endregion #region Cmdlet parameters for Event alert rules /// <summary> /// Gets or sets the EventName parameters /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The event name for rule")] [ValidateNotNullOrEmpty] public string EventName { get; set; } /// <summary> /// Gets or sets the EventSource parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The event source for rule")] public string EventSource { get; set; } /// <summary> /// Gets or sets the Level parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The level for rule")] public string Level { get; set; } /// <summary> /// Gets or sets the OperationName parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The operation name for rule")] public string OperationName { get; set; } /// <summary> /// Gets or sets the ResourceProvider parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource provider for rule")] public string ResourceProvider { get; set; } /// <summary> /// Gets or sets the Status parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The status for rule")] public string Status { get; set; } /// <summary> /// Gets or sets the SubStatus parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The substatus for rule")] public string SubStatus { get; set; } #endregion #region Cmdlet parameters for Metric alert rules /// <summary> /// Gets or sets the EmailAddress parameter /// </summary> [Parameter(ParameterSetName = AddEventAlertParamGroup, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The e-mail address for rule")] public string EmailAddress { get; set; } /// <summary> /// Gets or sets the MetricName parameter /// </summary> [Parameter(ParameterSetName = AddMetricAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The metric name for rule")] [ValidateNotNullOrEmpty] public string MetricName { get; set; } /// <summary> /// Gets or sets the TimeAggregationOperator parameter /// </summary> [Parameter(ParameterSetName = AddMetricAlertParamGroup, ValueFromPipelineByPropertyName = true, HelpMessage = "The time aggregation operator for rule")] public TimeAggregationOperator? TimeAggregationOperator { get; set; } #endregion #region Cmdlet parameters for Webtest alert rules /// <summary> /// Gets or sets the FailedLocationCount parameter /// </summary> [Parameter(ParameterSetName = AddWebtestAlertParamGroup, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The failed location count for rule")] public int FailedLocationCount { get; set; } #endregion private ManagementEventRuleCondition CreateEventRuleCondition() { return new ManagementEventRuleCondition() { Aggregation = new ManagementEventAggregationCondition() { Operator = this.Operator, Threshold = this.Threshold, WindowSize = this.WindowSize, }, DataSource = new RuleManagementEventDataSource() { EventName = this.EventName, EventSource = this.EventSource, Level = this.Level, OperationName = this.OperationName, ResourceGroupName = this.ResourceGroup, ResourceProviderName = this.ResourceProvider, ResourceUri = this.ResourceId, Status = this.Status, SubStatus = this.SubStatus, Claims = new RuleManagementEventClaimsDataSource() { EmailAddress = this.EmailAddress, }, }, }; } private void VerifyRuleTypeToParametersConsistency() { WriteVerboseWithTimestamp(string.Format("VerifyRuleTypeToParametersConsistency: input type:{0}", this.RuleType)); AlertRuleTypes type = AlertRuleTypes.Event; // NOTE: the parameters EventName and MetricName cannot appear both at same time (see the parameters declaration), but they can be both absent simultaneously (i.e. Webtest data source type) if (string.IsNullOrWhiteSpace(this.EventName)) { type = string.IsNullOrWhiteSpace(MetricName) ? AlertRuleTypes.Webtest : AlertRuleTypes.Metric; } // This comparison is more or less superflous because the parameter sets enforce consistency. But the user will be informed if the input is not consistent with the intention if (type != this.RuleType) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourcesForAlertCmdlets.RuleTypeNotConsistentWithParamGroup, this.RuleType)); } } private ThresholdRuleCondition CreateThresholdRuleCondition() { return new ThresholdRuleCondition() { DataSource = new RuleMetricDataSource() { MetricName = this.MetricName, ResourceUri = this.ResourceId, }, Operator = this.Operator, Threshold = this.Threshold, TimeAggregation = this.TimeAggregationOperator ?? DefaultTimeAggregationOperator, WindowSize = this.WindowSize, }; } private RuleCondition CreateRuleCondition() { // Since WindowSize is not mandatory, but it cannot be null (TimeSpan) checking for default value if (this.WindowSize == default(TimeSpan)) { this.WindowSize = DefaultWindowSize; } RuleCondition condition; switch (this.RuleType) { case AlertRuleTypes.Event: WriteVerboseWithTimestamp(string.Format("CreateRuleCondition: Creating event rule condition (event-based rule)")); condition = this.CreateEventRuleCondition(); break; case AlertRuleTypes.Metric: WriteVerboseWithTimestamp(string.Format("CreateRuleCondition: Creating threshold rule condition (metric-based rule")); condition = this.CreateThresholdRuleCondition(); break; case AlertRuleTypes.Webtest: WriteVerboseWithTimestamp(string.Format("CreateRuleCondition: Creating location threshold rule condition (webtest rule)")); condition = new LocationThresholdRuleCondition() { DataSource = new RuleMetricDataSource(), FailedLocationCount = this.FailedLocationCount, WindowSize = this.WindowSize, }; break; default: throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourcesForAlertCmdlets.RuleTypeNotSupported, this.RuleType)); } return condition; } protected override RuleCreateOrUpdateParameters CreateSdkCallParameters() { this.VerifyRuleTypeToParametersConsistency(); RuleCondition condition = this.CreateRuleCondition(); WriteVerboseWithTimestamp(string.Format("CreateSdkCallParameters: Creating rule object")); return new RuleCreateOrUpdateParameters() { Location = this.Location, Properties = new Rule() { Name = this.Name, IsEnabled = !this.DisableRule, Description = this.Description ?? Utilities.GetDefaultDescription("alert rule"), LastUpdatedTime = DateTime.Now, Condition = condition, Action = new RuleEmailAction() { CustomEmails = this.CustomEmails == null ? null : this.CustomEmails.Where(e => !string.IsNullOrWhiteSpace(e)).ToList(), SendToServiceOwners = this.SendToServiceOwners, }, }, // DO NOT REMOVE OR CHANGE the following. The two elements in the Tags are required by other services. Tags = new LazyDictionary<string, string>() { {"$type" , "Microsoft.WindowsAzure.Management.Common.Storage.CasePreservedDictionary,Microsoft.WindowsAzure.Management.Common.Storage"}, {"hidden-link:" + this.ResourceId, "Resource" }, }, }; } } }
48.140741
203
0.604862
[ "MIT" ]
Peter-Schneider/azure-powershell
src/ResourceManager/Insights/Commands.Insights/Alerts/AddAlertRuleCommand.cs
12,731
C#
using System; using System.Collections.Generic; namespace Nutrients.DataAccess.Models { public partial class DerivationCode { public DerivationCode() { this.NutrientDatas = new List<NutrientData>(); } public string DerivationCode1 { get; set; } public string Description { get; set; } public int Id { get; set; } public virtual ICollection<NutrientData> NutrientDatas { get; set; } } }
24.631579
76
0.632479
[ "MIT" ]
suvroc/NutrientApi
Nutrients.DataAccess/Models/DerivationCode.cs
468
C#
 using System.Collections; using System.Collections.Generic; using UnityEngine; public class DisplayImage2 : MonoBehaviour { public enum State { normal, zoom, ChangedView, idle }; public State CurrentState { get; set; } public int CurrentWall { get { return currentWall; } set { if (value == 2) currentWall = 1; else if (value == 0) currentWall = 1; else currentWall = value; } } private int currentWall; private int previousWall; void Start() { CurrentState = State.idle; previousWall = 0; currentWall = 1; } void Update() { if (currentWall != previousWall) { GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Sprites/wall2" + currentWall.ToString()); } previousWall = currentWall; } }
18.207547
117
0.536788
[ "MIT" ]
asleshapokhrel/Escape-Lab
Assets/NewResources/Level2/DisplayImage2.cs
967
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Batch.Protocol.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Defines headers for Patch operation. /// </summary> public partial class JobSchedulePatchHeaders { /// <summary> /// Initializes a new instance of the JobSchedulePatchHeaders class. /// </summary> public JobSchedulePatchHeaders() { CustomInit(); } /// <summary> /// Initializes a new instance of the JobSchedulePatchHeaders class. /// </summary> /// <param name="clientRequestId">The client-request-id provided by the /// client during the request. This will be returned only if the /// return-client-request-id parameter was set to true.</param> /// <param name="requestId">A unique identifier for the request that /// was made to the Batch service. If a request is consistently failing /// and you have verified that the request is properly formulated, you /// may use this value to report the error to Microsoft. In your /// report, include the value of this request ID, the approximate time /// that the request was made, the Batch account against which the /// request was made, and the region that account resides in.</param> /// <param name="eTag">The ETag HTTP response header. This is an opaque /// string. You can use it to detect whether the resource has changed /// between requests. In particular, you can pass the ETag to one of /// the If-Modified-Since, If-Unmodified-Since, If-Match or /// If-None-Match headers.</param> /// <param name="lastModified">The time at which the resource was last /// modified.</param> /// <param name="dataServiceId">The OData ID of the resource to which /// the request applied.</param> public JobSchedulePatchHeaders(System.Guid? clientRequestId = default(System.Guid?), System.Guid? requestId = default(System.Guid?), string eTag = default(string), System.DateTime? lastModified = default(System.DateTime?), string dataServiceId = default(string)) { ClientRequestId = clientRequestId; RequestId = requestId; ETag = eTag; LastModified = lastModified; DataServiceId = dataServiceId; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the client-request-id provided by the client during /// the request. This will be returned only if the /// return-client-request-id parameter was set to true. /// </summary> [JsonProperty(PropertyName = "client-request-id")] public System.Guid? ClientRequestId { get; set; } /// <summary> /// Gets or sets a unique identifier for the request that was made to /// the Batch service. If a request is consistently failing and you /// have verified that the request is properly formulated, you may use /// this value to report the error to Microsoft. In your report, /// include the value of this request ID, the approximate time that the /// request was made, the Batch account against which the request was /// made, and the region that account resides in. /// </summary> [JsonProperty(PropertyName = "request-id")] public System.Guid? RequestId { get; set; } /// <summary> /// Gets or sets the ETag HTTP response header. This is an opaque /// string. You can use it to detect whether the resource has changed /// between requests. In particular, you can pass the ETag to one of /// the If-Modified-Since, If-Unmodified-Since, If-Match or /// If-None-Match headers. /// </summary> [JsonProperty(PropertyName = "ETag")] public string ETag { get; set; } /// <summary> /// Gets or sets the time at which the resource was last modified. /// </summary> [JsonConverter(typeof(DateTimeRfc1123JsonConverter))] [JsonProperty(PropertyName = "Last-Modified")] public System.DateTime? LastModified { get; set; } /// <summary> /// Gets or sets the OData ID of the resource to which the request /// applied. /// </summary> [JsonProperty(PropertyName = "DataServiceId")] public string DataServiceId { get; set; } } }
44.403509
270
0.63552
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Batch/DataPlane/Azure.Batch/GeneratedProtocol/Models/JobSchedulePatchHeaders.cs
5,062
C#
namespace exam_center.usercontrols { partial class loginx { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // loginx // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ActiveCaption; this.Name = "loginx"; this.Size = new System.Drawing.Size(697, 453); this.ResumeLayout(false); } #endregion } }
30.042553
107
0.548867
[ "MIT" ]
denicos/android_andela
exam_center/exam_center/usercontrols/loginx.Designer.cs
1,414
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using DiagnosticId = String; using LanguageKind = String; [Export(typeof(ICodeFixService)), Shared] internal partial class CodeFixService : ICodeFixService { private static readonly Comparison<DiagnosticData> s_diagnosticDataComparisonById = new((d1, d2) => DiagnosticId.CompareOrdinal(d1.Id, d2.Id)); private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly Func< Workspace, ImmutableDictionary< LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> > > _getWorkspaceFixersMap; private ImmutableDictionary< LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> >? _lazyWorkspaceFixersMap; private readonly ConditionalWeakTable< IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> > _projectFixersMap; // Shared by project fixers and workspace fixers. private ImmutableDictionary< CodeFixProvider, ImmutableArray<DiagnosticId> > _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty; private readonly Lazy< ImmutableDictionary<CodeFixProvider, CodeChangeProviderMetadata> > _lazyFixerToMetadataMap; private readonly Func< Workspace, ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> > _getFixerPriorityMap; private ImmutableDictionary< LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>> >? _lazyFixerPriorityMap; private readonly ConditionalWeakTable< AnalyzerReference, ProjectCodeFixProvider > _analyzerReferenceToFixersMap; private readonly ConditionalWeakTable< AnalyzerReference, ProjectCodeFixProvider >.CreateValueCallback _createProjectCodeFixProvider; private readonly ImmutableDictionary< LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>> > _configurationProvidersMap; private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers; private ImmutableDictionary<object, FixAllProviderInfo?> _fixAllProviderMap; [ImportingConstructor] [SuppressMessage( "RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814" )] public CodeFixService( IDiagnosticAnalyzerService diagnosticAnalyzerService, [ImportMany] IEnumerable<Lazy<IErrorLoggerService>> loggers, [ImportMany] IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers, [ImportMany] IEnumerable< Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata> > configurationProviders ) { _errorLoggers = loggers; _diagnosticService = diagnosticAnalyzerService; _lazyFixerToMetadataMap = new( () => fixers .Where(service => service.IsValueCreated) .ToImmutableDictionary( service => service.Value, service => service.Metadata ) ); var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages(); var configurationProvidersPerLanguageMap = configurationProviders.ToPerLanguageMapWithMultipleLanguages(); _getWorkspaceFixersMap = workspace => GetFixerPerLanguageMap(fixersPerLanguageMap, workspace); _configurationProvidersMap = GetConfigurationProvidersPerLanguageMap( configurationProvidersPerLanguageMap ); // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable. _getFixerPriorityMap = workspace => GetFixerPriorityPerLanguageMap(fixersPerLanguageMap, workspace); // Per-project fixers _projectFixersMap = new ConditionalWeakTable< IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>> >(); _analyzerReferenceToFixersMap = new ConditionalWeakTable< AnalyzerReference, ProjectCodeFixProvider >(); _createProjectCodeFixProvider = new ConditionalWeakTable< AnalyzerReference, ProjectCodeFixProvider >.CreateValueCallback(r => new ProjectCodeFixProvider(r)); _fixAllProviderMap = ImmutableDictionary<object, FixAllProviderInfo?>.Empty; } private ImmutableDictionary< CodeFixProvider, CodeChangeProviderMetadata > FixerToMetadataMap => _lazyFixerToMetadataMap.Value; public async Task<FirstDiagnosticResult> GetMostSevereFixableDiagnosticAsync( Document document, TextSpan range, CancellationToken cancellationToken ) { if (document == null || !document.IsOpen()) { return default; } using var _ = ArrayBuilder<DiagnosticData>.GetInstance(out var diagnostics); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource( cancellationToken ); var linkedToken = linkedTokenSource.Token; // This flag is used by SuggestedActionsSource to track what solution is was // last able to get "full results" for. var isFullResult = await _diagnosticService .TryAppendDiagnosticsForSpanAsync( document, range, diagnostics, cancellationToken: linkedToken ) .ConfigureAwait(false); var errorDiagnostics = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); var otherDiagnostics = diagnostics.Where(d => d.Severity != DiagnosticSeverity.Error); // Kick off a task that will determine there's an Error Diagnostic with a fixer var errorDiagnosticsTask = Task.Run( () => GetFirstDiagnosticWithFixAsync(document, errorDiagnostics, range, linkedToken), linkedToken ); // Kick off a task that will determine if any non-Error Diagnostic has a fixer var otherDiagnosticsTask = Task.Run( () => GetFirstDiagnosticWithFixAsync(document, otherDiagnostics, range, linkedToken), linkedToken ); // If the error diagnostics task happens to complete with a non-null result before // the other diagnostics task, we can cancel the other task. var diagnostic = await errorDiagnosticsTask.ConfigureAwait(false) ?? await otherDiagnosticsTask.ConfigureAwait(false); linkedTokenSource.Cancel(); return new FirstDiagnosticResult( partialResult: !isFullResult, hasFix: diagnostic != null, diagnostic: diagnostic ); } private async Task<DiagnosticData?> GetFirstDiagnosticWithFixAsync( Document document, IEnumerable<DiagnosticData> severityGroup, TextSpan range, CancellationToken cancellationToken ) { foreach (var diagnostic in severityGroup) { if (!range.IntersectsWith(diagnostic.GetTextSpan())) { continue; } if ( await ContainsAnyFixAsync(document, diagnostic, cancellationToken) .ConfigureAwait(false) ) { return diagnostic; } } return null; } public Task<ImmutableArray<CodeFixCollection>> GetFixesAsync( Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken ) => GetFixesAsync( document, range, includeConfigurationFixes, isBlocking: false, cancellationToken ); public Task<ImmutableArray<CodeFixCollection>> GetFixesAsync( Document document, TextSpan range, bool includeConfigurationFixes, bool isBlocking, CancellationToken cancellationToken ) => GetFixesAsync( document, range, includeConfigurationFixes, isBlocking, addOperationScope: _ => null, cancellationToken ); public async Task<ImmutableArray<CodeFixCollection>> GetFixesAsync( Document document, TextSpan range, bool includeConfigurationFixes, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken ) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) // group diagnostics by their diagnostics span // invariant: later code gathers & runs CodeFixProviders for diagnostics with one identical diagnostics span (that gets set later as CodeFixCollection's TextSpan) // order diagnostics by span. SortedDictionary<TextSpan, List<DiagnosticData>>? aggregatedDiagnostics = null; foreach ( var diagnostic in await _diagnosticService .GetDiagnosticsForSpanAsync( document, range, diagnosticIdOpt: null, includeConfigurationFixes, addOperationScope, cancellationToken ) .ConfigureAwait(false) ) { if (diagnostic.IsSuppressed) { continue; } cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics ??= new SortedDictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics .GetOrAdd(diagnostic.GetTextSpan(), _ => new List<DiagnosticData>()) .Add(diagnostic); } if (aggregatedDiagnostics == null) { return ImmutableArray<CodeFixCollection>.Empty; } // Order diagnostics by DiagnosticId so the fixes are in a deterministic order. foreach (var diagnosticsWithSpan in aggregatedDiagnostics.Values) { diagnosticsWithSpan.Sort(s_diagnosticDataComparisonById); } // append fixes for all diagnostics with the same diagnostics span using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result); foreach (var spanAndDiagnostic in aggregatedDiagnostics) { await AppendFixesAsync( document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false, isBlocking, result, addOperationScope, cancellationToken ) .ConfigureAwait(false); } if ( result.Count > 0 && TryGetWorkspaceFixersPriorityMap(document, out var fixersForLanguage) ) { // sort the result to the order defined by the fixers #pragma warning disable IDE0007 // Use implicit type - Explicit type is need to suppress an incorrect nullable warning on dereferencing the map. ImmutableDictionary<CodeFixProvider, int> priorityMap = fixersForLanguage.Value; #pragma warning restore IDE0007 // Use implicit type result.Sort((d1, d2) => GetValue(d1).CompareTo(GetValue(d2))); int GetValue(CodeFixCollection c) => priorityMap.TryGetValue((CodeFixProvider)c.Provider, out var value) ? value : int.MaxValue; } // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if ( document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeConfigurationFixes ) { // Ensure that we do not register duplicate configuration fixes. using var _ = PooledHashSet<string>.GetInstance( out var registeredConfigurationFixTitles ); foreach (var spanAndDiagnostic in aggregatedDiagnostics) { await AppendConfigurationsAsync( document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, registeredConfigurationFixTitles, cancellationToken ) .ConfigureAwait(false); } } return result.ToImmutable(); } public async Task<CodeFixCollection?> GetDocumentFixAllForIdInSpanAsync( Document document, TextSpan range, string diagnosticId, CancellationToken cancellationToken ) { var diagnostics = ( await _diagnosticService .GetDiagnosticsForSpanAsync( document, range, diagnosticId, includeSuppressedDiagnostics: false, cancellationToken: cancellationToken ) .ConfigureAwait(false) ).ToList(); if (diagnostics.Count == 0) { return null; } using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result); await AppendFixesAsync( document, range, diagnostics, fixAllForInSpan: true, isBlocking: false, result, addOperationScope: _ => null, cancellationToken ) .ConfigureAwait(false); // TODO: Just get the first fix for now until we have a way to config user's preferred fix // https://github.com/dotnet/roslyn/issues/27066 return result.ToImmutable().FirstOrDefault(); } public async Task<Document> ApplyCodeFixesForSpecificDiagnosticIdAsync( Document document, string diagnosticId, IProgressTracker progressTracker, CancellationToken cancellationToken ) { var tree = await document .GetRequiredSyntaxTreeAsync(cancellationToken) .ConfigureAwait(false); var textSpan = new TextSpan(0, tree.Length); var fixCollection = await GetDocumentFixAllForIdInSpanAsync( document, textSpan, diagnosticId, cancellationToken ) .ConfigureAwait(false); if (fixCollection == null) { return document; } var fixAllService = document.Project.Solution.Workspace.Services.GetRequiredService<IFixAllGetFixesService>(); var solution = await fixAllService .GetFixAllChangedSolutionAsync( new FixAllContext(fixCollection.FixAllState, progressTracker, cancellationToken) ) .ConfigureAwait(false); return solution.GetDocument(document.Id) ?? throw new NotSupportedException( FeaturesResources.Removal_of_document_not_supported ); } private bool TryGetWorkspaceFixersMap( Document document, [NotNullWhen(true)] out Lazy< ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>> >? fixerMap ) { if (_lazyWorkspaceFixersMap == null) { var workspaceFixersMap = _getWorkspaceFixersMap( document.Project.Solution.Workspace ); Interlocked.CompareExchange(ref _lazyWorkspaceFixersMap, workspaceFixersMap, null); } return _lazyWorkspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); } private bool TryGetWorkspaceFixersPriorityMap( Document document, [NotNullWhen(true)] out Lazy<ImmutableDictionary<CodeFixProvider, int>>? fixersPriorityMap ) { if (_lazyFixerPriorityMap == null) { var fixersPriorityByLanguageMap = _getFixerPriorityMap( document.Project.Solution.Workspace ); Interlocked.CompareExchange( ref _lazyFixerPriorityMap, fixersPriorityByLanguageMap, null ); } return _lazyFixerPriorityMap.TryGetValue( document.Project.Language, out fixersPriorityMap ); } private bool TryGetWorkspaceFixer( Lazy<CodeFixProvider, CodeChangeProviderMetadata> lazyFixer, Workspace workspace, bool logExceptionWithInfoBar, [NotNullWhen(returnValue: true)] out CodeFixProvider? fixer ) { try { fixer = lazyFixer.Value; return true; } catch (Exception ex) { // Gracefully handle exceptions in creating fixer instance. // Log exception and show info bar, if needed. if (logExceptionWithInfoBar) { var errorReportingService = workspace.Services.GetRequiredService<IErrorReportingService>(); var message = lazyFixer.Metadata.Name != null ? string.Format( FeaturesResources.Error_creating_instance_of_CodeFixProvider_0, lazyFixer.Metadata.Name ) : FeaturesResources.Error_creating_instance_of_CodeFixProvider; errorReportingService.ShowGlobalErrorInfo( message, new InfoBarUI( WorkspacesResources.Show_Stack_Trace, InfoBarUI.UIKind.HyperLink, () => errorReportingService.ShowDetailedErrorInfo(ex), closeAfterAction: true ) ); foreach (var errorLogger in _errorLoggers) { errorLogger.Value.LogException(this, ex); } } fixer = null; return false; } } private async Task AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, bool fixAllForInSpan, bool isBlocking, ArrayBuilder<CodeFixCollection> result, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken ) { var hasAnySharedFixer = TryGetWorkspaceFixersMap(document, out var fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return; } var allFixers = new List<CodeFixProvider>(); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive var isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive; // gather CodeFixProviders for all distinct diagnostics found for current span foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); // Prioritize NuGet based project code fixers over VSIX based workspace code fixers. if ( hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers) ) { Debug.Assert(!isInteractive); allFixers.AddRange(projectFixers); } if ( hasAnySharedFixer && fixerMap!.Value.TryGetValue(diagnosticId, out var workspaceFixers) ) { if (isInteractive) { allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider)); } else { allFixers.AddRange(workspaceFixers); } } } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); // Run each CodeFixProvider to gather individual CodeFixes for reported diagnostics. // Ensure that no diagnostic has registered code actions from different code fix providers with same equivalance key. // This prevents duplicate registered code actions from NuGet and VSIX code fix providers. // See https://github.com/dotnet/roslyn/issues/18818 for details. var uniqueDiagosticToEquivalenceKeysMap = new Dictionary< Diagnostic, PooledHashSet<string?> >(); // NOTE: For backward compatibility, we allow multiple registered code actions from the same code fix provider // to have the same equivalence key. See https://github.com/dotnet/roslyn/issues/44553 for details. // To ensure this, we track the fixer that first registered a code action to fix a diagnostic with a specific equivalence key. var diagnosticAndEquivalenceKeyToFixersMap = new Dictionary< (Diagnostic diagnostic, string? equivalenceKey), CodeFixProvider >(); try { foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); await AppendFixesOrConfigurationsAsync( document, span, diagnostics, fixAllForInSpan, result, fixer, hasFix: d => this.GetFixableDiagnosticIds(fixer, extensionManager) .Contains(d.Id), getFixes: dxs => { var fixerName = fixer.GetType().Name; FixerToMetadataMap.TryGetValue(fixer, out var fixerMetadata); using (addOperationScope(fixerName)) using ( RoslynEventSource.LogInformationalBlock( FunctionId.CodeFixes_GetCodeFixesAsync, fixerName, cancellationToken ) ) { if (fixAllForInSpan) { var primaryDiagnostic = dxs.First(); return GetCodeFixesAsync( document, primaryDiagnostic.Location.SourceSpan, fixer, fixerMetadata, isBlocking, ImmutableArray.Create(primaryDiagnostic), uniqueDiagosticToEquivalenceKeysMap, diagnosticAndEquivalenceKeyToFixersMap, cancellationToken ); } else { return GetCodeFixesAsync( document, span, fixer, fixerMetadata, isBlocking, dxs, uniqueDiagosticToEquivalenceKeysMap, diagnosticAndEquivalenceKeyToFixersMap, cancellationToken ); } } }, cancellationToken: cancellationToken ) .ConfigureAwait(false); // Just need the first result if we are doing fix all in span if (fixAllForInSpan && result.Any()) return; } } finally { foreach (var pooledSet in uniqueDiagosticToEquivalenceKeysMap.Values) { pooledSet.Free(); } } } private static async Task<ImmutableArray<CodeFix>> GetCodeFixesAsync( Document document, TextSpan span, CodeFixProvider fixer, CodeChangeProviderMetadata? fixerMetadata, bool isBlocking, ImmutableArray<Diagnostic> diagnostics, Dictionary<Diagnostic, PooledHashSet<string?>> uniqueDiagosticToEquivalenceKeysMap, Dictionary< (Diagnostic diagnostic, string? equivalenceKey), CodeFixProvider > diagnosticAndEquivalenceKeyToFixersMap, CancellationToken cancellationToken ) { using var fixesDisposer = ArrayBuilder<CodeFix>.GetInstance(out var fixes); var context = new CodeFixContext( document, span, diagnostics, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (action, applicableDiagnostics) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { // Filter out applicable diagnostics which already have a registered code action with same equivalence key. applicableDiagnostics = FilterApplicableDiagnostics( applicableDiagnostics, action.EquivalenceKey, fixer, uniqueDiagosticToEquivalenceKeysMap, diagnosticAndEquivalenceKeyToFixersMap ); if (!applicableDiagnostics.IsEmpty) { // Add the CodeFix Provider Name to the parent CodeAction's CustomTags. // Always add a name even in cases of 3rd party fixers that do not export // name metadata. action.AddCustomTag(fixerMetadata?.Name ?? fixer.GetTypeDisplayName()); fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics)); } } }, verifyArguments: false, isBlocking, cancellationToken: cancellationToken ); var task = fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; await task.ConfigureAwait(false); return fixes.ToImmutable(); static ImmutableArray<Diagnostic> FilterApplicableDiagnostics( ImmutableArray<Diagnostic> applicableDiagnostics, string? equivalenceKey, CodeFixProvider fixer, Dictionary<Diagnostic, PooledHashSet<string?>> uniqueDiagosticToEquivalenceKeysMap, Dictionary< (Diagnostic diagnostic, string? equivalenceKey), CodeFixProvider > diagnosticAndEquivalenceKeyToFixersMap ) { using var disposer = ArrayBuilder<Diagnostic>.GetInstance( out var newApplicableDiagnostics ); foreach (var diagnostic in applicableDiagnostics) { if ( !uniqueDiagosticToEquivalenceKeysMap.TryGetValue( diagnostic, out var equivalenceKeys ) ) { // First code action registered to fix this diagnostic with any equivalenceKey. // Record the equivalence key and the fixer that registered this action. equivalenceKeys = PooledHashSet<string?>.GetInstance(); equivalenceKeys.Add(equivalenceKey); uniqueDiagosticToEquivalenceKeysMap[diagnostic] = equivalenceKeys; diagnosticAndEquivalenceKeyToFixersMap.Add( (diagnostic, equivalenceKey), fixer ); } else if (equivalenceKeys.Add(equivalenceKey)) { // First code action registered to fix this diagnostic with the given equivalenceKey. // Record the the fixer that registered this action. diagnosticAndEquivalenceKeyToFixersMap.Add( (diagnostic, equivalenceKey), fixer ); } else if ( diagnosticAndEquivalenceKeyToFixersMap[(diagnostic, equivalenceKey)] != fixer ) { // Diagnostic already has a registered code action with same equivalence key from a different fixer. // Note that we allow same fixer to register multiple such code actions with the same equivalence key // for backward compatibility. See https://github.com/dotnet/roslyn/issues/44553 for details. continue; } newApplicableDiagnostics.Add(diagnostic); } return newApplicableDiagnostics.Count == applicableDiagnostics.Length ? applicableDiagnostics : newApplicableDiagnostics.ToImmutable(); } } private async Task AppendConfigurationsAsync( Document document, TextSpan diagnosticsSpan, IEnumerable<DiagnosticData> diagnostics, ArrayBuilder<CodeFixCollection> result, PooledHashSet<string> registeredConfigurationFixTitles, CancellationToken cancellationToken ) { if ( !_configurationProvidersMap.TryGetValue( document.Project.Language, out var lazyConfigurationProviders ) || lazyConfigurationProviders.Value == null ) { return; } // append CodeFixCollection for each CodeFixProvider foreach (var provider in lazyConfigurationProviders.Value) { using ( RoslynEventSource.LogInformationalBlock( FunctionId.CodeFixes_GetCodeFixesAsync, provider, cancellationToken ) ) { await AppendFixesOrConfigurationsAsync( document, diagnosticsSpan, diagnostics, fixAllForInSpan: false, result, provider, hasFix: d => provider.IsFixableDiagnostic(d), getFixes: async dxs => { var fixes = await provider .GetFixesAsync( document, diagnosticsSpan, dxs, cancellationToken ) .ConfigureAwait(false); return fixes.WhereAsArray( f => registeredConfigurationFixTitles.Add(f.Action.Title) ); }, cancellationToken ) .ConfigureAwait(false); } } } private async Task AppendFixesOrConfigurationsAsync<TCodeFixProvider>( Document document, TextSpan fixesSpan, IEnumerable<DiagnosticData> diagnosticsWithSameSpan, bool fixAllForInSpan, ArrayBuilder<CodeFixCollection> result, TCodeFixProvider fixer, Func<Diagnostic, bool> hasFix, Func<ImmutableArray<Diagnostic>, Task<ImmutableArray<CodeFix>>> getFixes, CancellationToken cancellationToken ) where TCodeFixProvider : notnull { var allDiagnostics = await diagnosticsWithSameSpan .OrderByDescending(d => d.Severity) .ToDiagnosticsAsync(document.Project, cancellationToken) .ConfigureAwait(false); var diagnostics = allDiagnostics.WhereAsArray(hasFix); if (diagnostics.Length <= 0) { // this can happen for suppression case where all diagnostics can't be suppressed return; } var extensionManager = document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); var fixes = await extensionManager .PerformFunctionAsync( fixer, () => getFixes(diagnostics), defaultValue: ImmutableArray<CodeFix>.Empty ) .ConfigureAwait(false); if (fixes.IsDefaultOrEmpty) { return; } // If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context. var fixAllProviderInfo = extensionManager.PerformFunction<FixAllProviderInfo?>( fixer, () => ImmutableInterlocked.GetOrAdd( ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create ), defaultValue: null ); FixAllState? fixAllState = null; var supportedScopes = ImmutableArray<FixAllScope>.Empty; if (fixAllProviderInfo != null) { var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider( (IConfigurationFixProvider)fixer, diagnostics.Select(d => d.Id) ); var diagnosticIds = diagnostics .Where(fixAllProviderInfo.CanBeFixed) .Select(d => d.Id) .ToImmutableHashSet(); // When computing FixAll for unnecessary pragma suppression diagnostic, // we need to include suppressed diagnostics, as well as reported compiler and analyzer diagnostics. // A null value for 'diagnosticIdsForDiagnosticProvider' passed to 'FixAllDiagnosticProvider' // ensures the latter. ImmutableHashSet<string>? diagnosticIdsForDiagnosticProvider; bool includeSuppressedDiagnostics; if ( diagnosticIds.Contains( IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId ) ) { diagnosticIdsForDiagnosticProvider = null; includeSuppressedDiagnostics = true; } else { diagnosticIdsForDiagnosticProvider = diagnosticIds; includeSuppressedDiagnostics = false; } var diagnosticProvider = fixAllForInSpan ? new FixAllPredefinedDiagnosticProvider(allDiagnostics) : (FixAllContext.DiagnosticProvider)new FixAllDiagnosticProvider( this, diagnosticIdsForDiagnosticProvider, includeSuppressedDiagnostics ); fixAllState = new FixAllState( fixAllProvider: fixAllProviderInfo.FixAllProvider, document: document, codeFixProvider: codeFixProvider, scope: FixAllScope.Document, codeActionEquivalenceKey: null, diagnosticIds: diagnosticIds, fixAllDiagnosticProvider: diagnosticProvider ); supportedScopes = fixAllProviderInfo.SupportedScopes; } var codeFix = new CodeFixCollection( fixer, fixesSpan, fixes, fixAllState, supportedScopes, diagnostics.First() ); result.Add(codeFix); } /// <summary> Looks explicitly for an <see cref="AbstractSuppressionCodeFixProvider"/>.</summary> public CodeFixProvider? GetSuppressionFixer( string language, IEnumerable<string> diagnosticIds ) { if ( !_configurationProvidersMap.TryGetValue( language, out var lazyConfigurationProviders ) || lazyConfigurationProviders.Value.IsDefault ) { return null; } // Explicitly looks for an AbstractSuppressionCodeFixProvider var fixer = lazyConfigurationProviders.Value .OfType<AbstractSuppressionCodeFixProvider>() .FirstOrDefault(); if (fixer == null) { return null; } return new WrapperCodeFixProvider(fixer, diagnosticIds); } private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync( Document document, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics, CancellationToken cancellationToken ) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var diagnostics = await _diagnosticService .GetDiagnosticsForIdsAsync( solution, null, document.Id, diagnosticIds, includeSuppressedDiagnostics, cancellationToken ) .ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return await diagnostics .ToDiagnosticsAsync(document.Project, cancellationToken) .ConfigureAwait(false); } private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync( Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics, CancellationToken cancellationToken ) { Contract.ThrowIfNull(project); if (includeAllDocumentDiagnostics) { // Get all diagnostics for the entire project, including document diagnostics. var diagnostics = await _diagnosticService .GetDiagnosticsForIdsAsync( project.Solution, project.Id, documentId: null, diagnosticIds, includeSuppressedDiagnostics, cancellationToken ) .ConfigureAwait(false); return await diagnostics .ToDiagnosticsAsync(project, cancellationToken) .ConfigureAwait(false); } else { // Get all no-location diagnostics for the project, doesn't include document diagnostics. var diagnostics = await _diagnosticService .GetProjectDiagnosticsForIdsAsync( project.Solution, project.Id, diagnosticIds, includeSuppressedDiagnostics, cancellationToken ) .ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); return await diagnostics .ToDiagnosticsAsync(project, cancellationToken) .ConfigureAwait(false); } } private async Task<bool> ContainsAnyFixAsync( Document document, DiagnosticData diagnostic, CancellationToken cancellationToken ) { var workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; var hasAnySharedFixer = TryGetWorkspaceFixersMap(document, out var fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project) .TryGetValue(diagnostic.Id, out var projectFixers); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if ( hasAnySharedFixer && document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive ) { workspaceFixers = workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider); hasAnySharedFixer = workspaceFixers.Any(); } var hasConfigurationFixer = _configurationProvidersMap.TryGetValue( document.Project.Language, out var lazyConfigurationProviders ) && !lazyConfigurationProviders.Value.IsDefaultOrEmpty; if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasConfigurationFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers!); } var dx = await diagnostic .ToDiagnosticAsync(document.Project, cancellationToken) .ConfigureAwait(false); if (hasConfigurationFixer) { foreach (var lazyConfigurationProvider in lazyConfigurationProviders!.Value) { if (lazyConfigurationProvider.IsFixableDiagnostic(dx)) { return true; } } } var fixes = new List<CodeFix>(); var context = new CodeFixContext( document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (action, applicableDiagnostics) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics)); } }, verifyArguments: false, cancellationToken: cancellationToken ); var extensionManager = document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager .PerformActionAsync( fixer, () => fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask ) .ConfigureAwait(false); if (fixes.Count > 0) return true; } return false; } private bool IsInteractiveCodeFixProvider(CodeFixProvider provider) { // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive return provider is FullyQualify.AbstractFullyQualifyCodeFixProvider || provider is AddImport.AbstractAddImportCodeFixProvider; } private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>(); private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds( CodeFixProvider fixer, IExtensionManager? extensionManager ) { // If we are passed a null extension manager it means we do not have access to a document so there is nothing to // show the user. In this case we will log any exceptions that occur, but the user will not see them. if (extensionManager != null) { return extensionManager.PerformFunction( fixer, () => ImmutableInterlocked.GetOrAdd( ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f) ), defaultValue: ImmutableArray<DiagnosticId>.Empty ); } try { return ImmutableInterlocked.GetOrAdd( ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f) ); } catch (Exception e) when (!(e is OperationCanceledException)) { foreach (var logger in _errorLoggers) { logger.Value.LogException(fixer, e); } return ImmutableArray<DiagnosticId>.Empty; } } private static ImmutableArray<string> GetAndTestFixableDiagnosticIds( CodeFixProvider codeFixProvider ) { var ids = codeFixProvider.FixableDiagnosticIds; if (ids.IsDefault) { throw new InvalidOperationException( string.Format( WorkspacesResources._0_returned_an_uninitialized_ImmutableArray, codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds) ) ); } return ids; } private ImmutableDictionary< LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> > GetFixerPerLanguageMap( Dictionary< LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> > fixersPerLanguage, Workspace workspace ) { var fixerMap = ImmutableDictionary.Create< LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> >(); var extensionManager = workspace.Services.GetService<IExtensionManager>(); foreach (var languageKindAndFixers in fixersPerLanguage) { var lazyMap = new Lazy< ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>> >( () => { var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>(); foreach (var lazyFixer in languageKindAndFixers.Value) { if ( !TryGetWorkspaceFixer( lazyFixer, workspace, logExceptionWithInfoBar: true, out var fixer ) ) { continue; } foreach ( var id in this.GetFixableDiagnosticIds(fixer, extensionManager) ) { if (string.IsNullOrWhiteSpace(id)) { continue; } var list = mutableMap.GetOrAdd(id, s_createList); list.Add(fixer); } } var immutableMap = ImmutableDictionary.CreateBuilder< DiagnosticId, ImmutableArray<CodeFixProvider> >(); foreach (var diagnosticIdAndFixers in mutableMap) { immutableMap.Add( diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty() ); } return immutableMap.ToImmutable(); }, isThreadSafe: true ); fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap); } return fixerMap; } private static ImmutableDictionary< LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>> > GetConfigurationProvidersPerLanguageMap( Dictionary< LanguageKind, List<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>> > configurationProvidersPerLanguage ) { var configurationFixerMap = ImmutableDictionary.Create< LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>> >(); foreach (var languageKindAndFixers in configurationProvidersPerLanguage) { var lazyConfigurationFixers = new Lazy<ImmutableArray<IConfigurationFixProvider>>( () => GetConfigurationFixProviders(languageKindAndFixers.Value) ); configurationFixerMap = configurationFixerMap.Add( languageKindAndFixers.Key, lazyConfigurationFixers ); } return configurationFixerMap; static ImmutableArray<IConfigurationFixProvider> GetConfigurationFixProviders( List< Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata> > languageKindAndFixers ) { using var builderDisposer = ArrayBuilder<IConfigurationFixProvider>.GetInstance( out var builder ); var orderedLanguageKindAndFixers = ExtensionOrderer.Order(languageKindAndFixers); foreach (var languageKindAndFixersValue in orderedLanguageKindAndFixers) { builder.Add(languageKindAndFixersValue.Value); } return builder.ToImmutable(); } } private ImmutableDictionary< LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>> > GetFixerPriorityPerLanguageMap( Dictionary< LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> > fixersPerLanguage, Workspace workspace ) { var languageMap = ImmutableDictionary.CreateBuilder< LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>> >(); foreach (var languageAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>( () => { var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>(); var lazyFixers = ExtensionOrderer.Order(languageAndFixers.Value); for (var i = 0; i < lazyFixers.Count; i++) { if ( !TryGetWorkspaceFixer( lazyFixers[i], workspace, logExceptionWithInfoBar: false, out var fixer ) ) { continue; } priorityMap.Add(fixer, i); } return priorityMap.ToImmutable(); }, isThreadSafe: true ); languageMap.Add(languageAndFixers.Key, lazyMap); } return languageMap.ToImmutable(); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers( Project project ) { // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive return project.Solution.Workspace.Kind == WorkspaceKind.Interactive ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty : _projectFixersMap.GetValue( project.AnalyzerReferences, pId => ComputeProjectFixers(project) ); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers( Project project ) { var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>(); ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder? builder = null; foreach (var reference in project.AnalyzerReferences) { var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue( reference, _createProjectCodeFixProvider ); foreach (var fixer in projectCodeFixerProvider.GetExtensions(project.Language)) { var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager); foreach (var id in fixableIds) { if (string.IsNullOrWhiteSpace(id)) { continue; } builder ??= ImmutableDictionary.CreateBuilder< DiagnosticId, List<CodeFixProvider> >(); var list = builder.GetOrAdd(id, s_createList); list.Add(fixer); } } } if (builder == null) { return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty; } return builder.ToImmutable(); } } }
40.851459
174
0.517791
[ "MIT" ]
belav/roslyn
src/Features/Core/Portable/CodeFixes/CodeFixService.cs
61,606
C#
using System; using System.Collections.Generic; using System.Text; namespace ResultSharp { /// <summary> /// Interface for common Result operations /// </summary> public interface IResult { /// <summary> /// Type of the Ok value /// </summary> Type OkType { get; } /// <summary> /// Type of the Error value /// </summary> Type ErrType { get; } /// <summary> /// Returns true if the Result is ok /// </summary> bool IsOk { get; } /// <summary> /// Returns true if the Result is faulted /// </summary> bool IsErr { get; } /// <summary> /// Match the two states of the Result /// </summary> /// <typeparam name="R">Type of the return value</typeparam> /// <param name="ok">Ok match operation</param> /// <param name="err">Error match operation</param> /// <returns>R</returns> R MatchUntyped<R>(Func<object?, R> ok, Func<object?, R> err); /// <summary> /// Unwrap the ok value as nullable object /// </summary> object? UnwrapUntyped(); /// <summary> /// Unwrap the error value as nullable object /// </summary> object? UnwrapErrUntyped(); } }
21.5
63
0.615385
[ "MIT" ]
sebbert/ResultSharp
ResultSharp/IResult.cs
1,120
C#
using Micro.Mails; namespace Micro.Auth.Api.Internal.Configs { public class Mail { public EmailUrlConfig EmailUrlConfig { set; get; } public Smtp Smtp { set; get; } public Sender DefaultSender { set; get; } } }
20.666667
58
0.633065
[ "MIT" ]
fossapps/Micro.Auth
Micro.Auth.Api/Internal/Configs/Mail.cs
248
C#
using System.Text; namespace _04.Software_University_Learning_System.People.Students { public class CurrentStudent : Student { private string currentCourse; public CurrentStudent(string firstName, string lastName, int age, int studentNumber, double averageGrade, string currentCourse) : base(firstName, lastName, age, studentNumber, averageGrade) { this.CurrentCourse = currentCourse; } public string CurrentCourse { get { return currentCourse; } set { currentCourse = CheckStr(value, "Current course"); } } public override string ToString() { var sb = new StringBuilder(base.ToString()); sb.AppendLine("Current course".PadRight(Printpadding) + $"{CurrentCourse}"); return sb.ToString(); } } }
23.59375
107
0.721854
[ "MIT" ]
HouseBreaker/OOP
01. Defining classes/04. Software University Learning System/People/Students/CurrentStudent.cs
757
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Direct3D11 { [NativeName("Name", "D3D11_QUERY_DATA_SO_STATISTICS")] public unsafe partial struct QueryDataSOStatistics { public QueryDataSOStatistics ( ulong? numPrimitivesWritten = null, ulong? primitivesStorageNeeded = null ) : this() { if (numPrimitivesWritten is not null) { NumPrimitivesWritten = numPrimitivesWritten.Value; } if (primitivesStorageNeeded is not null) { PrimitivesStorageNeeded = primitivesStorageNeeded.Value; } } [NativeName("Type", "UINT64")] [NativeName("Type.Name", "UINT64")] [NativeName("Name", "NumPrimitivesWritten")] public ulong NumPrimitivesWritten; [NativeName("Type", "UINT64")] [NativeName("Type.Name", "UINT64")] [NativeName("Name", "PrimitivesStorageNeeded")] public ulong PrimitivesStorageNeeded; } }
27.283019
72
0.643154
[ "MIT" ]
ThomasMiz/Silk.NET
src/Microsoft/Silk.NET.Direct3D11/Structs/QueryDataSOStatistics.gen.cs
1,446
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DomainResults.Common; using Raven.Client.Documents; using Raven.Client.Documents.Linq; using Raven.Client.Documents.Session; using Raven.Yabt.Database.Common; using Raven.Yabt.Database.Common.BacklogItem; using Raven.Yabt.Database.Common.References; using Raven.Yabt.Database.Models.BacklogItems; using Raven.Yabt.Database.Models.BacklogItems.Indexes; using Raven.Yabt.Domain.BacklogItemServices.Commands.DTOs; using Raven.Yabt.Domain.Common; using Raven.Yabt.Domain.CustomFieldServices.Query; using Raven.Yabt.Domain.CustomFieldServices.Query.DTOs; using Raven.Yabt.Domain.Helpers; using Raven.Yabt.Domain.UserServices.Query; namespace Raven.Yabt.Domain.BacklogItemServices.Commands { public interface IBacklogItemDtoToEntityConversion { Task<IDomainResult<BacklogItem>> ConvertToEntity<TModel, TDto>(TDto dto, TModel? entity = null) where TModel : BacklogItem, new() where TDto : BacklogItemAddUpdRequestBase; } public class BacklogItemDtoToEntityConversion : BaseService<BacklogItem>, IBacklogItemDtoToEntityConversion { private readonly IUserReferenceResolver _userResolver; private readonly ICustomFieldListQueryService _customFieldQueryService; public BacklogItemDtoToEntityConversion(IAsyncDocumentSession dbSession, IUserReferenceResolver userResolver, ICustomFieldListQueryService customFieldQueryService) : base(dbSession) { _userResolver = userResolver; _customFieldQueryService = customFieldQueryService; } public async Task<IDomainResult<BacklogItem>> ConvertToEntity<TModel, TDto>(TDto dto, TModel? entity = null) where TModel : BacklogItem, new() where TDto : BacklogItemAddUpdRequestBase { entity ??= new TModel(); entity.Title = dto.Title; entity.State = dto.State; entity.EstimatedSize = dto.EstimatedSize; entity.Assignee = dto.AssigneeId != null ? await _userResolver.GetReferenceById(dto.AssigneeId) : null; if (dto.Tags?.Any(t => t.Length > 11) == true) return DomainResult<BacklogItem>.Failed("Each tag can't exceed 10 symbols"); entity.Tags = dto.Tags?.Distinct().ToArray(); entity.AddHistoryRecord( await _userResolver.GetCurrentUserReference(), entity.ModifiedBy.Any() ? "Modified" : "Created" // TODO: Provide more informative description in case of modifications ); if (dto.ChangedCustomFields != null) { entity.CustomFields ??= new Dictionary<string, object>(); await ResolveChangedCustomFields(entity.CustomFields, dto.ChangedCustomFields); } await ResolveChangedRelatedItems(entity.RelatedItems, dto.ChangedRelatedItems); if (dto is BugAddUpdRequest bugDto && entity is BacklogItemBug bugEntity) { bugEntity.Severity = bugDto.Severity; bugEntity.Priority = bugDto.Priority; bugEntity.StepsToReproduce = bugDto.StepsToReproduce; bugEntity.AcceptanceCriteria = bugDto.AcceptanceCriteria; } else if (dto is UserStoryAddUpdRequest storyDto && entity is BacklogItemUserStory storyEntity) { storyEntity.AcceptanceCriteria = storyDto.AcceptanceCriteria; } else if (dto is TaskAddUpdRequest taskDto && entity is BacklogItemTask taskEntity) { taskEntity.Description = taskDto.Description; } else if (dto is FeatureAddUpdRequest featureDto && entity is BacklogItemFeature featureEntity) { featureEntity.Description = featureDto.Description; } return DomainResult.Success<BacklogItem>(entity); } private async Task ResolveChangedRelatedItems(List<BacklogItemRelatedItem> existingRelatedItems, IList<BacklogRelationshipAction>? actions) { if (actions == null) return; // Remove 'old' links foreach (var (id, linkType) in from a in actions where a.ActionType == ListActionType.Remove select (a.BacklogItemId, a.RelationType)) { existingRelatedItems.RemoveAll(existing => existing.RelatedTo.Id == id && existing.LinkType == linkType); } // Add new links (string fullId, BacklogRelationshipType linkType)[] array = (from a in actions where a.ActionType == ListActionType.Add select (GetFullId(a.BacklogItemId), a.RelationType) ).ToArray(); if (array.Any()) { // Resolve new references var fullIds = array.Select(a => a.fullId).Distinct(); var references = await (from b in DbSession.Query<BacklogItemIndexedForList, BacklogItems_ForList>() where b.Id.In(fullIds) select new BacklogItemReference { Id = b.Id, Name = b.Title, Type = b.Type }).ToListAsync(); // Add resolved references foreach (var (fullId, linkType) in array) { var relatedTo = references.SingleOrDefault(r => r.Id == fullId); if (relatedTo == null) continue; existingRelatedItems.Add(new BacklogItemRelatedItem { LinkType = linkType, RelatedTo = relatedTo.RemoveEntityPrefixFromId() }); } } } private async Task ResolveChangedCustomFields(IDictionary<string, object> existingFields, IList<BacklogCustomFieldAction>? actions) { if (actions == null) return; // Remove 'old' fields foreach (var id in from a in actions where a.ActionType == ListActionType.Remove || a.Value is null select a.CustomFieldId) { existingFields.Remove(id); } // Add new fields var array = (from a in actions where a.ActionType == ListActionType.Add // Keep only the ones that we're adding select a ).ToList(); if (array.Any()) { var fieldRequest = new CustomFieldListGetRequest { Ids = array.Select(a => a.CustomFieldId).Distinct(), PageSize = Int32.MaxValue }; var verifiedCustomFields = await _customFieldQueryService.GetArray(fieldRequest); foreach (var a in array) { var field = verifiedCustomFields.SingleOrDefault(f => f.Id == a.CustomFieldId); if (a.Value is null || field is null) continue; var obj = field.FieldType switch { CustomFieldType.Text or CustomFieldType.Url => a.GetValue<string>(), CustomFieldType.Numeric => a.GetValue<decimal>(), CustomFieldType.Date => a.GetValue<DateTime>(), CustomFieldType.Checkbox => a.GetValue<bool>(), _ => throw new ArgumentOutOfRangeException($"Unsupported field type: {field.FieldType}") }; if (obj is null) continue; if (existingFields.ContainsKey(a.CustomFieldId)) existingFields[a.CustomFieldId] = obj; else existingFields.Add(a.CustomFieldId, obj); } } } } }
34.421053
183
0.727829
[ "MIT" ]
gregolsky/samples-yabt
back-end/Domain/BacklogItemServices/Commands/BacklogItemDtoToEntityConversion.cs
6,540
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Docker.Outputs { [OutputType] public sealed class ContainerMountVolumeOptions { public readonly string? DriverName; public readonly ImmutableDictionary<string, string>? DriverOptions; /// <summary> /// User-defined key/value metadata /// </summary> public readonly ImmutableArray<Outputs.ContainerMountVolumeOptionsLabel> Labels; public readonly bool? NoCopy; [OutputConstructor] private ContainerMountVolumeOptions( string? driverName, ImmutableDictionary<string, string>? driverOptions, ImmutableArray<Outputs.ContainerMountVolumeOptionsLabel> labels, bool? noCopy) { DriverName = driverName; DriverOptions = driverOptions; Labels = labels; NoCopy = noCopy; } } }
29.341463
88
0.660848
[ "Apache-2.0" ]
stevesloka/pulumi-docker
sdk/dotnet/Outputs/ContainerMountVolumeOptions.cs
1,203
C#
using System; using System.Collections.Generic; using Xunit; using Bunit; using Moq; using ToolsApp.Components.Shared; namespace ToolsApp.Components.UnitTests.Shared { public class ActionDataListCSharpTest : TestContext { [Fact] public void ActionDataListComponentActionButtonClicked() { // Arrange List<string> colors = new() { "red", "green", "blue" }; string emptyMessage = "No Colors"; var actionButtonLabel = "X"; var itemActionMock = Mock.Of<Action<string>>(); // Act var cut = RenderComponent<ActionDataList>(parameters => parameters .Add(p => p.Items, colors) .Add(p => p.EmptyMessage, emptyMessage) .Add(p => p.ActionButtonLabel, actionButtonLabel) .Add(p => p.OnItemAction, itemActionMock) .AddChildContent("<h3>Colors</h3>")); var buttonElement = cut.Find("li:nth-child(2) button"); buttonElement.Click(); // Assert Mock.Get(itemActionMock).Verify(mock => mock("green"), Times.Once()); } } }
22.8125
75
0.613699
[ "MIT" ]
t4d-classes/blazor-server_08022021
ToolsApp/ToolsApp.Components.UnitTests/Shared/ActionDataListCSharpTest.cs
1,097
C#
using Rhino.ServiceBus.StructureMap; using StructureMap.Configuration.DSL; namespace TaskRunner.Core.BootStrappers { public class CustomBootStrapper<TType> : StructureMapBootStrapper where TType : Registry, new() { protected override void ConfigureContainer() { base.ConfigureContainer(); Container.Configure(cfg => cfg.AddRegistry<TType>()); } } public class CustomBootStrapper<TType, TType2> : StructureMapBootStrapper where TType : Registry, new() where TType2 : Registry, new() { protected override void ConfigureContainer() { base.ConfigureContainer(); Container.Configure(cfg => { cfg.AddRegistry<TType>(); cfg.AddRegistry<TType2>(); }); } } public class CustomBootStrapper<TType, TType2, TType3> : StructureMapBootStrapper where TType : Registry, new() where TType3 : Registry, new() where TType2 : Registry, new() { protected override void ConfigureContainer() { base.ConfigureContainer(); Container.Configure(cfg => { cfg.AddRegistry<TType>(); cfg.AddRegistry<TType2>(); cfg.AddRegistry<TType3>(); }); } } public class CustomBootStrapper<TType, TType2, TType3, TType4> : StructureMapBootStrapper where TType : Registry, new() where TType4 : Registry, new() where TType2 : Registry, new() where TType3 : Registry, new() { protected override void ConfigureContainer() { base.ConfigureContainer(); Container.Configure(cfg => { cfg.AddRegistry<TType>(); cfg.AddRegistry<TType2>(); cfg.AddRegistry<TType3>(); cfg.AddRegistry<TType4>(); }); } } }
31.703125
116
0.546575
[ "MIT" ]
Foxpips/LayeredArchitecture
TaskRunner.Core/BootStrappers/CustomBootStrapper.cs
2,029
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml; namespace System.Runtime.Serialization.Json { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime; using System.Security; using System.Xml; internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames); internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); internal sealed class JsonFormatReaderGenerator { private readonly CriticalHelper _helper; public JsonFormatReaderGenerator() { _helper = new CriticalHelper(); } public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return _helper.GenerateClassReader(classContract); } public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateCollectionReader(collectionContract); } public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateGetOnlyCollectionReader(collectionContract); } private sealed class CriticalHelper { private CodeGenerator _ilg = null!; // initialized in GenerateXXXReader private LocalBuilder _objectLocal = null!; // initialized in CreateObject and ReadCollection private Type? _objectType; private ArgBuilder _xmlReaderArg = null!; // initialized in InitArgs private ArgBuilder _contextArg = null!; // initialized in InitArgs private ArgBuilder _memberNamesArg = null!; // initialized in InitArgs private ArgBuilder? _collectionContractArg; private ArgBuilder _emptyDictionaryStringArg = null!; // initialized in InitArgs public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName!.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); CreateObject(classContract); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); InvokeOnDeserializing(classContract); if (classContract.IsISerializable) ReadISerializable(classContract); else ReadClass(classContract); if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType)) { _ilg.Call(_objectLocal, JsonFormatGeneratorStatics.OnDeserializationMethod, null); } InvokeOnDeserialized(classContract); if (!InvokeFactoryMethod(classContract)) { _ilg.Load(_objectLocal); // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization. // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod); _ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType); } //Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>. else if (classContract.IsKeyValuePairAdapter) { _ilg.Call(classContract.GetKeyValuePairMethodInfo); _ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType); } else { _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); } } return (JsonFormatClassReaderDelegate)_ilg.EndMethod(); } public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { _ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/); ReadCollection(collectionContract); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); return (JsonFormatCollectionReaderDelegate)_ilg.EndMethod(); } public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { _ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/); ReadGetOnlyCollection(collectionContract); return (JsonFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod(); } private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection) { _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null); try { if (isGetOnlyCollection) { BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson" + "IsGetOnly", typeof(JsonFormatGetOnlyCollectionReaderDelegate), memberAccessFlag); } else { BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson", typeof(JsonFormatCollectionReaderDelegate), memberAccessFlag); } } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); _collectionContractArg = _ilg.GetArg(4); return _ilg; } private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = delegateType.GetMethod("Invoke")!; ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].ParameterType; DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatReaderGenerator).Module, allowPrivateMemberAccess); ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess); } private void InitArgs() { _xmlReaderArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(1); _emptyDictionaryStringArg = _ilg.GetArg(2); _memberNamesArg = _ilg.GetArg(3); } private void CreateObject(ClassDataContract classContract) { _objectType = classContract.UnderlyingType; Type type = classContract.ObjectType; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")!); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) { if (type.IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(classContract.GetNonAttributedTypeConstructor()!); _ilg.Stloc(_objectLocal); } } else { _ilg.Call(null, JsonFormatGeneratorStatics.GetUninitializedObjectMethod, classContract.TypeForInitialization); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserializing); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserialized); } } private bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } private bool InvokeFactoryMethod(ClassDataContract classContract) { if (HasFactoryMethod(classContract)) { _ilg.Load(_contextArg); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, Globals.TypeOfIObjectReference); _ilg.Load(Globals.NewObjectId); _ilg.Call(XmlFormatGeneratorStatics.GetRealObjectMethod); _ilg.ConvertValue(Globals.TypeOfObject, _ilg.CurrentMethod.ReturnType); return true; } return false; } private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); _ilg.New(JsonFormatGeneratorStatics.ExtensionDataObjectCtor); _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); ClassDataContract? currentContract = classContract; while (currentContract != null) { MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; } } else { ReadMembers(classContract, null /*extensionDataLocal*/); } } private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal) { int memberCount = classContract.MemberNames!.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements"); byte[] requiredElements = new byte[expectedElements.GetLocalCount()]; SetRequiredElements(classContract, requiredElements); SetExpectedElements(expectedElements, 0 /*startIndex*/); LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); Label throwDuplicateMemberLabel = _ilg.DefineLabel(); Label throwMissingRequiredMembersLabel = _ilg.DefineLabel(); object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); _ilg.IfFalseBreak(forReadElements); _ilg.Call(_contextArg, JsonFormatGeneratorStatics.GetJsonMemberIndexMethod, _xmlReaderArg, _memberNamesArg, memberIndexLocal, extensionDataLocal); if (memberCount > 0) { Label[] memberLabels = _ilg.Switch(memberCount); ReadMembers(classContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); _ilg.EndSwitch(); } else { _ilg.Pop(); } _ilg.EndFor(); CheckRequiredElements(expectedElements, requiredElements, throwMissingRequiredMembersLabel); Label endOfTypeLabel = _ilg.DefineLabel(); _ilg.Br(endOfTypeLabel); _ilg.MarkLabel(throwDuplicateMemberLabel); _ilg.Call(null, JsonFormatGeneratorStatics.ThrowDuplicateMemberExceptionMethod, _objectLocal, _memberNamesArg, memberIndexLocal); _ilg.MarkLabel(throwMissingRequiredMembersLabel); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfObject); _ilg.Load(_memberNamesArg); expectedElements.LoadArray(); LoadArray(requiredElements, "requiredElements"); _ilg.Call(JsonFormatGeneratorStatics.ThrowMissingRequiredMembersMethod); _ilg.MarkLabel(endOfTypeLabel); } private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expectedElements, Label[] memberLabels, Label throwDuplicateMemberLabel, LocalBuilder memberIndexLocal) { int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; _ilg.Case(memberLabels[memberCount], dataMember.Name); _ilg.Set(memberIndexLocal, memberCount); expectedElements.Load(memberCount); _ilg.Brfalse(throwDuplicateMemberLabel); LocalBuilder? value = null; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name); } else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetCollectionMemberInfoMethod); value = ReadValue(memberType, dataMember.Name); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Ldloc(value); _ilg.StoreMember(dataMember.MemberInfo); } ResetExpectedElements(expectedElements, memberCount); _ilg.EndCase(); } return memberCount; } private void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements, Label throwMissingRequiredMembersLabel) { for (int i = 0; i < requiredElements.Length; i++) { _ilg.Load(expectedElements.GetLocal(i)); _ilg.Load(requiredElements[i]); _ilg.And(); _ilg.Load(0); _ilg.Ceq(); _ilg.Brfalse(throwMissingRequiredMembersLabel); } } private void LoadArray(byte[] array, string name) { LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray, name); _ilg.NewArray(typeof(byte), array.Length); _ilg.Store(localArray); for (int i = 0; i < array.Length; i++) { _ilg.StoreArrayElement(localArray, i, array[i]); } _ilg.Load(localArray); } private int SetRequiredElements(ClassDataContract contract, byte[] requiredElements) { int memberCount = (contract.BaseContract == null) ? 0 : SetRequiredElements(contract.BaseContract, requiredElements); List<DataMember> members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { if (members[i].IsRequired) { BitFlagsGenerator.SetBit(requiredElements, memberCount); } } return memberCount; } private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex) { int memberCount = expectedElements.GetBitCount(); for (int i = startIndex; i < memberCount; i++) { expectedElements.Store(i, true); } } private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index) { expectedElements.Store(index, false); } private void ReadISerializable(ClassDataContract classContract) { ConstructorInfo? ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, JsonFormatGeneratorStatics.SerInfoCtorArgs); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(ctor); } private LocalBuilder ReadValue(Type type, string name) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); LocalBuilder? nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); // Deserialize null _ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { _ilg.LoadAddress(value); _ilg.InitObj(value.LocalType); } else if (type.IsValueType) ThrowSerializationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); else { _ilg.Load(null); _ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty _ilg.ElseIfIsEmptyString(objectId); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); if (type.IsValueType) { _ilg.IfNotIsEmptyString(objectId); ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); _ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = _ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); if (!type.IsValueType) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } else { InternalDeserialize(value, type, name); } // Deserialize ref _ilg.Else(); if (type.IsValueType) ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, string.Empty); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } _ilg.EndIf(); if (nullableValue != null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); _ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name); } return value; } private void InternalDeserialize(LocalBuilder value, Type type, string name) { _ilg.Load(_contextArg); _ilg.Load(_xmlReaderArg); Type declaredType = type; _ilg.Load(DataContract.GetId(declaredType.TypeHandle)); _ilg.Ldtoken(declaredType); _ilg.Load(name); // Empty namespace _ilg.Load(string.Empty); _ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables) { Type innerType = innerValue.LocalType, outerType = outerValue.LocalType; _ilg.LoadAddress(outerValue); _ilg.Load(innerValue); for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); _ilg.New(type.GetConstructor(new Type[] { innerType })!); innerType = type; } _ilg.Call(outerType.GetConstructor(new Type[] { innerType })!); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); ConstructorInfo constructor = collectionContract.Constructor!; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes)!; break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes)!; break; case CollectionKind.Collection: case CollectionKind.GenericCollection: case CollectionKind.Enumerable: case CollectionKind.GenericEnumerable: case CollectionKind.List: case CollectionKind.GenericList: type = itemType.MakeArrayType(); isArray = true; break; } } _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (!isArray) { if (type.IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(constructor); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } } bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; if (canReadSimpleDictionary) { _ilg.Load(_contextArg); _ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty); _ilg.If(); ReadSimpleDictionary(collectionContract, itemType); _ilg.Else(); } LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); bool canReadPrimitiveArray = false; if (isArray && TryReadPrimitiveArray(itemType)) { canReadPrimitiveArray = true; _ilg.IfNot(); } LocalBuilder? growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, int.MaxValue); // Empty namespace IsStartElement(_memberNamesArg, _emptyDictionaryStringArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { Debug.Assert(growingCollection != null); MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); _ilg.StoreArrayElement(growingCollection, i, value); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); if (isArray) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, trimArraySizeMethod, growingCollection, i); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); } if (canReadPrimitiveArray) { _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); _ilg.EndIf(); } if (canReadSimpleDictionary) { _ilg.EndIf(); } } private void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType) { Type[] keyValueTypes = keyValueType.GetGenericArguments(); Type keyType = keyValueTypes[0]; Type valueType = keyValueTypes[1]; int keyTypeNullableDepth = 0; Type keyTypeOriginal = keyType; while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { keyTypeNullableDepth++; keyType = keyType.GetGenericArguments()[0]; } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; DataContract keyDataContract = keyValueDataContract.Members![0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject) { keyParseMode = KeyParseMode.AsString; } else if (keyType.IsEnum) { keyParseMode = KeyParseMode.UsingParseEnum; } else if (keyDataContract.ParseMethod != null) { keyParseMode = KeyParseMode.UsingCustomParse; } if (keyParseMode == KeyParseMode.Fail) { ThrowSerializationException( SR.Format( SR.KeyTypeCannotBeParsedInSimpleDictionary, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType), DataContract.GetClrTypeFullName(keyType))); } else { LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType), "nodeType"); _ilg.BeginWhileCondition(); _ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod); _ilg.Stloc(nodeType); _ilg.Load(nodeType); _ilg.Load(XmlNodeType.EndElement); _ilg.BeginWhileBody(Cmp.NotEqualTo); _ilg.Load(nodeType); _ilg.Load(XmlNodeType.Element); _ilg.If(Cmp.NotEqualTo); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); if (keyParseMode == KeyParseMode.UsingParseEnum) { _ilg.Load(keyType); } _ilg.Load(_xmlReaderArg); _ilg.Call(JsonFormatGeneratorStatics.GetJsonMemberNameMethod); if (keyParseMode == KeyParseMode.UsingParseEnum) { _ilg.Call(JsonFormatGeneratorStatics.ParseEnumMethod); _ilg.ConvertValue(Globals.TypeOfObject, keyType); } else if (keyParseMode == KeyParseMode.UsingCustomParse) { _ilg.Call(keyDataContract.ParseMethod!); } LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key"); _ilg.Stloc(pairKey); if (keyTypeNullableDepth > 0) { LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal, "keyOriginal"); WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth); pairKey = pairKeyNullable; } LocalBuilder pairValue = ReadValue(valueType, string.Empty); StoreKeyValuePair(_objectLocal, collectionContract, pairKey, pairValue); _ilg.EndWhile(); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; if (canReadSimpleDictionary) { _ilg.Load(_contextArg); _ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty); _ilg.If(); if (!type.IsValueType) { _ilg.If(_objectLocal, Cmp.EqualTo, null); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.EndIf(); } ReadSimpleDictionary(collectionContract, itemType); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg); _ilg.Else(); } //check that items are actually going to be deserialized into the collection IsStartElement(_memberNamesArg, _emptyDictionaryStringArg); _ilg.If(); if (!type.IsValueType) { _ilg.If(_objectLocal, Cmp.EqualTo, null); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.EndIf(); } if (isArray) { _ilg.Load(_objectLocal); _ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod); _ilg.Stloc(size); } LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _emptyDictionaryStringArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { _ilg.If(size, Cmp.EqualTo, i); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type); _ilg.Else(); _ilg.StoreArrayElement(_objectLocal, i, value); _ilg.EndIf(); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg); _ilg.EndIf(); if (canReadSimpleDictionary) { _ilg.EndIf(); } } private bool TryReadPrimitiveArray(Type itemType) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string? readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: readArrayMethod = "TryReadBooleanArray"; break; case TypeCode.Decimal: readArrayMethod = "TryReadDecimalArray"; break; case TypeCode.Int32: readArrayMethod = "TryReadInt32Array"; break; case TypeCode.Int64: readArrayMethod = "TryReadInt64Array"; break; case TypeCode.Single: readArrayMethod = "TryReadSingleArray"; break; case TypeCode.Double: readArrayMethod = "TryReadDoubleArray"; break; case TypeCode.DateTime: readArrayMethod = "TryReadJsonDateTimeArray"; break; default: break; } if (readArrayMethod != null) { _ilg.Load(_xmlReaderArg); _ilg.ConvertValue(typeof(XmlReaderDelegator), typeof(JsonReaderDelegator)); _ilg.Load(_contextArg); _ilg.Load(_memberNamesArg); // Empty namespace _ilg.Load(_emptyDictionaryStringArg); // -1 Array Size _ilg.Load(-1); _ilg.Ldloca(_objectLocal); _ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)!); return true; } return false; } private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); _ilg.Load(_collectionContractArg); _ilg.Call(JsonFormatGeneratorStatics.GetItemContractMethod); _ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod); _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Call(JsonFormatGeneratorStatics.ReadJsonValueMethod); _ilg.ConvertValue(Globals.TypeOfObject, itemType); _ilg.Stloc(value); return value; } else { return ReadValue(itemType, JsonGlobals.itemString); } } private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { Fx.Assert("Failed to create contract for KeyValuePair type"); } DataMember keyMember = keyValuePairContract.Members![0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); _ilg.LoadAddress(value); _ilg.LoadMember(valueMember.MemberInfo); _ilg.Stloc(pairValue); StoreKeyValuePair(collection, collectionContract, pairKey, pairValue); } else { Debug.Assert(collectionContract.AddMethod != null); _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } } private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue) { Debug.Assert(collectionContract.AddMethod != null); _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } private void HandleUnexpectedItemInCollection(LocalBuilder iterator) { IsStartElement(); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg); _ilg.Dec(iterator); _ilg.Else(); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); } private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg) { _ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg); } private void IsStartElement() { _ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod0); } private void IsEndElement() { _ilg.Load(_xmlReaderArg); _ilg.LoadMember(JsonFormatGeneratorStatics.NodeTypeProperty); _ilg.Load(XmlNodeType.EndElement); _ilg.Ceq(); } private void ThrowUnexpectedStateException(XmlNodeType expectedState) { _ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg); _ilg.Throw(); } private void ThrowSerializationException(string msg, params object[] values) { if (values != null && values.Length > 0) _ilg.CallStringFormat(msg, values); else _ilg.Load(msg); ThrowSerializationException(); } private void ThrowSerializationException() { _ilg.New(JsonFormatGeneratorStatics.SerializationExceptionCtor); _ilg.Throw(); } private enum KeyParseMode { Fail, AsString, UsingParseEnum, UsingCustomParse } } } }
47.059501
273
0.552003
[ "MIT" ]
Jacksondr5/runtime
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs
49,036
C#
// uScript Action Node // (C) 2015 Detox Studios LLC #if (UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_2017 || UNITY_2017_1_OR_NEWER) using UnityEngine; [NodePath("Actions/Animation/Animator")] [NodeCopyright("Copyright 2015 by Detox Studios LLC")] [NodeToolTip("Resets a Trigger parameter of a Animator Controller on the target GameObject(s) to False.")] [NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")] [NodeHelp("http://docs.uscript.net/#3-Working_With_uScript/3.4-Nodes.htm")] [FriendlyName("Reset Animator Trigger", "Resets a Trigger parameter of a Animator Controller on the target GameObject(s) to False.")] public class uScriptAct_AnimatorResetParameterTrigger : uScriptLogic { public bool Out { get { return true; } } public void In( [FriendlyName("Target", "The target GameObject(s) that contain the Animator Controller component with the paremeter you wish to set."), AutoLinkType(typeof(GameObject))] GameObject[] Target, [FriendlyName("Name", "The name of the trigger parameter you wish to activate.")] string Name ) { foreach (GameObject obj in Target) { Animator animController = obj.GetComponent<Animator>(); if (null != animController) { animController.ResetTrigger(Name); } else { uScriptDebug.Log("The specified Target (" + obj.ToString() + ") does not have an Animator Controller component and will be skipped."); } } } } #endif
34.022222
175
0.675376
[ "MIT" ]
detoxstudios/uscript
uScript_Dev/Assets/uScript/uScriptRuntime/Nodes/Actions/Animation/Animator/uScriptAct_AnimatorResetParameterTrigger.cs
1,531
C#
using System; using System.Collections.Generic; using System.Linq; using LazyStackDynamoDBRepo; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using PetStoreSchema.Models; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace PetStoreRepo.Models { public class PetEnvelope : DataEnvelope<Pet> { protected override void SetDbRecordFromEnvelopeInstance() { // Set the Envelope Key fields from the EntityInstance data TypeName = "Pet.v1.0.0"; // Primary Key is PartitionKey + SortKey PK = "Pets:"; // Partition key SK = $"Pet:{EntityInstance.Id}"; // sort/range key // The base method copies information from the envelope keys into the dbRecord base.SetDbRecordFromEnvelopeInstance(); } } public interface IPetRepo : IDYDBRepository<PetEnvelope, Pet> { Task<ActionResult<Pet>> AddPetAsync(Pet pet); Task<StatusCodeResult> DeletePetAsync(string api_key, long petId); Task<ActionResult<ICollection<Pet>>> FindPetsByStatusAsync(IEnumerable<PetStatus> status); Task<ActionResult<ICollection<Pet>>> FindPetsByTagsAsync(IEnumerable<string> tags); Task<ActionResult<Pet>> GetPetByIdAsync(long petId); Task<ActionResult<Pet>> UpdatePetAsync(Pet body); Task<ActionResult<ICollection<Pet>>> GetInventoryAsync(); Task<ActionResult<ICollection<Category>>> GetPetCategoriesAsync(); Task<ActionResult<ICollection<PetStoreSchema.Models.Tag>>> GetPetTagsAsync(); Task<StatusCodeResult> SeedPetsAsync(); } public class PetRepo : DYDBRepository<PetEnvelope, Pet>, IPetRepo { public PetRepo( IAmazonDynamoDB client, ITagRepo tagRepo, ICategoryRepo categoryRepo ) : base(client, envVarTableName: "TABLE_NAME") { this.tagRepo = tagRepo; this.categoryRepo = categoryRepo; } private ITagRepo tagRepo; private ICategoryRepo categoryRepo; // This dictionary allows us to use class attribute names that happen to also be // DynamoDB reserved words in our ProjectionExpressions Dictionary<string, string> _ExpressionAttributeNames = new Dictionary<string, string>() { {"#Data", "Data" }, {"#Status", "Status" }, {"#General", "General" } }; public async Task<ActionResult<Pet>> AddPetAsync(Pet pet) { return await CreateAsync(pet); } public async Task<StatusCodeResult> DeletePetAsync(string api_key, long petId) { // Ignoring api_key argument // PK=Pet:, SK=Pet:<petId> return await DeleteAsync( pK: "Pets:", sK: "Pet:" + petId.ToString()); } public async Task<ActionResult<ICollection<Pet>>> FindPetsByStatusAsync(IEnumerable<PetStatus> status) { var queryRequest = new QueryRequest() { TableName = tablename, KeyConditionExpression = "PK = :PKval AND begins_with(SK, :SKval)", ExpressionAttributeValues = new Dictionary<string, AttributeValue> { {":PKval", new AttributeValue() {S = "Pets:"} }, {":SKval", new AttributeValue() {S = "Pet:"} } }, ExpressionAttributeNames = _ExpressionAttributeNames, ProjectionExpression = "#Data, TypeName, #Status, UpdateUtcTick, CreateUtcTick, #General" }; var queryResult = await ListAsync(queryRequest); if (queryResult.Value == null) return queryResult.Result; var statusList = status.ToList(); // Filter the list var list = new List<Pet>(); foreach (var pet in queryResult.Value) { if (statusList.Contains(pet.PetStatus)) list.Add(pet); } return list; } public async Task<ActionResult<ICollection<Pet>>> FindPetsByTagsAsync(IEnumerable<string> tags) { var queryRequest = new QueryRequest() { TableName = tablename, KeyConditionExpression = "PK = :PKval AND begins_with (SK, :SKval)", ExpressionAttributeValues = new Dictionary<string, AttributeValue> { {":PKval", new AttributeValue() {S = "Pets:"} }, {":SKval", new AttributeValue() {S = "Pet:"} } }, ExpressionAttributeNames = _ExpressionAttributeNames, ProjectionExpression = "#Data, TypeName, #Status, UpdateUtcTick, CreateUtcTick, #General" }; var queryResult = await ListAsync(queryRequest); if (queryResult.Result != null) return queryResult.Result; // Filter the list var list = new List<Pet>(); foreach (var pet in queryResult.Value) foreach (var tag in pet.Tags) if (tags.Contains(tag.Name)) list.Add(pet); return list; } public async Task<ActionResult<Pet>> GetPetByIdAsync(long petId) { return await ReadAsync( pK: "Pets:", sK: "Pet:" + petId.ToString()); } public async Task<ActionResult<Pet>> UpdatePetAsync(Pet body) { return await UpdateAsync(body); } public async Task<ActionResult<ICollection<Pet>>> GetInventoryAsync() { var queryRequest = new QueryRequest() { TableName = tablename, KeyConditionExpression = "PK = :PKval AND begins_with (SK, :SKval)", ExpressionAttributeValues = new Dictionary<string, AttributeValue> { {":PKval", new AttributeValue() {S = "Pets:"} }, {":SKval",new AttributeValue() {S = "Pet:"} } }, ExpressionAttributeNames = _ExpressionAttributeNames, ProjectionExpression = "#Data, TypeName, #Status, UpdateUtcTick, CreateUtcTick, #General" }; return await ListAsync(queryRequest); } public async Task<ActionResult<Pet>> PingAsync() { await Task.Delay(0); return new OkObjectResult( new Pet() { Id = 10, Category = categoryRepo.Categories[1], Name = "pingpet", PetStatus = PetStatus.Available, Tags = new List<PetStoreSchema.Models.Tag> { tagRepo.Tags[1] }, PhotoUrls = new List<string> { "https://www.example.com" } }); } public async Task<ActionResult<ICollection<Category>>> GetPetCategoriesAsync() { await Task.Delay(0); return categoryRepo.Categories.Values.ToList(); } public async Task<ActionResult<ICollection<PetStoreSchema.Models.Tag>>> GetPetTagsAsync() { await Task.Delay(0); return tagRepo.Tags.Values.ToList(); } public async Task<StatusCodeResult> SeedPetsAsync() { var pet = new Pet() { Id = 1, Category = categoryRepo.Categories[1], // dog Name = "Alf", PhotoUrls = new List<string> { "www.example.com" }, Tags = new List<PetStoreSchema.Models.Tag> { tagRepo.Tags[1], tagRepo.Tags[2] }, PetStatus = PetStatus.Available }; await AddPetAsync(pet); pet = new Pet() { Id = 2, Category = categoryRepo.Categories[2], // cat Name = "Sweetie", PhotoUrls = new List<string> { "www.example.com" }, Tags = new List<PetStoreSchema.Models.Tag> { tagRepo.Tags[1], tagRepo.Tags[2], tagRepo.Tags[3] }, PetStatus = PetStatus.Available }; await AddPetAsync(pet); return new OkResult(); } } }
37.222707
113
0.544932
[ "MIT" ]
InSciCo/InSciCo
docs/assets/tutorial/code/PetStoreRepo/PetRepo.cs
8,524
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise6 { class Program { static void Main(string[] args) { List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); for (int i = 0; i < numbers.Count; i++) { string currentNumber = numbers[i].ToString(); string newNum = ""; for (int a = currentNumber.Length-1; a >=0; a--) { newNum += currentNumber[a]; } numbers[i] = int.Parse(newNum); } int result = 0; for (int i = 0; i < numbers.Count; i++) { result += numbers[i]; } Console.WriteLine(result); } } }
22.769231
89
0.463964
[ "MIT" ]
ghostdog87/Programming-Fundamentals-2018
Lesson12 - Lists/Exercise6/Program.cs
890
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Windows; namespace GitHelper { public static class Utility { public static bool? ShowDialog(Window window) { window.Owner = Application.Current.MainWindow; return window.ShowDialog(); } public static bool IsNullOrEmpty<T>(IList<T> formats) { return formats == null || formats.Count == 0; } public static string GetResourceText(string uriLink, Encoding encoding = null) { var uri = new Uri(uriLink); if (encoding == null) { encoding = Encoding.GetEncoding("UTF-8"); } var stream = Application.GetResourceStream(uri); if (stream == null) { return ""; } using (var reader = new StreamReader(stream.Stream, encoding)) { return reader.ReadToEnd(); } } } }
24.488372
86
0.529915
[ "MIT" ]
g2384/GitHelper
GitHelper/Utility.cs
1,053
C#
// Файл IP2PService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.ServiceModel; namespace P2P { [ServiceContract] public interface IP2PService { [OperationContract] string GetName(); [OperationContract(IsOneWay = true)] void SendMessage(string message, string from); } }
20.65
54
0.7046
[ "MIT" ]
silicium-one/OTUS_EXAMPLES
Examples/p2pWpf/IP2PService.cs
419
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Medallion.Shell.Signals; using Medallion.Shell.Streams; namespace Medallion.Shell { /// <summary> /// Represents an executing <see cref="Process"/> as well as related asynchronous activity (e. g. the piping of /// input and output streams) /// </summary> public abstract class Command : IDisposable { // prevent external inheritors internal Command() { } /// <summary> /// The <see cref="System.Diagnostics.Process"/> associated with this <see cref="Command"/>. In a multi-process command, /// this will be the final <see cref="System.Diagnostics.Process"/> in the chain. NOTE: this property cannot be accessed when using /// the <see cref="Shell.Options.DisposeOnExit(bool)"/> option /// </summary> public abstract Process Process { get; } /// <summary> /// All <see cref="System.Diagnostics.Process"/>es associated with this <see cref="Command"/>. NOTE: this property cannot be accessed when using /// the <see cref="Shell.Options.DisposeOnExit(bool)"/> option /// </summary> public abstract IReadOnlyList<Process> Processes { get; } /// <summary> /// The PID of the process associated with this <see cref="Command"/>. In a multi-process command, /// this will be the PID of the final <see cref="System.Diagnostics.Process"/> in the chain. NOTE: unlike /// the <see cref="Process"/> property, this property is compatible with the <see cref="Shell.Options.DisposeOnExit(bool)"/> /// option /// </summary> public abstract int ProcessId { get; } /// <summary> /// All PIDs of the <see cref="System.Diagnostics.Process"/>es associated with this <see cref="Command"/>. NOTE: unlike /// the <see cref="Processes"/> property, this property is compatible with the /// <see cref="Shell.Options.DisposeOnExit(bool)"/> option /// </summary> public abstract IReadOnlyList<int> ProcessIds { get; } /// <summary> /// Writes to the process's standard input /// </summary> public abstract ProcessStreamWriter StandardInput { get; } /// <summary> /// Reads from the process's standard output /// </summary> public abstract ProcessStreamReader StandardOutput { get; } /// <summary> /// Reads from the process's standard error /// </summary> public abstract ProcessStreamReader StandardError { get; } /// <summary> /// Kills the <see cref="Process"/> if it is still executing /// </summary> public abstract void Kill(); /// <summary> /// Attempts to send the specified <see cref="CommandSignal"/> to each <see cref="System.Diagnostics.Process"/> /// underlying the current <see cref="Command"/>. Returns true if at least one <see cref="System.Diagnostics.Process"/> /// received the signal and false otherwise. /// /// There are several reasons that signaling could fail, for example: /// * The provided signal number is not valid for the OS /// * The <see cref="System.Diagnostics.Process"/> has already exited /// * On Windows, signals can only be sent to console processes /// </summary> public Task<bool> TrySignalAsync(CommandSignal signal) { if (signal == null) { throw new ArgumentNullException(nameof(signal)); } this.ThrowIfDisposed(); return TrySignalHelperAsync(); async Task<bool> TrySignalHelperAsync() { var result = false; foreach (var processId in this.ProcessIds) { result |= await ProcessSignaler.TrySignalAsync(processId, signal).ConfigureAwait(false); } return result; } } /// <summary> /// A convenience method for <code>command.Task.Wait()</code>. If the task faulted or was canceled, /// this will throw the faulting <see cref="Exception"/> or <see cref="TaskCanceledException"/> rather than /// the wrapped <see cref="AggregateException"/> thrown by <see cref="Task{TResult}.Result"/> /// </summary> public void Wait() => this.Task.GetAwaiter().GetResult(); /// <summary> /// A convenience method for <code>command.Task.Result</code>. If the task faulted or was canceled, /// this will throw the faulting <see cref="Exception"/> or <see cref="TaskCanceledException"/> rather than /// the wrapped <see cref="AggregateException"/> thrown by <see cref="Task{TResult}.Result"/> /// </summary> public CommandResult Result => this.Task.GetAwaiter().GetResult(); /// <summary> /// A <see cref="Task"/> representing the progress of this <see cref="Command"/> /// </summary> public abstract Task<CommandResult> Task { get; } #region ---- Fluent redirection ---- /// <summary> /// Implements <see cref="Command"/> piping as in bash. The first <see cref="Command"/>'s standard output is piped /// to the second's standard input. Returns a new <see cref="Command"/> instance whose <see cref="Command.Task"/> tracks /// the progress of the entire chain /// </summary> public Command PipeTo(Command second) { Throw.IfNull(second, nameof(second)); return new PipedCommand(this, second); } /// <summary> /// Standard output redirection as in bash. The <see cref="Command"/>'s standard output is written to the given /// <paramref name="stream"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectTo(Stream stream) { Throw.IfNull(stream, nameof(stream)); return new IOCommand(this, this.StandardOutput.PipeToAsync(stream, leaveStreamOpen: true), StandardIOStream.Out, stream); } /// <summary> /// Standard error redirection as in bash. The <see cref="Command"/>'s standard error is written to the given /// <paramref name="stream"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectStandardErrorTo(Stream stream) { Throw.IfNull(stream, nameof(stream)); return new IOCommand(this, this.StandardError.PipeToAsync(stream, leaveStreamOpen: true), StandardIOStream.Error, stream); } /// <summary> /// Standard input redirection as in bash. The given <paramref name="stream"/> is written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectFrom(Stream stream) { Throw.IfNull(stream, nameof(stream)); return new IOCommand(this, this.StandardInput.PipeFromAsync(stream, leaveStreamOpen: true), StandardIOStream.In, stream); } /// <summary> /// Standard output redirection as in bash. The <see cref="Command"/>'s standard output is written to the given /// <paramref name="file"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectTo(FileInfo file) { Throw.IfNull(file, nameof(file)); return new IOCommand(this, this.StandardOutput.PipeToAsync(file), StandardIOStream.Out, file); } /// <summary> /// Standard error redirection as in bash. The <see cref="Command"/>'s standard error is written to the given /// <paramref name="file"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectStandardErrorTo(FileInfo file) { Throw.IfNull(file, nameof(file)); return new IOCommand(this, this.StandardError.PipeToAsync(file), StandardIOStream.Error, file); } /// <summary> /// Standard input redirection as in bash. The given <paramref name="file"/> is written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectFrom(FileInfo file) { Throw.IfNull(file, nameof(file)); return new IOCommand(this, this.StandardInput.PipeFromAsync(file), StandardIOStream.In, file); } /// <summary> /// Standard output redirection as in bash. The lines of <see cref="Command"/>'s standard output are added to the given /// collection (<paramref name="lines"/> Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks /// the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectTo(ICollection<string> lines) { Throw.IfNull(lines, nameof(lines)); return new IOCommand(this, this.StandardOutput.PipeToAsync(lines), StandardIOStream.Out, lines.GetType()); } /// <summary> /// Standard error redirection as in bash. The lines of <see cref="Command"/>'s standard error are added to the given /// collection (<paramref name="lines"/> Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks /// the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectStandardErrorTo(ICollection<string> lines) { Throw.IfNull(lines, nameof(lines)); return new IOCommand(this, this.StandardError.PipeToAsync(lines), StandardIOStream.Error, lines.GetType()); } /// <summary> /// Standard input redirection as in bash. The items in <paramref name="lines"/> are written to the <see cref="Command"/>'s /// standard output as lines of text. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the /// progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectFrom(IEnumerable<string> lines) { Throw.IfNull(lines, nameof(lines)); return new IOCommand(this, this.StandardInput.PipeFromAsync(lines), StandardIOStream.In, lines.GetType()); } /// <summary> /// Standard output redirection as in bash. The chars of <see cref="Command"/>'s standard output are added to the given /// collection (<paramref name="chars"/> Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks /// the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectTo(ICollection<char> chars) { Throw.IfNull(chars, nameof(chars)); return new IOCommand(this, this.StandardOutput.PipeToAsync(chars), StandardIOStream.Out, chars.GetType()); } /// <summary> /// Standard error redirection as in bash. The chars of <see cref="Command"/>'s standard error are added to the given /// collection (<paramref name="chars"/> Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks /// the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectStandardErrorTo(ICollection<char> chars) { Throw.IfNull(chars, nameof(chars)); return new IOCommand(this, this.StandardError.PipeToAsync(chars), StandardIOStream.Error, chars.GetType()); } /// <summary> /// Standard input redirection as in bash. The items in <paramref name="chars"/> are written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the /// progress of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectFrom(IEnumerable<char> chars) { Throw.IfNull(chars, nameof(chars)); return new IOCommand(this, this.StandardInput.PipeFromAsync(chars), StandardIOStream.In, chars.GetType()); } /// <summary> /// Standard output redirection as in bash. The <see cref="Command"/>'s standard output is written to the given /// <paramref name="writer"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectTo(TextWriter writer) { Throw.IfNull(writer, nameof(writer)); return new IOCommand(this, this.StandardOutput.PipeToAsync(writer, leaveWriterOpen: true), StandardIOStream.Out, writer); } /// <summary> /// Standard error redirection as in bash. The <see cref="Command"/>'s standard error is written to the given /// <paramref name="writer"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectStandardErrorTo(TextWriter writer) { Throw.IfNull(writer, nameof(writer)); return new IOCommand(this, this.StandardError.PipeToAsync(writer, leaveWriterOpen: true), StandardIOStream.Error, writer); } /// <summary> /// Standard input redirection as in bash. The given <paramref name="reader"/> is written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public Command RedirectFrom(TextReader reader) { Throw.IfNull(reader, nameof(reader)); return new IOCommand(this, this.StandardInput.PipeFromAsync(reader, leaveReaderOpen: true), StandardIOStream.In, reader); } /// <summary> /// Returns a single streaming <see cref="IEnumerable{T}"/> which merges the outputs of /// <see cref="ProcessStreamReader.GetLines"/> on <see cref="StandardOutput"/> and /// <see cref="StandardError"/>. This is similar to doing 2>&amp;1 on the command line. /// /// Merging at the line level means that interleaving of the outputs cannot break up any single /// lines /// </summary> public IEnumerable<string> GetOutputAndErrorLines() => new MergedLinesEnumerable(standardOutput: this.StandardOutput, standardError: this.StandardError); #endregion #region ---- Operator overloads ---- /// <summary> /// Implements <see cref="Command"/> piping as in bash. The first <see cref="Command"/>'s standard output is piped /// to the second's standard input. Returns a new <see cref="Command"/> instance whose <see cref="Command.Task"/> tracks /// the progress of the entire chain /// </summary> public static Command operator |(Command first, Command second) { Throw.IfNull(first, "first"); return first.PipeTo(second); } #region ---- Standard input and output redirection ---- /// <summary> /// Standard output redirection as in bash. The <see cref="Command"/>'s standard output is written to the given /// <paramref name="stream"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator >(Command command, Stream stream) { Throw.IfNull(command, "command"); return command.RedirectTo(stream); } /// <summary> /// Standard input redirection as in bash. The given <paramref name="stream"/> is written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator <(Command command, Stream stream) { Throw.IfNull(command, "command"); return command.RedirectFrom(stream); } /// <summary> /// Standard output redirection as in bash. The <see cref="Command"/>'s standard output is written to the given /// <paramref name="file"/>. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator >(Command command, FileInfo file) { Throw.IfNull(command, "command"); return command.RedirectTo(file); } /// <summary> /// Standard input redirection as in bash. The given <paramref name="file"/> is written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the progress /// of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator <(Command command, FileInfo file) { Throw.IfNull(command, "command"); return command.RedirectFrom(file); } /// <summary> /// Standard output redirection as in bash. The lines of <see cref="Command"/>'s standard output are added to the given /// collection (<paramref name="lines"/> MUST be an instance of <see cref="ICollection{String}"/>; the use of the <see cref="IEnumerable{String}"/>. /// type is to provide the required parity with the input redirection operator. Returns a new <see cref="Command"/> /// whose <see cref="Command.Task"/> tracks the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator >(Command command, IEnumerable<string> lines) { Throw.IfNull(command, nameof(command)); Throw.IfNull(lines, nameof(lines)); return lines is ICollection<string> linesCollection ? command.RedirectTo(linesCollection) : throw new ArgumentException("must implement ICollection<string> in order to recieve output", nameof(lines)); } /// <summary> /// Standard input redirection as in bash. The items in <paramref name="lines"/> are written to the <see cref="Command"/>'s /// standard output as lines of text. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the /// progress of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator <(Command command, IEnumerable<string> lines) { Throw.IfNull(command, "command"); return command.RedirectFrom(lines); } /// <summary> /// Standard output redirection as in bash. The chars of <see cref="Command"/>'s standard output are added to the given /// collection (<paramref name="chars"/> MUST be an instance of <see cref="ICollection{Char}"/>; the use of the <see cref="IEnumerable{Character}"/>. /// type is to provide the required parity with the input redirection operator. Returns a new <see cref="Command"/> /// whose <see cref="Command.Task"/> tracks the progress of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator >(Command command, IEnumerable<char> chars) { Throw.IfNull(command, nameof(command)); Throw.IfNull(chars, nameof(chars)); return chars is ICollection<char> charCollection ? command.RedirectTo(charCollection) : throw new ArgumentException("must implement ICollection<char> in order to receive output", nameof(chars)); } /// <summary> /// Standard input redirection as in bash. The items in <paramref name="chars"/> are written to the <see cref="Command"/>'s /// standard output. Returns a new <see cref="Command"/> whose <see cref="Command.Task"/> tracks the /// progress of both this <see cref="Command"/> and the IO being performed /// </summary> public static Command operator <(Command command, IEnumerable<char> chars) { Throw.IfNull(command, "command"); return command.RedirectFrom(chars); } #endregion #endregion #region ---- Static API ---- /// <summary> /// A convenience method for calling <see cref="Shell.Run(string, IEnumerable{object}, Action{Shell.Options})"/> on <see cref="Shell.Default"/> /// </summary> public static Command Run(string executable, IEnumerable<object>? arguments = null, Action<Shell.Options>? options = null) => Shell.Default.Run(executable, arguments, options); /// <summary> /// A convenience method for calling <see cref="Shell.TryAttachToProcess(int, Action{Shell.Options}, out Medallion.Shell.Command)"/> on <see cref="Shell.Default"/> /// </summary> public static bool TryAttachToProcess(int processId, Action<Shell.Options> options, [NotNullWhen(returnValue: true)] out Command? attachedCommand) => Shell.Default.TryAttachToProcess(processId, options, out attachedCommand); /// <summary> /// A convenience method for calling <see cref="Shell.TryAttachToProcess(int, out Medallion.Shell.Command)"/> on <see cref="Shell.Default"/> /// </summary> public static bool TryAttachToProcess(int processId, [NotNullWhen(returnValue: true)] out Command? attachedCommand) => Shell.Default.TryAttachToProcess(processId, out attachedCommand); /// <summary> /// A convenience method for calling <see cref="Shell.Run(string, object[])"/> on <see cref="Shell.Default"/> /// </summary> public static Command Run(string executable, params object[] arguments) { return Shell.Default.Run(executable, arguments); } #endregion // NOTE: we used to also override true, false, ! and & to support boolean conditions as in bash. The problem with // this is that a statement like a || b || c uses "|" to evaluate a || b before combining it with c. We already override // "|" to be the pipe operator, so this doesn't end up doing what we'd like. Rather than sacrifice piping (which is useful), // I'm choosing to sacrifice boolean overloads, which are cool but not particularly useful given that you can just do // .Result.Success #region ---- Dispose ---- private int _disposed; /// <summary> /// Releases all resources associated with this <see cref="Command"/>. This is only required /// if the <see cref="Shell.Options.DisposeOnExit"/> has been set to false /// </summary> void IDisposable.Dispose() { if (Interlocked.Exchange(ref this._disposed, 1) == 0) { this.DisposeInternal(); } } /// <summary> /// Subclass-specific implementation of <see cref="IDisposable.Dispose"/> /// </summary> protected abstract void DisposeInternal(); /// <summary> /// Throws <see cref="ObjectDisposedException"/> if the <see cref="Command"/> has been disposed /// </summary> protected void ThrowIfDisposed() { Throw<ObjectDisposedException>.If(Volatile.Read(ref this._disposed) != 0, () => this.ToString()); } #endregion } }
50.407631
171
0.623232
[ "MIT" ]
JTOne123/MedallionShell
MedallionShell/Command.cs
25,105
C#
/* Copyright (C) 2008, 2009 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Runtime.InteropServices; #if !NO_SYMBOL_WRITER using System.Diagnostics.SymbolStore; #endif using IKVM.Reflection.Emit; namespace IKVM.Reflection.Impl { [StructLayout(LayoutKind.Sequential)] struct IMAGE_DEBUG_DIRECTORY { public uint Characteristics; public uint TimeDateStamp; public ushort MajorVersion; public ushort MinorVersion; public uint Type; public uint SizeOfData; public uint AddressOfRawData; public uint PointerToRawData; } #if NO_SYMBOL_WRITER struct SymbolToken { internal SymbolToken(int value) { } } interface ISymbolWriterImpl { byte[] GetDebugInfo(ref IMAGE_DEBUG_DIRECTORY idd); void RemapToken(int oldToken, int newToken); void DefineLocalVariable2(string name, FieldAttributes attributes, int signature, int addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset); void OpenMethod(SymbolToken symbolToken, MethodBase mb); bool IsDeterministic { get; } } #else interface ISymbolWriterImpl : ISymbolWriter { byte[] GetDebugInfo(ref IMAGE_DEBUG_DIRECTORY idd); void RemapToken(int oldToken, int newToken); void DefineLocalVariable2(string name, FieldAttributes attributes, int signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset); void OpenMethod(SymbolToken symbolToken, MethodBase mb); bool IsDeterministic { get; } } #endif static class SymbolSupport { internal static ISymbolWriterImpl CreateSymbolWriterFor(ModuleBuilder moduleBuilder) { #if NO_SYMBOL_WRITER throw new NotSupportedException("IKVM.Reflection compiled with NO_SYMBOL_WRITER does not support writing debugging symbols."); #else if (Universe.MonoRuntime) { #if MONO return new MdbWriter(moduleBuilder); #else return new DummySymbolWriter(); #endif } else { return new PdbWriter(moduleBuilder); } #endif } internal static byte[] GetDebugInfo(ISymbolWriterImpl writer, ref IMAGE_DEBUG_DIRECTORY idd) { return writer.GetDebugInfo(ref idd); } internal static void RemapToken(ISymbolWriterImpl writer, int oldToken, int newToken) { writer.RemapToken(oldToken, newToken); } } class DummySymbolDocumentWriter : ISymbolDocumentWriter { public void SetSource(byte[] source) { } public void SetCheckSum(Guid algorithmId, byte[] checkSum) { } } class DummySymbolWriter : ISymbolWriterImpl { public void Initialize(IntPtr emitter, string filename, bool fFullBuild) { } public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { return new DummySymbolDocumentWriter(); } public void SetUserEntryPoint(SymbolToken entryMethod) { } public void OpenMethod(SymbolToken method) { } public void CloseMethod() { } public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { } public int OpenScope(int startOffset) { return 0; } public void CloseScope(int endOffset) { } public void SetScopeRange(int scopeID, int startOffset, int endOffset) { } public void DefineLocalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { } public void DefineParameter(string name, System.Reflection.ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineField(SymbolToken parent, string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineGlobalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void Close() { } public void SetSymAttribute(SymbolToken parent, string name, byte[] data) { } public void OpenNamespace(string name) { } public void CloseNamespace() { } public void UsingNamespace(string fullName) { } public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) { } public void SetUnderlyingWriter(IntPtr underlyingWriter) { } public byte[] GetDebugInfo(ref IMAGE_DEBUG_DIRECTORY idd) { return new byte[0]; } public void RemapToken(int oldToken, int newToken) { } public void DefineLocalVariable2(string name, FieldAttributes attributes, int signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { } public void OpenMethod(SymbolToken symbolToken, MethodBase mb) { } public bool IsDeterministic => true; } }
28.331858
174
0.684523
[ "MIT" ]
Nicero/uno
src/compiler/backend/ikvm/reflect/Impl/SymbolSupport.cs
6,403
C#
// Copyright (c) 2009, Semyon A. Chertkov (semyonc@gmail.com) // 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 author 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 ''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 AUTHOR 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.Globalization; using System.Xml; using System.Xml.Schema; using DataEngine.CoreServices; namespace DataEngine.XQuery.Util { public class TimeValue: IComparable, IXmlConvertable { public const int ProxyValueCode = 14; public TimeValue(DateTimeOffset value) { DateTime today = DateTime.Today; Value = new DateTimeOffset(new DateTime(today.Year, today.Month, today.Day, value.DateTime.Hour, value.DateTime.Minute, value.DateTime.Second, value.DateTime.Millisecond), value.Offset); IsLocal = false; } public TimeValue(DateTime value) { DateTime today = DateTime.Today; Value = new DateTimeOffset(new DateTime(today.Year, today.Month, today.Day, value.Hour, value.Minute, value.Second, value.Millisecond)); IsLocal = true; } public DateTimeOffset Value { get; private set; } public bool IsLocal { get; private set; } public override bool Equals(object obj) { TimeValue other = obj as TimeValue; if (other != null) return Value.Equals(other.Value); return false; } public override int GetHashCode() { return Value.GetHashCode(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(Value.ToString("HH:mm:ss", CultureInfo.InvariantCulture)); if (Value.DateTime.Millisecond != 0) { sb.Append('.'); sb.Append(Math.Abs(Value.DateTime.Millisecond).ToString("000").TrimEnd('0')); } if (!IsLocal) { if (Value.Offset == TimeSpan.Zero) sb.Append("Z"); else sb.Append(Value.ToString("zzz", CultureInfo.InvariantCulture)); } return sb.ToString(); } private static string[] TimeFormats = new string[] { "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.fffffff", "HH:mm:ss.ffffffff" }; private static string[] TimeOffsetFormats = new string[] { "HH:mm:sszzz", "HH:mm:ss.fzzz", "HH:mm:ss.ffzzz", "HH:mm:ss.fffzzz", "HH:mm:ss.ffffzzz", "HH:mm:ss.fffffzzz", "HH:mm:ss.fffffffzzz", "HH:mm:ss.ffffffffzzz" }; public static TimeValue Parse(string text) { DateTimeOffset dateTimeOffset; DateTime dateTime; text = text.Trim(); int p = text.IndexOf("24:00:00"); if (p != -1) { if (p + 8 < text.Length && text[p + 8] == '.') throw new XQueryException(Properties.Resources.InvalidFormat, text, "xs:dateTime"); text = text.Substring(0, p) + "00:00:00" + text.Substring(p + 8); } if (text.EndsWith("Z")) { if (!DateTimeOffset.TryParseExact(text.Substring(0, text.Length - 1), TimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out dateTimeOffset)) throw new XQueryException(Properties.Resources.InvalidFormat, text, "xs:time"); return new TimeValue(dateTimeOffset); } else { if (DateTime.TryParseExact(text, TimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out dateTime)) return new TimeValue(dateTime); if (!DateTimeOffset.TryParseExact(text, TimeOffsetFormats, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out dateTimeOffset)) throw new XQueryException(Properties.Resources.InvalidFormat, text, "xs:time"); return new TimeValue(dateTimeOffset); } } #region IComparable Members int IComparable.CompareTo(object obj) { TimeValue other = obj as TimeValue; if (other == null) throw new ArgumentException("obj"); return Value.CompareTo(other.Value); } #endregion public static TimeValue Add(TimeValue tm, DayTimeDurationValue duration) { DateTimeValue dat; if (tm.IsLocal) dat = new DateTimeValue(false, DateTime.Today, tm.Value.DateTime); else dat = new DateTimeValue(false, DateTime.Today, tm.Value.DateTime, tm.Value.Offset); DateTime dt = DateTimeValue.Add(dat, duration).Value.DateTime; DateTime today = DateTime.Today; dt = new DateTime(today.Year, today.Month, today.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); if (tm.IsLocal) return new TimeValue(dt); else return new TimeValue(new DateTimeOffset(dt, tm.Value.Offset)); } public static DayTimeDurationValue Sub(TimeValue tm1, TimeValue tm2) { return new DayTimeDurationValue(tm1.Value - tm2.Value); } internal class ProxyFactory : ValueProxyFactory { public override ValueProxy Create(object value) { return new Proxy((TimeValue)value); } public override int GetValueCode() { return ProxyValueCode; } public override Type GetValueType() { return typeof(TimeValue); } public override bool IsNumeric { get { return false; } } public override int Compare(ValueProxyFactory other) { return 0; } } internal class Proxy : ValueProxy { private TimeValue _value; public Proxy(TimeValue value) { _value = value; } public override int GetValueCode() { return ProxyValueCode; } public override object Value { get { return _value; } } protected override bool Eq(ValueProxy val) { if (val.GetValueCode() != ProxyValueCode) throw new OperatorMismatchException(Funcs.Eq, _value, val.Value); return _value.Equals(((Proxy)val)._value); } protected override bool Gt(ValueProxy val) { if (val.GetValueCode() != ProxyValueCode) throw new OperatorMismatchException(Funcs.Gt, _value, val.Value); return ((IComparable)_value).CompareTo(((Proxy)val)._value) > 0; } protected override ValueProxy Promote(ValueProxy val) { throw new NotImplementedException(); } protected override ValueProxy Neg() { throw new OperatorMismatchException(Funcs.Neg, _value, null); } protected override ValueProxy Add(ValueProxy value) { switch (value.GetValueCode()) { case DayTimeDurationValue.ProxyValueCode: return new Proxy(TimeValue.Add(_value, (DayTimeDurationValue)value.Value)); default: throw new OperatorMismatchException(Funcs.Add, _value, value.Value); } } protected override ValueProxy Sub(ValueProxy value) { switch (value.GetValueCode()) { case TimeValue.ProxyValueCode: return new DayTimeDurationValue.Proxy(TimeValue.Sub(_value, (TimeValue)value.Value)); case DayTimeDurationValue.ProxyValueCode: return new Proxy(TimeValue.Add(_value, -(DayTimeDurationValue)value.Value)); default: throw new OperatorMismatchException(Funcs.Sub, _value, value.Value); } } protected override ValueProxy Mul(ValueProxy value) { throw new OperatorMismatchException(Funcs.Mul, _value, value.Value); } protected override ValueProxy Div(ValueProxy value) { throw new OperatorMismatchException(Funcs.Div, _value, value.Value); } protected override Integer IDiv(ValueProxy value) { throw new OperatorMismatchException(Funcs.IDiv, _value, value.Value); } protected override ValueProxy Mod(ValueProxy value) { throw new OperatorMismatchException(Funcs.Div, _value, value.Value); } } #region IXmlConvertable Members object IXmlConvertable.ValueAs(XQuerySequenceType type, XmlNamespaceManager nsmgr) { switch (type.TypeCode) { case XmlTypeCode.AnyAtomicType: case XmlTypeCode.Time: return this; case XmlTypeCode.String: return ToString(); case XmlTypeCode.UntypedAtomic: return new UntypedAtomic(ToString()); default: throw new InvalidCastException(); } } #endregion } }
37.457055
115
0.535828
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/Xameleon/QueryMachine/QueryMachine.XQuery/Util/TimeValue.cs
12,213
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Toolkit.Uwp.UI.Lottie.UIData.Tools; using Microsoft.UI.Xaml.Controls; using Windows.UI.Composition; namespace Microsoft.Toolkit.Uwp.UI.Lottie { /// <summary> /// Information from which a composition's content can be instantiated. Contains the WinCompData /// translation of a composition and some metadata. This allows multiple instances of the translation /// to be instantiated without requiring repeated translations. /// </summary> sealed class AnimatedVisualFactory : IAnimatedVisualSource { readonly Dictionary<Uri, ICompositionSurface?> _imageCache = new Dictionary<Uri, ICompositionSurface?>(); readonly LottieVisualDiagnostics? _diagnostics; Loader? _loader; WinCompData.Visual? _wincompDataRootVisual; WinCompData.CompositionPropertySet? _wincompDataThemingPropertySet; CompositionPropertySet? _themingPropertySet; double _width; double _height; TimeSpan _duration; internal AnimatedVisualFactory(Loader loader, LottieVisualDiagnostics? diagnostics) { _loader = loader; _diagnostics = diagnostics; } internal void SetDimensions(double width, double height, TimeSpan duration) { _width = width; _height = height; _duration = duration; } internal void SetRootVisual(WinCompData.Visual rootVisual) { // Save the root visual. _wincompDataRootVisual = rootVisual; // Find the theming property set, if any. var graph = ObjectGraph<Graph.Node>.FromCompositionObject(_wincompDataRootVisual, includeVertices: false); _wincompDataThemingPropertySet = graph. CompositionObjectNodes. Where(n => n.Object is WinCompData.CompositionPropertySet cps && cps.Owner is null). Select(n => (WinCompData.CompositionPropertySet)n.Object).FirstOrDefault(); } internal bool CanInstantiate => _wincompDataRootVisual is not null; public IAnimatedVisual? TryCreateAnimatedVisual(Compositor compositor, [MaybeNull] out object diagnostics) { // Clone the Diagnostics object so that the data from the translation is captured, then we // will update the clone with information about this particular instantiation. var diags = _diagnostics?.Clone(); diagnostics = diags; if (!CanInstantiate) { return null; } else { var sw = Stopwatch.StartNew(); var instantiator = new Instantiator(compositor, surfaceResolver: LoadImageFromUri); // _wincompDataRootVisual is not null is implied by CanInstantiate. var result = new DisposableAnimatedVisual((Visual)instantiator.GetInstance(_wincompDataRootVisual!)) { Size = new System.Numerics.Vector2((float)_width, (float)_height), Duration = _duration, }; if (diags is not null) { if (_wincompDataThemingPropertySet is not null && _themingPropertySet is null) { // Instantiate the theming property set. This is shared by all of the instantiations. _themingPropertySet = (CompositionPropertySet)instantiator.GetInstance(_wincompDataThemingPropertySet); // _diagnostics is not null is implied by diags is not null; diags.ThemingPropertySet = _diagnostics!.ThemingPropertySet = _themingPropertySet; } diags.InstantiationTime = sw.Elapsed; } // After the first instantiation, all the images are cached so the // loader is no longer needed. _loader?.Dispose(); _loader = null; return result; } } ICompositionSurface? LoadImageFromUri(Uri uri) { if (!_imageCache.TryGetValue(uri, out var result)) { // The loader will not be null, because either this is the // first instantiation of the animated visual in which case the // image loader hasn't been set to null, or it's a second instantiation // so the images are already cached. result = _loader!.LoadImage(uri); // Cache the result so we can share the surfaces. _imageCache.Add(uri, result); } return result; } } }
40.356589
132
0.607184
[ "MIT" ]
CommunityToolkit/Lottie-Windows
source/Lottie/AnimatedVisualFactory.cs
5,208
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestConsoleApp1 { class Program { static void Main(string[] args) { string hello = "asdf" } } }
16
39
0.625
[ "MIT" ]
StanleyGoldman/GitHubActionsMSBuildLogger
test-resources/simple-project-error/TestConsoleApp1/Program.cs
274
C#
using System; using System.Runtime.CompilerServices; using XamariNES.Cartridge.Mappers.Enums; using XamariNES.Common.Extensions; namespace XamariNES.Cartridge.Mappers.impl { /// <summary> /// NES Mapper 1 (MMC1) /// /// More Info: https://wiki.nesdev.com/w/index.php/MMC1 /// </summary> public class MMC1 : MapperBase, IMapper { /// <summary> /// PRG ROM /// /// 256kb Capacity /// </summary> private readonly byte[] _prgRom; /// <summary> /// Number of PRG ROM Banks on this Cartridge /// </summary> private readonly int _prgRomBanks; /// <summary> /// PRG RAM /// /// 32kb Capacity /// </summary> private readonly byte[] _prgRam = new byte[0x8000]; /// <summary> /// CHR ROM /// /// 128kb Capacity /// </summary> private readonly byte[] _chrRom; //Registers private int _registerShift; private int _registerShiftOffset; private int _registerControl; private int _chrBank0; private int _chrBank1; private int _prgBank; //Bank Switching Modes for CHR and PRG private int _currentPrgMode; private int _currentChrMode; //Current Offset of the banks in the total bank memory space private int _chrBank0Offset; private int _chrBank1Offset; private int _prgBank0Offset; private int _prgBank1Offset; //Toggles for RAM private readonly bool _useChrRam; private bool _usePrgRam; public enumNametableMirroring NametableMirroring { get; set; } public MMC1(int prgRomBanks, byte[] chrRom, byte[] prgRom, bool useChrRam, bool usePrgRam, enumNametableMirroring mirroring = enumNametableMirroring.Horizontal) { _prgRomBanks = prgRomBanks; _chrRom = chrRom; _prgRom = prgRom; NametableMirroring = mirroring; _useChrRam = useChrRam; _usePrgRam = usePrgRam; //Set Startup Values _registerShift = 0x0C; _prgBank1Offset = (_prgRomBanks - 1) * 0x4000; } /// <summary> /// Reads one byte from the specified bank, at the specified offset /// </summary> /// <param name="memoryType"></param> /// <param name="offset"></param> /// <returns></returns> public byte ReadByte(int offset) { // CHR Bank 0 == $0000-$0FFF // CHR Bank 1 == $1000-$1FFF if (offset <= 0x1FFF) { var chrBankOffset = offset / 0x1000 == 0 ? _chrBank0Offset : _chrBank1Offset; chrBankOffset += offset % 0x1000; return _chrRom[chrBankOffset]; } //PPU Registers if (offset <= 0x3FFF) return ReadInterceptors.TryGetValue(offset, out currentReadInterceptor) ? currentReadInterceptor(offset) : (byte) 0x0; // PRG RAM Bank == $6000-$7FFF if (offset >= 0x6000 && offset <= 0x7FFF) { if (!_usePrgRam) { //throw new AccessViolationException($"Attempt to read PRG RAM when disabled. Offset ${offset:X4}"); throw new Exception($"Attempt to read PRG RAM when disabled. Offset ${offset:X4}"); } return _prgRam[offset - 0x6000]; } // PRG Bank 0 == $8000-$BFFF // PRG Bank 1 == $C000-$FFFF if (offset >= 0x8000 && offset <= 0xFFFF) { //Map address $8000 to our _prgRom start of 0x0000; var prgBaseOffset = offset - 0x8000; var prgBankOffset = prgBaseOffset / 0x4000 == 0 ? _prgBank0Offset : _prgBank1Offset; prgBankOffset += prgBaseOffset % 0x4000; return _prgRom[prgBankOffset]; } throw new ArgumentOutOfRangeException(nameof(offset), offset, "Maximum value of offset is 0xFFFF"); } /// <summary> /// Writes one byte to the specified bank, at the specified offset /// </summary> /// <param name="memoryType"></param> /// <param name="offset"></param> /// <param name="data"></param> public void WriteByte(int offset, byte data) { // CHR Bank 0 == $0000-$0FFF // CHR Bank 1 == $1000-$1FFF if (offset <= 0x1FFF) { if (!_useChrRam) { //throw new AccessViolationException($"Invalid write to CHR ROM (CHR RAM not enabled). Offset: {offset:X4}"); throw new Exception($"Invalid write to CHR ROM (CHR RAM not enabled). Offset: {offset:X4}"); } var chrOffset = (offset / 0x1000) == 0 ? _chrBank0Offset : _chrBank1Offset; chrOffset += offset % 0x1000; _chrRom[chrOffset] = data; return; } //PPU Registers if (offset <= 0x3FFF || offset == 0x4014) { if (WriteInterceptors.TryGetValue(offset, out currentWriteInterceptor)) currentWriteInterceptor(offset, data); return; } // PRG RAM Bank == $6000-$7FFF if (offset >= 0x6000 && offset <= 0x7FFF) { if (!_usePrgRam) { //throw new AccessViolationException($"Attempt to write PRG RAM when disabled. Offset ${offset:X4}"); throw new Exception($"Attempt to write PRG RAM when disabled. Offset ${offset:X4}"); } _prgRam[offset - 0x6000] = data; return; } //Writes to this range are handled by the Load Register if (offset >= 0x8000 && offset <= 0xFFFF) { WriteLoadRegister(offset, data); return; } //Sanity Check if we reach this point throw new ArgumentOutOfRangeException(nameof(offset), "Maximum value of offset is 0xFFFF"); } /// <summary> /// Load Register is mapped to $8000->$FFFF in the Mapper Memory Space /// /// From there, the Load Register processes the write one bit at a time shifting left, until 5 writes /// at which point we write to the internal register mapped to the given address of the final write. /// </summary> /// <param name="offset"></param> /// <param name="data"></param> private void WriteLoadRegister(int offset, byte data) { if (data.IsBitSet(7)) { //Write Control with (Control OR $0C), //locking PRG ROM at $C000-$FFFF to the last bank. _registerShift = _registerControl | 0x0C; WriteInternalRegister(0x0); //Reset Shift Register _registerShiftOffset = 0; _registerShift = 0; return; } _registerShift |= (data & 1) << _registerShiftOffset; _registerShiftOffset++; //5th write gets written to the internal registers if (_registerShiftOffset == 5) { _registerShiftOffset = 0; WriteInternalRegister(offset); _registerShift = 0; } } /// <summary> /// Determines, based on the offset of the write, which internal register /// will be written to: /// /// Internal Registers: /// $8000->$9FFF == Control Register /// $A000->$BFFF == CHR0 Register /// $C000->$DFFF == CHR1 Register /// $E000->$FFFF == PRG Register /// </summary> /// <param name="offset"></param> private void WriteInternalRegister(int offset) { if (offset <= 0x9FFF) { _registerControl = _registerShift; _currentPrgMode = (_registerShift >> 2) & 0x03; _currentChrMode = (_registerShift >> 4) & 0x01; switch (_registerControl & 0x03) { case 0: NametableMirroring = enumNametableMirroring.SingleLower; break; case 1: NametableMirroring = enumNametableMirroring.SingleUpper; break; case 2: NametableMirroring = enumNametableMirroring.Vertical; break; case 3: NametableMirroring = enumNametableMirroring.Horizontal; break; } } else if (offset <= 0xBFFF) { _chrBank0 = _registerShift; } else if (offset <= 0xDFFF) { _chrBank1 = _registerShift; } else { _prgBank = _registerShift; _usePrgRam = _registerShift >> 4 == 0; } //Based off this write, update the offsets of the PRG and CHR Banks UpdateBankOffsets(); } /// <summary> /// Updates the offsets for CHR0, CHR1, and PRG based off updates to /// the control registers, or any of the other registers. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private void UpdateBankOffsets() { switch (_currentChrMode) { case 0: //8K (4K+4K contiguous) _chrBank0Offset = ((_chrBank0 & 0x1E) >> 1) * 0x1000; _chrBank1Offset = _chrBank0Offset + 0x1000; break; case 1: //4K Switched + 4K Switched _chrBank0Offset = _chrBank0 * 0x1000; _chrBank1Offset = _chrBank1 * 0x1000; break; default: throw new ArgumentException("Invalid CHR Mode Specified"); } switch (_currentPrgMode) { case 0: case 1: //32KB (16KB+16KB contiguous) Switched _prgBank0Offset = ((_prgBank & 0xE) >> 1) * 0x4000; _prgBank1Offset = _prgBank0Offset + 0x4000; break; case 2: //16KB Fixed (First) + 16KB Switched //Fixed first bank at $8000 _prgBank0Offset = 0; //Switched 16KB bank at $C000 _prgBank1Offset = (_prgBank & 0xF) * 0x4000; break; case 3: //16KB Switched + 16KB Fixed (Last) //Switched 16 KB bank at $8000 _prgBank0Offset = (_prgBank & 0xF) * 0x4000; //Fixed last bank at $C000 _prgBank1Offset = (_prgRomBanks - 1) * 0x4000; break; default: throw new ArgumentException("Invalid PRG Mode Specified"); } } } }
36.100313
134
0.500087
[ "MIT" ]
mediaexplorer74/XamariNES
XamariNES.Cartridge/Mappers/impl/MMC1.cs
11,518
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Moq; using Web.Extensions; using Xunit; namespace Test.Web.UnitTests { [Trait("Category", "Unit")] public class Logger { private readonly ServiceProvider _provider; public Logger() { var services = new ServiceCollection(); var mockEnv = new Mock<IHostingEnvironment>(); mockEnv .SetupGet(environment => environment.EnvironmentName) .Returns("Testing"); var mockConfig = new Mock<IConfiguration>(); services.RegisterSharedServices(mockEnv.Object, mockConfig.Object); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Trace)); _provider = services.BuildServiceProvider(); Console.SetOut(TextWriter.Null); } public static IEnumerable<object[]> LogLevels => Enum .GetValues(typeof(LogLevel)) .Cast<LogLevel>() .Where(l => l != LogLevel.None) .Select(v => new object[] { v }); [Theory] [MemberData(nameof(LogLevels))] public void LoggerNoExceptions(LogLevel level) { _provider .GetService<ILoggerFactory>() .AddExtendedLogger( LogLevel.Trace, new string[] { } ); var logger = _provider.GetRequiredService<ILogger<Logger>>(); logger.Log(level, "Hello"); } [Fact] public void Exceptions() { _provider .GetService<ILoggerFactory>() .AddExtendedLogger( LogLevel.Trace, new string[] { } ); var logger = _provider.GetRequiredService<ILogger<Logger>>(); logger.LogError(0, new Exception(), "Error"); } [Fact] public void Exclusions() { _provider .GetService<ILoggerFactory>() .AddExtendedLogger( LogLevel.Trace, new string[] { "Logger" } ); var logger = _provider.GetRequiredService<ILogger<Logger>>(); logger.LogInformation("Hello"); } } }
20.791667
70
0.687375
[ "MIT" ]
dbogatov/ore-benchmark
test/Web/UnitTests/LoggerTests.cs
1,996
C#
using System.Collections.Generic; using Recruit.Vacancies.Client.Domain.Entities; namespace Esfa.Recruit.Vacancies.Client.Infrastructure.QueryStore.Projections.BlockedOrganisations { public class BlockedProviderOrganisations : QueryProjectionBase { public BlockedProviderOrganisations() : base(QueryViewType.BlockedProviderOrganisations.TypeName) {} public IEnumerable<BlockedOrganisationSummary> Data { get; set; } } }
35.153846
105
0.78337
[ "MIT" ]
SkillsFundingAgency/das-recru
src/Shared/Recruit.Vacancies.Client/Infrastructure/QueryStore/Projections/BlockedOrganisations/BlockedProviderOrganisations.cs
457
C#
namespace DIAssignment.ESEntryPoint { class Program { static void Main() { ESEntryPointService.Start().WaitForExit(); } } }
15.727273
54
0.543353
[ "MIT" ]
Davidblkx/DIAssignment
DIAssignment.ESEntryPoint/Program.cs
175
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif public class ParticleSceneControls : MonoBehaviour { public DemoParticleSystemList demoParticles; public float distFromSurface = 0.5f; public float multiply = 1; public bool clearOnChange = false; public GUIText titleGuiText; public Transform demoCam; public GUIText interactionGuiText; ParticleSystemMultiplier particleMultiplier; List<Transform> currentParticleList = new List<Transform>(); Transform instance; static int selectedIndex = 0; Vector3 camOffsetVelocity = Vector3.zero; Vector3 lastPos; public enum Mode { Activate, Instantiate, Trail } public enum AlignMode { Normal, Up } static DemoParticleSystem selected; void Awake() { Select(selectedIndex); } void Update() { demoCam.localPosition = Vector3.SmoothDamp (demoCam.localPosition, Vector3.forward * -selected.camOffset, ref camOffsetVelocity, 1); if (CrossPlatformInput.GetButtonDown("NextParticleSystem")) { selectedIndex++; if (selectedIndex == demoParticles.items.Length) selectedIndex = 0; Select (selectedIndex); return; } if (CrossPlatformInput.GetButtonDown("PreviousParticleSystem")) { selectedIndex--; if (selectedIndex == -1) selectedIndex = demoParticles.items.Length-1; Select (selectedIndex); return; } if (selected.mode == Mode.Activate) { // this is for a particle system that just needs activating, and needs no interaction (eg, duststorm) return; } bool oneShotClick = (Input.GetMouseButtonDown(0) && selected.mode == Mode.Instantiate); bool repeat = (Input.GetMouseButton(0) && selected.mode == Mode.Trail); if (oneShotClick || repeat) { Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition ); RaycastHit hit; if (Physics.Raycast(ray,out hit)) { var rot = Quaternion.LookRotation(hit.normal); if (selected.align == AlignMode.Up) rot = Quaternion.identity; var pos = hit.point + hit.normal * distFromSurface; if ((pos-lastPos).magnitude > selected.minDist) { if (selected.mode != Mode.Trail || instance == null) { instance = (Transform)Instantiate( selected.transform, pos, rot ); if (particleMultiplier != null) { instance.GetComponent<ParticleSystemMultiplier>().multiplier = multiply; } currentParticleList.Add (instance); if (selected.maxCount > 0 && currentParticleList.Count > selected.maxCount) { if (currentParticleList[0] != null) { Destroy (currentParticleList[0].gameObject); } currentParticleList.RemoveAt(0); } } else { instance.position = pos; instance.rotation = rot; } if (selected.mode == Mode.Trail) { instance.transform.GetComponent<ParticleSystem>().enableEmission = false; instance.transform.GetComponent<ParticleSystem>().Emit(1); } instance.parent = hit.transform; lastPos = pos; } } } } void Select(int i) { selected = demoParticles.items[i]; instance = null; foreach (var otherEffect in demoParticles.items) { if ((otherEffect != selected) && (otherEffect.mode == Mode.Activate)) { if (otherEffect != null) { otherEffect.transform.gameObject.SetActive(false); } } } if (selected.mode == Mode.Activate) { selected.transform.gameObject.SetActive(true); } particleMultiplier = selected.transform.GetComponent<ParticleSystemMultiplier>(); multiply = 1; if (clearOnChange) { while(currentParticleList.Count > 0) { Destroy (currentParticleList[0].gameObject); currentParticleList.RemoveAt(0); } } interactionGuiText.text = selected.instructionText; titleGuiText.text = selected.transform.name; } [System.Serializable] public class DemoParticleSystem { public Transform transform; public Mode mode; public AlignMode align; public int maxCount; public float minDist; public int camOffset = 15; public string instructionText; } [System.Serializable] public class DemoParticleSystemList { public DemoParticleSystem[] items; } } /* #if UNITY_EDITOR [CustomPropertyDrawer (typeof(ParticleSceneControls.DemoParticleSystemList))] public class DemoParticleSystemListDrawer : PropertyDrawer { float lineHeight = 18; float spacing = 4; public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty (position, label, property); float x = position.x; float y = position.y; float inspectorWidth = position.width; // Don't make child fields be indented var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var items = property.FindPropertyRelative ("items"); float lineHeight = 18; bool changedLength = false; if (items.arraySize > 0) { for (int i=-1; i<items.arraySize; ++i) { var item = items.GetArrayElementAtIndex (i); string[] titles = new string[] { "Effect", "Mode", "Align To", "Max Count", "Min Dist", "Offset" }; string[] props = new string[] { "transform", "mode", "align", "maxCount", "minDist", "camOffset"}; float[] widths = new float[] { .35f, .2f, .15f, .1f, .1f, .1f }; float rowX = x; for (int n=0; n<props.Length; ++n) { float w = widths[n] * inspectorWidth; // Calculate rects Rect rect = new Rect (rowX, y, w, lineHeight); rowX += w; if (i == -1) { // draw title labels EditorGUI.LabelField(rect, titles[n]); } else { if (props[n]=="-" || props[n]=="^" || props[n]=="v") { if (GUI.Button (rect, props[n])) { switch (props[n]) { case "-": items.DeleteArrayElementAtIndex(i); items.DeleteArrayElementAtIndex(i); changedLength = true; break; case "v": if (i > 0) items.MoveArrayElement(i,i+1); break; case "^": if (i < items.arraySize-1) items.MoveArrayElement(i,i-1); break; } } } else { SerializedProperty prop = item.FindPropertyRelative(props[n]); EditorGUI.PropertyField(rect, prop, GUIContent.none); } } } y += lineHeight + spacing; titles = new string[] { "Instructions Text", "", "", "" }; props = new string[] { "instructionText", "^", "v", "-" }; widths = new float[] { .85f, .05f, .05f, .05f }; rowX = x; for (int n=0; n<props.Length; ++n) { float w = widths[n] * inspectorWidth; // Calculate rects Rect rect = new Rect (rowX, y, w, lineHeight); rowX += w; if (i == -1) { // draw title labels EditorGUI.LabelField(rect, titles[n]); } else { if (props[n]=="-" || props[n]=="^" || props[n]=="v") { if (GUI.Button (rect, props[n])) { switch (props[n]) { case "-": items.DeleteArrayElementAtIndex(i); items.DeleteArrayElementAtIndex(i); changedLength = true; break; case "v": if (i > 0) items.MoveArrayElement(i,i+1); break; case "^": if (i < items.arraySize-1) items.MoveArrayElement(i,i-1); break; } } } else { SerializedProperty prop = item.FindPropertyRelative(props[n]); EditorGUI.PropertyField(rect, prop, GUIContent.none); } } } y += lineHeight + spacing + 5; if (changedLength) { break; } } } // add button var addButtonRect = new Rect ((x + position.width) - .05f*inspectorWidth, y, .05f*inspectorWidth, lineHeight); if (GUI.Button (addButtonRect, "+")) { items.InsertArrayElementAtIndex(items.arraySize); } y += lineHeight + spacing; // Set indent back to what it was EditorGUI.indentLevel = indent; EditorGUI.EndProperty (); } public override float GetPropertyHeight (SerializedProperty property, GUIContent label) { SerializedProperty items = property.FindPropertyRelative ("items"); float lineAndSpace = lineHeight + spacing; return 40 + (items.arraySize * ((lineAndSpace * 2) + 5)) + lineAndSpace + 5; } } #endif */
22.956164
134
0.626328
[ "BSD-3-Clause" ]
GuillaumeArruda/LOG4715
Cadriciel_TP1_2015_v2/Assets/Sample Assets/Sample Scenes/Scripts/ParticleSceneControls.cs
8,381
C#
using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Libsodium { internal const int crypto_sign_ed25519_BYTES = 64; internal const int crypto_sign_ed25519_PUBLICKEYBYTES = 32; internal const int crypto_sign_ed25519_SECRETKEYBYTES = (32 + 32); internal const int crypto_sign_ed25519_SEEDBYTES = 32; [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static extern UIntPtr crypto_sign_ed25519_bytes(); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static unsafe extern int crypto_sign_ed25519_detached( byte* sig, out ulong siglen_p, byte* m, ulong mlen, byte* sk); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static extern UIntPtr crypto_sign_ed25519_publickeybytes(); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static extern UIntPtr crypto_sign_ed25519_secretkeybytes(); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static unsafe extern int crypto_sign_ed25519_seed_keypair( PublicKeyBytes* pk, byte* sk, byte* seed); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static extern UIntPtr crypto_sign_ed25519_seedbytes(); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static unsafe extern int crypto_sign_ed25519_sk_to_seed( byte* seed, byte* sk); [DllImport(Libraries.Libsodium, CallingConvention = CallingConvention.Cdecl)] internal static unsafe extern int crypto_sign_ed25519_verify_detached( byte* sig, byte* m, ulong mlen, PublicKeyBytes* pk); } }
39.557692
85
0.695673
[ "MIT" ]
Bobface/DotNetLightning
src/NSec/Interop/Interop.Ed25519.cs
2,057
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Custom/PlayerData")] public class SO_PlayerData : ScriptableObject { const int itemQuantity = 13; public int level; public bool[] collectedItems = new bool[itemQuantity]; }
26.090909
56
0.783972
[ "MIT" ]
TanookiVerde/Muquirana
Assets/code/muquirana/SO_PlayerData.cs
289
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:WeixinUserInfoResult.cs 文件功能描述:获取用户信息返回结果 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20180305 修改描述: ----------------------------------------------------------------*/ using Senparc.CO2NET.Helpers; using Senparc.Weixin.Entities; using Senparc.Weixin.Helpers; using System; namespace Senparc.Weixin.MP.Entities { /// <summary> /// 用户信息 /// </summary> public class WeixinUserInfoResult : WxJsonResult { /// <summary> /// 用户是否订阅该公众号标识,值为0时,拉取不到其余信息 /// </summary> public int subscribe { get; set; } /// <summary> /// 普通用户的标识,对当前公众号唯一 /// </summary> public string openid { get; set; } /// <summary> /// 用户的昵称 /// </summary> public string nickname { get; set; } /// <summary> /// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 /// </summary> public int sex { get; set; } /// <summary> /// 用户所在城市 /// </summary> public string city { get; set; } /// <summary> /// 用户所在国家 /// </summary> public string country { get; set; } /// <summary> /// 用户所在省份 /// </summary> public string province { get; set; } /// <summary> /// 用户的语言,zh-CN 简体,zh-TW 繁体,en 英语,默认为zh-CN /// </summary> public string language { get; set; } /// <summary> /// <para>用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。</para> /// <para>示例:http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0 </para> /// </summary> public string headimgurl { get; set; } /// <summary> /// 获取指定大小的用户头像网址 /// </summary> /// <param name="size">代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像)</param> /// <returns></returns> public string GetHeadImageUrl(int size = 0) { var url = headimgurl; if (url == null) return null; var tail = "/" + size.ToString("d"); if (url.EndsWith(tail)) return url; var slashIndex = url.LastIndexOf('/'); if (slashIndex < 0) return url; return url.Substring(0, slashIndex) + tail; } /// <summary> /// 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间 /// </summary> public long subscribe_time { get; set; } public DateTime GetSubscribeTime() { return DateTimeHelper.GetDateTimeFromXml(subscribe_time); } /// <summary> /// 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段 /// </summary> public string unionid { get; set; } /// <summary> /// 公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注 /// </summary> public string remark { get; set; } /// <summary> /// 用户所在的分组ID /// </summary> public int groupid { get; set; } /// <summary> /// 用户被打上的标签ID列表 /// </summary> public int[] tagid_list { get; set; } } }
30.251799
160
0.539358
[ "Apache-2.0" ]
29366365/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/Entities/JsonResult/WeixinUserInfoResult.cs
4,987
C#
/// System.Extensions License /// /// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org /// /// This software is provided 'as-is', without any express or implied warranty. /// In no event will the authors be held liable for any damages arising from /// the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// including commercial applications, and to alter it and redistribute it /// freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; /// you must not claim that you wrote the original software. /// If you use this software in a product, an acknowledgment in the product /// documentation would be appreciated but is not required. /// /// 2. Altered source versions must be plainly marked as such, /// and must not be misrepresented as being the original software. /// ///3. This notice may not be removed or altered from any source distribution. using System; using System.CodeDom; namespace System.Extensions.CodeDom { using System.Extensions.CodeDom.Collections; /// <summary> /// Summary description for ImplementationMemberDeclaration. /// </summary> public abstract class ImplementationMemberDeclaration : MemberDeclaration { private ITypeDeclaration privateImplementationType = null; private TypeDeclarationCollection implementationTypes = new TypeDeclarationCollection(); internal ImplementationMemberDeclaration(string name, Declaration declaringType) :base(name,declaringType) {} public ITypeDeclaration PrivateImplementationType { get { return this.privateImplementationType; } set { this.privateImplementationType = value; } } public TypeDeclarationCollection ImplementationTypes { get { return this.implementationTypes; } } protected void SetImplementationTypes(CodeMemberMethod member) { if (this.privateImplementationType!=null) member.PrivateImplementationType = this.privateImplementationType.TypeReference; foreach(ITypeDeclaration td in this.implementationTypes) { member.ImplementationTypes.Add(td.TypeReference); } } protected void SetImplementationTypes(CodeMemberProperty member) { if (this.privateImplementationType!=null) member.PrivateImplementationType = this.privateImplementationType.TypeReference; foreach(ITypeDeclaration td in this.implementationTypes) { member.ImplementationTypes.Add(td.TypeReference); } } } }
29.045977
90
0.754254
[ "MIT" ]
Plankankul/Framework-w-WebApp
Framework/CodeDOM/ImplementationMemberDeclaration.cs
2,527
C#
using System; class Program { static void Main() { string hexademical = Console.ReadLine(); Console.WriteLine("{0}", Convert.ToInt32(hexademical, 16)); } }
18.5
67
0.610811
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
01.Short Fundamentals/11.DATA TYPES AND VARIABLES - EXERCISES/04. Variable in Hex Format/Program.cs
187
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; namespace Microsoft.Build.BackEnd.Logging { /// <summary> /// Intended to be used in the nodes, during a build, where a base LoggingContext is created when the node /// initializes for a build (this is the public constructor.) When a new project, target batch /// or task batch is started, the appropriate method on the current LoggingContext is invoked /// and a new LoggingContext is returned. This new LoggingContext should be used for all /// subsequent logging within the subcontext. /// </summary> internal class BuildLoggingContext : LoggingContext { /// <summary> /// True if this context comes from the in-proc node. /// </summary> private bool _isInProcNode; /// <summary> /// Constructs the logging context from a logging service and an event context. /// </summary> /// <param name="loggingService">The logging service to use</param> /// <param name="buildEventContext">The event context</param> /// <param name="inProc">Flag indicating if this context belongs to an in-proc node.</param> protected BuildLoggingContext(ILoggingService loggingService, BuildEventContext buildEventContext, bool inProc) : base(loggingService, buildEventContext) { _isInProcNode = inProc; } /// <inheritdoc cref="LoggingContext"/> protected BuildLoggingContext(BuildLoggingContext baseContext) : base(baseContext) { _isInProcNode = baseContext._isInProcNode; } /// <summary> /// Flag indicating if the context is being used for the in-proc node. /// </summary> public bool IsInProcNode { [DebuggerStepThrough] get { return _isInProcNode; } } /// <summary> /// Log an error based on an exception during the execution of a task /// </summary> /// <param name="exception">The exception wich is to be logged</param> /// <param name="file">The file in which the error occurred</param> /// <param name="taskName">The task in which the error occurred</param> internal void LogFatalTaskError(Exception exception, BuildEventFileInfo file, string taskName) { ErrorUtilities.VerifyThrow(IsValid, "must be valid"); LoggingService.LogFatalTaskError(BuildEventContext, exception, file, taskName); } } }
41.042254
161
0.66987
[ "MIT" ]
AaronRobinsonMSFT/msbuild
src/Build/BackEnd/Components/Logging/BuildLoggingContext.cs
2,916
C#