content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Quasar.Common.Models; using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace Quasar.Common.IO { public class FileSplit : IEnumerable<FileChunk>, IDisposable { /// <summary> /// The maximum size per file chunk. /// </summary> public readonly int MaxChunkSize = 65535; /// <summary> /// The file path of the opened file. /// </summary> public string FilePath => _fileStream.Name; /// <summary> /// The file size of the opened file. /// </summary> public long FileSize => _fileStream.Length; /// <summary> /// The file stream of the opened file. /// </summary> private readonly FileStream _fileStream; /// <summary> /// Initializes a new instance of the <see cref="FileSplit"/> class using the given file path and access mode. /// </summary> /// <param name="filePath">The path to the file to open.</param> /// <param name="fileAccess">The file access mode for opening the file. Allowed are <see cref="FileAccess.Read"/> and <see cref="FileAccess.Write"/>.</param> public FileSplit(string filePath, FileAccess fileAccess) { switch (fileAccess) { case FileAccess.Read: _fileStream = File.OpenRead(filePath); break; case FileAccess.Write: _fileStream = File.OpenWrite(filePath); break; default: throw new ArgumentException($"{nameof(fileAccess)} must be either Read or Write."); } } /// <summary> /// Writes a chunk to the file. In other words. /// </summary> /// <param name="chunk"></param> public void WriteChunk(FileChunk chunk) { _fileStream.Seek(chunk.Offset, SeekOrigin.Begin); _fileStream.Write(chunk.Data, 0, chunk.Data.Length); } /// <summary> /// Reads a chunk of the file. /// </summary> /// <param name="offset">Offset of the file, must be a multiple of <see cref="MaxChunkSize"/> for proper reconstruction.</param> /// <returns>The read file chunk at the given offset.</returns> /// <remarks> /// The returned file chunk can be smaller than <see cref="MaxChunkSize"/> iff the /// remaining file size from the offset is smaller than <see cref="MaxChunkSize"/>, /// then the remaining file size is used. /// </remarks> public FileChunk ReadChunk(long offset) { _fileStream.Seek(offset, SeekOrigin.Begin); long chunkSize = _fileStream.Length - _fileStream.Position < MaxChunkSize ? _fileStream.Length - _fileStream.Position : MaxChunkSize; var chunkData = new byte[chunkSize]; _fileStream.Read(chunkData, 0, chunkData.Length); return new FileChunk { Data = chunkData, Offset = _fileStream.Position - chunkData.Length }; } /// <summary> /// Returns an enumerator that iterates through the file chunks. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the file chunks.</returns> public IEnumerator<FileChunk> GetEnumerator() { for (long currentChunk = 0; currentChunk <= _fileStream.Length / MaxChunkSize; currentChunk++) { yield return ReadChunk(currentChunk * MaxChunkSize); } } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } protected virtual void Dispose(bool disposing) { if (disposing) { _fileStream.Dispose(); } } /// <summary> /// Disposes all managed and unmanaged resources associated with this class. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
34.248
165
0.555478
[ "Apache-2.0", "MIT" ]
2-young-2-simple/QuasarRAT
Quasar.Common/IO/FileSplit.cs
4,283
C#
namespace Katalye.Components.Configuration.ValueParsers { public interface IValueParser { object Parse(string value); } // ReSharper disable once UnusedTypeParameter public interface IValueParser<out T> : IValueParser { } }
21.75
56
0.697318
[ "MIT" ]
Katalye/Katalye
src/Katalye.Components/Configuration/ValueParsers/IValueParser.cs
263
C#
using System.Collections.Generic; using System.Threading.Tasks; using Pulumi; using Pulumi.Azure.AppService; using Pulumi.Azure.AppService.Inputs; using Pulumi.Azure.Core; using Pulumi.Azure.Dns; using Pulumi.Azure.Dns.Inputs; internal class Program { private const string DnsId = "/subscriptions/6bd72948-e492-4ae3-8bee-dd49284a07ac/resourceGroups/emoos/providers/Microsoft.Network/dnszones/emoos.solutions"; private static Task<int> Main() { return Deployment.RunAsync(Run); } private static IDictionary<string, object> Run() { var resourceGroup = new ResourceGroup("emoos-dev", new ResourceGroupArgs {Location = "WestEurope"}); Output<string> resourceGroupName = resourceGroup.Name; var planSkuArgs = new PlanSkuArgs {Tier = "Basic", Size = "B1"}; var plan = new Plan("DevAppServicePlan", new PlanArgs {ResourceGroupName = resourceGroupName, Kind = "Linux", Sku = planSkuArgs, Reserved = true}); var appSettings = new InputMap<string> {{"WEBSITES_ENABLE_APP_SERVICE_STORAGE", "false"}}; var image = "sqeezy/emoos.solutions:latest"; var siteConfig = new AppServiceSiteConfigArgs {AlwaysOn = false, LinuxFxVersion = $"DOCKER|{image}"}; var appService = new AppService("DevAppService", new AppServiceArgs { ResourceGroupName = resourceGroupName, AppServicePlanId = plan.Id, AppSettings = appSettings, HttpsOnly = false, SiteConfig = siteConfig }); var emoosDns = new Zone("emoos.solutions", new ZoneArgs {ResourceGroupName = "emoos", Name = "emoos.solutions"}, new CustomResourceOptions {ImportId = DnsId, Protect = true}); var txtRecord = new TxtRecord("@", new TxtRecordArgs { Name = "@", ResourceGroupName = emoosDns.ResourceGroupName, Ttl = 60, ZoneName = emoosDns.Name, Records = new InputList<TxtRecordRecordsArgs> { new TxtRecordRecordsArgs {Value = appService.DefaultSiteHostname} } }); var cname = new CNameRecord("dev", new CNameRecordArgs { Name = "dev", ResourceGroupName = emoosDns.ResourceGroupName, Ttl = 60, ZoneName = emoosDns.Name, Record = appService.DefaultSiteHostname }); var hostNameBinding = new CustomHostnameBinding("dev.emoos.solutions", new CustomHostnameBindingArgs { AppServiceName = appService.Name, Hostname = "dev.emoos.solutions", ResourceGroupName = resourceGroupName // SslState = "SniEnabled", // Thumbprint = "19A0220DE45552EE931E0959B10F6DDDAD5F946B" }); return new Dictionary<string, object?> { {"default route", appService.DefaultSiteHostname}, {"resource group", resourceGroup.Name} // {"domain binding", hostNameBinding.Hostname} }; } }
50.574713
136
0.438636
[ "MIT" ]
e-moos/emoos.solutions
infra/Program.cs
4,402
C#
using Assets.Kanau.UnityScene; namespace Assets.Kanau.ThreeScene.Lights { public class AmbientLightElem : LightElem { public override string Type { get { return "AmbientLight"; } } public override void Accept(IVisitor v) { v.Visit(this); } public AmbientLightElem(ProjectSettings settings) : base() { this.UnityColor = settings.AmbientColor; this.Name = "AmbientLight"; } } }
29.8
70
0.646532
[ "MIT" ]
5minlab/UnitySceneWebExporter
UnityProject/Assets/Kanau/Editor/ThreeScene/Lights/AmbientLightElem.cs
449
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Query.Core.Parser { using System; internal sealed class ParseException : Exception { public ParseException(string message = null, Exception innerException = null) : base(message, innerException) { } } }
28.294118
85
0.484407
[ "MIT" ]
Arithmomaniac/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Query/Core/Parser/ParseException.cs
483
C#
using UnityEngine; using System.Collections; public class SerializeMyClass : OFPlugin { override public System.Type[] types { get { return new System.Type [] { typeof ( MyClass ) }; } } // Deserialize the class from JSON override public void Deserialize ( JSONObject input, Component output ) { MyClass myClass = output as MyClass; myClass.myInt = (int) input.GetField ( "myInt" ).n; myClass.myFloat = input.GetField ( "myFloat" ).n; myClass.myBool = input.GetField ( "myBool" ).b; myClass.myString = input.GetField ( "myString" ).str; // Assign the myObject variable only after all objects have been instantiated OFDeserializer.planner.DeferConnection ( ( OFSerializedObject so ) => { myClass.myObject = so.gameObject; }, input.GetField ( "myObject" ).str ); } // Serialize the class to JSON override public JSONObject Serialize ( Component input ) { JSONObject output = new JSONObject ( JSONObject.Type.OBJECT ); MyClass myClass = input as MyClass; output.AddField ( "myInt", myClass.myInt ); output.AddField ( "myFloat", myClass.myFloat ); output.AddField ( "myBool", myClass.myBool ); output.AddField ( "myObject", myClass.myObject.GetComponent < OFSerializedObject > ().id ); output.AddField ( "myString", myClass.myString ); return output; } }
34.421053
93
0.70948
[ "MIT" ]
mrzapp/opened
OpenEd/Assets/Example/Scripts/SerializeMyClass.cs
1,310
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Igtampe.Neco.Common; using Igtampe.Neco.Common.Requests; using Igtampe.Neco.Data; namespace Igtampe.Neco.Backend.Controllers { [Route("Auth")] [ApiController] public class AuthController: Controller { private readonly NecoContext _context; public AuthController(NecoContext context) { _context = context; } // POST: Auth [HttpPost] public async Task<IActionResult> Check(UserAuth U) { if (string.IsNullOrEmpty(U.ID)) { return BadRequest("Blank User Auth object"); } //Find a user: UserAuth DBU = await _context.UserAuth.FindAsync(U.ID); if (DBU == null) { return Ok(Guid.Empty); } if (DBU.Equals(U)) { //Log in return Ok(SessionManager.Manager.LogIn(U.ID)); } //Otherwise return an empty guid return Ok(Guid.Empty); } //POST: Auth/Out [HttpPost("Out")] public async Task<IActionResult> LogOut(Guid SessionID) { bool LogoutSuccess = await Task.Run(() => SessionManager.Manager.LogOut(SessionID)); return Ok(LogoutSuccess); } //POST: Auth/Out [HttpPost("OutAll")] public async Task<IActionResult> LogOutAll(Guid SessionID) { Session S = SessionManager.Manager.FindSession(SessionID); if (S == null) { return Unauthorized("Invalid session"); } int LogoutCount = await Task.Run(()=> SessionManager.Manager.LogOutAll(S.UserID)); return Ok(LogoutCount); } // PUT: Auth [HttpPut] public async Task<IActionResult> Update(PasswordChangeRequest PCR) { if (PCR.SessionID == System.Guid.Empty) { return BadRequest("Blank Session ID"); } //Find Session Session S = SessionManager.Manager.FindSession(PCR.SessionID); if (S == null) { return BadRequest("Session ID not found"); } //Find a user: UserAuth DBU = await _context.UserAuth.FindAsync(S.UserID); if (!DBU.CheckPin(PCR.CurrentPassword)) { return BadRequest("Password did not match"); } //OK go for change DBU.Pin = PCR.NewPassword; _context.Update(DBU); await _context.SaveChangesAsync(); return Ok(true); } } }
31.948052
100
0.592683
[ "CC0-1.0" ]
igtampe/Neco
Neco.Backend/Controllers/AuthController.cs
2,462
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("02.PrintMyName")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.PrintMyName")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d228ddcc-7e15-4e02-a064-c522c9474450")] // 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.864865
84
0.744468
[ "MIT" ]
mdraganov/Telerik-Academy
C#/C# Programming Part I/IntroToProgramming/02.PrintMyName/Properties/AssemblyInfo.cs
1,404
C#
using UnityEngine; public class GUIHandler : MonoBehaviour { [HideInInspector] public InventoryOld inventory; void OnGUI() { } }
10.588235
39
0.561111
[ "MIT" ]
WoolMagician/8-Cores
Assets/8-Cores Assets/Classes/GUI/GUIHandler.cs
180
C#
using System.Net.Http; using System.Threading.Tasks; namespace Moments.AWSBackend.Services { public interface IAwsClient { Task<HttpResponseMessage> SendMessage(HttpRequestMessage request); } }
22.4
75
0.71875
[ "MIT" ]
AvantiPoint/Moments
src/Moments.AWSBackend/Services/IAwsClient.cs
226
C#
//---------------------------------------------------------------------------- // <auto-generated> // This is autogenerated code by CppSharp. // Do not edit this file or all your changes will be lost after re-generation. // </auto-generated> //---------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Security; namespace LLDB { public unsafe partial class TypeSynthetic : IDisposable { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct Internal { [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSynthetic@lldb@@QAE@XZ")] internal static extern global::System.IntPtr ctor_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSynthetic@lldb@@QAE@ABV01@@Z")] internal static extern global::System.IntPtr cctor_1(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??1SBTypeSynthetic@lldb@@QAE@XZ")] internal static extern void dtor_0(global::System.IntPtr instance, int delete); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithClassName@SBTypeSynthetic@lldb@@SA?AV12@PBDI@Z")] internal static extern void CreateWithClassName_0(global::System.IntPtr @return, global::System.IntPtr data, uint options); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithScriptCode@SBTypeSynthetic@lldb@@SA?AV12@PBDI@Z")] internal static extern void CreateWithScriptCode_0(global::System.IntPtr @return, global::System.IntPtr data, uint options); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsValid@SBTypeSynthetic@lldb@@QBE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsValid_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsClassCode@SBTypeSynthetic@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsClassCode_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsClassName@SBTypeSynthetic@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsClassName_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetDescription@SBTypeSynthetic@lldb@@QAE_NAAVSBStream@2@W4DescriptionLevel@2@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool GetDescription_0(global::System.IntPtr instance, global::System.IntPtr description, LLDB.DescriptionLevel description_level); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsEqualTo@SBTypeSynthetic@lldb@@QAE_NAAV12@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsEqualTo_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??8SBTypeSynthetic@lldb@@QAE_NAAV01@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool OperatorEqualEqual_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??9SBTypeSynthetic@lldb@@QAE_NAAV01@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool OperatorExclaimEqual_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?CopyOnWrite_Impl@SBTypeSynthetic@lldb@@IAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool CopyOnWrite_Impl_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetData@SBTypeSynthetic@lldb@@QAEPBDXZ")] internal static extern global::System.IntPtr GetData_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetClassName@SBTypeSynthetic@lldb@@QAEXPBD@Z")] internal static extern void SetClassName_0(global::System.IntPtr instance, global::System.IntPtr data); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetClassCode@SBTypeSynthetic@lldb@@QAEXPBD@Z")] internal static extern void SetClassCode_0(global::System.IntPtr instance, global::System.IntPtr data); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetOptions@SBTypeSynthetic@lldb@@QAEIXZ")] internal static extern uint GetOptions_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetOptions@SBTypeSynthetic@lldb@@QAEXI@Z")] internal static extern void SetOptions_0(global::System.IntPtr instance, uint _0); } public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; public static readonly System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSynthetic> NativeToManagedMap = new System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSynthetic>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; public static TypeSynthetic __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new TypeSynthetic(native.ToPointer(), skipVTables); } public static TypeSynthetic __CreateInstance(TypeSynthetic.Internal native, bool skipVTables = false) { return new TypeSynthetic(native, skipVTables); } private static void* __CopyValue(TypeSynthetic.Internal native) { var ret = Marshal.AllocHGlobal(8); LLDB.TypeSynthetic.Internal.cctor_1(ret, new global::System.IntPtr(&native)); return ret.ToPointer(); } private TypeSynthetic(TypeSynthetic.Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected TypeSynthetic(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public TypeSynthetic() { __Instance = Marshal.AllocHGlobal(8); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; Internal.ctor_0((__Instance + __PointerAdjustment)); } public TypeSynthetic(LLDB.TypeSynthetic rhs) { __Instance = Marshal.AllocHGlobal(8); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; if (ReferenceEquals(rhs, null)) throw new global::System.ArgumentNullException("rhs", "Cannot be null because it is a C++ reference (&)."); var arg0 = rhs.__Instance; Internal.cctor_1((__Instance + __PointerAdjustment), arg0); } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { LLDB.TypeSynthetic __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); Internal.dtor_0((__Instance + __PointerAdjustment), 0); if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); } public bool IsValid() { var __ret = Internal.IsValid_0((__Instance + __PointerAdjustment)); return __ret; } public bool IsClassCode() { var __ret = Internal.IsClassCode_0((__Instance + __PointerAdjustment)); return __ret; } public bool IsClassName() { var __ret = Internal.IsClassName_0((__Instance + __PointerAdjustment)); return __ret; } public bool GetDescription(LLDB.Stream description, LLDB.DescriptionLevel description_level) { if (ReferenceEquals(description, null)) throw new global::System.ArgumentNullException("description", "Cannot be null because it is a C++ reference (&)."); var arg0 = description.__Instance; var arg1 = description_level; var __ret = Internal.GetDescription_0((__Instance + __PointerAdjustment), arg0, arg1); return __ret; } public bool IsEqualTo(LLDB.TypeSynthetic rhs) { if (ReferenceEquals(rhs, null)) throw new global::System.ArgumentNullException("rhs", "Cannot be null because it is a C++ reference (&)."); var arg0 = rhs.__Instance; var __ret = Internal.IsEqualTo_0((__Instance + __PointerAdjustment), arg0); return __ret; } public static bool operator ==(LLDB.TypeSynthetic __op, LLDB.TypeSynthetic rhs) { bool __opNull = ReferenceEquals(__op, null); bool rhsNull = ReferenceEquals(rhs, null); if (__opNull || rhsNull) return __opNull && rhsNull; var arg0 = __op.__Instance; var arg1 = rhs.__Instance; var __ret = Internal.OperatorEqualEqual_0(arg0, arg1); return __ret; } public override bool Equals(object obj) { return this == obj as TypeSynthetic; } public override int GetHashCode() { if (__Instance == global::System.IntPtr.Zero) return global::System.IntPtr.Zero.GetHashCode(); return (*(Internal*) __Instance).GetHashCode(); } public static bool operator !=(LLDB.TypeSynthetic __op, LLDB.TypeSynthetic rhs) { bool __opNull = ReferenceEquals(__op, null); bool rhsNull = ReferenceEquals(rhs, null); if (__opNull || rhsNull) return !(__opNull && rhsNull); var arg0 = __op.__Instance; var arg1 = rhs.__Instance; var __ret = Internal.OperatorExclaimEqual_0(arg0, arg1); return __ret; } protected bool CopyOnWrite_Impl() { var __ret = Internal.CopyOnWrite_Impl_0((__Instance + __PointerAdjustment)); return __ret; } public static LLDB.TypeSynthetic CreateWithClassName(string data, uint options) { var arg0 = Marshal.StringToHGlobalAnsi(data); var __ret = new LLDB.TypeSynthetic.Internal(); Internal.CreateWithClassName_0(new IntPtr(&__ret), arg0, options); Marshal.FreeHGlobal(arg0); return LLDB.TypeSynthetic.__CreateInstance(__ret); } public static LLDB.TypeSynthetic CreateWithScriptCode(string data, uint options) { var arg0 = Marshal.StringToHGlobalAnsi(data); var __ret = new LLDB.TypeSynthetic.Internal(); Internal.CreateWithScriptCode_0(new IntPtr(&__ret), arg0, options); Marshal.FreeHGlobal(arg0); return LLDB.TypeSynthetic.__CreateInstance(__ret); } public string Data { get { var __ret = Internal.GetData_0((__Instance + __PointerAdjustment)); return Marshal.PtrToStringAnsi(__ret); } } public string ClassName { set { var arg0 = Marshal.StringToHGlobalAnsi(value); Internal.SetClassName_0((__Instance + __PointerAdjustment), arg0); Marshal.FreeHGlobal(arg0); } } public string ClassCode { set { var arg0 = Marshal.StringToHGlobalAnsi(value); Internal.SetClassCode_0((__Instance + __PointerAdjustment), arg0); Marshal.FreeHGlobal(arg0); } } public uint Options { get { var __ret = Internal.GetOptions_0((__Instance + __PointerAdjustment)); return __ret; } set { Internal.SetOptions_0((__Instance + __PointerAdjustment), value); } } } }
45.184848
206
0.634029
[ "MIT" ]
tritao/LLDBSharp
LLDBSharp/i686-pc-windows-msvc/SBTypeSynthetic.cs
14,911
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/winioctl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR" /> struct.</summary> public static unsafe class STORAGE_HW_ENDURANCE_DATA_DESCRIPTORTests { /// <summary>Validates that the <see cref="STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR>(), Is.EqualTo(sizeof(STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR))); } /// <summary>Validates that the <see cref="STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR), Is.EqualTo(56)); } } }
43.361111
149
0.707239
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/winioctl/STORAGE_HW_ENDURANCE_DATA_DESCRIPTORTests.cs
1,563
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace MinimalGame.Data { [CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/Create LevelData", order = 1)] public class LevelDataController : ScriptableObject { public List<Level> Levels = new List<Level>(); static LevelDataController _instance; public static LevelDataController Instance { get { _instance = Resources.Load<LevelDataController>("LevelData"); return _instance; } } public void ReceiveNewData(List<Level> newLevels) { foreach (Level level in Levels) level.IsDone = false; foreach (Level newLevel in newLevels) { foreach (Level level in Levels.Where(level => level.Id == newLevel.Id)) { level.IsDone = newLevel.IsDone; break; } } } public bool HasNextLevel(Level curLevel) { int currentIndex = Levels.IndexOf(curLevel); return currentIndex < (Levels.Count - 1); } public Level GetNextLevel(Level curLevel) { int currentIndex = Levels.IndexOf(curLevel); int newIndex = currentIndex + 1; return Levels[newIndex]; } public bool CanPlayLevel(Level level) { int levelIndex = Levels.IndexOf(level); //if is first level if (levelIndex == 0) return true; int levelToCheckIndex = levelIndex - 1; return Levels[levelToCheckIndex].IsDone; } } }
27.84127
100
0.54504
[ "MIT" ]
lipemon1/MinimalistGame
Assets/Scripts/UserData/LevelDataController.cs
1,756
C#
using UIForia.Attributes; using UIForia.Rendering; using UnityEngine; namespace UIForia.Elements { [TemplateTagName("Image")] public class UIImageElement : UIContainerElement { public ImageLocator? src; internal Texture texture; private Mesh mesh; public float Width; public float Height; public UIImageElement() { flags |= UIElementFlags.Primitive; } [OnPropertyChanged(nameof(src))] public void OnSrcChanged() { SetupBackground(); } public override void OnEnable() { SetupBackground(); } private void SetupBackground() { if (src == null) { style.SetBackgroundImage(null, StyleState.Normal); return; } texture = src.Value.texture ?? application.ResourceManager.GetTexture(src.Value.imagePath); if (texture == null) { style.SetBackgroundImage(null, StyleState.Normal); return; } style.SetBackgroundImage((Texture2D)texture, StyleState.Normal); if (Width > 0) { style.SetPreferredHeight(Width * texture.height / texture.width, StyleState.Normal); style.SetPreferredWidth(Width, StyleState.Normal); } if (Height > 0) { style.SetPreferredWidth(Height * texture.width / texture.height, StyleState.Normal); style.SetPreferredHeight(Height, StyleState.Normal); } } public override string GetDisplayName() { return "Image"; } } }
28.35
103
0.560259
[ "MIT" ]
criedel/UIForia
Packages/UIForia/Src/Elements/UIImageElement.cs
1,701
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: IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IManagedAllDeviceCertificateStateRequest. /// </summary> public partial interface IManagedAllDeviceCertificateStateRequest : IBaseRequest { /// <summary> /// Creates the specified ManagedAllDeviceCertificateState using POST. /// </summary> /// <param name="managedAllDeviceCertificateStateToCreate">The ManagedAllDeviceCertificateState to create.</param> /// <returns>The created ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> CreateAsync(ManagedAllDeviceCertificateState managedAllDeviceCertificateStateToCreate); /// <summary> /// Creates the specified ManagedAllDeviceCertificateState using POST. /// </summary> /// <param name="managedAllDeviceCertificateStateToCreate">The ManagedAllDeviceCertificateState to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> CreateAsync(ManagedAllDeviceCertificateState managedAllDeviceCertificateStateToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified ManagedAllDeviceCertificateState. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified ManagedAllDeviceCertificateState. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified ManagedAllDeviceCertificateState. /// </summary> /// <returns>The ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> GetAsync(); /// <summary> /// Gets the specified ManagedAllDeviceCertificateState. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified ManagedAllDeviceCertificateState using PATCH. /// </summary> /// <param name="managedAllDeviceCertificateStateToUpdate">The ManagedAllDeviceCertificateState to update.</param> /// <returns>The updated ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> UpdateAsync(ManagedAllDeviceCertificateState managedAllDeviceCertificateStateToUpdate); /// <summary> /// Updates the specified ManagedAllDeviceCertificateState using PATCH. /// </summary> /// <param name="managedAllDeviceCertificateStateToUpdate">The ManagedAllDeviceCertificateState to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated ManagedAllDeviceCertificateState.</returns> System.Threading.Tasks.Task<ManagedAllDeviceCertificateState> UpdateAsync(ManagedAllDeviceCertificateState managedAllDeviceCertificateStateToUpdate, CancellationToken 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> IManagedAllDeviceCertificateStateRequest Expand(string value); /// <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> IManagedAllDeviceCertificateStateRequest Expand(Expression<Func<ManagedAllDeviceCertificateState, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IManagedAllDeviceCertificateStateRequest Select(string value); /// <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> IManagedAllDeviceCertificateStateRequest Select(Expression<Func<ManagedAllDeviceCertificateState, object>> selectExpression); } }
53.981481
194
0.686449
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IManagedAllDeviceCertificateStateRequest.cs
5,830
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #nullable disable namespace StyleCop.Analyzers.Test.CSharp10.DocumentationRules { using StyleCop.Analyzers.Test.CSharp9.DocumentationRules; public class SA1618CSharp10UnitTests : SA1618CSharp9UnitTests { } }
27.928571
91
0.780051
[ "MIT" ]
RogerHowellDfE/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp10/DocumentationRules/SA1618CSharp10UnitTests.cs
393
C#
using Plugin.Connectivity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; namespace XamarinFormsStarterKit { public partial class App : Application { internal static bool IsConnected; public App() { InitializeComponent(); CrossConnectivity.Current.ConnectivityChanged += (sender, e) => { IsConnected = e.IsConnected; }; MainPage = new NavigationPage(new MainPage()); } protected override void OnStart() { // Handle when your app starts App.IsConnected = CrossConnectivity.Current.IsConnected; } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes App.IsConnected = CrossConnectivity.Current.IsConnected; } } }
22.744186
109
0.605317
[ "Apache-2.0" ]
websolutionsAIO/LearningAndroidAppDevNew
XamarinFormsStarterKit/XamarinFormsStarterKit/App.xaml.cs
980
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 iotsitewise-2019-12-02.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.IoTSiteWise.Model { /// <summary> /// Contains information about an AWS Identity and Access Management (IAM) user. /// </summary> public partial class IAMUserIdentity { private string _arn; /// <summary> /// Gets and sets the property Arn. /// <para> /// The ARN of the IAM user. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html">IAM /// ARNs</a> in the <i>IAM User Guide</i>. /// </para> /// <note> /// <para> /// If you delete the IAM user, access policies that contain this identity include an /// empty <code>arn</code>. You can delete the access policy for the IAM user that no /// longer exists. /// </para> /// </note> /// </summary> [AWSProperty(Required=true, Min=1, Max=1600)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } } }
32.409091
153
0.610098
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTSiteWise/Generated/Model/IAMUserIdentity.cs
2,139
C#
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Pioneer.Logs.Tubs.AspNetCore; namespace PIoneer.Logs.Samples.AspNetCore._31.Controllers { [ApiController] public class TestController : ControllerBase { [HttpGet] [Route("api/exception")] //[PioneerLogsTrackUsage(Message = "TestController Get")] public ActionResult<IEnumerable<string>> Get() { PioneerLogsTub.LogDiagnostic("Hi, I am about to force an Exception.", HttpContext, new Dictionary<string, object> { { "Test", "Parameter" } }); throw new Exception("I just manually forced an Exception. Enjoy!"); } [HttpGet] [Route("api/test")] [PioneerLogsTrackUsage(Message = "TestController Get")] public ActionResult<IEnumerable<string>> GetTest() { PioneerLogsTub.CorrelationId = Guid.NewGuid().ToString(); PioneerLogsTub.LogUsage("RunUsageLoggingTask", HttpContext); PioneerLogsTub.LogDiagnostic("Some Random Message.", HttpContext); //return Ok(); var errors = new ModelStateDictionary(); errors.AddModelError("date", "frick"); return ValidationProblem(errors); } } }
36.621622
81
0.63321
[ "MIT" ]
PioneerCode/pioneer-logs
samples/PIoneer.Logs.Samples.AspNetCore.31/Controllers/TestController.cs
1,357
C#
namespace PayrollSplitter { partial class Main { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.previewList = new System.Windows.Forms.ListBox(); this.PreviewLabel3 = new System.Windows.Forms.Label(); this.PreviewBtn = new System.Windows.Forms.Button(); this.PreviewLabel2 = new System.Windows.Forms.Label(); this.SaveBtn = new System.Windows.Forms.Button(); this.PreviewLabel1 = new System.Windows.Forms.Label(); this.FinishLbl = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.ChoosePDFBtn = new System.Windows.Forms.Button(); this.FilePath = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.SettingsBtn = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.groupBox1.SuspendLayout(); this.panel1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.panel1); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.ChoosePDFBtn); this.groupBox1.Controls.Add(this.FilePath); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(572, 517); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Payroll"; // // panel1 // this.panel1.Controls.Add(this.label4); this.panel1.Controls.Add(this.label5); this.panel1.Controls.Add(this.previewList); this.panel1.Controls.Add(this.PreviewLabel3); this.panel1.Controls.Add(this.PreviewBtn); this.panel1.Controls.Add(this.PreviewLabel2); this.panel1.Controls.Add(this.SaveBtn); this.panel1.Controls.Add(this.PreviewLabel1); this.panel1.Controls.Add(this.FinishLbl); this.panel1.Location = new System.Drawing.Point(6, 104); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(558, 407); this.panel1.TabIndex = 16; this.panel1.Visible = false; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(3, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(198, 25); this.label4.TabIndex = 5; this.label4.Text = "STEP 2: PREVIEW"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(213, 7); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(164, 17); this.label5.TabIndex = 15; this.label5.Text = "(Click on items in the list)"; // // previewList // this.previewList.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.previewList.FormattingEnabled = true; this.previewList.ItemHeight = 22; this.previewList.Location = new System.Drawing.Point(3, 29); this.previewList.Margin = new System.Windows.Forms.Padding(4); this.previewList.Name = "previewList"; this.previewList.Size = new System.Drawing.Size(249, 246); this.previewList.TabIndex = 4; this.previewList.SelectedIndexChanged += new System.EventHandler(this.previewList_SelectedIndexChanged); // // PreviewLabel3 // this.PreviewLabel3.AutoSize = true; this.PreviewLabel3.Location = new System.Drawing.Point(260, 181); this.PreviewLabel3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.PreviewLabel3.Name = "PreviewLabel3"; this.PreviewLabel3.Size = new System.Drawing.Size(0, 17); this.PreviewLabel3.TabIndex = 14; // // PreviewBtn // this.PreviewBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.PreviewBtn.Location = new System.Drawing.Point(336, 41); this.PreviewBtn.Margin = new System.Windows.Forms.Padding(4); this.PreviewBtn.Name = "PreviewBtn"; this.PreviewBtn.Size = new System.Drawing.Size(130, 36); this.PreviewBtn.TabIndex = 8; this.PreviewBtn.Text = "Preview File"; this.PreviewBtn.UseVisualStyleBackColor = true; this.PreviewBtn.Visible = false; this.PreviewBtn.Click += new System.EventHandler(this.PreviewBtn_Click); // // PreviewLabel2 // this.PreviewLabel2.AutoSize = true; this.PreviewLabel2.Location = new System.Drawing.Point(260, 151); this.PreviewLabel2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.PreviewLabel2.Name = "PreviewLabel2"; this.PreviewLabel2.Size = new System.Drawing.Size(0, 17); this.PreviewLabel2.TabIndex = 13; // // SaveBtn // this.SaveBtn.BackColor = System.Drawing.Color.LimeGreen; this.SaveBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SaveBtn.Location = new System.Drawing.Point(8, 323); this.SaveBtn.Margin = new System.Windows.Forms.Padding(4); this.SaveBtn.Name = "SaveBtn"; this.SaveBtn.Size = new System.Drawing.Size(272, 69); this.SaveBtn.TabIndex = 10; this.SaveBtn.Text = "Save All PDFs to Folder"; this.SaveBtn.UseVisualStyleBackColor = false; this.SaveBtn.Click += new System.EventHandler(this.SaveBtn_Click); // // PreviewLabel1 // this.PreviewLabel1.AutoSize = true; this.PreviewLabel1.Location = new System.Drawing.Point(260, 120); this.PreviewLabel1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.PreviewLabel1.Name = "PreviewLabel1"; this.PreviewLabel1.Size = new System.Drawing.Size(0, 17); this.PreviewLabel1.TabIndex = 12; // // FinishLbl // this.FinishLbl.AutoSize = true; this.FinishLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FinishLbl.Location = new System.Drawing.Point(3, 294); this.FinishLbl.Name = "FinishLbl"; this.FinishLbl.Size = new System.Drawing.Size(170, 25); this.FinishLbl.TabIndex = 11; this.FinishLbl.Text = "STEP 3: FINISH"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(7, 32); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(318, 25); this.label6.TabIndex = 5; this.label6.Text = "STEP 1: OPEN PAYSTUB FILE"; // // ChoosePDFBtn // this.ChoosePDFBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ChoosePDFBtn.Location = new System.Drawing.Point(415, 56); this.ChoosePDFBtn.Margin = new System.Windows.Forms.Padding(4); this.ChoosePDFBtn.Name = "ChoosePDFBtn"; this.ChoosePDFBtn.Size = new System.Drawing.Size(150, 29); this.ChoosePDFBtn.TabIndex = 3; this.ChoosePDFBtn.Text = "Choose PDF"; this.ChoosePDFBtn.UseVisualStyleBackColor = true; this.ChoosePDFBtn.Click += new System.EventHandler(this.ChoosePDFBtn_Click); // // FilePath // this.FilePath.Location = new System.Drawing.Point(7, 61); this.FilePath.Margin = new System.Windows.Forms.Padding(4); this.FilePath.Name = "FilePath"; this.FilePath.ReadOnly = true; this.FilePath.Size = new System.Drawing.Size(391, 22); this.FilePath.TabIndex = 2; // // groupBox2 // this.groupBox2.Controls.Add(this.SettingsBtn); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Location = new System.Drawing.Point(590, 12); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(420, 517); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "Settings"; // // SettingsBtn // this.SettingsBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SettingsBtn.Location = new System.Drawing.Point(99, 164); this.SettingsBtn.Name = "SettingsBtn"; this.SettingsBtn.Size = new System.Drawing.Size(203, 80); this.SettingsBtn.TabIndex = 1; this.SettingsBtn.Text = "Go to settings"; this.SettingsBtn.UseVisualStyleBackColor = true; this.SettingsBtn.Click += new System.EventHandler(this.SettingsBtn_Click); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(8, 81); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(294, 24); this.label3.TabIndex = 0; this.label3.Text = "to intelligently split your payroll file."; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(8, 54); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(387, 24); this.label2.TabIndex = 0; this.label2.Text = "in the settings. We use the employee settings"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(8, 28); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(388, 24); this.label1.TabIndex = 0; this.label1.Text = "Make sure you have defined your employees"; // // openFileDialog1 // this.openFileDialog1.Filter = "PDF File|*.pdf"; // // Main // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1022, 541); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Main"; this.Text = "Title"; this.Load += new System.EventHandler(this.Main_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label FinishLbl; private System.Windows.Forms.Button SaveBtn; private System.Windows.Forms.Button PreviewBtn; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label4; private System.Windows.Forms.ListBox previewList; private System.Windows.Forms.Button ChoosePDFBtn; private System.Windows.Forms.TextBox FilePath; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button SettingsBtn; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.Label PreviewLabel3; private System.Windows.Forms.Label PreviewLabel2; private System.Windows.Forms.Label PreviewLabel1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Panel panel1; } }
50.119497
172
0.596122
[ "MIT" ]
michaelwda/PayrollSplitter
PayrollSplitter/Main.Designer.cs
15,940
C#
using System; using Automatonymous; using Automatonymous.Binders; using MassTransit; using static CommunicationFoodDelivery.Contracts.Commands; using static CommunicationFoodDelivery.Contracts.Events; namespace CommunicationFoodDelivery { public class OrderState : SagaStateMachineInstance { public Guid CorrelationId { get; set; } public int CurrentState { get; set; } public Guid OrderId { get; set; } public string OrderDetails { get; set; } public string Address { get; set; } public DateTime Placed { get; set; } public DateTime Accepted { get; set; } public DateTime Cooked { get; set; } public DateTime Delivered { get; set; } } public class OrderStateMachine : MassTransitStateMachine<OrderState> { public OrderStateMachine() { InstanceState(x => x.CurrentState, Placed, Accepted, Cooked); Event(() => PlaceOrder, x => x.CorrelateById(m => m.Message.OrderId)); Event(() => AcceptOrder, x => x.CorrelateById(m => m.Message.OrderId)); Event(() => DishCooked, x => x.CorrelateById(m => m.Message.OrderId)); Event(() => OrderDelivered, x => x.CorrelateById(m => m.Message.OrderId)); Initially( When(PlaceOrder) .SetOrderDetails() .TransitionTo(Placed) .PublishOrderPlaced()); During(Placed, When(AcceptOrder) .SetAcceptedTime() .TransitionTo(Accepted) .PublishCookDish()); During(Accepted, When(DishCooked) .SetCookedTime() .TransitionTo(Cooked) .PublishDeliverOrder()); During(Cooked, When(OrderDelivered) .SetDeliveredTime() .Finalize()); } public Event<PlaceOrder> PlaceOrder { get; private set; } public Event<AcceptOrder> AcceptOrder { get; private set; } public Event<DishCooked> DishCooked { get; private set; } public Event<OrderDelivered> OrderDelivered { get; private set; } public State Placed { get; private set; } public State Accepted { get; private set; } public State Cooked { get; private set; } } public static class OrderStateMachineExtensions { public static EventActivityBinder<OrderState, PlaceOrder> SetOrderDetails( this EventActivityBinder<OrderState, PlaceOrder> binder) { return binder.Then(x => { x.Instance.OrderId = x.Data.OrderId; x.Instance.OrderDetails = x.Data.OrderDetails; x.Instance.Address = x.Data.Address; x.Instance.Placed = DateTime.UtcNow; }); } public static EventActivityBinder<OrderState, PlaceOrder> PublishOrderPlaced( this EventActivityBinder<OrderState, PlaceOrder> binder) { return binder.PublishAsync(context => context.Init<OrderPlaced>(new OrderPlaced { OrderId = context.Data.OrderId, OrderDetails = context.Data.OrderDetails })); } public static EventActivityBinder<OrderState, AcceptOrder> SetAcceptedTime( this EventActivityBinder<OrderState, AcceptOrder> binder) { return binder.Then(x => { x.Instance.Accepted = DateTime.UtcNow; }); } public static EventActivityBinder<OrderState, AcceptOrder> PublishCookDish( this EventActivityBinder<OrderState, AcceptOrder> binder) { return binder.PublishAsync(context => context.Init<CookDish>(new CookDish { OrderId = context.Data.OrderId, OrderDetails = context.Instance.OrderDetails })); } public static EventActivityBinder<OrderState, DishCooked> SetCookedTime( this EventActivityBinder<OrderState, DishCooked> binder) { return binder.Then(x => { x.Instance.Cooked = DateTime.UtcNow; }); } public static EventActivityBinder<OrderState, DishCooked> PublishDeliverOrder( this EventActivityBinder<OrderState, DishCooked> binder) { return binder.PublishAsync(context => context.Init<DeliverOrder>(new DeliverOrder { OrderId = context.Data.OrderId, Address = context.Instance.Address })); } public static EventActivityBinder<OrderState, OrderDelivered> SetDeliveredTime( this EventActivityBinder<OrderState, OrderDelivered> binder) { return binder.Then(x => { x.Instance.Delivered = DateTime.UtcNow; }); } } }
37.396947
93
0.592774
[ "MIT" ]
rafaelldi/communication-food-delivery
OrderStateMachine.cs
4,899
C#
namespace Mantle.Plugins.Messaging.Forums.Models { public class ForumBreadcrumbModel { public int ForumGroupId { get; set; } public string ForumGroupName { get; set; } public string ForumGroupSeName { get; set; } public int ForumId { get; set; } public string ForumName { get; set; } public string ForumSeName { get; set; } public int ForumTopicId { get; set; } public string ForumTopicSubject { get; set; } public string ForumTopicSeName { get; set; } } }
23.869565
53
0.621129
[ "MIT" ]
gordon-matt/MantleCMS
Plugins/Mantle.Plugins.Messaging.Forums/Models/ForumBreadcrumbModel.cs
551
C#
using UnityEngine; using System.Collections; public class GuidanceMission : MonoBehaviour { private Transform _list; void OnEnable() { GameObject map = GameObject.FindGameObjectWithTag("Map"); _list = map.transform.GetChild(0); } public void Update() { if (transform.name.Contains("1")) { transform.position = _list.GetChild(0).position; } else { transform.position = _list.GetChild(1).position; } } }
20.84
65
0.585413
[ "MIT" ]
BlueMonk1107/SushiNinja
Assets/Scripts/Guidance/Effect/GuidanceMission.cs
523
C#
using System.IO.Abstractions.TestingHelpers; using System.Threading.Tasks; using Shouldly; using Stryker.Core.Baseline.Providers; using Stryker.Core.Options; using Stryker.Core.Reporters.Json; using Stryker.Core.UnitTest.Reporters; using Xunit; namespace Stryker.Core.UnitTest.Baseline.Providers { public class DiskBaselineProviderTests : TestBase { [Fact] public async Task ShouldWriteToDiskAsync() { // Arrange var fileSystemMock = new MockFileSystem(); var options = new StrykerOptions() { BasePath = @"C:/Users/JohnDoe/Project/TestFolder" }; var sut = new DiskBaselineProvider(options, fileSystemMock); // Act await sut.Save(JsonReport.Build(options, JsonReportTestHelper.CreateProjectWith()), "baseline/version"); // Assert var path = FilePathUtils.NormalizePathSeparators(@"C:/Users/JohnDoe/Project/TestFolder/StrykerOutput/baseline/version/stryker-report.json"); MockFileData file = fileSystemMock.GetFile(path); file.ShouldNotBeNull(); } [Fact] public async Task ShouldHandleFileNotFoundExceptionOnLoadAsync() { // Arrange var fileSystemMock = new MockFileSystem(); var options = new StrykerOptions { BasePath = "C:/Dev" }; var sut = new DiskBaselineProvider(options, fileSystemMock); // Act var result = await sut.Load("testversion"); result.ShouldBeNull(); } [Fact] public async Task ShouldLoadReportFromDiskAsync() { // Arrange var fileSystemMock = new MockFileSystem(); var options = new StrykerOptions() { BasePath = @"C:/Users/JohnDoe/Project/TestFolder" }; var report = JsonReport.Build(options, JsonReportTestHelper.CreateProjectWith()); fileSystemMock.AddFile("C:/Users/JohnDoe/Project/TestFolder/StrykerOutput/baseline/version/stryker-report.json", report.ToJson()); var target = new DiskBaselineProvider(options, fileSystemMock); // Act var result = await target.Load("baseline/version"); // Assert result.ShouldNotBeNull(); result.ToJson().ShouldBe(report.ToJson()); } } }
33.273973
152
0.615068
[ "Apache-2.0" ]
AlexNDRmac/stryker-net
src/Stryker.Core/Stryker.Core.UnitTest/Baseline/Providers/DiskBaselineProviderTests.cs
2,429
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.Configuration; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Resources; using System.Reflection; using System.Security; using System.Text; using System.Threading; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.BackEnd; using Microsoft.Build.Execution; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; #if (!STANDALONEBUILD) using Microsoft.Internal.Performance; #endif #if MSBUILDENABLEVSPROFILING using Microsoft.VisualStudio.Profiler; #endif using FileLogger = Microsoft.Build.Logging.FileLogger; using ConsoleLogger = Microsoft.Build.Logging.ConsoleLogger; using LoggerDescription = Microsoft.Build.Logging.LoggerDescription; using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord; using System.Runtime.CompilerServices; namespace Microsoft.Build.CommandLine { /// <summary> /// This class implements the MSBuild.exe command-line application. It processes /// command-line arguments and invokes the build engine. /// </summary> static public class MSBuildApp { /// <summary> /// Enumeration of the various ways in which the MSBuild.exe application can exit. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "shipped already")] public enum ExitType { /// <summary> /// The application executed successfully. /// </summary> Success, /// <summary> /// There was a syntax error in a command line argument. /// </summary> SwitchError, /// <summary> /// A command line argument was not valid. /// </summary> InitializationError, /// <summary> /// The build failed. /// </summary> BuildError, /// <summary> /// A logger aborted the build. /// </summary> LoggerAbort, /// <summary> /// A logger failed unexpectedly. /// </summary> LoggerFailure, /// <summary> /// The build stopped unexpectedly, for example, /// because a child died or hung. /// </summary> Unexpected } /// <summary> /// Whether the static constructor ran successfully. /// </summary> private static bool s_initialized; /// <summary> /// The object used to synchronize access to shared build state /// </summary> private static Object s_buildLock = new Object(); /// <summary> /// The currently active build, if any. /// </summary> private static BuildSubmission s_activeBuild; /// <summary> /// Event signalled when the build is complete. /// </summary> private static ManualResetEvent s_buildComplete = new ManualResetEvent(false); /// <summary> /// Event signalled when the cancel method is complete. /// </summary> private static ManualResetEvent s_cancelComplete = new ManualResetEvent(true); /// <summary> /// Set to 1 when the cancel method has been invoked. /// Never reset to false: subsequent hits of Ctrl-C should do nothing /// </summary> private static int s_receivedCancel; /// <summary> /// Static constructor /// </summary> static MSBuildApp() { try { //////////////////////////////////////////////////////////////////////////////// // Only initialize static fields here, not inline! // // This forces the type to initialize in this static constructor and thus // // any configuration file exceptions can be caught here. // //////////////////////////////////////////////////////////////////////////////// s_exePath = Path.GetDirectoryName(FileUtilities.ExecutingAssemblyPath); s_initialized = true; } catch (TypeInitializationException ex) { if (ex.InnerException == null || ex.InnerException.GetType() != typeof(ConfigurationErrorsException)) { throw; } HandleConfigurationException(ex); } catch (ConfigurationException ex) { HandleConfigurationException(ex); } } /// <summary> /// Static no-op method to force static constructor to run and initialize resources. /// This is useful for unit tests. /// </summary> internal static void Initialize() { } /// <summary> /// Dump any exceptions reading the configuration file, nicely /// </summary> private static void HandleConfigurationException(Exception ex) { // Error reading the configuration file - eg., unexpected element // Since we expect users to edit it to add toolsets, this is not unreasonable to expect StringBuilder builder = new StringBuilder(); Exception exception = ex; do { string message = exception.Message.TrimEnd(); builder.Append(message); // One of the exceptions is missing a period! if (message[message.Length - 1] != '.') { builder.Append("."); } builder.Append(" "); exception = exception.InnerException; } while (exception != null); Console.WriteLine(ResourceUtilities.FormatResourceString("InvalidConfigurationFile", builder.ToString())); s_initialized = false; } /// <summary> /// This is the entry point for the application. /// </summary> /// <remarks> /// MSBuild no longer runs any arbitrary code (tasks or loggers) on the main thread, so it never needs the /// main thread to be in an STA. Accordingly, to avoid ambiguity, we explicitly use the [MTAThread] attribute. /// This doesn't actually do any work unless COM interop occurs for some reason. /// </remarks> /// <returns>0 on success, 1 on failure</returns> [MTAThread] public static int Main() { if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1") { DumpCounters(true /* initialize only */); } // return 0 on success, non-zero on failure int exitCode = ((s_initialized && Execute(Environment.CommandLine) == ExitType.Success) ? 0 : 1); if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1") { DumpCounters(false /* log to console */); } return exitCode; } /// <summary> /// Append output file with elapsedTime /// </summary> /// <comments> /// This is a non-supported feature to facilitate timing multiple runs /// </comments> static private void AppendOutputFile(string path, Int64 elapsedTime) { if (!File.Exists(path)) { using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine(elapsedTime); } } else { using (StreamWriter sw = File.AppendText(path)) { sw.WriteLine(elapsedTime); } } } /// <summary> /// Dump process counters in parseable format. /// These can't be gotten after the process ends, so log them here. /// These are for the current process only: remote nodes are not counted. /// </summary> /// <comments> /// Because some of these counters give bogus results or are poorly defined, /// we only dump counters if an undocumented environment variable is set. /// Also, the strings are not localized. /// Before execution, this is called with initialize only, causing counters to get called with NextValue() to /// initialize them. /// </comments> private static void DumpCounters(bool initializeOnly) { Process currentProcess = Process.GetCurrentProcess(); if (!initializeOnly) { Console.WriteLine("\n{0}{1}{0}", new String('=', 41 - "Process".Length / 2), "Process"); Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Working Set", currentProcess.PeakWorkingSet64, "bytes"); Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Paged Memory", currentProcess.PeakPagedMemorySize64, "bytes"); // Not very useful one Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Virtual Memory", currentProcess.PeakVirtualMemorySize64, "bytes"); // Not very useful one Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Privileged Processor Time", currentProcess.PrivilegedProcessorTime.TotalMilliseconds, "ms"); Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak User Processor Time", currentProcess.UserProcessorTime.TotalMilliseconds, "ms"); Console.WriteLine("||{0,50}|{1,20:N0}|{2,8}|", "Peak Total Processor Time", currentProcess.TotalProcessorTime.TotalMilliseconds, "ms"); Console.WriteLine("{0}{0}", new String('=', 41)); } // Now some Windows performance counters // First get the instance name of this process, in order to look them up. // Generally, the instance names, such as "msbuild" and "msbuild#2" are non deterministic; we want this process. // Don't use the "ID Process" counter out of the "Process" category, as it doesn't use the same naming scheme // as the .NET counters. However, the "Process ID" counter out of the ".NET CLR Memory" category apparently uses // the same scheme as the other .NET categories. string currentInstance = null; PerformanceCounterCategory processCategory = new PerformanceCounterCategory("Process"); foreach (string instance in processCategory.GetInstanceNames()) { using (PerformanceCounter counter = new PerformanceCounter(".NET CLR Memory", "Process ID", instance, true)) { try { if ((int)counter.RawValue == currentProcess.Id) { currentInstance = instance; break; } } catch (InvalidOperationException) // Instance 'WmiApSrv' does not exist in the specified Category. (??) { } } } foreach (PerformanceCounterCategory category in PerformanceCounterCategory.GetCategories()) { DumpAllInCategory(currentInstance, category, initializeOnly); } } /// <summary> /// Dumps all counters in the category /// </summary> private static void DumpAllInCategory(string currentInstance, PerformanceCounterCategory category, bool initializeOnly) { if (category.CategoryName.IndexOf("remoting", StringComparison.OrdinalIgnoreCase) != -1) // not interesting { return; } PerformanceCounter[] counters; try { counters = category.GetCounters(currentInstance); } catch (InvalidOperationException) { // This is a system-wide category, ignore those return; } if (!initializeOnly) { Console.WriteLine("\n{0}{1}{0}", new String('=', 41 - category.CategoryName.Length / 2), category.CategoryName); } foreach (PerformanceCounter counter in counters) { DumpCounter(counter, initializeOnly); } if (!initializeOnly) { Console.WriteLine("{0}{0}", new String('=', 41)); } } /// <summary> /// Dumps one counter /// </summary> private static void DumpCounter(PerformanceCounter counter, bool initializeOnly) { try { if (counter.CounterName.IndexOf("not displayed", StringComparison.OrdinalIgnoreCase) != -1) { return; } float value = counter.NextValue(); if (!initializeOnly) { string friendlyCounterType = GetFriendlyCounterType(counter.CounterType, counter.CounterName); string valueFormat; // At least some (such as % in GC; maybe all) "%" counters are already multiplied by 100. So we don't do that here. // Show decimal places if meaningful valueFormat = value < 10 ? "{0,20:N2}" : "{0,20:N0}"; string valueString = String.Format(CultureInfo.CurrentCulture, valueFormat, value); Console.WriteLine("||{0,50}|{1}|{2,8}|", counter.CounterName, valueString, friendlyCounterType); } } catch (InvalidOperationException) // Instance 'WmiApSrv' does not exist in the specified Category. (??) { } } /// <summary> /// Gets a friendly representation of the counter units /// </summary> private static string GetFriendlyCounterType(PerformanceCounterType type, string name) { if (name.IndexOf("bytes", StringComparison.OrdinalIgnoreCase) != -1) { return "bytes"; } if (name.IndexOf("threads", StringComparison.OrdinalIgnoreCase) != -1) { return "threads"; } switch (type) { case PerformanceCounterType.ElapsedTime: case PerformanceCounterType.AverageTimer32: return "s"; case PerformanceCounterType.Timer100Ns: case PerformanceCounterType.Timer100NsInverse: return "100ns"; case PerformanceCounterType.SampleCounter: case PerformanceCounterType.AverageCount64: case PerformanceCounterType.NumberOfItems32: case PerformanceCounterType.NumberOfItems64: case PerformanceCounterType.NumberOfItemsHEX32: case PerformanceCounterType.NumberOfItemsHEX64: case PerformanceCounterType.RateOfCountsPerSecond32: case PerformanceCounterType.RateOfCountsPerSecond64: case PerformanceCounterType.CountPerTimeInterval32: case PerformanceCounterType.CountPerTimeInterval64: case PerformanceCounterType.CounterTimer: case PerformanceCounterType.CounterTimerInverse: case PerformanceCounterType.CounterMultiTimer: case PerformanceCounterType.CounterMultiTimerInverse: case PerformanceCounterType.CounterDelta32: case PerformanceCounterType.CounterDelta64: return "#"; case PerformanceCounterType.CounterMultiTimer100Ns: case PerformanceCounterType.CounterMultiTimer100NsInverse: case PerformanceCounterType.RawFraction: case PerformanceCounterType.SampleFraction: return "%"; case PerformanceCounterType.AverageBase: case PerformanceCounterType.RawBase: case PerformanceCounterType.SampleBase: case PerformanceCounterType.CounterMultiBase: default: return "?"; } } /// <summary> /// Orchestrates the execution of the application, and is also responsible /// for top-level error handling. /// </summary> /// <param name="commandLine">The command line to process. The first argument /// on the command line is assumed to be the name/path of the executable, and /// is ignored.</param> /// <returns>A value of type ExitType that indicates whether the build succeeded, /// or the manner in which it failed.</returns> public static ExitType Execute(string commandLine) { // Indicate to the engine that it can toss extraneous file content // when it loads microsoft.*.targets. We can't do this in the general case, // because tasks in the build can (and occasionally do) load MSBuild format files // with our OM and modify and save them. They'll never do this for Microsoft.*.targets, though, // and those form the great majority of our unnecessary memory use. Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", "true"); string debugFlag = Environment.GetEnvironmentVariable("MSBUILDDEBUGONSTART"); if (debugFlag == "1") { Debugger.Launch(); } else if (debugFlag == "2") { // Sometimes easier to attach rather than deal with JIT prompt Console.ReadLine(); } ErrorUtilities.VerifyThrowArgumentLength(commandLine, "commandLine"); ExitType exitType = ExitType.Success; ConsoleCancelEventHandler cancelHandler = new ConsoleCancelEventHandler(Console_CancelKeyPress); try { #if (!STANDALONEBUILD) // Enable CodeMarkers for MSBuild.exe CodeMarkers.Instance.InitPerformanceDll(CodeMarkerApp.MSBUILDPERF, @"Software\Microsoft\MSBuild\4.0"); #endif #if MSBUILDENABLEVSPROFILING string startMSBuildExe = String.Format(CultureInfo.CurrentCulture, "Running MSBuild.exe with command line {0}", commandLine); DataCollection.CommentMarkProfile(8800, startMSBuildExe); #endif Console.CancelKeyPress += cancelHandler; // check the operating system the code is running on VerifyThrowSupportedOS(); // Setup the console UI. SetConsoleUI(); // reset the application state for this new build ResetBuildState(); // process the detected command line switches -- gather build information, take action on non-build switches, and // check for non-trivial errors string projectFile = null; string[] targets = { }; string toolsVersion = null; Dictionary<string, string> globalProperties = null; ILogger[] loggers = { }; LoggerVerbosity verbosity = LoggerVerbosity.Normal; List<DistributedLoggerRecord> distributedLoggerRecords = null; bool needToValidateProject = false; string schemaFile = null; int cpuCount = 1; bool enableNodeReuse = true; TextWriter preprocessWriter = null; bool debugger = false; bool detailedSummary = false; CommandLineSwitches switchesFromAutoResponseFile; CommandLineSwitches switchesNotFromAutoResponseFile; GatherAllSwitches(commandLine, out switchesFromAutoResponseFile, out switchesNotFromAutoResponseFile); if (ProcessCommandLineSwitches( switchesFromAutoResponseFile, switchesNotFromAutoResponseFile, ref projectFile, ref targets, ref toolsVersion, ref globalProperties, ref loggers, ref verbosity, ref distributedLoggerRecords, ref needToValidateProject, ref schemaFile, ref cpuCount, ref enableNodeReuse, ref preprocessWriter, ref debugger, ref detailedSummary, recursing: false )) { // Unfortunately /m isn't the default, and we are not yet brave enough to make it the default. // However we want to give a hint to anyone who is building single proc without realizing it that there // is a better way. if (cpuCount == 1 && FileUtilities.IsSolutionFilename(projectFile) && verbosity > LoggerVerbosity.Minimal) { Console.WriteLine(ResourceUtilities.FormatResourceString("PossiblyOmittedMaxCPUSwitch")); } if (preprocessWriter != null || debugger) { // Indicate to the engine that it can NOT toss extraneous file content: we want to // see that in preprocessing/debugging Environment.SetEnvironmentVariable("MSBUILDLOADALLFILESASWRITEABLE", "1"); } DateTime t1 = DateTime.Now; #if !STANDALONEBUILD if (Environment.GetEnvironmentVariable("MSBUILDOLDOM") != "1") #endif { // if everything checks out, and sufficient information is available to start building if (!BuildProject(projectFile, targets, toolsVersion, globalProperties, loggers, verbosity, distributedLoggerRecords.ToArray(), needToValidateProject, schemaFile, cpuCount, enableNodeReuse, preprocessWriter, debugger, detailedSummary)) { exitType = ExitType.BuildError; } } #if !STANDALONEBUILD else { exitType = OldOMBuildProject(exitType, projectFile, targets, toolsVersion, globalProperties, loggers, verbosity, needToValidateProject, schemaFile, cpuCount); } #endif DateTime t2 = DateTime.Now; TimeSpan elapsedTime = t2.Subtract(t1); string timerOutputFilename = Environment.GetEnvironmentVariable("MSBUILDTIMEROUTPUTS"); if (!String.IsNullOrEmpty(timerOutputFilename)) { AppendOutputFile(timerOutputFilename, elapsedTime.Milliseconds); } } else { // if there was no need to start the build e.g. because /help was triggered // do nothing } } /********************************************************************************************************************** * WARNING: Do NOT add any more catch blocks below! Exceptions should be caught as close to their point of origin as * possible, and converted into one of the known exceptions. The code that causes an exception best understands the * reason for the exception, and only that code can provide the proper error message. We do NOT want to display * messages from unknown exceptions, because those messages are most likely neither localized, nor composed in the * canonical form with the correct prefix. *********************************************************************************************************************/ // handle switch errors catch (CommandLineSwitchException e) { Console.WriteLine(e.Message); Console.WriteLine(); // prompt user to display help for proper switch usage ShowHelpPrompt(); exitType = ExitType.SwitchError; } // handle configuration exceptions: problems reading toolset information from msbuild.exe.config or the registry catch (InvalidToolsetDefinitionException e) { // Brief prefix to indicate that it's a configuration failure, and provide the "error" indication Console.WriteLine(ResourceUtilities.FormatResourceString("ConfigurationFailurePrefixNoErrorCode", e.ErrorCode, e.Message)); exitType = ExitType.InitializationError; } // handle initialization failures catch (InitializationException e) { Console.WriteLine(e.Message); exitType = ExitType.InitializationError; } // handle polite logger failures: don't dump the stack or trigger watson for these catch (LoggerException e) { // display the localized message from the outer exception in canonical format if (null != e.ErrorCode) { // Brief prefix to indicate that it's a logger failure, and provide the "error" indication Console.WriteLine(ResourceUtilities.FormatResourceString("LoggerFailurePrefixNoErrorCode", e.ErrorCode, e.Message)); } else { // Brief prefix to indicate that it's a logger failure, adding a generic error code to make sure // there's something for the user to look up in the documentation Console.WriteLine(ResourceUtilities.FormatResourceString("LoggerFailurePrefixWithErrorCode", e.Message)); } if (null != e.InnerException) { // write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming // from buggy loggers written by users Console.WriteLine(e.InnerException.ToString()); } exitType = ExitType.LoggerAbort; } // handle logger failures (logger bugs) catch (InternalLoggerException e) { if (!e.InitializationException) { // display the localized message from the outer exception in canonical format Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message); #if DEBUG Console.WriteLine("This is an unhandled exception from a logger -- PLEASE OPEN A BUG AGAINST THE LOGGER OWNER."); #endif // write out exception details -- don't bother triggering Watson, because most of these exceptions will be coming // from buggy loggers written by users Console.WriteLine(e.InnerException.ToString()); exitType = ExitType.LoggerFailure; } else { Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message + (e.InnerException != null ? " " + e.InnerException.Message : "")); exitType = ExitType.InitializationError; } } catch (BuildAbortedException e) { Console.WriteLine("MSBUILD : error " + e.ErrorCode + ": " + e.Message + (e.InnerException != null ? " " + e.InnerException.Message : String.Empty)); exitType = ExitType.Unexpected; } // handle fatal errors catch (Exception e) { // display a generic localized message for the user Console.WriteLine("{0}\r\n{1}", AssemblyResources.GetString("FatalError"), e.ToString()); #if DEBUG Console.WriteLine("This is an unhandled exception in MSBuild Engine -- PLEASE OPEN A BUG AGAINST THE MSBUILD TEAM.\r\n{0}", e.ToString()); #endif // rethrow, in case Watson is enabled on the machine -- if not, the CLR will write out exception details // allow the build lab to set an env var to avoid jamming the build if (Environment.GetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER") != "1") { throw; } } finally { s_buildComplete.Set(); Console.CancelKeyPress -= cancelHandler; // Wait for any pending cancel, so that we get any remaining messages s_cancelComplete.WaitOne(); #if (!STANDALONEBUILD) // Turn off codemarkers CodeMarkers.Instance.UninitializePerformanceDLL(CodeMarkerApp.MSBUILDPERF); #endif } /********************************************************************************************************************** * WARNING: Do NOT add any more catch blocks above! *********************************************************************************************************************/ return exitType; } #if (!STANDALONEBUILD) /// <summary> /// Use the Orcas Engine to build the project /// ############################################################################################# /// #### Segregated into another method to avoid loading the old Engine in the regular case. #### /// #### Do not move back in to the main code path! ############################################# /// ############################################################################################# /// We have marked this method as NoInlining because we do not want Microsoft.Build.Engine.dll to be loaded unless we really execute this code path /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private static ExitType OldOMBuildProject(ExitType exitType, string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, bool needToValidateProject, string schemaFile, int cpuCount) { // Log something to avoid confusion caused by errant environment variable sending us down here Console.WriteLine(AssemblyResources.GetString("Using35Engine")); Microsoft.Build.BuildEngine.BuildPropertyGroup oldGlobalProps = new Microsoft.Build.BuildEngine.BuildPropertyGroup(); // Copy over the global properties to the old OM foreach (KeyValuePair<string, string> globalProp in globalProperties) { oldGlobalProps.SetProperty(globalProp.Key, globalProp.Value); } if (!BuildProjectWithOldOM(projectFile, targets, toolsVersion, oldGlobalProps, loggers, verbosity, null, needToValidateProject, schemaFile, cpuCount)) { exitType = ExitType.BuildError; } return exitType; } #endif /// <summary> /// Handler for when CTRL-C or CTRL-BREAK is called. /// CTRL-BREAK means "die immediately" /// CTRL-C means "try to stop work and exit cleanly" /// </summary> private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { if (e.SpecialKey == ConsoleSpecialKey.ControlBreak) { e.Cancel = false; // required; the process will now be terminated rudely return; } e.Cancel = true; // do not terminate rudely bool alreadyCalled = (Interlocked.CompareExchange(ref s_receivedCancel, 1, 0) == 1); if (alreadyCalled) { return; } Console.WriteLine(ResourceUtilities.FormatResourceString("AbortingBuild")); // The OS takes a lock in // kernel32.dll!_SetConsoleCtrlHandler, so if a task // waits for that lock somehow before quitting, it would hang // because we're in it here. One way a task can end up here is // by calling Microsoft.Win32.SystemEvents.Initialize. // So do our work asynchronously so we can return immediately. // We're already on a threadpool thread anyway. WaitCallback callback = new WaitCallback( delegate (Object state) { s_cancelComplete.Reset(); // If the build is already complete, just exit. // Cannot use WaitOne(int) overload because it does not exist in BCL 3.5; this is equivalent if (s_buildComplete.WaitOne(0, false /* do not exit context */)) { s_cancelComplete.Set(); return; } // If the build has already started (or already finished), we will cancel it // If the build has not yet started, it will cancel itself, because // we set alreadyCalled=1 BuildSubmission result = null; lock (s_buildLock) { result = s_activeBuild; } if (result != null) { BuildManager.DefaultBuildManager.CancelAllSubmissions(); s_buildComplete.WaitOne(); } s_cancelComplete.Set(); // This will release our main Execute method so we can finally exit. }); ThreadPoolExtensions.QueueThreadPoolWorkItemWithCulture(callback, Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture); } /// <summary> /// Clears out any state accumulated from previous builds, and resets /// member data in preparation for a new build. /// </summary> private static void ResetBuildState() { s_includedResponseFiles = new ArrayList(); usingSwitchesFromAutoResponseFile = false; } /// <summary> /// The location of the application executable. /// </summary> /// <remarks> /// Initialized in the static constructor. See comment there. /// </remarks> private static readonly string s_exePath; // Do not initialize /// <summary> /// Name of the exe (presumably msbuild.exe) /// </summary> private static string s_exeName; /// <summary> /// Default name for the msbuild log file /// </summary> private const string msbuildLogFileName = "msbuild.log"; /// <summary> /// Initializes the build engine, and starts the project building. /// </summary> /// <returns>true, if build succeeds</returns> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Not going to refactor it right now")] internal static bool BuildProject ( string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, bool needToValidateProject, string schemaFile, int cpuCount, bool enableNodeReuse, TextWriter preprocessWriter, bool debugger, bool detailedSummary ) { if (String.Equals(Path.GetExtension(projectFile), ".vcproj", StringComparison.OrdinalIgnoreCase) || String.Equals(Path.GetExtension(projectFile), ".dsp", StringComparison.OrdinalIgnoreCase)) { InitializationException.Throw(ResourceUtilities.FormatResourceString("ProjectUpgradeNeededToVcxProj", projectFile), null); } bool success = false; ProjectCollection projectCollection = null; bool onlyLogCriticalEvents = false; try { List<ForwardingLoggerRecord> remoteLoggerRecords = new List<ForwardingLoggerRecord>(); foreach (DistributedLoggerRecord distRecord in distributedLoggerRecords) { remoteLoggerRecords.Add(new ForwardingLoggerRecord(distRecord.CentralLogger, distRecord.ForwardingLoggerDescription)); } // Targeted perf optimization for the case where we only have our own parallel console logger, and verbosity is quiet. In such a case // we know we won't emit any messages except for errors and warnings, so the engine should not bother even logging them. // If we're using the original serial console logger we can't do this, as it shows project started/finished context // around errors and warnings. // Telling the engine to not bother logging non-critical messages means that typically it can avoid loading any resources in the successful // build case. if (loggers.Length == 1 && remoteLoggerRecords.Count == 0 && verbosity == LoggerVerbosity.Quiet && loggers[0].Parameters != null && loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1 && loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1 && loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1 && // Console logger could have had a verbosity loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1) // override with the /clp switch { // Must be exactly the console logger, not a derived type like the file logger. Type t1 = loggers[0].GetType(); Type t2 = typeof(ConsoleLogger); if (t1 == t2) { onlyLogCriticalEvents = true; } } // HACK HACK: this enables task parameter logging. // This is a hack for now to make sure the perf hit only happens // on diagnostic. This should be changed to pipe it through properly, // perhaps as part of a fuller tracing feature. bool logTaskInputs = verbosity == LoggerVerbosity.Diagnostic; if (!logTaskInputs) { foreach (var logger in loggers) { if (logger.Parameters != null && (logger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || logger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) ) { logTaskInputs = true; break; } } } if (!logTaskInputs) { foreach (var logger in distributedLoggerRecords) { if (logger.CentralLogger != null) { if (logger.CentralLogger.Parameters != null && (logger.CentralLogger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || logger.CentralLogger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) ) { logTaskInputs = true; break; } } } } projectCollection = new ProjectCollection ( globalProperties, loggers, null, Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry, cpuCount, onlyLogCriticalEvents ); if (debugger) { // Debugging is not currently fully supported so we don't want to open // public API for it. Also, we want to have a way to make it work when running inside VS. // So use an environment variable. The undocumented /debug switch is just an easy way to set it. Environment.SetEnvironmentVariable("MSBUILDDEBUGGING", "1"); } if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, toolsVersion); } // If the user has requested that the schema be validated, do that here. if (needToValidateProject && !FileUtilities.IsSolutionFilename(projectFile)) { Microsoft.Build.Evaluation.Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion); Microsoft.Build.Evaluation.Toolset toolset = projectCollection.GetToolset((toolsVersion == null) ? project.ToolsVersion : toolsVersion); if (toolset == null) { ThrowInvalidToolsVersionInitializationException(projectCollection.Toolsets, project.ToolsVersion); } ProjectSchemaValidationHandler.VerifyProjectSchema(projectFile, schemaFile, toolset.ToolsPath); // If there are schema validation errors, an InitializationException is thrown, so if we get here, // we can safely assume that the project successfully validated. projectCollection.UnloadProject(project); } if (preprocessWriter != null && !FileUtilities.IsSolutionFilename(projectFile)) { Project project = projectCollection.LoadProject(projectFile, globalProperties, toolsVersion); project.SaveLogicalProject(preprocessWriter); projectCollection.UnloadProject(project); success = true; } else { BuildRequestData request = new BuildRequestData(projectFile, globalProperties, toolsVersion, targets, null); BuildParameters parameters = new BuildParameters(projectCollection); // By default we log synchronously to the console for compatibility with previous versions, // but it is slightly slower if (!String.Equals(Environment.GetEnvironmentVariable("MSBUILDLOGASYNC"), "1", StringComparison.Ordinal)) { parameters.UseSynchronousLogging = true; } parameters.EnableNodeReuse = enableNodeReuse; parameters.NodeExeLocation = Assembly.GetExecutingAssembly().Location; parameters.MaxNodeCount = cpuCount; parameters.Loggers = projectCollection.Loggers; parameters.ForwardingLoggers = remoteLoggerRecords; parameters.ToolsetDefinitionLocations = Microsoft.Build.Evaluation.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.Evaluation.ToolsetDefinitionLocations.Registry; parameters.DetailedSummary = detailedSummary; parameters.LogTaskInputs = logTaskInputs; if (!String.IsNullOrEmpty(toolsVersion)) { parameters.DefaultToolsVersion = toolsVersion; } string memoryUseLimit = Environment.GetEnvironmentVariable("MSBUILDMEMORYUSELIMIT"); if (!String.IsNullOrEmpty(memoryUseLimit)) { parameters.MemoryUseLimit = Convert.ToInt32(memoryUseLimit, CultureInfo.InvariantCulture); // The following ensures that when we divide the use by node count to get the per-limit amount, we always end up with a // positive value - otherwise setting it too low will result in a zero, which will enable only the default cache behavior // which is not what is intended by using this environment variable. if (parameters.MemoryUseLimit < parameters.MaxNodeCount) { parameters.MemoryUseLimit = parameters.MaxNodeCount; } } BuildManager buildManager = BuildManager.DefaultBuildManager; #if MSBUILDENABLEVSPROFILING DataCollection.CommentMarkProfile(8800, "Pending Build Request from MSBuild.exe"); #endif BuildResult results = null; buildManager.BeginBuild(parameters); Exception exception = null; try { try { lock (s_buildLock) { s_activeBuild = buildManager.PendBuildRequest(request); // Even if Ctrl-C was already hit, we still pend the build request and then cancel. // That's so the build does not appear to have completed successfully. if (s_receivedCancel == 1) { buildManager.CancelAllSubmissions(); } } results = s_activeBuild.Execute(); } finally { buildManager.EndBuild(); } } catch (Exception ex) { exception = ex; success = false; } if (results != null && exception == null) { success = results.OverallResult == BuildResultCode.Success; exception = results.Exception; } if (exception != null) { success = false; // InvalidProjectFileExceptions have already been logged. if (exception.GetType() != typeof(InvalidProjectFileException)) { if ( exception.GetType() == typeof(LoggerException) || exception.GetType() == typeof(InternalLoggerException) ) { // We will rethrow this so the outer exception handler can catch it, but we don't // want to log the outer exception stack here. throw exception; } if (exception.GetType() == typeof(BuildAbortedException)) { // this is not a bug and should not dump stack. It will already have been logged // appropriately, there is no need to take any further action with it. } else { // After throwing again below the stack will be reset. Make certain we log everything we // can now Console.WriteLine(AssemblyResources.GetString("FatalError")); #if DEBUG Console.WriteLine("This is an unhandled exception in MSBuild -- PLEASE OPEN A BUG AGAINST THE MSBUILD TEAM."); #endif Console.WriteLine(exception.ToString()); Console.WriteLine(); throw exception; } } } } } // handle project file errors catch (InvalidProjectFileException ex) { // just eat the exception because it has already been logged ErrorUtilities.VerifyThrow(ex.HasBeenLogged, "Should have been logged"); success = false; } finally { FileUtilities.ClearCacheDirectory(); if (projectCollection != null) { projectCollection.Dispose(); } BuildManager.DefaultBuildManager.Dispose(); } return success; } #if (!STANDALONEBUILD) /// <summary> /// Initializes the build engine, and starts the project build. /// Uses the Whidbey/Orcas object model. /// ############################################################################################# /// #### Segregated into another method to avoid loading the old Engine in the regular case. #### /// #### Do not move back in to the main code path! ############################################# /// ############################################################################################# /// We have marked this method as NoInlining because we do not want Microsoft.Build.Engine.dll to be loaded unless we really execute this code path /// </summary> /// <returns>true, if build succeeds</returns> [MethodImpl(MethodImplOptions.NoInlining)] private static bool BuildProjectWithOldOM(string projectFile, string[] targets, string toolsVersion, Microsoft.Build.BuildEngine.BuildPropertyGroup propertyBag, ILogger[] loggers, LoggerVerbosity verbosity, DistributedLoggerRecord[] distributedLoggerRecords, bool needToValidateProject, string schemaFile, int cpuCount) { string msbuildLocation = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MSBuildApp)).Location); string localNodeProviderParameters = "msbuildlocation=" + msbuildLocation; /*This assembly is the exe*/ ; localNodeProviderParameters += ";nodereuse=false"; Microsoft.Build.BuildEngine.Engine engine = new Microsoft.Build.BuildEngine.Engine(propertyBag, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations.ConfigurationFile | Microsoft.Build.BuildEngine.ToolsetDefinitionLocations.Registry, cpuCount, localNodeProviderParameters); bool success = false; try { foreach (ILogger logger in loggers) { engine.RegisterLogger(logger); } // Targeted perf optimization for the case where we only have our own parallel console logger, and verbosity is quiet. In such a case // we know we won't emit any messages except for errors and warnings, so the engine should not bother even logging them. // If we're using the original serial console logger we can't do this, as it shows project started/finished context // around errors and warnings. // Telling the engine to not bother logging non-critical messages means that typically it can avoid loading any resources in the successful // build case. if (loggers.Length == 1 && verbosity == LoggerVerbosity.Quiet && loggers[0].Parameters.IndexOf("ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) != -1 && loggers[0].Parameters.IndexOf("DISABLEMPLOGGING", StringComparison.OrdinalIgnoreCase) == -1 && loggers[0].Parameters.IndexOf("V=", StringComparison.OrdinalIgnoreCase) == -1 && // Console logger could have had a verbosity loggers[0].Parameters.IndexOf("VERBOSITY=", StringComparison.OrdinalIgnoreCase) == -1) // override with the /clp switch { // Must be exactly the console logger, not a derived type like the file logger. Type t1 = loggers[0].GetType(); Type t2 = typeof(ConsoleLogger); if (t1 == t2) { engine.OnlyLogCriticalEvents = true; } } Microsoft.Build.BuildEngine.Project project = null; try { project = new Microsoft.Build.BuildEngine.Project(engine, toolsVersion); } catch (InvalidOperationException e) { InitializationException.Throw("InvalidToolsVersionError", toolsVersion, e, false /*no stack*/); } project.IsValidated = needToValidateProject; project.SchemaFile = schemaFile; project.Load(projectFile); success = engine.BuildProject(project, targets); } // handle project file errors catch (InvalidProjectFileException) { // just eat the exception because it has already been logged } finally { // Unregister loggers and finish with engine engine.Shutdown(); } return success; } #endif /// <summary> /// Verifies that the code is running on a supported operating system. /// </summary> private static void VerifyThrowSupportedOS() { if ((Environment.OSVersion.Platform == PlatformID.Win32S) || // Win32S (Environment.OSVersion.Platform == PlatformID.Win32Windows) || // Windows 95, Windows 98, Windows ME (Environment.OSVersion.Platform == PlatformID.WinCE) || // Windows CE ((Environment.OSVersion.Platform == PlatformID.Win32NT) && // Windows NT 4.0 and earlier (Environment.OSVersion.Version.Major <= 4))) { // If we're running on any of the unsupported OS's, fail immediately. This way, // we don't run into some obscure error down the line, totally confusing the user. InitializationException.VerifyThrow(false, "UnsupportedOS"); } } /// <summary> /// MSBuild.exe need to fallback to English if it cannot print Japanese (or other language) characters /// </summary> internal static void SetConsoleUI() { Thread thisThread = Thread.CurrentThread; // Eliminate the complex script cultures from the language selection. thisThread.CurrentUICulture = CultureInfo.CurrentUICulture.GetConsoleFallbackUICulture(); // Determine if the language can be displayed in the current console codepage, otherwise set to US English int codepage; try { codepage = System.Console.OutputEncoding.CodePage; } catch (NotSupportedException) { // Failed to get code page: some customers have hit this and we don't know why thisThread.CurrentUICulture = new CultureInfo("en-US"); return; } if ( codepage != 65001 // 65001 is Unicode && codepage != thisThread.CurrentUICulture.TextInfo.OEMCodePage && codepage != thisThread.CurrentUICulture.TextInfo.ANSICodePage ) { thisThread.CurrentUICulture = new CultureInfo("en-US"); } } /// <summary> /// Gets all specified switches, from the command line, as well as all /// response files, including the auto-response file. /// </summary> /// <param name="commandLine"></param> /// <returns>Combined bag of switches.</returns> private static void GatherAllSwitches(string commandLine, out CommandLineSwitches switchesFromAutoResponseFile, out CommandLineSwitches switchesNotFromAutoResponseFile) { // split the command line on (unquoted) whitespace ArrayList commandLineArgs = QuotingUtilities.SplitUnquoted(commandLine); // discard the first piece, because that's the path to the executable -- the rest are args s_exeName = QuotingUtilities.Unquote((string)commandLineArgs[0]); if (!s_exeName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { s_exeName += ".exe"; } commandLineArgs.RemoveAt(0); // parse the command line, and flag syntax errors and obvious switch errors switchesNotFromAutoResponseFile = new CommandLineSwitches(); GatherCommandLineSwitches(commandLineArgs, switchesNotFromAutoResponseFile); // parse the auto-response file (if "/noautoresponse" is not specified), and combine those switches with the // switches on the command line switchesFromAutoResponseFile = new CommandLineSwitches(); if (!switchesNotFromAutoResponseFile[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse]) { GatherAutoResponseFileSwitches(s_exePath, switchesFromAutoResponseFile); } } /// <summary> /// Coordinates the parsing of the command line. It detects switches on the command line, gathers their parameters, and /// flags syntax errors, and other obvious switch errors. /// </summary> /// <remarks> /// Internal for unit testing only. /// </remarks> internal static void GatherCommandLineSwitches(ArrayList commandLineArgs, CommandLineSwitches commandLineSwitches) { foreach (string commandLineArg in commandLineArgs) { int doubleQuotesRemovedFromArg; string unquotedCommandLineArg = QuotingUtilities.Unquote(commandLineArg, out doubleQuotesRemovedFromArg); if (unquotedCommandLineArg.Length > 0) { // response file switch starts with @ if (unquotedCommandLineArg.StartsWith("@", StringComparison.Ordinal)) { GatherResponseFileSwitch(unquotedCommandLineArg, commandLineSwitches); } else { string switchName; string switchParameters; // all switches should start with - or / unless a project is being specified if (!unquotedCommandLineArg.StartsWith("-", StringComparison.Ordinal) && !unquotedCommandLineArg.StartsWith("/", StringComparison.Ordinal)) { switchName = null; // add a (fake) parameter indicator for later parsing switchParameters = ":" + commandLineArg; } else { // check if switch has parameters (look for the : parameter indicator) int switchParameterIndicator = unquotedCommandLineArg.IndexOf(':'); // extract the switch name and parameters -- the name is sandwiched between the switch indicator (the // leading - or /) and the parameter indicator (if the switch has parameters); the parameters (if any) // follow the parameter indicator if (switchParameterIndicator == -1) { switchName = unquotedCommandLineArg.Substring(1); switchParameters = String.Empty; } else { switchName = unquotedCommandLineArg.Substring(1, switchParameterIndicator - 1); switchParameters = ExtractSwitchParameters(commandLineArg, unquotedCommandLineArg, doubleQuotesRemovedFromArg, switchName, switchParameterIndicator); } } CommandLineSwitches.ParameterlessSwitch parameterlessSwitch; CommandLineSwitches.ParameterizedSwitch parameterizedSwitch; string duplicateSwitchErrorMessage; bool multipleParametersAllowed; string missingParametersErrorMessage; bool unquoteParameters; // Special case: for the switch "/m" or "/maxCpuCount" we wish to pretend we saw "/m:<number of cpus>" // This allows a subsequent /m:n on the command line to override it. // We could create a new kind of switch with optional parameters, but it's a great deal of churn for this single case. // Note that if no "/m" or "/maxCpuCount" switch -- either with or without parameters -- is present, then we still default to 1 cpu // for backwards compatibility. if (String.IsNullOrEmpty(switchParameters)) { if (String.Equals(switchName, "m", StringComparison.OrdinalIgnoreCase) || String.Equals(switchName, "maxcpucount", StringComparison.OrdinalIgnoreCase)) { int numberOfCpus = Environment.ProcessorCount; switchParameters = ":" + numberOfCpus; } } if (CommandLineSwitches.IsParameterlessSwitch(switchName, out parameterlessSwitch, out duplicateSwitchErrorMessage)) { GatherParameterlessCommandLineSwitch(commandLineSwitches, parameterlessSwitch, switchParameters, duplicateSwitchErrorMessage, unquotedCommandLineArg); } else if (CommandLineSwitches.IsParameterizedSwitch(switchName, out parameterizedSwitch, out duplicateSwitchErrorMessage, out multipleParametersAllowed, out missingParametersErrorMessage, out unquoteParameters)) { GatherParameterizedCommandLineSwitch(commandLineSwitches, parameterizedSwitch, switchParameters, duplicateSwitchErrorMessage, multipleParametersAllowed, missingParametersErrorMessage, unquoteParameters, unquotedCommandLineArg); } else { commandLineSwitches.SetUnknownSwitchError(unquotedCommandLineArg); } } } } } /// <summary> /// Extracts a switch's parameters after processing all quoting around the switch. /// </summary> /// <remarks> /// This method is marked "internal" for unit-testing purposes only -- ideally it should be "private". /// </remarks> /// <param name="commandLineArg"></param> /// <param name="unquotedCommandLineArg"></param> /// <param name="doubleQuotesRemovedFromArg"></param> /// <param name="switchName"></param> /// <param name="switchParameterIndicator"></param> /// <returns>The given switch's parameters (with interesting quoting preserved).</returns> internal static string ExtractSwitchParameters ( string commandLineArg, string unquotedCommandLineArg, int doubleQuotesRemovedFromArg, string switchName, int switchParameterIndicator ) { string switchParameters = null; // find the parameter indicator again using the quoted arg // NOTE: since the parameter indicator cannot be part of a switch name, quoting around it is not relevant, because a // parameter indicator cannot be escaped or made into a literal int quotedSwitchParameterIndicator = commandLineArg.IndexOf(':'); // check if there is any quoting in the name portion of the switch int doubleQuotesRemovedFromSwitchIndicatorAndName; string unquotedSwitchIndicatorAndName = QuotingUtilities.Unquote(commandLineArg.Substring(0, quotedSwitchParameterIndicator), out doubleQuotesRemovedFromSwitchIndicatorAndName); ErrorUtilities.VerifyThrow(switchName == unquotedSwitchIndicatorAndName.Substring(1), "The switch name extracted from either the partially or completely unquoted arg should be the same."); ErrorUtilities.VerifyThrow(doubleQuotesRemovedFromArg >= doubleQuotesRemovedFromSwitchIndicatorAndName, "The name portion of the switch cannot contain more quoting than the arg itself."); // if quoting in the name portion of the switch was terminated if ((doubleQuotesRemovedFromSwitchIndicatorAndName % 2) == 0) { // get the parameters exactly as specified on the command line i.e. including quoting switchParameters = commandLineArg.Substring(quotedSwitchParameterIndicator); } else { // if quoting was not terminated in the name portion of the switch, and the terminal double-quote (if any) // terminates the switch parameters int terminalDoubleQuote = commandLineArg.IndexOf('"', quotedSwitchParameterIndicator + 1); if (((doubleQuotesRemovedFromArg - doubleQuotesRemovedFromSwitchIndicatorAndName) <= 1) && ((terminalDoubleQuote == -1) || (terminalDoubleQuote == (commandLineArg.Length - 1)))) { // then the parameters are not quoted in any interesting way, so use the unquoted parameters switchParameters = unquotedCommandLineArg.Substring(switchParameterIndicator); } else { // otherwise, use the quoted parameters, after compensating for the quoting that was started in the name // portion of the switch switchParameters = ":\"" + commandLineArg.Substring(quotedSwitchParameterIndicator + 1); } } ErrorUtilities.VerifyThrow(switchParameters != null, "We must be able to extract the switch parameters."); return switchParameters; } /// <summary> /// Used to keep track of response files to prevent them from /// being included multiple times (or even recursively). /// </summary> private static ArrayList s_includedResponseFiles; /// <summary> /// Called when a response file switch is detected on the command line. It loads the specified response file, and parses /// each line in it like a command line. It also prevents multiple (or recursive) inclusions of the same response file. /// </summary> /// <param name="unquotedCommandLineArg"></param> /// <param name="commandLineSwitches"></param> private static void GatherResponseFileSwitch(string unquotedCommandLineArg, CommandLineSwitches commandLineSwitches) { try { string responseFile = unquotedCommandLineArg.Substring(1); if (responseFile.Length == 0) { commandLineSwitches.SetSwitchError("MissingResponseFileError", unquotedCommandLineArg); } else if (!File.Exists(responseFile)) { commandLineSwitches.SetParameterError("ResponseFileNotFoundError", unquotedCommandLineArg); } else { // normalize the response file path to help catch multiple (or recursive) inclusions responseFile = Path.GetFullPath(responseFile); // NOTE: for network paths or mapped paths, normalization is not guaranteed to work bool isRepeatedResponseFile = false; foreach (string includedResponseFile in s_includedResponseFiles) { if (String.Compare(responseFile, includedResponseFile, StringComparison.OrdinalIgnoreCase) == 0) { commandLineSwitches.SetParameterError("RepeatedResponseFileError", unquotedCommandLineArg); isRepeatedResponseFile = true; break; } } if (!isRepeatedResponseFile) { s_includedResponseFiles.Add(responseFile); ArrayList argsFromResponseFile; using (StreamReader responseFileContents = new StreamReader(responseFile, Encoding.Default)) // HIGHCHAR: If response files have no byte-order marks, then assume ANSI rather than ASCII. { argsFromResponseFile = new ArrayList(); while (responseFileContents.Peek() != -1) { // ignore leading whitespace on each line string responseFileLine = responseFileContents.ReadLine().TrimStart(); // skip comment lines beginning with # if (!responseFileLine.StartsWith("#", StringComparison.Ordinal)) { // treat each line of the response file like a command line i.e. args separated by whitespace argsFromResponseFile.AddRange(QuotingUtilities.SplitUnquoted(Environment.ExpandEnvironmentVariables(responseFileLine))); } } } GatherCommandLineSwitches(argsFromResponseFile, commandLineSwitches); } } } catch (NotSupportedException e) { commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, e); } catch (SecurityException e) { commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, e); } catch (UnauthorizedAccessException e) { commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, e); } catch (IOException e) { commandLineSwitches.SetParameterError("ReadResponseFileError", unquotedCommandLineArg, e); } } /// <summary> /// Called when a switch that doesn't take parameters is detected on the command line. /// </summary> /// <param name="commandLineSwitches"></param> /// <param name="parameterlessSwitch"></param> /// <param name="switchParameters"></param> /// <param name="duplicateSwitchErrorMessage"></param> /// <param name="unquotedCommandLineArg"></param> private static void GatherParameterlessCommandLineSwitch ( CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, string switchParameters, string duplicateSwitchErrorMessage, string unquotedCommandLineArg ) { // switch should not have any parameters if (switchParameters.Length == 0) { // check if switch is duplicated, and if that's allowed if (!commandLineSwitches.IsParameterlessSwitchSet(parameterlessSwitch) || (duplicateSwitchErrorMessage == null)) { commandLineSwitches.SetParameterlessSwitch(parameterlessSwitch, unquotedCommandLineArg); } else { commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg); } } else { commandLineSwitches.SetUnexpectedParametersError(unquotedCommandLineArg); } } /// <summary> /// Called when a switch that takes parameters is detected on the command line. This method flags errors and stores the /// switch parameters. /// </summary> /// <param name="commandLineSwitches"></param> /// <param name="parameterizedSwitch"></param> /// <param name="switchParameters"></param> /// <param name="duplicateSwitchErrorMessage"></param> /// <param name="multipleParametersAllowed"></param> /// <param name="missingParametersErrorMessage"></param> /// <param name="unquoteParameters"></param> /// <param name="unquotedCommandLineArg"></param> private static void GatherParameterizedCommandLineSwitch ( CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterizedSwitch parameterizedSwitch, string switchParameters, string duplicateSwitchErrorMessage, bool multipleParametersAllowed, string missingParametersErrorMessage, bool unquoteParameters, string unquotedCommandLineArg ) { if (// switch must have parameters (switchParameters.Length > 1) || // unless the parameters are optional (missingParametersErrorMessage == null)) { // check if switch is duplicated, and if that's allowed if (!commandLineSwitches.IsParameterizedSwitchSet(parameterizedSwitch) || (duplicateSwitchErrorMessage == null)) { // skip the parameter indicator (if any) if (switchParameters.Length > 0) { switchParameters = switchParameters.Substring(1); } // save the parameters after unquoting and splitting them if necessary if (!commandLineSwitches.SetParameterizedSwitch(parameterizedSwitch, unquotedCommandLineArg, switchParameters, multipleParametersAllowed, unquoteParameters)) { // if parsing revealed there were no real parameters, flag an error, unless the parameters are optional if (missingParametersErrorMessage != null) { commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg); } } } else { commandLineSwitches.SetSwitchError(duplicateSwitchErrorMessage, unquotedCommandLineArg); } } else { commandLineSwitches.SetSwitchError(missingParametersErrorMessage, unquotedCommandLineArg); } } /// <summary> /// The name of the auto-response file. /// </summary> private const string autoResponseFileName = "MSBuild.rsp"; /// <summary> /// Whether switches from the auto-response file are being used. /// </summary> internal static bool usingSwitchesFromAutoResponseFile = false; /// <summary> /// Parses the auto-response file (assumes the "/noautoresponse" switch is not specified on the command line), and combines the /// switches from the auto-response file with the switches passed in. /// Returns true if the response file was found. /// </summary> private static bool GatherAutoResponseFileSwitches(string path, CommandLineSwitches switchesFromAutoResponseFile) { string autoResponseFile = Path.Combine(path, autoResponseFileName); bool found = false; // if the auto-response file does not exist, only use the switches on the command line if (File.Exists(autoResponseFile)) { found = true; GatherResponseFileSwitch("@" + autoResponseFile, switchesFromAutoResponseFile); // if the "/noautoresponse" switch was set in the auto-response file, flag an error if (switchesFromAutoResponseFile[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse]) { switchesFromAutoResponseFile.SetSwitchError("CannotAutoDisableAutoResponseFile", switchesFromAutoResponseFile.GetParameterlessSwitchCommandLineArg(CommandLineSwitches.ParameterlessSwitch.NoAutoResponse)); } if (switchesFromAutoResponseFile.HaveAnySwitchesBeenSet()) { // we picked up some switches from the auto-response file usingSwitchesFromAutoResponseFile = true; } } return found; } /// <summary> /// Coordinates the processing of all detected switches. It gathers information necessary to invoke the build engine, and /// performs deeper error checking on the switches and their parameters. /// </summary> /// <returns>true, if build can be invoked</returns> private static bool ProcessCommandLineSwitches ( CommandLineSwitches switchesFromAutoResponseFile, CommandLineSwitches switchesNotFromAutoResponseFile, ref string projectFile, ref string[] targets, ref string toolsVersion, ref Dictionary<string, string> globalProperties, ref ILogger[] loggers, ref LoggerVerbosity verbosity, ref List<DistributedLoggerRecord> distributedLoggerRecords, ref bool needToValidateProject, ref string schemaFile, ref int cpuCount, ref bool enableNodeReuse, ref TextWriter preprocessWriter, ref bool debugger, ref bool detailedSummary, bool recursing ) { bool invokeBuild = false; // combine the auto-response file switches with the command line switches in a left-to-right manner, where the // auto-response file switches are on the left (default options), and the command line switches are on the // right (overriding options) so that we consume switches in the following sequence of increasing priority: // (1) switches from the msbuild.rsp file/s, including recursively included response files // (2) switches from the command line, including recursively included response file switches inserted at the point they are declared with their "@" symbol CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); commandLineSwitches.Append(switchesFromAutoResponseFile); // lowest precedence commandLineSwitches.Append(switchesNotFromAutoResponseFile); // show copyright message if nologo switch is not set // NOTE: we heed the nologo switch even if there are switch errors if (!recursing && !commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoLogo] && !commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Preprocess)) { DisplayCopyrightMessage(); } // if help switch is set (regardless of switch errors), show the help message and ignore the other switches if (commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.Help]) { ShowHelpMessage(); } else if (commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.NodeMode)) { StartLocalNode(commandLineSwitches); } else { // if help switch is not set, and errors were found, abort (don't process the remaining switches) commandLineSwitches.ThrowErrors(); // if version switch is set, just show the version and quit (ignore the other switches) if (commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.Version]) { ShowVersion(); } else { // figure out what project we are building projectFile = ProcessProjectSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Project], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.IgnoreProjectExtensions], Directory.GetFiles); if (!recursing && !commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoAutoResponse]) { // gather any switches from an msbuild.rsp that is next to the project or solution file itself string projectDirectory = Path.GetDirectoryName(Path.GetFullPath(projectFile)); bool found = false; // Don't look for more response files if it's only in the same place we already looked (next to the exe) if (!String.Equals(projectDirectory, s_exePath, StringComparison.OrdinalIgnoreCase)) { // this combines any found, with higher precedence, with the switches from the original auto response file switches found = GatherAutoResponseFileSwitches(projectDirectory, switchesFromAutoResponseFile); } if (found) { // we presumably read in more switches, so start our switch processing all over again, // so that we consume switches in the following sequence of increasing priority: // (1) switches from the msbuild.rsp next to msbuild.exe, including recursively included response files // (2) switches from this msbuild.rsp next to the project or solution <<--------- these we have just now merged with (1) // (3) switches from the command line, including recursively included response file switches inserted at the point they are declared with their "@" symbol return ProcessCommandLineSwitches( switchesFromAutoResponseFile, switchesNotFromAutoResponseFile, ref projectFile, ref targets, ref toolsVersion, ref globalProperties, ref loggers, ref verbosity, ref distributedLoggerRecords, ref needToValidateProject, ref schemaFile, ref cpuCount, ref enableNodeReuse, ref preprocessWriter, ref debugger, ref detailedSummary, recursing: true ); } } // figure out which targets we are building targets = ProcessTargetSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Target]); // figure out which ToolsVersion has been set on the command line toolsVersion = ProcessToolsVersionSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ToolsVersion]); // figure out which properties have been set on the command line globalProperties = ProcessPropertySwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Property]); // figure out if there was a max cpu count provided cpuCount = ProcessMaxCPUCountSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.MaxCPUCount]); // figure out if we shold reuse nodes enableNodeReuse = ProcessNodeReuseSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.NodeReuse]); // determine what if any writer to preprocess to preprocessWriter = null; if (commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Preprocess)) { preprocessWriter = ProcessPreprocessSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Preprocess]); } #if FEATURE_MSBUILD_DEBUGGER debugger = commandLineSwitches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.Debugger); #endif detailedSummary = commandLineSwitches.IsParameterlessSwitchSet(CommandLineSwitches.ParameterlessSwitch.DetailedSummary); // figure out which loggers are going to listen to build events string[][] groupedFileLoggerParameters = commandLineSwitches.GetFileLoggerParameters(); loggers = ProcessLoggingSwitches( commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Logger], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.DistributedLogger], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Verbosity], commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger], commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters], // used by DistributedFileLogger commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ConsoleLoggerParameters], groupedFileLoggerParameters, out distributedLoggerRecords, out verbosity, ref detailedSummary, cpuCount ); // If we picked up switches from the autoreponse file, let the user know. This could be a useful // hint to a user that does not know that we are picking up the file automatically. // Since this is going to happen often in normal use, only log it in high verbosity mode. // Also, only log it to the console; logging to loggers would involve increasing the public API of // the Engine, and we don't want to do that. if (usingSwitchesFromAutoResponseFile && LoggerVerbosity.Diagnostic == verbosity) { Console.WriteLine(ResourceUtilities.FormatResourceString("PickedUpSwitchesFromAutoResponse", autoResponseFileName)); } if (verbosity == LoggerVerbosity.Diagnostic) { string equivalentCommandLine = commandLineSwitches.GetEquivalentCommandLineExceptProjectFile(); Console.WriteLine(Path.Combine(s_exePath, s_exeName) + " " + equivalentCommandLine + " " + projectFile); } // figure out if the project needs to be validated against a schema needToValidateProject = commandLineSwitches.IsParameterizedSwitchSet(CommandLineSwitches.ParameterizedSwitch.Validate); schemaFile = ProcessValidateSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Validate]); invokeBuild = true; } } ErrorUtilities.VerifyThrow(!invokeBuild || !String.IsNullOrEmpty(projectFile), "We should have a project file if we're going to build."); return invokeBuild; } /// <summary> /// Processes the node reuse switch, the user can set node reuse to true, false or not set the switch. If the switch is /// not set the system will check to see if the process is being run as an administrator. This check in localnode provider /// will determine the node reuse setting for that case. /// </summary> internal static bool ProcessNodeReuseSwitch(string[] parameters) { bool enableNodeReuse = true; if (Environment.GetEnvironmentVariable("MSBUILDDISABLENODEREUSE") == "1") // For example to disable node reuse in a gated checkin, without using the flag { enableNodeReuse = false; } if (parameters.Length > 0) { try { // There does not seem to be a localizable function for this enableNodeReuse = bool.Parse(parameters[parameters.Length - 1]); } catch (FormatException ex) { CommandLineSwitchException.Throw("InvalidNodeReuseValue", parameters[parameters.Length - 1], ex.Message); } catch (ArgumentNullException ex) { CommandLineSwitchException.Throw("InvalidNodeReuseValue", parameters[parameters.Length - 1], ex.Message); } } return enableNodeReuse; } /// <summary> /// Figure out what TextWriter we should preprocess the project file to. /// If no parameter is provided to the switch, the default is to output to the console. /// </summary> internal static TextWriter ProcessPreprocessSwitch(string[] parameters) { TextWriter writer = Console.Out; if (parameters.Length > 0) { try { writer = new StreamWriter(parameters[parameters.Length - 1]); } catch (Exception ex) { if (ExceptionHandling.NotExpectedException(ex)) { throw; } CommandLineSwitchException.Throw("InvalidPreprocessPath", parameters[parameters.Length - 1], ex.Message); } } return writer; } /// <summary> /// Uses the input from thinNodeMode switch to start a local node server /// </summary> /// <param name="commandLineSwitches"></param> private static void StartLocalNode(CommandLineSwitches commandLineSwitches) { string[] input = commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.NodeMode]; int nodeModeNumber = 0; if (input.Length > 0) { try { nodeModeNumber = int.Parse(input[0], CultureInfo.InvariantCulture); } catch (FormatException ex) { CommandLineSwitchException.Throw("InvalidNodeNumberValue", input[0], ex.Message); } catch (OverflowException ex) { CommandLineSwitchException.Throw("InvalidNodeNumberValue", input[0], ex.Message); } CommandLineSwitchException.VerifyThrow(nodeModeNumber >= 0, "InvalidNodeNumberValueIsNegative", input[0]); } #if !STANDALONEBUILD if (!commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.OldOM]) #endif { bool restart = true; while (restart) { Exception nodeException = null; NodeEngineShutdownReason shutdownReason = NodeEngineShutdownReason.Error; // normal OOP node case if (nodeModeNumber == 1) { OutOfProcNode node = new OutOfProcNode(); shutdownReason = node.Run(ProcessNodeReuseSwitch(commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.NodeReuse]), out nodeException); FileUtilities.ClearCacheDirectory(); } else if (nodeModeNumber == 2) { OutOfProcTaskHostNode node = new OutOfProcTaskHostNode(); shutdownReason = node.Run(out nodeException); } else { CommandLineSwitchException.Throw("InvalidNodeNumberValue", input[0]); } if (shutdownReason == NodeEngineShutdownReason.Error) { Debug.WriteLine("An error has happened, throwing an exception"); throw nodeException; } if (shutdownReason != NodeEngineShutdownReason.BuildCompleteReuse) { restart = false; } } } #if !STANDALONEBUILD else { StartLocalNodeOldOM(nodeModeNumber); } #endif } #if !STANDALONEBUILD /// <summary> /// Start an old-OM local node /// </summary> /// <remarks> /// ############################################################################################# /// #### Segregated into another method to avoid loading the old Engine in the regular case. #### /// #### Do not move back in to the main code path! ############################################# /// ############################################################################################# /// We have marked this method as NoInlining because we do not want Microsoft.Build.Engine.dll to be loaded unless we really execute this code path /// </remarks> [MethodImpl(MethodImplOptions.NoInlining)] private static void StartLocalNodeOldOM(int nodeNumber) { Microsoft.Build.BuildEngine.LocalNode.StartLocalNodeServer(nodeNumber); } #endif /// <summary> /// Process the /m: switch giving the CPU count /// </summary> /// <remarks> /// Internal for unit testing only /// </remarks> internal static int ProcessMaxCPUCountSwitch(string[] parameters) { int cpuCount = 1; if (parameters.Length > 0) { try { cpuCount = int.Parse(parameters[parameters.Length - 1], CultureInfo.InvariantCulture); } catch (FormatException ex) { CommandLineSwitchException.Throw("InvalidMaxCPUCountValue", parameters[parameters.Length - 1], ex.Message); } catch (OverflowException ex) { CommandLineSwitchException.Throw("InvalidMaxCPUCountValue", parameters[parameters.Length - 1], ex.Message); } CommandLineSwitchException.VerifyThrow(cpuCount > 0 && cpuCount <= 1024, "InvalidMaxCPUCountValueOutsideRange", parameters[parameters.Length - 1]); } return cpuCount; } /// <summary> /// Figures out what project to build. /// Throws if it cannot figure it out. /// </summary> /// <param name="parameters"></param> /// <returns>The project filename/path.</returns> /// Internal for testing purposes internal static string ProcessProjectSwitch ( string[] parameters, string[] projectsExtensionsToIgnore, DirectoryGetFiles getFiles ) { ErrorUtilities.VerifyThrow(parameters.Length <= 1, "It should not be possible to specify more than 1 project at a time."); string projectFile = null; // We need to look in the current directory for a project file... if (parameters.Length == 0) { // Get all files in the current directory that have a proj-like extension string[] potentialProjectFiles = getFiles(".", "*.*proj"); // Get all files in the current directory that have a sln extension string[] potentialSolutionFiles = getFiles(".", "*.sln"); List<string> extensionsToIgnore = new List<string>(); if (projectsExtensionsToIgnore != null) { extensionsToIgnore.AddRange(projectsExtensionsToIgnore); } if (potentialProjectFiles != null) { foreach (string s in potentialProjectFiles) { if (s.EndsWith("~", true, CultureInfo.CurrentCulture)) { extensionsToIgnore.Add(Path.GetExtension(s)); } } } if (potentialSolutionFiles != null) { foreach (string s in potentialSolutionFiles) { if (!FileUtilities.IsSolutionFilename(s)) { extensionsToIgnore.Add(Path.GetExtension(s)); } } } Dictionary<string, object> extensionsToIgnoreDictionary = ValidateExtensions(extensionsToIgnore.ToArray()); // Remove projects that are in the projectExtensionsToIgnore List // If we have no extensions to ignore we can skip removing any extensions if (extensionsToIgnoreDictionary.Count > 0) { // No point removing extensions if we have no project files if (potentialProjectFiles != null && potentialProjectFiles.Length > 0) { potentialProjectFiles = RemoveFilesWithExtensionsToIgnore(potentialProjectFiles, extensionsToIgnoreDictionary); } // No point removing extensions if we have no solutions if (potentialSolutionFiles != null && potentialSolutionFiles.Length > 0) { potentialSolutionFiles = RemoveFilesWithExtensionsToIgnore(potentialSolutionFiles, extensionsToIgnoreDictionary); } } // If there is exactly 1 project file and exactly 1 solution file if ((potentialProjectFiles.Length == 1) && (potentialSolutionFiles.Length == 1)) { // Grab the name of both project and solution without extensions string solutionName = Path.GetFileNameWithoutExtension(potentialSolutionFiles[0]); string projectName = Path.GetFileNameWithoutExtension(potentialProjectFiles[0]); // Compare the names and error if they are not identical InitializationException.VerifyThrow(String.Compare(solutionName, projectName, StringComparison.OrdinalIgnoreCase) == 0, "AmbiguousProjectError"); } // If there is more than one solution file in the current directory we have no idea which one to use else if (potentialSolutionFiles.Length > 1) { InitializationException.VerifyThrow(false, "AmbiguousProjectError"); } // If there is more than one project file in the current directory we may be able to figure it out else if (potentialProjectFiles.Length > 1) { // We have more than one project, it is ambiguous at the moment bool isAmbiguousProject = true; // If there are exactly two projects and one of them is a .proj use that one and ignore the other if (potentialProjectFiles.Length == 2) { string firstPotentialProjectExtension = Path.GetExtension(potentialProjectFiles[0]); string secondPotentialProjectExtension = Path.GetExtension(potentialProjectFiles[1]); // If the two projects have the same extension we can't decide which one to pick if (String.Compare(firstPotentialProjectExtension, secondPotentialProjectExtension, StringComparison.OrdinalIgnoreCase) != 0) { // Check to see if the first project is the proj, if it is use it if (String.Compare(firstPotentialProjectExtension, ".proj", StringComparison.OrdinalIgnoreCase) == 0) { potentialProjectFiles = new string[] { potentialProjectFiles[0] }; // We have made a decision isAmbiguousProject = false; } // If the first project is not the proj check to see if the second one is the proj, if so use it else if (String.Compare(secondPotentialProjectExtension, ".proj", StringComparison.OrdinalIgnoreCase) == 0) { potentialProjectFiles = new string[] { potentialProjectFiles[1] }; // We have made a decision isAmbiguousProject = false; } } } InitializationException.VerifyThrow(!isAmbiguousProject, "AmbiguousProjectError"); } // if there are no project or solution files in the directory, we can't build else if ((potentialProjectFiles.Length == 0) && (potentialSolutionFiles.Length == 0)) { InitializationException.VerifyThrow(false, "MissingProjectError"); } // We are down to only one project or solution. // If only 1 solution build the solution. If only 1 project build the project // If 1 solution and 1 project and they are of the same name build the solution projectFile = (potentialSolutionFiles.Length == 1) ? potentialSolutionFiles[0] : potentialProjectFiles[0]; } else { InitializationException.VerifyThrow(File.Exists(parameters[0]), "ProjectNotFoundError", parameters[0]); projectFile = parameters[0]; } return projectFile; } /// <summary> /// This method takes in a list of file name extensions to ignore. It will then validate the extensions /// to make sure they start with a period, have atleast one character after the period and do not contain /// any invalid path chars or wild cards /// </summary> /// <param name="projectsExtensionsToIgnore"></param> /// <returns></returns> private static Dictionary<string, object> ValidateExtensions(string[] projectsExtensionsToIgnore) { // Dictionary to contain the list of files which match the extensions to ignore. We are using a dictionary for fast lookups of extensions to ignore Dictionary<string, object> extensionsToIgnoreDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); // Go through each of the extensions to ignore and add them as a key in the dictionary if (projectsExtensionsToIgnore != null && projectsExtensionsToIgnore.Length > 0) { string extension = null; foreach (string extensionToIgnore in projectsExtensionsToIgnore) { // Use the path get extension method to figure out if there is an extension in the passed // in extension to ignore. Will return null or empty if there is no extension in the string try { // Use GetExtension to parse the extension from the extensionToIgnore extension = Path.GetExtension(extensionToIgnore); } catch (ArgumentException) { // There has been an invalid char in the extensionToIgnore InitializationException.Throw("InvalidExtensionToIgnore", extensionToIgnore, null, false); } // if null or empty is returned that means that there was not extension able to be parsed from the string InitializationException.VerifyThrow(!string.IsNullOrEmpty(extension), "InvalidExtensionToIgnore", extensionToIgnore); // There has to be more than a . passed in as the extension InitializationException.VerifyThrow(extension.Length >= 2, "InvalidExtensionToIgnore", extensionToIgnore); // The parsed extension does not match the passed in extension, this means that there were // some other chars before the last extension if (string.Compare(extension, extensionToIgnore, StringComparison.OrdinalIgnoreCase) != 0) { InitializationException.Throw("InvalidExtensionToIgnore", extensionToIgnore, null, false); } // Make sure that no wild cards are in the string because for now we dont allow wild card extensions if (extensionToIgnore.IndexOfAny(s_wildcards) > -1) { InitializationException.Throw("InvalidExtensionToIgnore", extensionToIgnore, null, false); }; if (!extensionsToIgnoreDictionary.ContainsKey(extensionToIgnore)) { extensionsToIgnoreDictionary.Add(extensionToIgnore, null); } } } return extensionsToIgnoreDictionary; } /// <summary> /// Removes filenames from the given list whose extensions are on the list of extensions to ignore /// </summary> /// <param name="potentialProjectOrSolutionFiles">A list of project or solution file names</param> /// <param name="extensionsToIgnore">A list of extensions to ignore</param> /// <returns>Array of project or solution files names which do not have an extension to be ignored </returns> private static string[] RemoveFilesWithExtensionsToIgnore ( string[] potentialProjectOrSolutionFiles, Dictionary<string, object> extensionsToIgnoreDictionary ) { // If we got to this method we should have to possible projects or solutions and some extensions to ignore ErrorUtilities.VerifyThrow(((potentialProjectOrSolutionFiles != null) && (potentialProjectOrSolutionFiles.Length > 0)), "There should be some potential project or solution files"); ErrorUtilities.VerifyThrow(((extensionsToIgnoreDictionary != null) && (extensionsToIgnoreDictionary.Count > 0)), "There should be some extensions to Ignore"); List<string> filesToKeep = new List<string>(); foreach (string projectOrSolutionFile in potentialProjectOrSolutionFiles) { string extension = Path.GetExtension(projectOrSolutionFile); // Check to see if the file extension of the project is in our ignore list. If not keep the file if (!extensionsToIgnoreDictionary.ContainsKey(extension)) { filesToKeep.Add(projectOrSolutionFile); } } return filesToKeep.ToArray(); } /// <summary> /// Figures out which targets are to be built. /// </summary> /// <param name="parameters"></param> /// <returns>List of target names.</returns> private static string[] ProcessTargetSwitch(string[] parameters) { return parameters; } /// <summary> /// The = sign is used to pair properties with their values on the command line. /// </summary> private static readonly char[] s_propertyValueSeparator = { '=' }; /// <summary> /// This is a set of wildcard chars which can cause a file extension to be invalid /// </summary> private static readonly char[] s_wildcards = { '*', '?' }; /// <summary> /// Determines which ToolsVersion was specified on the command line. If more than /// one ToolsVersion was specified, we honor only the final ToolsVersion. /// </summary> /// <param name="parameters"></param> /// <returns></returns> private static string ProcessToolsVersionSwitch(string[] parameters) { if (parameters.Length > 0) { // We don't do any validation on the value of the ToolsVersion here, since we don't // know what a valid value looks like. The engine will take care of this later. return parameters[parameters.Length - 1]; } return null; } /// <summary> /// Figures out which properties were set on the command line. /// Internal for unit testing. /// </summary> /// <param name="parameters"></param> /// <returns>BuildProperty bag.</returns> internal static Dictionary<string, string> ProcessPropertySwitch(string[] parameters) { Dictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string parameter in parameters) { // split each <prop>=<value> string into 2 pieces, breaking on the first = that is found string[] parameterSections = parameter.Split(s_propertyValueSeparator, 2); Debug.Assert((parameterSections.Length >= 1) && (parameterSections.Length <= 2), "String.Split() will return at least one string, and no more than two."); // check that the property name is not blank, and the property has a value CommandLineSwitchException.VerifyThrow((parameterSections[0].Length > 0) && (parameterSections.Length == 2), "InvalidPropertyError", parameter); // Validation of whether the property has a reserved name will occur when // we start to build: and it will be logged then, too. globalProperties[parameterSections[0]] = parameterSections[1]; } return globalProperties; } /// <summary> /// Instantiates the loggers that are going to listen to events from this build. /// </summary> /// <returns>List of loggers.</returns> private static ILogger[] ProcessLoggingSwitches ( string[] loggerSwitchParameters, string[] distributedLoggerSwitchParameters, string[] verbositySwitchParameters, bool noConsoleLogger, bool distributedFileLogger, string[] fileLoggerParameters, string[] consoleLoggerParameters, string[][] groupedFileLoggerParameters, out List<DistributedLoggerRecord> distributedLoggerRecords, out LoggerVerbosity verbosity, ref bool detailedSummary, int cpuCount ) { // if verbosity level is not specified, use the default verbosity = LoggerVerbosity.Normal; if (verbositySwitchParameters.Length > 0) { // Read the last verbosity switch found verbosity = ProcessVerbositySwitch(verbositySwitchParameters[verbositySwitchParameters.Length - 1]); } ArrayList loggers = ProcessLoggerSwitch(loggerSwitchParameters, verbosity); // Add any loggers which have been specified on the commandline distributedLoggerRecords = ProcessDistributedLoggerSwitch(distributedLoggerSwitchParameters, verbosity); ProcessConsoleLoggerSwitch(noConsoleLogger, consoleLoggerParameters, distributedLoggerRecords, verbosity, cpuCount, loggers); ProcessDistributedFileLogger(distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, cpuCount); ProcessFileLoggers(groupedFileLoggerParameters, distributedLoggerRecords, verbosity, cpuCount, loggers); if (verbosity == LoggerVerbosity.Diagnostic) { detailedSummary = true; } return (ILogger[])loggers.ToArray(typeof(ILogger)); } /// <summary> /// Parameters for a particular logger may be passed in fragments that we have to aggregate: for example, /// /flp:foo=bar;baz=biz /flp:boz=bez becomes "foo=bar;baz=biz;boz=bez" /// We are going to aggregate the LoggerParameters into one LoggerParameters string /// to do this we must first trim off the ; from the start and the end of the strings as /// this would interfere with the use of string.Join by possibly having ;; at the beginning or end of a /// logger parameter /// </summary> internal static string AggregateParameters(string anyPrefixingParameter, string[] parametersToAggregate) { for (int i = 0; i < parametersToAggregate.Length; i++) { parametersToAggregate[i] = parametersToAggregate[i].Trim(';'); } // Join the logger parameters into one string seperated by semicolons string result = anyPrefixingParameter ?? String.Empty; result += String.Join(";", parametersToAggregate); return result; } /// <summary> /// Add a file logger with the appropriate parameters to the loggers list for each /// non-empty set of file logger parameters provided. /// </summary> private static void ProcessFileLoggers(string[][] groupedFileLoggerParameters, List<DistributedLoggerRecord> distributedLoggerRecords, LoggerVerbosity verbosity, int cpuCount, ArrayList loggers) { for (int i = 0; i < groupedFileLoggerParameters.Length; i++) { // If we had no, say, "/fl5" then continue; we may have a "/fl6" and so on if (groupedFileLoggerParameters[i] == null) continue; string fileParameters = "SHOWPROJECTFILE=TRUE;"; // Use a default log file name of "msbuild.log", "msbuild1.log", "msbuild2.log", etc; put this first on the parameter // list so that any supplied log file parameter will override it if (i == 0) { fileParameters += "logfile=msbuild.log;"; } else { fileParameters += "logfile=msbuild" + i + ".log;"; } if (groupedFileLoggerParameters[i].Length > 0) { // Join the file logger parameters into one string seperated by semicolons fileParameters = AggregateParameters(fileParameters, groupedFileLoggerParameters[i]); } FileLogger fileLogger = new FileLogger(); // Set to detailed by default, can be overidden by fileLoggerParameters LoggerVerbosity defaultFileLoggerVerbosity = LoggerVerbosity.Detailed; fileLogger.Verbosity = defaultFileLoggerVerbosity; if (cpuCount == 1) { // We've decided to use the MP logger even in single proc mode. // Switch it on here, rather than in the logger, so that other hosts that use // the existing ConsoleLogger don't see the behavior change in single proc. fileLogger.Parameters = "ENABLEMPLOGGING;" + fileParameters; loggers.Add(fileLogger); } else { fileLogger.Parameters = fileParameters; // For performance, register this logger using the forwarding logger mechanism, rather than as an old-style // central logger. DistributedLoggerRecord forwardingLoggerRecord = CreateForwardingLoggerRecord(fileLogger, fileParameters, defaultFileLoggerVerbosity); distributedLoggerRecords.Add(forwardingLoggerRecord); } } } /// <summary> /// Process the noconsole switch and attach or not attach the correct console loggers /// </summary> internal static void ProcessConsoleLoggerSwitch ( bool noConsoleLogger, string[] consoleLoggerParameters, List<DistributedLoggerRecord> distributedLoggerRecords, LoggerVerbosity verbosity, int cpuCount, ArrayList loggers ) { // the console logger is always active, unless specifically disabled if (!noConsoleLogger) { // A central logger will be created for single proc and multiproc ConsoleLogger logger = new ConsoleLogger(verbosity); string consoleParameters = "SHOWPROJECTFILE=TRUE;"; if ((consoleLoggerParameters != null) && (consoleLoggerParameters.Length > 0)) { consoleParameters = AggregateParameters(consoleParameters, consoleLoggerParameters); } if (cpuCount == 1) { // We've decided to use the MP logger even in single proc mode. // Switch it on here, rather than in the logger, so that other hosts that use // the existing ConsoleLogger don't see the behavior change in single proc. logger.Parameters = "ENABLEMPLOGGING;" + consoleParameters; loggers.Add(logger); } else { logger.Parameters = consoleParameters; // For performance, register this logger using the forwarding logger mechanism, rather than as an old-style // central logger. DistributedLoggerRecord forwardingLoggerRecord = CreateForwardingLoggerRecord(logger, consoleParameters, verbosity); distributedLoggerRecords.Add(forwardingLoggerRecord); } } } /// <summary> /// Returns a DistributedLoggerRecord containing this logger and a ConfigurableForwardingLogger. /// Looks at the logger's parameters for any verbosity parameter in order to make sure it is setting up the ConfigurableForwardingLogger /// with the verbosity level that the logger will actually use. /// </summary> private static DistributedLoggerRecord CreateForwardingLoggerRecord(ILogger logger, string loggerParameters, LoggerVerbosity defaultVerbosity) { string verbosityParameter = ExtractAnyLoggerParameter(loggerParameters, "verbosity", "v"); string verbosityValue = ExtractAnyParameterValue(verbosityParameter); LoggerVerbosity effectiveVerbosity = defaultVerbosity; if (!String.IsNullOrEmpty(verbosityValue)) { effectiveVerbosity = ProcessVerbositySwitch(verbosityValue); } //Gets the currently loaded assembly in which the specified class is defined Assembly engineAssembly = Assembly.GetAssembly(typeof(ProjectCollection)); string loggerClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription forwardingLoggerDescription = new LoggerDescription(loggerClassName, loggerAssemblyName, null, loggerParameters, effectiveVerbosity); DistributedLoggerRecord distributedLoggerRecord = new DistributedLoggerRecord(logger, forwardingLoggerDescription); return distributedLoggerRecord; } /// <summary> /// Process the file logger switches and attach the correct file loggers. Internal for testing /// </summary> internal static void ProcessDistributedFileLogger ( bool distributedFileLogger, string[] fileLoggerParameters, List<DistributedLoggerRecord> distributedLoggerRecords, ArrayList loggers, int cpuCount ) { if (distributedFileLogger) { string fileParameters = string.Empty; if ((fileLoggerParameters != null) && (fileLoggerParameters.Length > 0)) { // Join the file logger parameters into one string seperated by semicolons fileParameters = AggregateParameters(null, fileLoggerParameters); } // Check to see if the logfile parameter has been set, if not set it to the current directory string logFileParameter = ExtractAnyLoggerParameter(fileParameters, "logfile"); string logFileName = ExtractAnyParameterValue(logFileParameter); try { // If the path is not an absolute path set the path to the current directory of the exe combined with the relative path // If the string is empty then send it through as the distributed file logger WILL deal with EMPTY logfile paths if (!String.IsNullOrEmpty(logFileName) && !Path.IsPathRooted(logFileName)) { fileParameters = fileParameters.Replace(logFileParameter, "logFile=" + Path.Combine(Directory.GetCurrentDirectory(), logFileName)); } } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } throw new LoggerException(e.Message, e); } if (String.IsNullOrEmpty(logFileName)) { // If the string is not empty and it does not end in a ;, we need to add a ; to seperate what is in the parameter from the logfile // if the string is empty, no ; is needed because logfile is the only parameter which will be passed in if (!String.IsNullOrEmpty(fileParameters) && !fileParameters.EndsWith(";", StringComparison.OrdinalIgnoreCase)) { fileParameters += ";"; } fileParameters += "logFile=" + Path.Combine(Directory.GetCurrentDirectory(), msbuildLogFileName); } //Gets the currently loaded assembly in which the specified class is defined Assembly engineAssembly = Assembly.GetAssembly(typeof(ProjectCollection)); string loggerClassName = "Microsoft.Build.Logging.DistributedFileLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; // Node the verbosity parameter is not used by the Distributed file logger so changing it here has no effect. It must be changed in the distributed file logger LoggerDescription forwardingLoggerDescription = new LoggerDescription(loggerClassName, loggerAssemblyName, null, fileParameters, LoggerVerbosity.Detailed); // Use the null as the central Logger, this will cause the engine to instantiate the NullCentralLogger, this logger will throw an exception if anything except for the buildstarted and buildFinished events are sent DistributedLoggerRecord distributedLoggerRecord = new DistributedLoggerRecord(null, forwardingLoggerDescription); distributedLoggerRecords.Add(distributedLoggerRecord); } } /// <summary> /// Given a string of aggregated parameters, such as "foo=bar;baz;biz=boz" and a list of parameter names, /// such as "biz", tries to find and return the LAST matching parameter, such as "biz=boz" /// </summary> internal static string ExtractAnyLoggerParameter(string parameters, params string[] parameterNames) { string[] nameValues = parameters.Split(';'); string result = null; foreach (string nameValue in nameValues) { foreach (string name in parameterNames) { bool found = nameValue.StartsWith(name + "=", StringComparison.OrdinalIgnoreCase) || // Parameters with value, such as "logfile=foo.txt" String.Equals(name, nameValue, StringComparison.OrdinalIgnoreCase); // Parameters without value, such as "append" if (found) { result = nameValue; } } } return result; } /// <summary> /// Given a parameter, such as "foo=bar", tries to find and return /// the value part, ie "bar"; otherwise returns null. /// </summary> private static string ExtractAnyParameterValue(string parameter) { string value = null; if (!String.IsNullOrEmpty(parameter)) { string[] nameValuePair = parameter.Split('='); value = (nameValuePair.Length > 1) ? nameValuePair[1] : null; } return value; } /// <summary> /// Figures out what verbosity level to assign to loggers. /// </summary> /// <remarks> /// Internal for unit testing only /// </remarks> /// <param name="parameters"></param> /// <returns>The logger verbosity level.</returns> internal static LoggerVerbosity ProcessVerbositySwitch(string value) { LoggerVerbosity verbosity = LoggerVerbosity.Normal; if (String.Equals(value, "q", StringComparison.OrdinalIgnoreCase) || String.Equals(value, "quiet", StringComparison.OrdinalIgnoreCase)) { verbosity = LoggerVerbosity.Quiet; } else if (String.Equals(value, "m", StringComparison.OrdinalIgnoreCase) || String.Equals(value, "minimal", StringComparison.OrdinalIgnoreCase)) { verbosity = LoggerVerbosity.Minimal; } else if (String.Equals(value, "n", StringComparison.OrdinalIgnoreCase) || String.Equals(value, "normal", StringComparison.OrdinalIgnoreCase)) { verbosity = LoggerVerbosity.Normal; } else if (String.Equals(value, "d", StringComparison.OrdinalIgnoreCase) || String.Equals(value, "detailed", StringComparison.OrdinalIgnoreCase)) { verbosity = LoggerVerbosity.Detailed; } else if (String.Equals(value, "diag", StringComparison.OrdinalIgnoreCase) || String.Equals(value, "diagnostic", StringComparison.OrdinalIgnoreCase)) { verbosity = LoggerVerbosity.Diagnostic; } else { CommandLineSwitchException.Throw("InvalidVerbosityError", value); } return verbosity; } /// <summary> /// Figures out which additional loggers are going to listen to build events. /// </summary> /// <returns>List of loggers.</returns> private static ArrayList ProcessLoggerSwitch(string[] parameters, LoggerVerbosity verbosity) { ArrayList loggers = new ArrayList(); foreach (string parameter in parameters) { string unquotedParameter = QuotingUtilities.Unquote(parameter); LoggerDescription loggerDescription = ParseLoggingParameter(parameter, unquotedParameter, verbosity); loggers.Add(CreateAndConfigureLogger(loggerDescription, verbosity, unquotedParameter)); } return loggers; } /// <summary> /// Parses command line arguments describing the distributed loggers /// </summary> /// <returns>List of distributed logger records</returns> private static List<DistributedLoggerRecord> ProcessDistributedLoggerSwitch(string[] parameters, LoggerVerbosity verbosity) { List<DistributedLoggerRecord> distributedLoggers = new List<DistributedLoggerRecord>(); foreach (string parameter in parameters) { // split each <central logger>|<node logger> string into two pieces, breaking on the first | that is found int emptySplits; // ignored ArrayList loggerSpec = QuotingUtilities.SplitUnquoted(parameter, 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, '*'); ErrorUtilities.VerifyThrow((loggerSpec.Count >= 1) && (loggerSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); string unquotedParameter = QuotingUtilities.Unquote((string)loggerSpec[0]); LoggerDescription centralLoggerDescription = ParseLoggingParameter((string)loggerSpec[0], unquotedParameter, verbosity); ILogger centralLogger = CreateAndConfigureLogger(centralLoggerDescription, verbosity, unquotedParameter); // By default if no forwarding logger description is specified the same logger is used for both functions LoggerDescription forwardingLoggerDescription = centralLoggerDescription; if (loggerSpec.Count > 1) { unquotedParameter = QuotingUtilities.Unquote((string)loggerSpec[1]); forwardingLoggerDescription = ParseLoggingParameter((string)loggerSpec[1], unquotedParameter, verbosity); } DistributedLoggerRecord distributedLoggerRecord = new DistributedLoggerRecord(centralLogger, forwardingLoggerDescription); distributedLoggers.Add(distributedLoggerRecord); } return distributedLoggers; } /// <summary> /// Parse a command line logger argument into a LoggerDescription structure /// </summary> /// <param name="parameter">the command line string</param> /// <returns></returns> private static LoggerDescription ParseLoggingParameter(string parameter, string unquotedParameter, LoggerVerbosity verbosity) { ArrayList loggerSpec; string loggerClassName; string loggerAssemblyName; string loggerAssemblyFile; string loggerParameters = null; int emptySplits; // ignored // split each <logger type>;<logger parameters> string into two pieces, breaking on the first ; that is found loggerSpec = QuotingUtilities.SplitUnquoted(parameter, 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, ';'); ErrorUtilities.VerifyThrow((loggerSpec.Count >= 1) && (loggerSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); // check that the logger is specified CommandLineSwitchException.VerifyThrow(((string)loggerSpec[0]).Length > 0, "InvalidLoggerError", unquotedParameter); // extract logger parameters if present if (loggerSpec.Count == 2) { loggerParameters = QuotingUtilities.Unquote((string)loggerSpec[1]); } // split each <logger class>,<logger assembly> string into two pieces, breaking on the first , that is found ArrayList loggerTypeSpec = QuotingUtilities.SplitUnquoted((string)loggerSpec[0], 2, true /* keep empty splits */, false /* keep quotes */, out emptySplits, ','); ErrorUtilities.VerifyThrow((loggerTypeSpec.Count >= 1) && (loggerTypeSpec.Count <= 2), "SplitUnquoted() must return at least one string, and no more than two."); string loggerAssemblySpec; // if the logger class and assembly are both specified if (loggerTypeSpec.Count == 2) { loggerClassName = QuotingUtilities.Unquote((string)loggerTypeSpec[0]); loggerAssemblySpec = QuotingUtilities.Unquote((string)loggerTypeSpec[1]); } else { loggerClassName = String.Empty; loggerAssemblySpec = QuotingUtilities.Unquote((string)loggerTypeSpec[0]); } CommandLineSwitchException.VerifyThrow(loggerAssemblySpec.Length > 0, "InvalidLoggerError", unquotedParameter); loggerAssemblyName = null; loggerAssemblyFile = null; // DDB Bug msbuild.exe -Logger:FileLogger,Microsoft.Build.Engine fails due to moved engine file. // Only add strong naming if the assembly is a non-strong named 'Microsoft.Build.Engine' (i.e, no additional characteristics) // Concat full Strong Assembly to match v4.0 if (String.Compare(loggerAssemblySpec, "Microsoft.Build.Engine", StringComparison.OrdinalIgnoreCase) == 0) { loggerAssemblySpec = "Microsoft.Build.Engine,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"; } // figure out whether the assembly's identity (strong/weak name), or its filename/path is provided if (File.Exists(loggerAssemblySpec)) { loggerAssemblyFile = loggerAssemblySpec; } else { loggerAssemblyName = loggerAssemblySpec; } return new LoggerDescription(loggerClassName, loggerAssemblyName, loggerAssemblyFile, loggerParameters, verbosity); } /// <summary> /// Loads a logger from its assembly, instantiates it, and handles errors. /// </summary> /// <returns>Instantiated logger.</returns> private static ILogger CreateAndConfigureLogger ( LoggerDescription loggerDescription, LoggerVerbosity verbosity, string unquotedParameter ) { ILogger logger = null; try { logger = loggerDescription.CreateLogger(); if (logger == null) { InitializationException.VerifyThrow(logger != null, "LoggerNotFoundError", unquotedParameter); } } catch (IOException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (BadImageFormatException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (SecurityException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (ReflectionTypeLoadException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (MemberAccessException e) { InitializationException.Throw("LoggerCreationError", unquotedParameter, e, false); } catch (TargetInvocationException e) { InitializationException.Throw("LoggerFatalError", unquotedParameter, e.InnerException, true); } // Configure the logger by setting the verbosity level and parameters try { // set its verbosity level logger.Verbosity = verbosity; // set the logger parameters (if any) if (loggerDescription.LoggerSwitchParameters != null) { logger.Parameters = loggerDescription.LoggerSwitchParameters; } } catch (LoggerException) { // Logger failed politely during parameter/verbosity setting throw; } catch (Exception e) { InitializationException.Throw("LoggerFatalError", unquotedParameter, e, true); } return logger; } /// <summary> /// Figures out if the project needs to be validated against a schema. /// </summary> /// <param name="parameters"></param> /// <returns>The schema to validate against, or null.</returns> private static string ProcessValidateSwitch(string[] parameters) { string schemaFile = null; foreach (string parameter in parameters) { InitializationException.VerifyThrow(schemaFile == null, "MultipleSchemasError", parameter); InitializationException.VerifyThrow(File.Exists(parameter), "SchemaNotFoundError", parameter); schemaFile = Path.Combine(Directory.GetCurrentDirectory(), parameter); } return schemaFile; } /// <summary> /// Given an invalid ToolsVersion string and the collection of valid toolsets, /// throws an InitializationException with the appropriate message. /// </summary> private static void ThrowInvalidToolsVersionInitializationException(IEnumerable<Toolset> toolsets, string toolsVersion) { string toolsVersionList = String.Empty; foreach (Toolset toolset in toolsets) { toolsVersionList += "\"" + toolset.ToolsVersion + "\", "; } // Remove trailing comma and space if (toolsVersionList.Length > 0) { toolsVersionList = toolsVersionList.Substring(0, toolsVersionList.Length - 2); } string message = ResourceUtilities.FormatResourceString ( "UnrecognizedToolsVersion", toolsVersion, toolsVersionList ); message = ResourceUtilities.FormatResourceString("InvalidToolsVersionError", message); InitializationException.Throw(message, toolsVersion); } /// <summary> /// Displays the application copyright message/logo. /// </summary> private static void DisplayCopyrightMessage() { Console.WriteLine(ResourceUtilities.FormatResourceString("CopyrightMessage", ProjectCollection.Version.ToString())); } /// <summary> /// Displays the help message that explains switch usage and syntax. /// </summary> private static void ShowHelpMessage() { // NOTE: the help message is broken into pieces because localization // prefers it that way -- see VSW #482758 "Entire command line help // message is stored in a single resource" Console.WriteLine(AssemblyResources.GetString("HelpMessage_1_Syntax")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_2_Description")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_3_SwitchesHeader")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_9_TargetSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_10_PropertySwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_17_MaximumCPUSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_23_ToolsVersionSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_12_VerbositySwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_13_ConsoleLoggerParametersSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_14_NoConsoleLoggerSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_20_FileLoggerSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_22_FileLoggerParametersSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_18_DistributedLoggerSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_21_DistributedFileLoggerSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_11_LoggerSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_15_ValidateSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_19_IgnoreProjectExtensionsSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_24_NodeReuse")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_25_PreprocessSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_26_DetailedSummarySwitch")); if (CommandLineSwitches.IsParameterlessSwitch("debug")) { Console.WriteLine(AssemblyResources.GetString("HelpMessage_27_DebuggerSwitch")); } Console.WriteLine(AssemblyResources.GetString("HelpMessage_7_ResponseFile")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_8_NoAutoResponseSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_5_NoLogoSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_6_VersionSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_4_HelpSwitch")); Console.WriteLine(AssemblyResources.GetString("HelpMessage_16_Examples")); } /// <summary> /// Displays a message prompting the user to look up help. /// </summary> private static void ShowHelpPrompt() { Console.WriteLine(AssemblyResources.GetString("HelpPrompt")); } /// <summary> /// Displays the build engine's version number. /// </summary> private static void ShowVersion() { Console.Write(ProjectCollection.Version.ToString()); } } }
49.797087
328
0.555601
[ "MIT" ]
HydAu/MsBuild
src/XMakeCommandLine/XMake.cs
147,419
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Fluent.Tests.Common; using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Compute.Fluent; using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.Network.Fluent.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using Xunit; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.Runtime.CompilerServices; using Azure.Tests; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System.Net; using Newtonsoft.Json.Linq; using Microsoft.Azure.Management.Graph.RBAC.Fluent; using Microsoft.Azure.Management.Storage.Fluent; namespace Fluent.Tests.Compute.VirtualMachine { public class ScaleSet { private readonly Region Location = Region.USEast; [Fact] public void CanUpdateWithExtensionProtectedSettings() { // Test for https://github.com/Azure/azure-sdk-for-net/issues/2716 // using (var context = FluentMockContext.Start(GetType().FullName)) { string rgName = TestUtilities.GenerateName("javacsmrg"); var vmssName = TestUtilities.GenerateName("vmss"); var uname = "jvuser"; var password = "123OData!@#123"; var azure = TestHelper.CreateRollupClient(); try { var resourceGroup = azure.ResourceGroups .Define(rgName) .WithRegion(Location) .Create(); var storageAccount = azure.StorageAccounts .Define(TestUtilities.GenerateName("stg")) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .Create(); var keys = storageAccount.GetKeys(); Assert.NotNull(keys); Assert.True(keys.Count() > 0); var storageAccountKey = keys.First(); string uri = prepareCustomScriptStorageUri(storageAccount.Name, storageAccountKey.Value, "scripts"); List<string> fileUris = new List<string>(); fileUris.Add(uri); var network = azure.Networks .Define(TestUtilities.GenerateName("vmssvnet")) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); var virtualMachineScaleSet = azure.VirtualMachineScaleSets.Define(vmssName) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithoutPrimaryInternetFacingLoadBalancer() .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(uname) .WithRootPassword(password) .WithUnmanagedDisks() .WithNewStorageAccount(TestUtilities.GenerateName("stg")) .WithExistingStorageAccount(storageAccount) .DefineNewExtension("CustomScriptForLinux") .WithPublisher("Microsoft.OSTCExtensions") .WithType("CustomScriptForLinux") .WithVersion("1.4") .WithMinorVersionAutoUpgrade() .WithPublicSetting("fileUris", fileUris) .WithProtectedSetting("commandToExecute", "bash install_apache.sh") .WithProtectedSetting("storageAccountName", storageAccount.Name) .WithProtectedSetting("storageAccountKey", storageAccountKey.Value) .Attach() .Create(); // Validate extensions after create // var extensions = virtualMachineScaleSet.Extensions; Assert.NotNull(extensions); Assert.Equal(1, extensions.Count); Assert.True(extensions.ContainsKey("CustomScriptForLinux")); var extension = extensions["CustomScriptForLinux"]; Assert.NotNull(extension.PublicSettings); Assert.Equal(1, extension.PublicSettings.Count); Assert.NotNull(extension.PublicSettingsAsJsonString); // Retrieve scale set var scaleSet = azure .VirtualMachineScaleSets .GetById(virtualMachineScaleSet.Id); // Validate extensions after get // extensions = virtualMachineScaleSet.Extensions; Assert.NotNull(extensions); Assert.Equal(1, extensions.Count); Assert.True(extensions.ContainsKey("CustomScriptForLinux")); extension = extensions["CustomScriptForLinux"]; Assert.NotNull(extension.PublicSettings); Assert.Equal(1, extension.PublicSettings.Count); Assert.NotNull(extension.PublicSettingsAsJsonString); // Update VMSS capacity // int newCapacity = (int)(scaleSet.Capacity + 1); virtualMachineScaleSet.Update() .WithCapacity(newCapacity) .Apply(); // Validate updated capacity // Assert.Equal(newCapacity, virtualMachineScaleSet.Capacity); // Validate extensions after update // extensions = virtualMachineScaleSet.Extensions; Assert.NotNull(extensions); Assert.Equal(1, extensions.Count); Assert.True(extensions.ContainsKey("CustomScriptForLinux")); extension = extensions["CustomScriptForLinux"]; Assert.NotNull(extension.PublicSettings); Assert.Equal(1, extension.PublicSettings.Count); Assert.NotNull(extension.PublicSettingsAsJsonString); } finally { try { azure.ResourceGroups.DeleteByName(rgName); } catch { } } } } [Fact] public void CanUpdateExtensionPublicProtectedSettings() { // Test for https://github.com/Azure/azure-sdk-for-net/issues/3398 // using (var context = FluentMockContext.Start(GetType().FullName)) { string rgName = TestUtilities.GenerateName("javacsmrg"); var vmssName = TestUtilities.GenerateName("vmss"); var uname = "jvuser"; var password = "123OData!@#123"; var azure = TestHelper.CreateRollupClient(); try { var resourceGroup = azure.ResourceGroups .Define(rgName) .WithRegion(Location) .Create(); var storageAccount = azure.StorageAccounts .Define(TestUtilities.GenerateName("stg")) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .Create(); var keys = storageAccount.GetKeys(); Assert.NotNull(keys); Assert.True(keys.Count() > 0); var storageAccountKey = keys.First(); string uri = prepareCustomScriptStorageUri(storageAccount.Name, storageAccountKey.Value, "scripts"); List<string> fileUris = new List<string>(); fileUris.Add(uri); var network = azure.Networks .Define(TestUtilities.GenerateName("vmssvnet")) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); var virtualMachineScaleSet = azure.VirtualMachineScaleSets.Define(vmssName) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithoutPrimaryInternetFacingLoadBalancer() .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername(uname) .WithRootPassword(password) .WithUnmanagedDisks() .WithNewStorageAccount(TestUtilities.GenerateName("stg")) .WithExistingStorageAccount(storageAccount) .DefineNewExtension("CustomScriptForLinux") .WithPublisher("Microsoft.OSTCExtensions") .WithType("CustomScriptForLinux") .WithVersion("1.4") .WithMinorVersionAutoUpgrade() .WithPublicSetting("fileUris", fileUris) .WithProtectedSetting("commandToExecute", "bash install_apache.sh") .WithProtectedSetting("storageAccountName", storageAccount.Name) .WithProtectedSetting("storageAccountKey", storageAccountKey.Value) .Attach() .Create(); // Validate extensions after create // var extensions = virtualMachineScaleSet.Extensions; Assert.NotNull(extensions); Assert.Equal(1, extensions.Count); Assert.True(extensions.ContainsKey("CustomScriptForLinux")); var customScriptExtension = extensions["CustomScriptForLinux"]; Assert.NotNull(customScriptExtension); Assert.Equal("Microsoft.OSTCExtensions", customScriptExtension.PublisherName); Assert.Equal("CustomScriptForLinux", customScriptExtension.TypeName); Assert.NotNull(customScriptExtension.PublicSettings); Assert.Equal(1, customScriptExtension.PublicSettings.Count); Assert.NotNull(customScriptExtension.PublicSettingsAsJsonString); Assert.True(customScriptExtension.AutoUpgradeMinorVersionEnabled); // Special check for C# implementation, seems runtime changed the actual type of public settings from // dictionary to Newtonsoft.Json.Linq.JObject. In future such changes needs to be catched before attemptting // inner conversion hence the below special validation (not applicable for Java) // Assert.NotNull(customScriptExtension.Inner); Assert.NotNull(customScriptExtension.Inner.Settings); bool isJObject = customScriptExtension.Inner.Settings is JObject; bool isDictionary = customScriptExtension.Inner.Settings is IDictionary<string, object>; Assert.True(isJObject || isDictionary); // Ensure the public settings are accessible, the protected settings won't be returned from the service. // var publicSettings = customScriptExtension.PublicSettings; Assert.NotNull(publicSettings); Assert.Equal(1, publicSettings.Count); Assert.True(publicSettings.ContainsKey("fileUris")); string fileUrisString = (publicSettings["fileUris"]).ToString(); if (HttpMockServer.Mode != HttpRecorderMode.Playback) { Assert.Contains(uri, fileUrisString); } /*** UPDATE THE EXTENSION WITH NEW PUBLIC AND PROTECTED SETTINGS **/ // Regenerate the storage account key // storageAccount.RegenerateKey(storageAccountKey.KeyName); keys = storageAccount.GetKeys(); Assert.NotNull(keys); Assert.True(keys.Count() > 0); var updatedStorageAccountKey = keys.FirstOrDefault(key => key.KeyName.Equals(storageAccountKey.KeyName, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(updatedStorageAccountKey); Assert.NotEqual(updatedStorageAccountKey.Value, storageAccountKey.Value); // Upload the script to a different container ("scripts2") in the same storage account // var uri2 = prepareCustomScriptStorageUri(storageAccount.Name, updatedStorageAccountKey.Value, "scripts2"); List<string> fileUris2 = new List<string>(); fileUris2.Add(uri2); string commandToExecute2 = "bash install_apache.sh"; virtualMachineScaleSet.Update() .UpdateExtension("CustomScriptForLinux") .WithPublicSetting("fileUris", fileUris2) .WithProtectedSetting("commandToExecute", commandToExecute2) .WithProtectedSetting("storageAccountName", storageAccount.Name) .WithProtectedSetting("storageAccountKey", updatedStorageAccountKey.Value) .Parent() .Apply(); extensions = virtualMachineScaleSet.Extensions; Assert.NotNull(extensions); Assert.Equal(1, extensions.Count); Assert.True(extensions.ContainsKey("CustomScriptForLinux")); var customScriptExtension2 = extensions["CustomScriptForLinux"]; Assert.NotNull(customScriptExtension2); Assert.Equal("Microsoft.OSTCExtensions", customScriptExtension2.PublisherName); Assert.Equal("CustomScriptForLinux", customScriptExtension2.TypeName); Assert.True(customScriptExtension2.AutoUpgradeMinorVersionEnabled); var publicSettings2 = customScriptExtension2.PublicSettings; Assert.NotNull(publicSettings2); Assert.Equal(1, publicSettings2.Count); Assert.True(publicSettings2.ContainsKey("fileUris")); string fileUris2String = (publicSettings2["fileUris"]).ToString(); if (HttpMockServer.Mode != HttpRecorderMode.Playback) { Assert.Contains(uri2, fileUris2String); } } finally { try { azure.ResourceGroups.DeleteByName(rgName); } catch { } } } } [Fact] public void CanCreateWithCustomScriptExtension() { using (var context = FluentMockContext.Start(GetType().FullName)) { string rgName = TestUtilities.GenerateName("javacsmrg"); string vmssName = TestUtilities.GenerateName("vmss"); string apacheInstallScript = "https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Tests/Fluent.Tests/Assets/install_apache.sh"; string installCommand = "bash install_apache.sh Abc.123x("; List<string> fileUris = new List<string>(); fileUris.Add(apacheInstallScript); var azure = TestHelper.CreateRollupClient(); try { IResourceGroup resourceGroup = azure.ResourceGroups .Define(rgName) .WithRegion(Location) .Create(); INetwork network = azure .Networks .Define(TestUtilities.GenerateName("vmssvnet")) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); ILoadBalancer publicLoadBalancer = CreateHttpLoadBalancers(azure, resourceGroup, "1", Location); IVirtualMachineScaleSet virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmssName) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithUnmanagedDisks() .WithNewStorageAccount(TestUtilities.GenerateName("stg")) .WithNewStorageAccount(TestUtilities.GenerateName("stg")) .DefineNewExtension("CustomScriptForLinux") .WithPublisher("Microsoft.OSTCExtensions") .WithType("CustomScriptForLinux") .WithVersion("1.4") .WithMinorVersionAutoUpgrade() .WithPublicSetting("fileUris", fileUris) .WithPublicSetting("commandToExecute", installCommand) .Attach() .WithUpgradeMode(UpgradeMode.Manual) .Create(); IReadOnlyList<string> publicIPAddressIds = virtualMachineScaleSet.PrimaryPublicIPAddressIds; IPublicIPAddress publicIPAddress = azure.PublicIPAddresses .GetById(publicIPAddressIds[0]); string fqdn = publicIPAddress.Fqdn; Assert.NotNull(fqdn); if (HttpMockServer.Mode != HttpRecorderMode.Playback) { // Assert public load balancing connection HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://" + fqdn); HttpResponseMessage response = client.GetAsync("/").Result; Assert.True(response.IsSuccessStatusCode); } } finally { try { azure.ResourceGroups.DeleteByName(rgName); } catch { } } } } [Fact] public void CanCreateUpdate() { using (var context = FluentMockContext.Start(GetType().FullName)) { string vmss_name = TestUtilities.GenerateName("vmss"); string rgName = TestUtilities.GenerateName("javacsmrg"); var azure = TestHelper.CreateRollupClient(); try { IResourceGroup resourceGroup = azure.ResourceGroups .Define(rgName) .WithRegion(Location) .Create(); INetwork network = azure .Networks .Define("vmssvnet") .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); ILoadBalancer publicLoadBalancer = CreateInternetFacingLoadBalancer(azure, resourceGroup, "1", LoadBalancerSkuType.Basic, Location); List<string> backends = new List<string>(); foreach (string backend in publicLoadBalancer.Backends.Keys) { backends.Add(backend); } Assert.True(backends.Count() == 2); IVirtualMachineScaleSet virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmss_name) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends[0], backends[1]) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithUnmanagedDisks() .WithNewStorageAccount(TestUtilities.GenerateName("stg")) .WithNewStorageAccount(TestUtilities.GenerateName("stg3")) .WithUpgradeMode(UpgradeMode.Manual) .Create(); Assert.Null(virtualMachineScaleSet.GetPrimaryInternalLoadBalancer()); Assert.True(virtualMachineScaleSet.ListPrimaryInternalLoadBalancerBackends().Count() == 0); Assert.True(virtualMachineScaleSet.ListPrimaryInternalLoadBalancerInboundNatPools().Count() == 0); Assert.NotNull(virtualMachineScaleSet.GetPrimaryInternetFacingLoadBalancer()); Assert.True(virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerBackends().Count() == 2); Assert.True(virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerInboundNatPools().Count() == 2); var primaryNetwork = virtualMachineScaleSet.GetPrimaryNetwork(); Assert.NotNull(primaryNetwork.Id); var nics = virtualMachineScaleSet.ListNetworkInterfaces(); int nicCount = 0; foreach (var nic in nics) { nicCount++; Assert.NotNull(nic.Id); Assert.StartsWith(virtualMachineScaleSet.Id.ToLower(), nic.VirtualMachineId.ToLower()); Assert.NotNull(nic.MacAddress); Assert.NotNull(nic.DnsServers); Assert.NotNull(nic.AppliedDnsServers); var ipConfigs = nic.IPConfigurations; Assert.Single(ipConfigs); foreach (var ipConfig in ipConfigs.Values) { Assert.NotNull(ipConfig); Assert.True(ipConfig.IsPrimary); Assert.NotNull(ipConfig.SubnetName); Assert.True(string.Compare(primaryNetwork.Id, ipConfig.NetworkId, true) == 0); Assert.NotNull(ipConfig.PrivateIPAddress); Assert.NotNull(ipConfig.PrivateIPAddressVersion); Assert.NotNull(ipConfig.PrivateIPAllocationMethod); var lbBackends = ipConfig.ListAssociatedLoadBalancerBackends(); // VMSS is created with a internet facing LB with two Backend pools so there will be two // backends in ip-config as well Assert.Equal(2, lbBackends.Count); foreach (var lbBackend in lbBackends) { var lbRules = lbBackend.LoadBalancingRules; Assert.Equal(1, lbRules.Count); foreach (var rule in lbRules.Values) { Assert.NotNull(rule); Assert.True((rule.FrontendPort == 80 && rule.BackendPort == 80) || (rule.FrontendPort == 443 && rule.BackendPort == 443)); } } var lbNatRules = ipConfig.ListAssociatedLoadBalancerInboundNatRules(); // VMSS is created with a internet facing LB with two nat pools so there will be two // nat rules in ip-config as well Assert.Equal(2, lbNatRules.Count); foreach (var lbNatRule in lbNatRules) { Assert.True((lbNatRule.FrontendPort >= 5000 && lbNatRule.FrontendPort <= 5099) || (lbNatRule.FrontendPort >= 6000 && lbNatRule.FrontendPort <= 6099)); Assert.True(lbNatRule.BackendPort == 22 || lbNatRule.BackendPort == 23); } } } Assert.True(nicCount > 0); Assert.Equal(2, virtualMachineScaleSet.VhdContainers.Count()); Assert.Equal(virtualMachineScaleSet.Sku, VirtualMachineScaleSetSkuTypes.StandardA0); // Check defaults Assert.True(virtualMachineScaleSet.UpgradeModel == UpgradeMode.Manual); Assert.Equal(2, virtualMachineScaleSet.Capacity); // Fetch the primary Virtual network primaryNetwork = virtualMachineScaleSet.GetPrimaryNetwork(); string inboundNatPoolToRemove = null; foreach (string inboundNatPoolName in virtualMachineScaleSet .ListPrimaryInternetFacingLoadBalancerInboundNatPools() .Keys) { var pool = virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerInboundNatPools()[inboundNatPoolName]; if (pool.FrontendPortRangeStart == 6000) { inboundNatPoolToRemove = inboundNatPoolName; break; } } Assert.True(inboundNatPoolToRemove != null, "Could not find nat pool entry with front endport start at 6000"); ILoadBalancer internalLoadBalancer = CreateInternalLoadBalancer(azure, resourceGroup, primaryNetwork, "1", Location); virtualMachineScaleSet .Update() .WithExistingPrimaryInternalLoadBalancer(internalLoadBalancer) .WithoutPrimaryInternetFacingLoadBalancerNatPools(inboundNatPoolToRemove) // Remove one NatPool .Apply(); virtualMachineScaleSet = azure .VirtualMachineScaleSets .GetByResourceGroup(rgName, vmss_name); // Check LB after update // Assert.NotNull(virtualMachineScaleSet.GetPrimaryInternetFacingLoadBalancer()); Assert.Equal(2, virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerBackends().Count()); Assert.Single(virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerInboundNatPools()); Assert.NotNull(virtualMachineScaleSet.GetPrimaryInternalLoadBalancer()); Assert.Equal(2, virtualMachineScaleSet.ListPrimaryInternalLoadBalancerBackends().Count()); Assert.Equal(2, virtualMachineScaleSet.ListPrimaryInternalLoadBalancerInboundNatPools().Count()); // Check NIC + IPConfig after update // nics = virtualMachineScaleSet.ListNetworkInterfaces(); nicCount = 0; foreach (var nic in nics) { nicCount++; var ipConfigs = nic.IPConfigurations; Assert.Equal(1, ipConfigs.Count); foreach (var ipConfig in ipConfigs.Values) { Assert.NotNull(ipConfig); var lbBackends = ipConfig.ListAssociatedLoadBalancerBackends(); Assert.NotNull(lbBackends); // Updated VMSS has a internet facing LB with two backend pools and a internal LB with two // backend pools so there should be 4 backends in ip-config // #1: But this is not always happening, it seems update is really happening only // for subset of vms [TODO: Report this to network team] // Assert.True(lbBackends.Count == 4); foreach (var lbBackend in lbBackends) { var lbRules = lbBackend.LoadBalancingRules; Assert.Equal(1, lbRules.Count); foreach (var rule in lbRules.Values) { Assert.NotNull(rule); Assert.True((rule.FrontendPort == 80 && rule.BackendPort == 80) || (rule.FrontendPort == 443 && rule.BackendPort == 443) || (rule.FrontendPort == 1000 && rule.BackendPort == 1000) || (rule.FrontendPort == 1001 && rule.BackendPort == 1001)); } } var lbNatRules = ipConfig.ListAssociatedLoadBalancerInboundNatRules(); // Updated VMSS has a internet facing LB with one nat pool and a internal LB with two // nat pools so there should be 3 nat rule in ip-config // Same issue as above #1 // But this is not always happening, it seems update is really happening only // for subset of vms [TODO: Report this to network team] // Assert.Equal(lbNatRules.Count(), 3); foreach (var lbNatRule in lbNatRules) { // As mentioned above some chnages are not propgating to all VM instances 6000+ should be there Assert.True((lbNatRule.FrontendPort >= 6000 && lbNatRule.FrontendPort <= 6099) || (lbNatRule.FrontendPort >= 5000 && lbNatRule.FrontendPort <= 5099) || (lbNatRule.FrontendPort >= 8000 && lbNatRule.FrontendPort <= 8099) || (lbNatRule.FrontendPort >= 9000 && lbNatRule.FrontendPort <= 9099)); // Same as above Assert.True(lbNatRule.BackendPort == 23 || lbNatRule.BackendPort == 22 || lbNatRule.BackendPort == 44 || lbNatRule.BackendPort == 45); } } } Assert.True(nicCount > 0); CheckVMInstances(virtualMachineScaleSet); } finally { try { azure.ResourceGroups.DeleteByName(rgName); } catch { } } } } [Fact] public void CanEnableMSIWithoutRoleAssignment() { using (var context = FluentMockContext.Start(GetType().FullName)) { string vmss_name = TestUtilities.GenerateName("vmss"); string groupName = TestUtilities.GenerateName("javacsmrg"); IAzure azure = null; try { azure = TestHelper.CreateRollupClient(); IResourceGroup resourceGroup = azure.ResourceGroups .Define(groupName) .WithRegion(Location) .Create(); INetwork network = azure .Networks .Define("vmssvnet") .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); ILoadBalancer publicLoadBalancer = CreateInternetFacingLoadBalancer(azure, resourceGroup, "1", LoadBalancerSkuType.Basic, Location); List<string> backends = new List<string>(); foreach (string backend in publicLoadBalancer.Backends.Keys) { backends.Add(backend); } Assert.True(backends.Count() == 2); IVirtualMachineScaleSet virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmss_name) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends[0], backends[1]) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithSystemAssignedManagedServiceIdentity() .Create(); var authenticatedClient = TestHelper.CreateAuthenticatedClient(); // IServicePrincipal servicePrincipal = authenticatedClient .ServicePrincipals .GetById(virtualMachineScaleSet.SystemAssignedManagedServiceIdentityPrincipalId); Assert.NotNull(servicePrincipal); Assert.NotNull(servicePrincipal.Inner); // Ensure no role assigned for resource group // var rgRoleAssignments = authenticatedClient.RoleAssignments.ListByScope(resourceGroup.Id); Assert.NotNull(rgRoleAssignments); bool found = false; foreach (var roleAssignment in rgRoleAssignments) { if (roleAssignment.PrincipalId != null && roleAssignment.PrincipalId.Equals(virtualMachineScaleSet.SystemAssignedManagedServiceIdentityPrincipalId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } Assert.False(found, "Resource group should not have a role assignment with virtual machine scale set MSI principal"); } finally { try { if (azure != null) { azure.ResourceGroups.BeginDeleteByName(groupName); } } catch { } } } } [Fact] public void CanEnableMSIWithMultipleRoleAssignment() { using (var context = FluentMockContext.Start(GetType().FullName)) { string vmss_name = TestUtilities.GenerateName("vmss"); string groupName = TestUtilities.GenerateName("javacsmrg"); var storageAccountName = TestUtilities.GenerateName("ja"); IAzure azure = null; try { azure = TestHelper.CreateRollupClient(); IResourceGroup resourceGroup = azure.ResourceGroups .Define(groupName) .WithRegion(Location) .Create(); INetwork network = azure .Networks .Define("vmssvnet") .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); ILoadBalancer publicLoadBalancer = CreateInternetFacingLoadBalancer(azure, resourceGroup, "1", LoadBalancerSkuType.Basic, Location); List<string> backends = new List<string>(); foreach (string backend in publicLoadBalancer.Backends.Keys) { backends.Add(backend); } Assert.True(backends.Count() == 2); IStorageAccount storageAccount = azure.StorageAccounts .Define(storageAccountName) .WithRegion(Location) .WithNewResourceGroup(groupName) .Create(); IVirtualMachineScaleSet virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmss_name) .WithRegion(Location) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends[0], backends[1]) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithSystemAssignedManagedServiceIdentity() .WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.Contributor) .WithSystemAssignedIdentityBasedAccessTo(storageAccount.Id, BuiltInRole.Contributor) .Create(); Assert.NotNull(virtualMachineScaleSet.ManagedServiceIdentityType); Assert.True(virtualMachineScaleSet.ManagedServiceIdentityType.Equals(ResourceIdentityType.SystemAssigned)); var authenticatedClient = TestHelper.CreateAuthenticatedClient(); // IServicePrincipal servicePrincipal = authenticatedClient .ServicePrincipals .GetById(virtualMachineScaleSet.SystemAssignedManagedServiceIdentityPrincipalId); Assert.NotNull(servicePrincipal); Assert.NotNull(servicePrincipal.Inner); // Ensure role assigned for resource group // var rgRoleAssignments = authenticatedClient.RoleAssignments.ListByScope(resourceGroup.Id); Assert.NotNull(rgRoleAssignments); bool found = false; foreach (var roleAssignment in rgRoleAssignments) { if (roleAssignment.PrincipalId != null && roleAssignment.PrincipalId.Equals(virtualMachineScaleSet.SystemAssignedManagedServiceIdentityPrincipalId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } Assert.True(found, "Resource group should have a role assignment with virtual machine scale set MSI principal"); // Ensure role assigned for storage account // var stgRoleAssignments = authenticatedClient.RoleAssignments.ListByScope(storageAccount.Id); Assert.NotNull(stgRoleAssignments); found = false; foreach (var roleAssignment in stgRoleAssignments) { if (roleAssignment.PrincipalId != null && roleAssignment.PrincipalId.Equals(virtualMachineScaleSet.SystemAssignedManagedServiceIdentityPrincipalId, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } Assert.True(found, "Storage account should have a role assignment with virtual machine scale set MSI principal"); } finally { try { if (azure != null) { azure.ResourceGroups.BeginDeleteByName(groupName); } } catch { } } } } [Fact] public void CanCreateTwoRegionalVMSSAndAssociateEachWithDifferentBackendPoolOfZoneResilientLoadBalancer() { using (var context = FluentMockContext.Start(GetType().FullName)) { string groupName = TestUtilities.GenerateName("javacsmrg"); var storageAccountName = TestUtilities.GenerateName("ja"); Region region = Region.USEast2; IAzure azure = null; try { azure = TestHelper.CreateRollupClient(); IResourceGroup resourceGroup = azure.ResourceGroups .Define(groupName) .WithRegion(region) .Create(); INetwork network = azure .Networks .Define("vmssvnet") .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); // Creates a STANDARD LB with one public frontend ip configuration with two backend pools // Each address pool of STANDARD LB can hold different VMSS resource. // ILoadBalancer publicLoadBalancer = CreateInternetFacingLoadBalancer(azure, resourceGroup, "1", LoadBalancerSkuType.Standard, region); // With default LB SKU BASIC, an attempt to associate two different VMSS to different // backend pool will cause below error (more accurately, while trying to put second VMSS) // { // "startTime": "2017-09-06T14:27:22.1849435+00:00", // "endTime": "2017-09-06T14:27:45.8885142+00:00", // "status": "Failed", // "error": { // "code": "VmIsNotInSameAvailabilitySetAsLb", // "message": "Virtual Machine /subscriptions/<sub-id>/resourceGroups/<rg-name>/providers/Microsoft.Compute/virtualMachines/|providers|Microsoft.Compute|virtualMachineScaleSets|<vm-ss-name>|virtualMachines|<instance-id> is using different Availability Set than other Virtual Machines connected to the Load Balancer(s) <lb-name>." // }, // "name": "97531d64-db37-4d21-a1cb-9c53aad7c342" // } List<string> backends = new List<string>(); foreach (string backend in publicLoadBalancer.Backends.Keys) { backends.Add(backend); } Assert.True(backends.Count() == 2); List<String> natpools = new List<string>(); foreach (String natPool in publicLoadBalancer.InboundNatPools.Keys) { natpools.Add(natPool); } Assert.True(natpools.Count() == 2); var vmss_name1 = TestUtilities.GenerateName("vmss1"); // HTTP goes to this virtual machine scale set // var virtualMachineScaleSet1 = azure.VirtualMachineScaleSets .Define(vmss_name1) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends.ElementAt(0)) // This VMSS in the first backend pool .WithPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.ElementAt(0)) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .Create(); var vmss_name2 = TestUtilities.GenerateName("vmss2"); // HTTPS goes to this virtual machine scale set // var virtualMachineScaleSet2 = azure.VirtualMachineScaleSets .Define(vmss_name2) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardA0) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends.ElementAt(1)) // This VMSS in the second backend pool .WithPrimaryInternetFacingLoadBalancerInboundNatPools(natpools.ElementAt(1)) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .Create(); // Assert.Null(virtualMachineScaleSet1.GetPrimaryInternalLoadBalancer()); Assert.True(virtualMachineScaleSet1.ListPrimaryInternalLoadBalancerBackends().Count() == 0); Assert.True(virtualMachineScaleSet1.ListPrimaryInternalLoadBalancerInboundNatPools().Count() == 0); Assert.NotNull(virtualMachineScaleSet1.GetPrimaryInternetFacingLoadBalancer()); Assert.True(virtualMachineScaleSet1.ListPrimaryInternetFacingLoadBalancerBackends().Count() == 1); Assert.Null(virtualMachineScaleSet2.GetPrimaryInternalLoadBalancer()); Assert.True(virtualMachineScaleSet2.ListPrimaryInternalLoadBalancerBackends().Count() == 0); Assert.True(virtualMachineScaleSet2.ListPrimaryInternalLoadBalancerInboundNatPools().Count() == 0); Assert.NotNull(virtualMachineScaleSet2.GetPrimaryInternetFacingLoadBalancer()); Assert.True(virtualMachineScaleSet2.ListPrimaryInternetFacingLoadBalancerBackends().Count() == 1); } finally { try { if (azure != null) { azure.ResourceGroups.BeginDeleteByName(groupName); } } catch { } } } } [Fact] public void CanCreateZoneRedundantVirtualMachineScaleSetWithZoneResilientLoadBalancer() { using (var context = FluentMockContext.Start(GetType().FullName)) { string groupName = TestUtilities.GenerateName("javacsmrg"); var storageAccountName = TestUtilities.GenerateName("ja"); Region region = Region.USEast2; IAzure azure = null; try { azure = TestHelper.CreateRollupClient(); IResourceGroup resourceGroup = azure.ResourceGroups .Define(groupName) .WithRegion(region) .Create(); INetwork network = azure .Networks .Define("vmssvnet") .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); // Zone redundant VMSS requires STANDARD LB // // Creates a STANDARD LB with one public frontend ip configuration with two backend pools // Each address pool of STANDARD LB can hold different VMSS resource. // ILoadBalancer publicLoadBalancer = CreateInternetFacingLoadBalancer(azure, resourceGroup, "1", LoadBalancerSkuType.Standard, region); List<string> backends = new List<string>(); foreach (string backend in publicLoadBalancer.Backends.Keys) { backends.Add(backend); } Assert.True(backends.Count() == 2); List<String> natpools = new List<string>(); foreach (String natPool in publicLoadBalancer.InboundNatPools.Keys) { natpools.Add(natPool); } Assert.True(natpools.Count() == 2); var vmss_name = TestUtilities.GenerateName("vmss"); // HTTP & HTTPS traffic on port 80, 443 of Internet-facing LB goes to corresponding port in virtual machine scale set // var virtualMachineScaleSet = azure.VirtualMachineScaleSets .Define(vmss_name) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardD3v2) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithExistingPrimaryInternetFacingLoadBalancer(publicLoadBalancer) .WithPrimaryInternetFacingLoadBalancerBackends(backends.ElementAt(0), backends.ElementAt(1)) .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithAvailabilityZone(AvailabilityZoneId.Zone_1) // Zone redundant - zone 1 + zone 2 .WithAvailabilityZone(AvailabilityZoneId.Zone_2) .Create(); // Check zones // Assert.NotNull(virtualMachineScaleSet.AvailabilityZones); Assert.Equal(2, virtualMachineScaleSet.AvailabilityZones.Count); // Validate Network specific properties (LB, VNet, NIC, IPConfig etc..) // Assert.Null(virtualMachineScaleSet.GetPrimaryInternalLoadBalancer()); Assert.True(virtualMachineScaleSet.ListPrimaryInternalLoadBalancerBackends().Count() == 0); Assert.True(virtualMachineScaleSet.ListPrimaryInternalLoadBalancerInboundNatPools().Count() == 0); Assert.NotNull(virtualMachineScaleSet.GetPrimaryInternetFacingLoadBalancer()); Assert.True(virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerBackends().Count() == 2); Assert.True(virtualMachineScaleSet.ListPrimaryInternetFacingLoadBalancerInboundNatPools().Count() == 2); var primaryNetwork = virtualMachineScaleSet.GetPrimaryNetwork(); Assert.NotNull(primaryNetwork.Id); } finally { try { if (azure != null) { azure.ResourceGroups.BeginDeleteByName(groupName); } } catch { } } } } [Fact] public void CanCreateVirtualMachineScaleSetWithOptionalNetworkSettings() { using (var context = FluentMockContext.Start(GetType().FullName)) { string vmss_name = TestUtilities.GenerateName("vmss"); string groupName = TestUtilities.GenerateName("javacsmrg"); string asgName = TestUtilities.GenerateName("asg"); string nsgName = TestUtilities.GenerateName("nsg"); string vmssVmDnsLabel = TestUtilities.GenerateName("pip"); Region region = Region.USEast2; IAzure azure = null; try { azure = TestHelper.CreateRollupClient(); var resourceGroup = azure.ResourceGroups.Define(groupName) .WithRegion(region) .Create(); var network = azure.Networks.Define("vmssvnet") .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithAddressSpace("10.0.0.0/28") .WithSubnet("subnet1", "10.0.0.0/28") .Create(); var asg = azure.ApplicationSecurityGroups .Define(asgName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .Create(); // Create VMSS with instance public ip var virtualMachineScaleSet = azure.VirtualMachineScaleSets.Define(vmss_name) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .WithSku(VirtualMachineScaleSetSkuTypes.StandardDS3v2) .WithExistingPrimaryNetworkSubnet(network, "subnet1") .WithoutPrimaryInternetFacingLoadBalancer() .WithoutPrimaryInternalLoadBalancer() .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts) .WithRootUsername("jvuser") .WithRootPassword("123OData!@#123") .WithVirtualMachinePublicIp(vmssVmDnsLabel) .WithExistingApplicationSecurityGroup(asg) .Create(); var currentIpConfig = virtualMachineScaleSet.VirtualMachinePublicIpConfig; Assert.NotNull(currentIpConfig); Assert.NotNull(currentIpConfig.DnsSettings); Assert.NotNull(currentIpConfig.DnsSettings.DomainNameLabel); currentIpConfig.IdleTimeoutInMinutes = 20; virtualMachineScaleSet.Update() .WithVirtualMachinePublicIp(currentIpConfig) .Apply(); currentIpConfig = virtualMachineScaleSet.VirtualMachinePublicIpConfig; Assert.NotNull(currentIpConfig); Assert.NotNull(currentIpConfig.IdleTimeoutInMinutes); Assert.Equal((long)20, (long)currentIpConfig.IdleTimeoutInMinutes); virtualMachineScaleSet.Refresh(); currentIpConfig = virtualMachineScaleSet.VirtualMachinePublicIpConfig; Assert.NotNull(currentIpConfig); Assert.NotNull(currentIpConfig.IdleTimeoutInMinutes); Assert.Equal((long)20, (long)currentIpConfig.IdleTimeoutInMinutes); var asgIds = virtualMachineScaleSet.ApplicationSecurityGroupIds; Assert.NotNull(asgIds); Assert.Equal(1, asgIds.Count); var nsg = azure.NetworkSecurityGroups.Define(nsgName) .WithRegion(region) .WithExistingResourceGroup(resourceGroup) .DefineRule("rule1") .AllowOutbound() .FromAnyAddress() .FromPort(80) .ToAnyAddress() .ToPort(80) .WithProtocol(SecurityRuleProtocol.Tcp) .Attach() .Create(); virtualMachineScaleSet.Update() .WithIpForwarding() .WithAcceleratedNetworking() .WithExistingNetworkSecurityGroup(nsg) .Apply(); Assert.True(virtualMachineScaleSet.IsIpForwardingEnabled); Assert.True(virtualMachineScaleSet.IsAcceleratedNetworkingEnabled); Assert.NotNull(virtualMachineScaleSet.NetworkSecurityGroupId); // virtualMachineScaleSet.Refresh(); // Assert.True(virtualMachineScaleSet.IsIpForwardingEnabled); Assert.True(virtualMachineScaleSet.IsAcceleratedNetworkingEnabled); Assert.NotNull(virtualMachineScaleSet.NetworkSecurityGroupId); virtualMachineScaleSet.Update() .WithoutIpForwarding() .WithoutAcceleratedNetworking() .WithoutNetworkSecurityGroup() .Apply(); Assert.False(virtualMachineScaleSet.IsIpForwardingEnabled); Assert.False(virtualMachineScaleSet.IsAcceleratedNetworkingEnabled); Assert.Null(virtualMachineScaleSet.NetworkSecurityGroupId); } finally { try { if (azure != null) { azure.ResourceGroups.BeginDeleteByName(groupName); } } catch { } } } } private void CheckVMInstances(IVirtualMachineScaleSet vmScaleSet) { var virtualMachineScaleSetVMs = vmScaleSet.VirtualMachines; var virtualMachines = virtualMachineScaleSetVMs.List(); Assert.Equal(virtualMachines.Count(), vmScaleSet.Capacity); Assert.True(virtualMachines.Count() > 0); virtualMachineScaleSetVMs.UpdateInstances(virtualMachines.First().InstanceId); foreach (var vm in virtualMachines) { Assert.NotNull(vm.Size); Assert.Equal(OperatingSystemTypes.Linux, vm.OSType); Assert.StartsWith(vmScaleSet.ComputerNamePrefix, vm.ComputerName); Assert.True(vm.IsLinuxPasswordAuthenticationEnabled); Assert.True(vm.IsOSBasedOnPlatformImage); Assert.Null(vm.StoredImageUnmanagedVhdUri); Assert.False(vm.IsWindowsAutoUpdateEnabled); Assert.False(vm.IsWindowsVMAgentProvisioned); Assert.Equal("jvuser", vm.AdministratorUserName, ignoreCase: true); var vmImage = vm.GetOSPlatformImage(); Assert.NotNull(vmImage); Assert.Equal(vm.Extensions.Count(), vmScaleSet.Extensions.Count); Assert.NotNull(vm.PowerState); vm.RefreshInstanceView(); } // Check actions var virtualMachineScaleSetVM = virtualMachines.FirstOrDefault(); Assert.NotNull(virtualMachineScaleSetVM); virtualMachineScaleSetVM.Restart(); virtualMachineScaleSetVM.PowerOff(); virtualMachineScaleSetVM.RefreshInstanceView(); Assert.Equal(virtualMachineScaleSetVM.PowerState, PowerState.Stopped); virtualMachineScaleSetVM.Start(); // Check Instance NICs // foreach (var vm in virtualMachines) { var nics = vmScaleSet.ListNetworkInterfacesByInstanceId(vm.InstanceId); Assert.NotNull(nics); Assert.Single(nics); var nic = nics.First(); Assert.NotNull(nic.VirtualMachineId); Assert.True(string.Compare(nic.VirtualMachineId, vm.Id, true) == 0); Assert.NotNull(vm.ListNetworkInterfaces()); } } public static ILoadBalancer CreateInternetFacingLoadBalancer(IAzure azure, IResourceGroup resourceGroup, string id, LoadBalancerSkuType lbSkuType, Region location, [CallerMemberName] string methodName = "testframework_failed") { string loadBalancerName = TestUtilities.GenerateName("extlb" + id + "-", methodName); string publicIPName = "pip-" + loadBalancerName; string frontendName = loadBalancerName + "-FE1"; string backendPoolName1 = loadBalancerName + "-BAP1"; string backendPoolName2 = loadBalancerName + "-BAP2"; string natPoolName1 = loadBalancerName + "-INP1"; string natPoolName2 = loadBalancerName + "-INP2"; // Sku of PublicIP and LoadBalancer must match // PublicIPSkuType publicIPSkuType = lbSkuType.Equals(LoadBalancerSkuType.Basic) ? PublicIPSkuType.Basic : PublicIPSkuType.Standard; IPublicIPAddress publicIPAddress = azure.PublicIPAddresses .Define(publicIPName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) .WithLeafDomainLabel(publicIPName) // Optionals .WithStaticIP() .WithSku(publicIPSkuType) // Create .Create(); ILoadBalancer loadBalancer = azure.LoadBalancers.Define(loadBalancerName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) // Add two rules that uses above backend and probe .DefineLoadBalancingRule("httpRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPort(80) .ToBackend(backendPoolName1) .WithProbe("httpProbe") .Attach() .DefineLoadBalancingRule("httpsRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPort(443) .ToBackend(backendPoolName2) .WithProbe("httpsProbe") .Attach() // Add two nat pools to enable direct VM connectivity to port SSH and 23 .DefineInboundNatPool(natPoolName1) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPortRange(5000, 5099) .ToBackendPort(22) .Attach() .DefineInboundNatPool(natPoolName2) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPortRange(6000, 6099) .ToBackendPort(23) .Attach() // Explicitly define the frontend .DefinePublicFrontend(frontendName) .WithExistingPublicIPAddress(publicIPAddress) .Attach() // Add two probes one per rule .DefineHttpProbe("httpProbe") .WithRequestPath("/") .Attach() .DefineHttpProbe("httpsProbe") .WithRequestPath("/") .Attach() .WithSku(lbSkuType) .Create(); loadBalancer = azure.LoadBalancers.GetByResourceGroup(resourceGroup.Name, loadBalancerName); Assert.True(loadBalancer.PublicIPAddressIds.Count() == 1); Assert.Equal(2, loadBalancer.HttpProbes.Count()); ILoadBalancerHttpProbe httpProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpProbe", out httpProbe)); Assert.Single(httpProbe.LoadBalancingRules); ILoadBalancerHttpProbe httpsProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpsProbe", out httpsProbe)); Assert.Single(httpProbe.LoadBalancingRules); Assert.Equal(2, loadBalancer.InboundNatPools.Count()); return loadBalancer; } public static ILoadBalancer CreateInternalLoadBalancer( IAzure azure, IResourceGroup resourceGroup, INetwork network, string id, Region location, [CallerMemberName] string methodName = "testframework_failed") { string loadBalancerName = TestUtilities.GenerateName("InternalLb" + id + "-", methodName); string privateFrontEndName = loadBalancerName + "-FE1"; string backendPoolName1 = loadBalancerName + "-BAP1"; string backendPoolName2 = loadBalancerName + "-BAP2"; string natPoolName1 = loadBalancerName + "-INP1"; string natPoolName2 = loadBalancerName + "-INP2"; string subnetName = "subnet1"; ILoadBalancer loadBalancer = azure.LoadBalancers.Define(loadBalancerName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) // Add two rules that uses above backend and probe .DefineLoadBalancingRule("httpRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPort(1000) .ToBackend(backendPoolName1) .WithProbe("httpProbe") .Attach() .DefineLoadBalancingRule("httpsRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPort(1001) .ToBackend(backendPoolName2) .WithProbe("httpsProbe") .Attach() // Add two nat pools to enable direct VM connectivity to port 44 and 45 .DefineInboundNatPool(natPoolName1) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPortRange(8000, 8099) .ToBackendPort(44) .Attach() .DefineInboundNatPool(natPoolName2) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(privateFrontEndName) .FromFrontendPortRange(9000, 9099) .ToBackendPort(45) .Attach() // Explicitly define the frontend .DefinePrivateFrontend(privateFrontEndName) .WithExistingSubnet(network, subnetName) .Attach() // Add two probes one per rule .DefineHttpProbe("httpProbe") .WithRequestPath("/") .Attach() .DefineHttpProbe("httpsProbe") .WithRequestPath("/") .Attach() .Create(); loadBalancer = azure.LoadBalancers.GetByResourceGroup(resourceGroup.Name, loadBalancerName); Assert.Empty(loadBalancer.PublicIPAddressIds); Assert.Equal(2, loadBalancer.Backends.Count()); ILoadBalancerBackend backend1 = null; Assert.True(loadBalancer.Backends.TryGetValue(backendPoolName1, out backend1)); ILoadBalancerBackend backend2 = null; Assert.True(loadBalancer.Backends.TryGetValue(backendPoolName2, out backend2)); ILoadBalancerHttpProbe httpProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpProbe", out httpProbe)); Assert.Single(httpProbe.LoadBalancingRules); ILoadBalancerHttpProbe httpsProbe = null; Assert.True(loadBalancer.HttpProbes.TryGetValue("httpsProbe", out httpsProbe)); Assert.Single(httpProbe.LoadBalancingRules); Assert.Equal(2, loadBalancer.InboundNatPools.Count()); return loadBalancer; } public static ILoadBalancer CreateHttpLoadBalancers( IAzure azure, IResourceGroup resourceGroup, string id, Region location, [CallerMemberName] string methodName = "testframework_failed") { string loadBalancerName = TestUtilities.GenerateName("extlb" + id + "-", methodName); string publicIPName = "pip-" + loadBalancerName; string frontendName = loadBalancerName + "-FE1"; string backendPoolName = loadBalancerName + "-BAP1"; string natPoolName = loadBalancerName + "-INP1"; var publicIPAddress = azure.PublicIPAddresses .Define(publicIPName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) .WithLeafDomainLabel(publicIPName) .Create(); var loadBalancer = azure.LoadBalancers.Define(loadBalancerName) .WithRegion(location) .WithExistingResourceGroup(resourceGroup) // Add two rules that uses above backend and probe .DefineLoadBalancingRule("httpRule") .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPort(80) .ToBackend(backendPoolName) .WithProbe("httpProbe") .Attach() .DefineInboundNatPool(natPoolName) .WithProtocol(TransportProtocol.Tcp) .FromFrontend(frontendName) .FromFrontendPortRange(5000, 5099) .ToBackendPort(22) .Attach() .DefinePublicFrontend(frontendName) .WithExistingPublicIPAddress(publicIPAddress) .Attach() .DefineHttpProbe("httpProbe") .WithRequestPath("/") .Attach() .Create(); loadBalancer = azure.LoadBalancers.GetByResourceGroup(resourceGroup.Name, loadBalancerName); Assert.True(loadBalancer.PublicIPAddressIds.Count() == 1); var httpProbe = loadBalancer.HttpProbes.Values.FirstOrDefault(); Assert.NotNull(httpProbe); var rule = httpProbe.LoadBalancingRules.Values.FirstOrDefault(); Assert.NotNull(rule); var natPool = loadBalancer.InboundNatPools.Values.FirstOrDefault(); Assert.NotNull(natPool); return loadBalancer; } private string prepareCustomScriptStorageUri(string storageAccountName, string storageAccountKey, string containerName) { if (HttpMockServer.Mode == HttpRecorderMode.Playback) { return "http://nonexisting.blob.core.windows.net/scripts2/install_apache.sh"; } var storageConnectionString = $"DefaultEndpointsProtocol=http;AccountName={storageAccountName};AccountKey={storageAccountKey}"; CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient cloudBlobClient = account.CreateCloudBlobClient(); CloudBlobContainer container = cloudBlobClient.GetContainerReference(containerName); bool createdNew = container.CreateIfNotExistsAsync().Result; CloudBlockBlob blob = container.GetBlockBlobReference("install_apache.sh"); using (HttpClient client = new HttpClient()) { blob.UploadFromStreamAsync(client.GetStreamAsync("https://raw.githubusercontent.com/Azure/azure-libraries-for-net/master/Samples/Asset/install_apache.sh").Result).Wait(); } return blob.Uri.ToString(); } } }
52.007378
360
0.527488
[ "MIT" ]
LekeFasola/azure-libraries-for-net
Tests/Fluent.Tests/Compute/VirtualMachineScaleSetTests.cs
77,545
C#
namespace TypinExamples.Application.Handlers.Commands.Terminal { using System.Threading; using System.Threading.Tasks; using TypinExamples.Application.Services; using TypinExamples.Application.Services.TypinWeb; using TypinExamples.Infrastructure.WebWorkers.Abstractions; using TypinExamples.Infrastructure.WebWorkers.Abstractions.Messaging; using TypinExamples.Infrastructure.WebWorkers.Abstractions.Payloads; public sealed class ClearCommand : ICommand { public string? TerminalId { get; init; } public class Handler : ICommandHandler<ClearCommand> { private readonly ITerminalRepository _terminalRepository; public Handler(ITerminalRepository terminalRepository) { _terminalRepository = terminalRepository; } public async ValueTask<CommandFinished> HandleAsync(ClearCommand request, IWorker worker, CancellationToken cancellationToken) { if (request.TerminalId is string id && _terminalRepository.GetOrDefault(id) is IWebTerminal webTerminal) { await webTerminal.ClearAsync(); } return CommandFinished.Instance; } } } }
35.27027
138
0.665134
[ "MIT" ]
MyClinicalOutcomesLtd/Typin
src/TypinExamples/TypinExamples.Application/Handlers/Commands/Terminal/ClearCommand.cs
1,307
C#
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; namespace NUnit.Framework.Constraints { /// <summary> /// CollectionOrderedConstraint is used to test whether a collection is ordered. /// </summary> public class CollectionOrderedConstraint : CollectionConstraint { private ComparisonAdapter comparer = ComparisonAdapter.Default; private string comparerName; private string propertyName; private bool descending; /// <summary> /// Construct a CollectionOrderedConstraint /// </summary> public CollectionOrderedConstraint() { this.DisplayName = "ordered"; } ///<summary> /// If used performs a reverse comparison ///</summary> public CollectionOrderedConstraint Descending { get { descending = true; return this; } } /// <summary> /// Modifies the constraint to use an IComparer and returns self. /// </summary> public CollectionOrderedConstraint Using(IComparer comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to use an IComparer&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(IComparer<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to use a Comparison&lt;T&gt; and returns self. /// </summary> public CollectionOrderedConstraint Using<T>(Comparison<T> comparer) { this.comparer = ComparisonAdapter.For(comparer); this.comparerName = comparer.GetType().FullName; return this; } /// <summary> /// Modifies the constraint to test ordering by the value of /// a specified property and returns self. /// </summary> public CollectionOrderedConstraint By(string propertyName) { this.propertyName = propertyName; return this; } /// <summary> /// Test whether the collection is ordered /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch(IEnumerable actual) { object previous = null; int index = 0; foreach (object obj in actual) { object objToCompare = obj; if (obj == null) throw new ArgumentNullException("actual", "Null value at index " + index.ToString()); if (this.propertyName != null) { PropertyInfo prop = obj.GetType().GetProperty(propertyName); objToCompare = prop.GetValue(obj, null); if (objToCompare == null) throw new ArgumentNullException("actual", "Null property value at index " + index.ToString()); } if (previous != null) { //int comparisonResult = comparer.Compare(al[i], al[i + 1]); int comparisonResult = comparer.Compare(previous, objToCompare); if (descending && comparisonResult < 0) return false; if (!descending && comparisonResult > 0) return false; } previous = objToCompare; index++; } return true; } /// <summary> /// Write a description of the constraint to a MessageWriter /// </summary> /// <param name="writer"></param> public override void WriteDescriptionTo(MessageWriter writer) { if (propertyName == null) writer.Write("collection ordered"); else { writer.WritePredicate("collection ordered by"); writer.WriteExpectedValue(propertyName); } if (descending) writer.WriteModifier("descending"); } /// <summary> /// Returns the string representation of the constraint. /// </summary> /// <returns></returns> protected override string GetStringRepresentation() { StringBuilder sb = new StringBuilder("<ordered"); if (propertyName != null) sb.Append("by " + propertyName); if (descending) sb.Append(" descending"); if (comparerName != null) sb.Append(" " + comparerName); sb.Append(">"); return sb.ToString(); } } }
35.237569
118
0.560677
[ "Apache-2.0" ]
Hitcents/iOS4Unity
Assets/NUnitLite/NUnitLite-0.7.0/Constraints/CollectionOrderedConstraint.cs
6,378
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 servicecatalog-2015-12-10.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.ServiceCatalog.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServiceCatalog.Model.Internal.MarshallTransformations { /// <summary> /// ListServiceActionsForProvisioningArtifact Request Marshaller /// </summary> public class ListServiceActionsForProvisioningArtifactRequestMarshaller : IMarshaller<IRequest, ListServiceActionsForProvisioningArtifactRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListServiceActionsForProvisioningArtifactRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListServiceActionsForProvisioningArtifactRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ServiceCatalog"); string target = "AWS242ServiceCatalogService.ListServiceActionsForProvisioningArtifact"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-12-10"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAcceptLanguage()) { context.Writer.WritePropertyName("AcceptLanguage"); context.Writer.Write(publicRequest.AcceptLanguage); } if(publicRequest.IsSetPageSize()) { context.Writer.WritePropertyName("PageSize"); context.Writer.Write(publicRequest.PageSize); } if(publicRequest.IsSetPageToken()) { context.Writer.WritePropertyName("PageToken"); context.Writer.Write(publicRequest.PageToken); } if(publicRequest.IsSetProductId()) { context.Writer.WritePropertyName("ProductId"); context.Writer.Write(publicRequest.ProductId); } if(publicRequest.IsSetProvisioningArtifactId()) { context.Writer.WritePropertyName("ProvisioningArtifactId"); context.Writer.Write(publicRequest.ProvisioningArtifactId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static ListServiceActionsForProvisioningArtifactRequestMarshaller _instance = new ListServiceActionsForProvisioningArtifactRequestMarshaller(); internal static ListServiceActionsForProvisioningArtifactRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListServiceActionsForProvisioningArtifactRequestMarshaller Instance { get { return _instance; } } } }
39.100775
198
0.6136
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ServiceCatalog/Generated/Model/Internal/MarshallTransformations/ListServiceActionsForProvisioningArtifactRequestMarshaller.cs
5,044
C#
using UnityEngine; namespace Chronos { /// <summary> /// An abstract base component that saves snapshots at regular intervals to enable rewinding. /// </summary> [HelpURL("http://ludiq.io/chronos/documentation#Recorder")] public abstract class Recorder<TSnapshot> : MonoBehaviour { private class DelegatedRecorder : RecorderTimeline<Component, TSnapshot> { private Recorder<TSnapshot> parent; public DelegatedRecorder(Recorder<TSnapshot> parent, Timeline timeline) : base(timeline, null) { this.parent = parent; } protected override void ApplySnapshot(TSnapshot snapshot) { parent.ApplySnapshot(snapshot); } protected override TSnapshot CopySnapshot() { return parent.CopySnapshot(); } protected override TSnapshot LerpSnapshots(TSnapshot from, TSnapshot to, float t) { return parent.LerpSnapshots(from, to, t); } } protected virtual void Awake() { CacheComponents(); } protected virtual void Start() { recorder.Start(); } protected virtual void Update() { recorder.Update(); } /// <summary> /// Modifies all snapshots via the specified modifier delegate. /// </summary> public virtual void ModifySnapshots(RecorderTimeline<Component, TSnapshot>.SnapshotModifier modifier) { recorder.ModifySnapshots(modifier); } private Timeline timeline; private RecorderTimeline<Component, TSnapshot> recorder; protected abstract void ApplySnapshot(TSnapshot snapshot); protected abstract TSnapshot CopySnapshot(); protected abstract TSnapshot LerpSnapshots(TSnapshot from, TSnapshot to, float t); public virtual void CacheComponents() { timeline = GetComponent<Timeline>(); if (timeline == null) { throw new ChronosException(string.Format("Missing timeline for recorder.")); } recorder = new DelegatedRecorder(this, timeline); } } }
23.78481
103
0.721128
[ "MIT" ]
uugspb/team1-NestedPCrew
Assets/ThirdParty/Chronos/Source/Recorder.cs
1,879
C#
/************************************************************* * Project: NetCoreCMS * * Web: http://dotnetcorecms.org * * Author: OnnoRokom Software Ltd. * * Website: www.onnorokomsoftware.com * * Email: info@onnorokomsoftware.com * * Copyright: OnnoRokom Software Ltd. * * License: BSD-3-Clause * *************************************************************/ using Microsoft.AspNetCore.Mvc.Rendering; using NetCoreCMS.Framework.Core.Models; using NetCoreCMS.Framework.Themes; using System; using System.Collections.Generic; using System.Text; namespace NetCoreCMS.Framework.Core.Models.ViewModels { public class StartupViewModel { public string Url { get; set; } public string StartupType { get; set; } public string RoleStartupType { get; set; } public string StartupFor { get; set; } public string PageId { get; set; } public SelectList Pages { get; set; } public string CategoryId { get; set; } public SelectList Categories { get; set; } public string PostId { get; set; } public SelectList Posts { get; set; } public string ModuleSiteMenuUrl { get; set; } public SelectList ModuleSiteMenus { get; set; } public SelectList Roles { get; set; } } }
39.945946
63
0.523004
[ "BSD-3-Clause" ]
NormanVu/NetCoreCMS
NetCoreCMS.Framework/Core/Models/ViewModels/StartupViewModel.cs
1,480
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementAndStatementStatementXssMatchStatementTextTransformationGetArgs : Pulumi.ResourceArgs { /// <summary> /// The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. /// </summary> [Input("priority", required: true)] public Input<int> Priority { get; set; } = null!; /// <summary> /// The transformation to apply, please refer to the Text Transformation [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementAndStatementStatementXssMatchStatementTextTransformationGetArgs() { } } }
45.46875
224
0.734708
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementAndStatementStatementXssMatchStatementTextTransformationGetArgs.cs
1,455
C#
namespace Pokladna_Dvoracek { partial class Form1 { /// <summary> /// Vyžaduje se proměnná návrháře. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Uvolněte všechny používané prostředky. /// </summary> /// <param name="disposing">hodnota true, když by se měl spravovaný prostředek odstranit; jinak false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Kód generovaný Návrhářem Windows Form /// <summary> /// Metoda vyžadovaná pro podporu Návrháře - neupravovat /// obsah této metody v editoru kódu. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.lvData = new System.Windows.Forms.ListView(); this.idDoklad = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.datum = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.castka = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.popis = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.zustatek = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.poznamka = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.cislo = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SuspendLayout(); // // panel1 // this.panel1.Dock = System.Windows.Forms.DockStyle.Right; this.panel1.Location = new System.Drawing.Point(569, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(272, 666); this.panel1.TabIndex = 0; // // lvData // this.lvData.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.idDoklad, this.cislo, this.datum, this.popis, this.castka, this.zustatek, this.poznamka}); this.lvData.Dock = System.Windows.Forms.DockStyle.Fill; this.lvData.HideSelection = false; this.lvData.Location = new System.Drawing.Point(0, 0); this.lvData.Name = "lvData"; this.lvData.Size = new System.Drawing.Size(569, 666); this.lvData.TabIndex = 0; this.lvData.UseCompatibleStateImageBehavior = false; this.lvData.View = System.Windows.Forms.View.Details; // // idDoklad // this.idDoklad.Text = "Č. dokladu"; // // datum // this.datum.Text = "Datum"; // // castka // this.castka.Text = "Částka"; // // popis // this.popis.Text = "Popis"; // // zustatek // this.zustatek.Text = "Zůstatek"; // // poznamka // this.poznamka.Text = "Poznámka"; // // cislo // this.cislo.Text = "Číslo"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(841, 666); this.Controls.Add(this.lvData); this.Controls.Add(this.panel1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ListView lvData; private System.Windows.Forms.ColumnHeader datum; private System.Windows.Forms.ColumnHeader idDoklad; private System.Windows.Forms.ColumnHeader popis; private System.Windows.Forms.ColumnHeader castka; private System.Windows.Forms.ColumnHeader zustatek; private System.Windows.Forms.ColumnHeader poznamka; private System.Windows.Forms.ColumnHeader cislo; } }
37.935484
118
0.55017
[ "MIT" ]
Kamils6/Pokladna
Pokladna/Form1.designer.cs
4,739
C#
using System; namespace DotNetRevolution.EventSourcing.Auditor.WebApi.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.536585
130
0.538603
[ "MIT" ]
DotNetRevolution/DotNetRevolution-Framework
src/DotNetRevolution.EventSourcing.Auditor.WebApi/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,088
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace P01_BillsPaymentSystem.Data.Models { public class User { public User() { PaymentMethods = new List<PaymentMethod>(); } [Key] public int UserId { get; set; } [MaxLength(80)] public string Email { get; set; } [MaxLength(50)] public string FirstName { get; set; } [MaxLength(50)] public string LastName { get; set; } [MaxLength(25)] public string Password { get; set; } public ICollection<PaymentMethod> PaymentMethods { get; set; } } }
21.28125
70
0.587372
[ "MIT" ]
ewgeni-dinew/04.Databases_Advanced-Entity_Framework
08.Advanced Relations/01.BillsPaymentSystem/P01_BillsPaymentSystem.Data.Models/User.cs
683
C#
namespace ChopstickDocker.Authorization.Accounts.Dto { public class IsTenantAvailableOutput { public TenantAvailabilityState State { get; set; } public int? TenantId { get; set; } public IsTenantAvailableOutput() { } public IsTenantAvailableOutput(TenantAvailabilityState state, int? tenantId = null) { State = state; TenantId = tenantId; } } }
22.4
91
0.607143
[ "MIT" ]
yhua045/chopstick-docker
aspnet-core/src/ChopstickDocker.Application/Authorization/Accounts/Dto/IsTenantAvailableOutput.cs
448
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Core { #if false || false || false || false [global::Uno.NotImplemented] #endif public partial class CoreDispatcher : global::Windows.UI.Core.ICoreAcceleratorKeys { #if false || false || false || false [global::Uno.NotImplemented] public bool HasThreadAccess { get { throw new global::System.NotImplementedException("The member bool CoreDispatcher.HasThreadAccess is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.UI.Core.CoreDispatcherPriority CurrentPriority { get { throw new global::System.NotImplementedException("The member CoreDispatcherPriority CoreDispatcher.CurrentPriority is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.CoreDispatcher", "CoreDispatcherPriority CoreDispatcher.CurrentPriority"); } } #endif // Forced skipping of method Windows.UI.Core.CoreDispatcher.HasThreadAccess.get #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void ProcessEvents( global::Windows.UI.Core.CoreProcessEventsOption options) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.CoreDispatcher", "void CoreDispatcher.ProcessEvents(CoreProcessEventsOption options)"); } #endif #if false || false || false || false [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction RunAsync( global::Windows.UI.Core.CoreDispatcherPriority priority, global::Windows.UI.Core.DispatchedHandler agileCallback) { throw new global::System.NotImplementedException("The member IAsyncAction CoreDispatcher.RunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback) is not implemented in Uno."); } #endif #if false || false || false || false [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction RunIdleAsync( global::Windows.UI.Core.IdleDispatchedHandler agileCallback) { throw new global::System.NotImplementedException("The member IAsyncAction CoreDispatcher.RunIdleAsync(IdleDispatchedHandler agileCallback) is not implemented in Uno."); } #endif // Forced skipping of method Windows.UI.Core.CoreDispatcher.AcceleratorKeyActivated.add // Forced skipping of method Windows.UI.Core.CoreDispatcher.AcceleratorKeyActivated.remove // Forced skipping of method Windows.UI.Core.CoreDispatcher.CurrentPriority.get // Forced skipping of method Windows.UI.Core.CoreDispatcher.CurrentPriority.set #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool ShouldYield() { throw new global::System.NotImplementedException("The member bool CoreDispatcher.ShouldYield() is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public bool ShouldYield( global::Windows.UI.Core.CoreDispatcherPriority priority) { throw new global::System.NotImplementedException("The member bool CoreDispatcher.ShouldYield(CoreDispatcherPriority priority) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public void StopProcessEvents() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.CoreDispatcher", "void CoreDispatcher.StopProcessEvents()"); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncOperation<bool> TryRunAsync( global::Windows.UI.Core.CoreDispatcherPriority priority, global::Windows.UI.Core.DispatchedHandler agileCallback) { throw new global::System.NotImplementedException("The member IAsyncOperation<bool> CoreDispatcher.TryRunAsync(CoreDispatcherPriority priority, DispatchedHandler agileCallback) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncOperation<bool> TryRunIdleAsync( global::Windows.UI.Core.IdleDispatchedHandler agileCallback) { throw new global::System.NotImplementedException("The member IAsyncOperation<bool> CoreDispatcher.TryRunIdleAsync(IdleDispatchedHandler agileCallback) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] public event global::Windows.Foundation.TypedEventHandler<global::Windows.UI.Core.CoreDispatcher, global::Windows.UI.Core.AcceleratorKeyEventArgs> AcceleratorKeyActivated { [global::Uno.NotImplemented] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.CoreDispatcher", "event TypedEventHandler<CoreDispatcher, AcceleratorKeyEventArgs> CoreDispatcher.AcceleratorKeyActivated"); } [global::Uno.NotImplemented] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.CoreDispatcher", "event TypedEventHandler<CoreDispatcher, AcceleratorKeyEventArgs> CoreDispatcher.AcceleratorKeyActivated"); } } #endif // Processing: Windows.UI.Core.ICoreAcceleratorKeys } }
47.289474
219
0.777036
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Core/CoreDispatcher.cs
5,391
C#
// Copyright (c) Microsoft. All rights reserved. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.Diagnostics; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.Exceptions; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.External; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.Helpers; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.Models; using Microsoft.Azure.IoTSolutions.IotHubManager.Services.Runtime; using Newtonsoft.Json; namespace Microsoft.Azure.IoTSolutions.IotHubManager.Services { public interface IDeviceProperties { Task<List<string>> GetListAsync(); Task<DevicePropertyServiceModel> UpdateListAsync( DevicePropertyServiceModel devicePropertyServiceModel); Task<bool> TryRecreateListAsync(bool force = false); } /// <summary> /// This class creates/reads cache of deviceProperties in/from CosmosDB. /// </summary> /// <remarks> /// This is done to avoid request throttling when deviceProperties are queried directly from IOT-Hub. /// This class is called "deviceProperties" even though it deals with both properties /// and tags of devices. /// </remarks> public class DeviceProperties : IDeviceProperties { private readonly IStorageAdapterClient storageClient; private readonly IDevices devices; private readonly ILogger log; /// Hardcoded in appsettings.ini private readonly string whitelist; /// Hardcoded in appsettings.ini private readonly long ttl; /// Hardcoded in appsettings.ini private readonly long rebuildTimeout; private readonly TimeSpan serviceQueryInterval = TimeSpan.FromSeconds(10); internal const string CACHE_COLLECTION_ID = "device-twin-properties"; internal const string CACHE_KEY = "cache"; private const string WHITELIST_TAG_PREFIX = "tags."; private const string WHITELIST_REPORTED_PREFIX = "reported."; private const string TAG_PREFIX = "Tags."; private const string REPORTED_PREFIX = "Properties.Reported."; private DateTime DevicePropertiesLastUpdated; /// <summary> /// The constructor. /// </summary> public DeviceProperties(IStorageAdapterClient storageClient, IServicesConfig config, ILogger logger, IDevices devices) { this.storageClient = storageClient; this.log = logger; this.whitelist = config.DevicePropertiesWhiteList; this.ttl = config.DevicePropertiesTTL; this.rebuildTimeout = config.DevicePropertiesRebuildTimeout; this.devices = devices; } /// <summary> /// Get List of deviceProperties from cache /// </summary> public async Task<List<string>> GetListAsync() { ValueApiModel response = new ValueApiModel(); try { response = await this.storageClient.GetAsync(CACHE_COLLECTION_ID, CACHE_KEY); } catch (ResourceNotFoundException) { this.log.Debug($"Cache get: cache {CACHE_COLLECTION_ID}:{CACHE_KEY} was not found", () => { }); } catch (Exception e) { throw new ExternalDependencyException( $"Cache get: unable to get device-twin-properties cache", e); } DevicePropertyServiceModel properties = new DevicePropertyServiceModel(); try { properties = JsonConvert.DeserializeObject<DevicePropertyServiceModel>(response.Data); } catch (Exception e) { throw new InvalidInputException("Unable to deserialize deviceProperties from CosmosDB", e); } List<string> result = new List<string>(); foreach (string tag in properties.Tags) { result.Add(TAG_PREFIX + tag); } foreach (string reported in properties.Reported) { result.Add(REPORTED_PREFIX + reported); } return result; } /// <summary> /// Try to create cache of deviceProperties if lock failed retry after 10 seconds /// </summary> public async Task<bool> TryRecreateListAsync(bool force = false) { var @lock = new StorageWriteLock<DevicePropertyServiceModel>( this.storageClient, CACHE_COLLECTION_ID, CACHE_KEY, (c, b) => c.Rebuilding = b, m => this.ShouldCacheRebuild(force, m)); while (true) { var locked = await @lock.TryLockAsync(); if (locked == null) { this.log.Warn("Cache rebuilding: lock failed due to conflict. Retry soon", () => { }); continue; } if (!locked.Value) { return false; } // Build the cache content var twinNamesTask = this.GetValidNamesAsync(); try { Task.WaitAll(twinNamesTask); } catch (Exception) { this.log.Warn( $"Some underlying service is not ready. Retry after {this.serviceQueryInterval}", () => { }); try { await @lock.ReleaseAsync(); } catch (Exception e) { log.Error("Cache rebuilding: Unable to release lock", () => e); } await Task.Delay(this.serviceQueryInterval); continue; } var twinNames = twinNamesTask.Result; try { var updated = await @lock.WriteAndReleaseAsync( new DevicePropertyServiceModel { Tags = twinNames.Tags, Reported = twinNames.ReportedProperties }); if (updated) { this.DevicePropertiesLastUpdated = DateTime.Now; return true; } } catch (Exception e) { log.Error("Cache rebuilding: Unable to write and release lock", () => e); } this.log.Warn("Cache rebuilding: write failed due to conflict. Retry soon", () => { }); } } /// <summary> /// Update Cache when devices are modified/created /// </summary> public async Task<DevicePropertyServiceModel> UpdateListAsync( DevicePropertyServiceModel deviceProperties) { // To simplify code, use empty set to replace null set deviceProperties.Tags = deviceProperties.Tags ?? new HashSet<string>(); deviceProperties.Reported = deviceProperties.Reported ?? new HashSet<string>(); string etag = null; while (true) { ValueApiModel model = null; try { model = await this.storageClient.GetAsync(CACHE_COLLECTION_ID, CACHE_KEY); } catch (ResourceNotFoundException) { this.log.Info($"Cache updating: cache {CACHE_COLLECTION_ID}:{CACHE_KEY} was not found", () => { }); } if (model != null) { DevicePropertyServiceModel devicePropertiesFromStorage; try { devicePropertiesFromStorage = JsonConvert. DeserializeObject<DevicePropertyServiceModel>(model.Data); } catch { devicePropertiesFromStorage = new DevicePropertyServiceModel(); } devicePropertiesFromStorage.Tags = devicePropertiesFromStorage.Tags ?? new HashSet<string>(); devicePropertiesFromStorage.Reported = devicePropertiesFromStorage.Reported ?? new HashSet<string>(); deviceProperties.Tags.UnionWith(devicePropertiesFromStorage.Tags); deviceProperties.Reported.UnionWith(devicePropertiesFromStorage.Reported); etag = model.ETag; // If the new set of deviceProperties are already there in cache, return if (deviceProperties.Tags.Count == devicePropertiesFromStorage.Tags.Count && deviceProperties.Reported.Count == devicePropertiesFromStorage.Reported.Count) { return deviceProperties; } } var value = JsonConvert.SerializeObject(deviceProperties); try { var response = await this.storageClient.UpdateAsync( CACHE_COLLECTION_ID, CACHE_KEY, value, etag); return JsonConvert.DeserializeObject<DevicePropertyServiceModel>(response.Data); } catch (ConflictingResourceException) { this.log.Info("Cache updating: failed due to conflict. Retry soon", () => { }); } catch (Exception e) { this.log.Info("Cache updating: failed", () => e); throw new Exception("Cache updating: failed"); } } } /// <summary> /// Get list of DeviceTwinNames from IOT-hub and whitelist it. /// </summary> /// <remarks> /// List of Twin Names to be whitelisted is hardcoded in appsettings.ini /// </remarks> private async Task<DeviceTwinName> GetValidNamesAsync() { ParseWhitelist(this.whitelist, out var fullNameWhitelist, out var prefixWhitelist); var validNames = new DeviceTwinName { Tags = fullNameWhitelist.Tags, ReportedProperties = fullNameWhitelist.ReportedProperties }; if (prefixWhitelist.Tags.Any() || prefixWhitelist.ReportedProperties.Any()) { DeviceTwinName allNames = new DeviceTwinName(); try { /// Get list of DeviceTwinNames from IOT-hub allNames = await this.devices.GetDeviceTwinNamesAsync(); } catch (Exception e) { throw new ExternalDependencyException("Unable to fetch IoT devices", e); } validNames.Tags.UnionWith(allNames.Tags. Where(s => prefixWhitelist.Tags.Any(s.StartsWith))); validNames.ReportedProperties.UnionWith( allNames.ReportedProperties.Where( s => prefixWhitelist.ReportedProperties.Any(s.StartsWith))); } return validNames; } /// <summary> /// Parse the comma seperated string "whitelist" and create two separate list /// One with regex(*) and one without regex(*) /// </summary> /// <param name="whitelist">Comma seperated list of deviceTwinName to be /// whitlisted which is hardcoded in appsettings.ini.</param> /// <param name="fullNameWhitelist">An out paramenter which is a list of /// deviceTwinName to be whitlisted without regex.</param> /// <param name="prefixWhitelist">An out paramenter which is a list of /// deviceTwinName to be whitlisted with regex.</param> private static void ParseWhitelist(string whitelist, out DeviceTwinName fullNameWhitelist, out DeviceTwinName prefixWhitelist) { /// <example> /// whitelist = "tags.*, reported.Protocol, reported.SupportedMethods, /// reported.DeviceMethodStatus, reported.FirmwareUpdateStatus" /// whitelistItems = [tags.*, /// reported.Protocol, /// reported.SupportedMethods, /// reported.DeviceMethodStatus, /// reported.FirmwareUpdateStatus] /// </example> var whitelistItems = whitelist.Split(',').Select(s => s.Trim()); /// <example> /// tags = [tags.*] /// </example> var tags = whitelistItems .Where(s => s.StartsWith(WHITELIST_TAG_PREFIX, StringComparison.OrdinalIgnoreCase)) .Select(s => s.Substring(WHITELIST_TAG_PREFIX.Length)); /// <example> /// reported = [reported.Protocol, /// reported.SupportedMethods, /// reported.DeviceMethodStatus, /// reported.FirmwareUpdateStatus] /// </example> var reported = whitelistItems .Where(s => s.StartsWith(WHITELIST_REPORTED_PREFIX, StringComparison.OrdinalIgnoreCase)) .Select(s => s.Substring(WHITELIST_REPORTED_PREFIX.Length)); /// <example> /// fixedTags = [] /// </example> var fixedTags = tags.Where(s => !s.EndsWith("*")); /// <example> /// fixedReported = [reported.Protocol, /// reported.SupportedMethods, /// reported.DeviceMethodStatus, /// reported.FirmwareUpdateStatus] /// </example> var fixedReported = reported.Where(s => !s.EndsWith("*")); /// <example> /// regexTags = [tags.] /// </example> var regexTags = tags.Where(s => s.EndsWith("*")).Select(s => s.Substring(0, s.Length - 1)); /// <example> /// regexReported = [] /// </example> var regexReported = reported. Where(s => s.EndsWith("*")). Select(s => s.Substring(0, s.Length - 1)); /// <example> /// fullNameWhitelist = {Tags = [], /// ReportedProperties = [ /// reported.Protocol, /// reported.SupportedMethods, /// reported.DeviceMethodStatus, /// reported.FirmwareUpdateStatus] /// } /// </example> fullNameWhitelist = new DeviceTwinName { Tags = new HashSet<string>(fixedTags), ReportedProperties = new HashSet<string>(fixedReported) }; /// <example> /// prefixWhitelist = {Tags = [tags.], /// ReportedProperties = []} /// </example> prefixWhitelist = new DeviceTwinName { Tags = new HashSet<string>(regexTags), ReportedProperties = new HashSet<string>(regexReported) }; } /// <summary> /// A function to decide whether or not cache needs to be rebuilt based on force flag and existing /// cache's validity /// </summary> /// <param name="force">A boolean flag to decide if cache needs to be rebuilt.</param> /// <param name="valueApiModel">An existing valueApiModel to check whether or not cache /// has expired</param> private bool ShouldCacheRebuild(bool force, ValueApiModel valueApiModel) { if (force) { this.log.Info("Cache will be rebuilt due to the force flag", () => { }); return true; } if (valueApiModel == null) { this.log.Info("Cache will be rebuilt since no cache was found", () => { }); return true; } DevicePropertyServiceModel cacheValue = new DevicePropertyServiceModel(); DateTimeOffset timstamp = new DateTimeOffset(); try { cacheValue = JsonConvert.DeserializeObject<DevicePropertyServiceModel>(valueApiModel.Data); timstamp = DateTimeOffset.Parse(valueApiModel.Metadata["$modified"]); } catch { this.log.Info("DeviceProperties will be rebuilt because the last one is broken.", () => { }); return true; } if (cacheValue.Rebuilding) { if (timstamp.AddSeconds(this.rebuildTimeout) < DateTimeOffset.UtcNow) { this.log.Debug("Cache will be rebuilt because last rebuilding had timedout", () => { }); return true; } else { this.log.Debug ("Cache rebuilding skipped because it is being rebuilt by other instance", () => { }); return false; } } else { if (cacheValue.IsNullOrEmpty()) { this.log.Info("Cache will be rebuilt since it is empty", () => { }); return true; } if (timstamp.AddSeconds(this.ttl) < DateTimeOffset.UtcNow) { this.log.Info("Cache will be rebuilt because it has expired", () => { }); return true; } else { this.log.Debug("Cache rebuilding skipped because it has not expired", () => { }); return false; } } } } }
40.527233
110
0.515859
[ "MIT" ]
Azure-Samples/AI-Video-Intelligence-Solution-Accelerator
pcs/services/iothub-manager/Services/DeviceProperties.cs
18,604
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using TravelAPI.Models; namespace TravelAPI.Migrations { [DbContext(typeof(TravelAPIContext))] [Migration("20210525224819_userName")] partial class userName { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("TravelAPI.Models.Location", b => { b.Property<int>("LocationId") .ValueGeneratedOnAdd(); b.Property<string>("City") .IsRequired() .HasMaxLength(20); b.Property<string>("Country") .IsRequired() .HasMaxLength(20); b.Property<int>("Rating"); b.Property<string>("Review") .IsRequired(); b.Property<string>("User_Name") .IsRequired() .HasMaxLength(30); b.HasKey("LocationId"); b.ToTable("Locations"); }); #pragma warning restore 612, 618 } } }
30.607843
75
0.536835
[ "MIT" ]
CommaderDavid/TravelAPI.Solution
TravelAPI/Migrations/20210525224819_userName.Designer.cs
1,563
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace AppPicker { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
19.333333
59
0.553292
[ "MIT" ]
dfilitto/ProjetosXamarinForms
AppPicker/AppPicker/AppPicker/App.xaml.cs
640
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Squidex.Areas.Frontend.Middlewares { public sealed class IndexMiddleware { private readonly RequestDelegate next; public IndexMiddleware(RequestDelegate next) { this.next = next; } public async Task InvokeAsync(HttpContext context) { if (context.IsHtmlPath() && !context.Response.IsNotModified()) { var responseBuffer = new MemoryStream(); var responseBody = context.Response.Body; context.Response.Body = responseBuffer; await next(context); if (!context.Response.IsNotModified()) { context.Response.Body = responseBody; var html = Encoding.UTF8.GetString(responseBuffer.ToArray()); html = html.AdjustBase(context); if (context.IsIndex()) { html = html.AddOptions(context); } context.Response.ContentLength = Encoding.UTF8.GetByteCount(html); context.Response.Body = responseBody; await context.Response.WriteAsync(html, context.RequestAborted); } } else { await next(context); } } } }
30.491803
86
0.474194
[ "MIT" ]
Dakraid/squidex
backend/src/Squidex/Areas/Frontend/Middlewares/IndexMiddleware.cs
1,862
C#
using System.Collections.Generic; using System.Security.Claims; using NetModular.Module.Admin.Domain.Account; namespace NetModular.Module.Admin.Web.Core { /// <summary> /// 登录Claims扩展处理器 /// </summary> public interface ILoginClaimsExtendProvider { /// <summary> /// 获取扩展Claims列表 /// </summary> /// <param name="account"></param> /// <returns></returns> List<Claim> GetExtendClaims(AccountEntity account); } }
24.15
59
0.627329
[ "MIT" ]
neeker007/NetModular
src/Admin/Web/Core/ILoginClaimsExtendProvider.cs
511
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class GeneratedTypesManager { private class GeneratedFieldSymbol : FieldSymbol { private NamedTypeSymbol _containingType; private ConstantValue _constantValue; public GeneratedFieldSymbol(GeneratedFieldMemberDescriptor descriptor) { Descriptor = descriptor; } protected GeneratedFieldMemberDescriptor Descriptor { get; } public virtual GeneratedFieldSymbol Build(NamedTypeSymbol containingType, Symbol ownerMemberSymbol, ConstantValue constantValue) { // the member that owns this field - the "associated" member / the member to which this field is "attached" // - for "backing fields" this would be the "property symbol" OwnerMemberSymbol = ownerMemberSymbol; _containingType = containingType; return this; } protected GeneratedTypesManager Manager { get { var generatedType = _containingType as GeneratedTypeSymbol; return ((object)generatedType != null) ? generatedType.Manager : ((GeneratedTypeSymbol)_containingType).Manager; } } public Symbol OwnerMemberSymbol { get; internal set; } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) => Descriptor.Type; public override string Name => Descriptor.Name; public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override bool HasSpecialName => false; internal override bool HasRuntimeSpecialName => false; internal override bool IsNotSerialized => false; internal override MarshalPseudoCustomAttributeData MarshallingInformation => null; internal override int? TypeLayoutOffset => null; public override Symbol AssociatedSymbol => OwnerMemberSymbol; public override bool IsReadOnly => Descriptor.IsReadOnly; public override bool IsVolatile => Descriptor.IsVolatile; public override bool IsConst => Descriptor.IsConst; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) => _constantValue; public override Symbol ContainingSymbol => _containingType; public override NamedTypeSymbol ContainingType => _containingType; public override ImmutableArray<Location> Locations => Descriptor.Locations ?? ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => Descriptor.DeclaringSyntaxReferences ?? ImmutableArray<SyntaxReference>.Empty; public override Accessibility DeclaredAccessibility => Descriptor.Accessibility ?? Accessibility.Internal; public override bool IsStatic => Descriptor.IsStatic; public override bool IsImplicitlyDeclared => true; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (!Descriptor.IsDebuggerBrowsable) { AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(new TypedConstant(Manager.KnownSymbols.System_Diagnostics_DebuggerBrowsableState, TypedConstantKind.Enum, DebuggerBrowsableState.Never))) ); } if (Descriptor.IsDebuggerHidden) { AddSynthesizedAttribute(ref attributes, Manager.Compilation.TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); } } } } }
37.671642
183
0.639461
[ "MIT" ]
bilsaboob/roslyn
src/Compilers/CSharp/Portable/Symbols/GeneratedTypes/SynthesizedSymobls/GeneratedType.FieldSymbol.cs
5,050
C#
namespace Methods { using System; public class Student { // The date is 10 simbols. I think consts can have underscores. public const int MIN_INFO_LENGHT = 10; private string firstName; private string lastName; private string otherInfo; private DateTime birthday; public Student(string firstNameInput, string lastNameInput, string otherInfoInput) { this.FirstName = firstNameInput; this.LastName = lastNameInput; this.OtherInfo = otherInfoInput; } public string FirstName { get { return this.firstName; } set { if (value.Trim().Length > 1) { this.firstName = value; } else { throw new ArgumentOutOfRangeException("First name must be with more than one simbol."); } } } public string LastName { get { return this.lastName; } set { if (value.Trim().Length > 1) { this.lastName = value; } else { throw new ArgumentOutOfRangeException("Last name must be with more than one simbol."); } } } public string OtherInfo { get { return this.otherInfo; } set { DateTime birthdayInput; // Trim for useless empty spaces. if (value.Trim().Length < MIN_INFO_LENGHT) { throw new ArgumentOutOfRangeException("Student info must contain more than " + MIN_INFO_LENGHT + " simbols."); } // Check if the last 10 simbols are not a valid date. if (DateTime.TryParse(value.Substring(value.Length - 10), out birthdayInput) == false) { throw new FormatException("Bad data format in Other Info section."); } this.birthday = DateTime.Parse(value.Substring(value.Length - 10)); this.otherInfo = value; } } public bool IsOlderThan(Student other) { bool isOlder = this.birthday < other.birthday; return isOlder; } } }
27.21875
130
0.457329
[ "MIT" ]
TsvetanKT/TelerikHomeworks
HQC/07.HighQualityMethods/Methods/Student.cs
2,615
C#
// <copyright file="IDataContainer.cs" company="SoluiNet"> // Copyright (c) SoluiNet. All rights reserved. // </copyright> namespace SoluiNet.DevTools.Core.Plugin.Data { using System; using System.Collections.Generic; using System.Text; using SoluiNet.DevTools.Core.Data; /// <summary> /// Provides a container for data. /// </summary> public interface IDataContainer { /// <summary> /// Gets the data. /// </summary> BaseDictionary Data { get; } } }
22.869565
59
0.617871
[ "MIT" ]
Kimiyou/SoluiNet.DevTools
SoluiNet.DevTools.Core/Plugin/Data/IDataContainer.cs
528
C#
using UnityEngine; using System.Collections; public class Projectile : MonoBehaviour { [SerializeField] private float lifetime = 10; [SerializeField] private float speed = 2; public void FixedUpdate() { if (!GameManager.Instance.Running) return; lifetime -= Time.fixedDeltaTime; if (lifetime <= 0) Destroy(gameObject); this.transform.position += this.transform.forward * speed; } }
18.92
66
0.623679
[ "MIT" ]
icsti1379/MS-GameJam-2016
Assets/Scripts/Projectile.cs
475
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using EnsureThat; using Microsoft.Health.CosmosDb.Features.Storage; using Microsoft.Health.Fhir.Core.Features.Operations; using Microsoft.Health.Fhir.Core.Features.Operations.Export.Models; using Newtonsoft.Json; namespace Microsoft.Health.Fhir.CosmosDb.Features.Storage.Operations.Export { /// <summary> /// A wrapper around the <see cref="ExportJobRecord"/> class that contains metadata specific to CosmosDb. /// </summary> internal class CosmosExportJobRecordWrapper : CosmosJobRecordWrapper { public CosmosExportJobRecordWrapper(ExportJobRecord exportJobRecord) { EnsureArg.IsNotNull(exportJobRecord, nameof(exportJobRecord)); JobRecord = exportJobRecord; Id = exportJobRecord.Id; } [JsonConstructor] protected CosmosExportJobRecordWrapper() { } [JsonProperty(KnownDocumentProperties.PartitionKey)] public override string PartitionKey { get; } = CosmosDbExportConstants.ExportJobPartitionKey; [JsonProperty(JobRecordProperties.JobRecord)] public ExportJobRecord JobRecord { get; private set; } } }
38.846154
109
0.626403
[ "MIT" ]
Bhaskers-Blu-Org2/fhir-server
src/Microsoft.Health.Fhir.CosmosDb/Features/Storage/Operations/Export/CosmosExportJobRecordWrapper.cs
1,517
C#
/* ******************************************************************** * * 曹旭升(sheng.c) * E-mail: cao.silhouette@msn.com * QQ: 279060597 * https://github.com/iccb1013 * http://shengxunwei.com * * © Copyright 2017 * ********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Sheng.Weixin.OfficialAccount { [DataContract] public class ButtonMediaId : TypeButton { /// <summary> /// 调用新增永久素材接口返回的合法media_id /// </summary> [DataMember(Name = "media_id")] public string MediaId { get; set; } public ButtonMediaId() { this.Type = ButtonType.MediaId; } } }
20.44186
69
0.491468
[ "MIT" ]
iccb1013/Sheng.WeixinConstruction.WeixinContract
Sheng.Weixin/OfficialAccount/Menu/ButtonMediaId.cs
922
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 devicefarm-2015-06-23.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.DeviceFarm.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UntagResource operation /// </summary> public class UntagResourceResponseUnmarshaller : 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) { UntagResourceResponse response = new UntagResourceResponse(); 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) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("ArgumentException")) { return new ArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("TagOperationException")) { return new TagOperationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonDeviceFarmException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static UntagResourceResponseUnmarshaller _instance = new UntagResourceResponseUnmarshaller(); internal static UntagResourceResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UntagResourceResponseUnmarshaller Instance { get { return _instance; } } } }
38.785714
165
0.676401
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/UntagResourceResponseUnmarshaller.cs
3,801
C#
//************************************************************************************************ // Copyright © 2010 Steven M. Cohn. All Rights Reserved. // //************************************************************************************************ namespace iTunerTests { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using iTunesLib; using iTuner.iTunes; [TestClass] public class CatalogTests : TestBase { private static iTunesAppClass itunes; private static string libraryXMLPath; //======================================================================================== // Lifecycle //======================================================================================== #region Lifecycle [ClassInitialize()] public static void MyClassInitialize (TestContext testContext) { itunes = new iTunesAppClass(); libraryXMLPath = itunes.LibraryXMLPath; } [ClassCleanup] public static void MyClassCleanup () { Console.WriteLine("**** Unit test shutdown"); if (itunes != null) { itunes = null; } } #endregion Lifecycle //======================================================================================== // Loading Tests //======================================================================================== [TestMethod] [Ignore] public void LoadFlat () { ICatalog catalog = new FlatCatalog(); catalog.Initialize(libraryXMLPath); } [TestMethod] public void LoadTerse () { ICatalog catalog = new TerseCatalog(); catalog.Initialize(libraryXMLPath); string music = catalog.MusicPath; //catalog.DeleteFile(@"C:\Music\4 Non Blondes\Bigger, Better, Faster, More\02 Superfly.mp3"); //catalog.DeleteFile(@"C:\Music\4 Non Blondes\Bigger, Better, Faster, More\02 Superfly.mp3"); } //======================================================================================== // Tests //======================================================================================== [TestMethod] public void FlatTerseComparisons () { // create two playlists, both name "Ben" and use this to test that we can // find the extensions in the first one ICatalog flat = new FlatCatalog(); flat.Initialize(libraryXMLPath); ICatalog terse = new TerseCatalog(); terse.Initialize(libraryXMLPath); PersistentID pid = GetPlaylistPersistentID("Ben"); // FindExtensionsByPlaylist() StringCollection flatExtensions = flat.FindExtensionsByPlaylist(pid); Assert.IsNotNull(flatExtensions); Assert.AreNotEqual(0, flatExtensions.Count); StringCollection terseExtensions = terse.FindExtensionsByPlaylist(pid); Assert.IsNotNull(terseExtensions); Assert.AreNotEqual(0, terseExtensions.Count); Assert.AreEqual(flatExtensions.Count, terseExtensions.Count); foreach (string ext in terseExtensions) { Assert.IsTrue(flatExtensions.Contains(ext)); } Console.WriteLine("FindExtensionsByPlaylist() OK"); // FindPlaylistName() string name = flat.FindPlaylistName(pid); Assert.AreEqual("Ben", name); name = terse.FindPlaylistName(pid); Assert.AreEqual("Ben", name); Console.WriteLine("FindPlaylistName() OK"); // FindTracksByAlbum() PersistentIDCollection flatTracks = flat.FindTracksByAlbum("Greatest Hits", "Alice Cooper"); Assert.IsNotNull(flatTracks); Assert.AreNotEqual(0, flatTracks.Count); PersistentIDCollection terseTracks = terse.FindTracksByAlbum("Greatest Hits", "Alice Cooper"); Assert.IsNotNull(terseTracks); Assert.AreNotEqual(0, terseTracks.Count); Assert.AreEqual(flatTracks.Count, terseTracks.Count); foreach (PersistentID id in terseTracks) { Assert.IsTrue(flatTracks.Contains(id)); } Console.WriteLine("FindTracksByAlbum() OK"); // FindTracksByArtist() flatTracks = flat.FindTracksByArtist("Alice Cooper"); Assert.IsNotNull(flatTracks); Assert.AreNotEqual(0, flatTracks.Count); terseTracks = terse.FindTracksByArtist("Alice Cooper"); Assert.IsNotNull(terseTracks); Assert.AreNotEqual(0, terseTracks.Count); Assert.AreEqual(flatTracks.Count, terseTracks.Count); foreach (PersistentID id in terseTracks) { Assert.IsTrue(flatTracks.Contains(id)); } Console.WriteLine("FindTracksByArtist() OK"); // FindTracksByPlaylist() pid = GetPlaylistPersistentID("My Top Rated"); flatTracks = flat.FindTracksByPlaylist(pid); Assert.IsNotNull(flatTracks); Assert.AreNotEqual(0, flatTracks.Count); terseTracks = terse.FindTracksByPlaylist(pid); Assert.IsNotNull(terseTracks); Assert.AreNotEqual(0, terseTracks.Count); Assert.AreEqual(flatTracks.Count, terseTracks.Count); foreach (PersistentID id in terseTracks) { Assert.IsTrue(flatTracks.Contains(id)); } Console.WriteLine("FindTracksByPlaylist() OK"); } private PersistentID GetPlaylistPersistentID (string name) { IITPlaylist playlist = itunes.LibrarySource.Playlists.get_ItemByName(name); PersistentID pid = GetPersistentID(playlist); return pid; } //======================================================================================== // Linq Speed Tests //======================================================================================== #region Linq Speed Tests //FindCatalogedTracksByAlbum-------------------------------------------------------------- //new FlatCatalog() -> 14284.0023654521 ms //FindTracksByAlbum -> 22.4926922855539 ms //Tracks[] -> 3.66109802877771 ms //Completed in 14310.163854851 ms //FindCatalogedTracksByAlbum Completed: Passed-------------------------------------------- [TestMethod] public void FindCatalogedTracksByAlbum () { // FlatCatalog ICatalog catalog = new FlatCatalog(); catalog.Initialize(libraryXMLPath); Console.WriteLine(String.Format("new FlatCatalog() -> {0} ms", watch.GetSplitMilliseconds())); PersistentIDCollection trackIDs = catalog.FindTracksByAlbum("Ganging Up on the Sun", "Guster"); Console.WriteLine(String.Format("FindTracksByAlbum -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(trackIDs); Assert.AreNotEqual(0, trackIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", trackIDs.Count)); ReportPrivateDelta(); // TerseCatalog catalog = new TerseCatalog(); catalog.Initialize(libraryXMLPath); Console.WriteLine(String.Format("new TerseCatalog() -> {0} ms", watch.GetSplitMilliseconds())); trackIDs = catalog.FindTracksByAlbum("Ganging Up on the Sun", "Guster"); Console.WriteLine(String.Format("FindTracksByAlbum -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(trackIDs); Assert.AreNotEqual(0, trackIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", trackIDs.Count)); ReportPrivateDelta(); // Controller using (var controller = new Controller()) { System.Threading.Thread.Sleep(2000); // let the controller initialize List<Track> tracks = new List<Track>(); foreach (PersistentID persistentID in trackIDs) { Track track = controller.LibraryPlaylist.GetTrack(persistentID); tracks.Add(track); } Console.WriteLine(String.Format("Tracks[] -> {0} ms", watch.GetSplitMilliseconds())); // iTunes List<Track> tracks2 = new List<Track>(); foreach (PersistentID persistentID in trackIDs) { IITTrack itrack = itunes.LibraryPlaylist.Tracks.get_ItemByPersistentID( persistentID.HighBits, persistentID.LowBits); Track track = new Track(itrack); tracks2.Add(track); } Console.WriteLine(String.Format("ITracks[] -> {0} ms", watch.GetSplitMilliseconds())); Assert.AreNotEqual(0, tracks.Count); } } [TestMethod] public void FindCatalogedTracksByArtist () { // FlatCatalog ICatalog catalog = new FlatCatalog(); catalog.Initialize(libraryXMLPath); Console.WriteLine(String.Format("new FlatCatalog() -> {0} ms", watch.GetSplitMilliseconds())); PersistentIDCollection trackIDs = catalog.FindTracksByArtist("Guster"); Console.WriteLine(String.Format("FindTracksByArtist/Flat -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(trackIDs); Assert.AreNotEqual(0, trackIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", trackIDs.Count)); ReportPrivateDelta(); // TerseCatalog catalog = new TerseCatalog(); catalog.Initialize(libraryXMLPath); Console.WriteLine(String.Format("new TerseCatalog() -> {0} ms", watch.GetSplitMilliseconds())); trackIDs = catalog.FindTracksByArtist("Guster"); Console.WriteLine(String.Format("FindTracksByArtist/Terse -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(trackIDs); Assert.AreNotEqual(0, trackIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", trackIDs.Count)); ReportPrivateDelta(); // Controller using (var controller = new Controller()) { System.Threading.Thread.Sleep(2000); // let the controller initialize trackIDs = new PersistentIDCollection(); foreach (Track track in controller.LibraryPlaylist.Tracks.Values) { if ((track != null) && !String.IsNullOrEmpty(track.Artist)) { if (track.Artist.Equals("Guster")) { trackIDs.Add(track.PersistentID); } } } } Console.WriteLine(String.Format("FindTracksByArtist/Controller -> {0} ms", watch.GetSplitMilliseconds())); // iTunes trackIDs = new PersistentIDCollection(); foreach (IITTrack track in itunes.LibraryPlaylist.Tracks) { if ((track != null) && !String.IsNullOrEmpty(track.Artist)) { if (track.Artist.Equals("Guster")) { trackIDs.Add(GetPersistentID(track)); } } } Console.WriteLine(String.Format("FindTracksByArtist/iTunes -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(trackIDs); Assert.AreNotEqual(0, trackIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", trackIDs.Count)); ReportPrivateDelta(); } private PersistentID GetPersistentID (IITObject obj) { object refobj = obj; int high, low; itunes.GetITObjectPersistentIDs(ref refobj, out high, out low); return new PersistentID(high, low); } //FindITunesTracksByAlbum----------------------------------------------------------------- //Completed in 29889.8081351461 ms //FindITunesTracksByAlbum Completed: Passed----------------------------------------------- [TestMethod] public void FindITunesTracksByAlbum () { List<Track> tracks = new List<Track>(); foreach (IITTrack track in itunes.LibraryPlaylist.Tracks) { if (track.Album != null) { if (track.Album.ToLower().Equals("ganging up on the sun")) { tracks.Add(new Track(track)); } } } } [TestMethod] public void FindCatalogedTracksByPlaylist () { // FlatCatalog ICatalog catalog = new FlatCatalog(); catalog.Initialize(libraryXMLPath); Console.WriteLine(String.Format("new FlatCatalog() -> {0} ms", watch.GetSplitMilliseconds())); var tracks = new List<IITTrack>(); PersistentID pid = GetPlaylistPersistentID("ituner"); PersistentIDCollection persistentIDs = catalog.FindTracksByPlaylist(pid); foreach (PersistentID persistentID in persistentIDs) { IITTrack itrack = itunes.LibraryPlaylist.Tracks.get_ItemByPersistentID( persistentID.HighBits, persistentID.LowBits); tracks.Add(itrack); } Console.WriteLine(String.Format("FindTracksByPlaylist -> {0} ms", watch.GetSplitMilliseconds())); Assert.IsNotNull(persistentIDs); Assert.AreNotEqual(0, persistentIDs.Count); Console.WriteLine(String.Format("Found {0} tracks", persistentIDs.Count)); watch.Stop(); Console.WriteLine(String.Format("Completed in {0} ms", watch.GetElapsedMilliseconds())); // iTunes watch.Reset(); watch.Start(); IITTrackCollection itracks = itunes.LibrarySource.Playlists.get_ItemByName("ituner").Tracks; Console.WriteLine(String.Format("get_ItemByName -> {0} ms", watch.GetSplitMilliseconds())); watch.Stop(); Console.WriteLine(String.Format("Completed in {0} ms", watch.GetElapsedMilliseconds())); } #endregion Linq Speed Tests [TestMethod] public void ReloadPlaylist () { // 46CD262697DA37D9 == Classical Music PersistentID persistentID = PersistentID.Parse("46CD262697DA37D9"); XElement playlist = null; try { using (Stream stream = File.Open(libraryXMLPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; settings.DtdProcessing = DtdProcessing.Ignore; using (var reader = XmlReader.Create(stream, settings)) { // read into //plist/dict and stop at the first ./array // this is the playlists collection if (reader.ReadToDescendant("array")) { // by using this subreader and pumping the stream through // XElement.ReadFrom, we should avoid the Large Object Heap using (var subreader = reader.ReadSubtree()) { playlist = XElement.ReadFrom(subreader) as XElement; } } } } } catch (Exception exc) { Debug.WriteLine(exc.Message); return; } if (playlist != null) { XElement target = (from node in playlist .Elements("dict") .Elements("key") where node.Value == "Playlist Persistent ID" && ((XElement)node.NextNode).Value == (string)persistentID select node.Parent).FirstOrDefault(); if (target != null) { var list = from node in target .Elements("array") .Elements("dict") .Elements("integer") select node.Value; } } } } }
28.041916
109
0.642181
[ "MIT" ]
stevencohn/iTuner
iTunerTests/CatalogTests.cs
14,052
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Mts.Transform; using Aliyun.Acs.Mts.Transform.V20140618; using System.Collections.Generic; namespace Aliyun.Acs.Mts.Model.V20140618 { public class AddTemplateRequest : RpcAcsRequest<AddTemplateResponse> { public AddTemplateRequest() : base("Mts", "2014-06-18", "AddTemplate", "mts", "openAPI") { } private string container; private long? resourceOwnerId; private string resourceOwnerAccount; private string ownerAccount; private string name; private string action; private string transConfig; private string muxConfig; private string video; private string audio; private long? ownerId; private string accessKeyId; public string Container { get { return container; } set { container = value; DictionaryUtil.Add(QueryParameters, "Container", value); } } public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public string Name { get { return name; } set { name = value; DictionaryUtil.Add(QueryParameters, "Name", value); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string TransConfig { get { return transConfig; } set { transConfig = value; DictionaryUtil.Add(QueryParameters, "TransConfig", value); } } public string MuxConfig { get { return muxConfig; } set { muxConfig = value; DictionaryUtil.Add(QueryParameters, "MuxConfig", value); } } public string Video { get { return video; } set { video = value; DictionaryUtil.Add(QueryParameters, "Video", value); } } public string Audio { get { return audio; } set { audio = value; DictionaryUtil.Add(QueryParameters, "Audio", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string AccessKeyId { get { return accessKeyId; } set { accessKeyId = value; DictionaryUtil.Add(QueryParameters, "AccessKeyId", value); } } public override AddTemplateResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return AddTemplateResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
18.9819
111
0.626937
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-mts/Mts/Model/V20140618/AddTemplateRequest.cs
4,195
C#
/* Copyright 2020-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; namespace MongoDB.Driver.Tests.UnifiedTestOperations { public class UnifiedFindOneAndUpdateOperation : IUnifiedEntityTestOperation { private readonly IMongoCollection<BsonDocument> _collection; private readonly FilterDefinition<BsonDocument> _filter; private readonly FindOneAndUpdateOptions<BsonDocument> _options; private readonly UpdateDefinition<BsonDocument> _update; private readonly IClientSessionHandle _session; public UnifiedFindOneAndUpdateOperation( IMongoCollection<BsonDocument> collection, FilterDefinition<BsonDocument> filter, UpdateDefinition<BsonDocument> update, IClientSessionHandle session, FindOneAndUpdateOptions<BsonDocument> options) { _collection = collection; _filter = filter; _update = update; _session = session; _options = options; } public OperationResult Execute(CancellationToken cancellationToken) { try { var result = _session == null ? _collection.FindOneAndUpdate(_filter, _update, _options, cancellationToken) : _collection.FindOneAndUpdate(_session, _filter, _update, _options, cancellationToken); return OperationResult.FromResult(result); } catch (Exception exception) { return OperationResult.FromException(exception); } } public async Task<OperationResult> ExecuteAsync(CancellationToken cancellationToken) { try { var result = _session == null ? await _collection.FindOneAndUpdateAsync(_filter, _update, _options, cancellationToken) : await _collection.FindOneAndUpdateAsync(_session, _filter, _update, _options, cancellationToken); return OperationResult.FromResult(result); } catch (Exception exception) { return OperationResult.FromException(exception); } } } public class UnifiedFindOneAndUpdateOperationBuilder { private readonly UnifiedEntityMap _entityMap; public UnifiedFindOneAndUpdateOperationBuilder(UnifiedEntityMap entityMap) { _entityMap = entityMap; } public UnifiedFindOneAndUpdateOperation Build(string targetCollectionId, BsonDocument arguments) { var collection = _entityMap.GetCollection(targetCollectionId); FilterDefinition<BsonDocument> filter = null; FindOneAndUpdateOptions<BsonDocument> options = null; UpdateDefinition<BsonDocument> update = null; IClientSessionHandle session = null; foreach (var argument in arguments) { switch (argument.Name) { case "comment": options ??= new FindOneAndUpdateOptions<BsonDocument>(); options.Comment = argument.Value; break; case "filter": filter = new BsonDocumentFilterDefinition<BsonDocument>(argument.Value.AsBsonDocument); break; case "hint": options ??= new FindOneAndUpdateOptions<BsonDocument>(); options.Hint = argument.Value; break; case "let": options ??= new FindOneAndUpdateOptions<BsonDocument>(); options.Let = argument.Value.AsBsonDocument; break; case "returnDocument": options ??= new FindOneAndUpdateOptions<BsonDocument>(); options.ReturnDocument = (ReturnDocument)Enum.Parse(typeof(ReturnDocument), argument.Value.AsString); break; case "session": session = _entityMap.GetSession(argument.Value.AsString); break; case "sort": options ??= new FindOneAndUpdateOptions<BsonDocument>(); options.Sort = new BsonDocumentSortDefinition<BsonDocument>(argument.Value.AsBsonDocument); break; case "update": switch (argument.Value) { case BsonDocument: update = argument.Value.AsBsonDocument; break; case BsonArray: update = PipelineDefinition<BsonDocument, BsonDocument>.Create(argument.Value.AsBsonArray.Cast<BsonDocument>()); break; default: throw new FormatException($"Invalid FindOneAndUpdateOperation update argument: '{argument.Value}'."); } break; default: throw new FormatException($"Invalid FindOneAndUpdateOperation argument name: '{argument.Name}'."); } } return new UnifiedFindOneAndUpdateOperation(collection, filter, update, session, options); } } }
41.543624
144
0.576898
[ "Apache-2.0" ]
Etherna/mongo-csharp-driver
tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedFindOneAndUpdateOperation.cs
6,192
C#
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace IJsfontein.AppUpdater { [CustomEditor(typeof(UpdaterSettings))] public class UpdaterSettingsEditor : Editor { override public void OnInspectorGUI() { DrawDefaultInspector(); UpdaterSettings settings = (target as UpdaterSettings); if (settings.useBasicAuthentication) { settings.username = EditorGUILayout.TextField("Username", settings.username); settings.password = EditorGUILayout.PasswordField("Password", settings.password); } } } }
25.851852
97
0.65616
[ "MIT" ]
museum4punkt0/VR-Spiel_Auf-dem-weiten-Meer
Unity/VR-Navigation/Assets/IJsfontein/Packages/AppUpdater/Editor/UpdaterSettingsEditor.cs
698
C#
namespace FootballManager.Services { using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using FootballManager.ViewModels.Users; using FootballManager.ViewModels.Players; using static Data.DataConstants; public class Validator : IValidator { public ICollection<string> ValidateUser(UserRegisterModel model) { var errors = new List<string>(); if (model.Username.Length < UserMinUsername || model.Username.Length > DefaultMaxLength) { errors.Add($"Username '{model.Username}' is not valid. It must be between {UserMinUsername} and {DefaultMaxLength} charecters long."); } if (!Regex.IsMatch(model.Email, UserEmailRegularExpression)) { errors.Add($"Email '{model.Email}' is not a valid e-mail address."); } if (model.Password.Any(x => x == ' ')) { errors.Add($"The provided password cannot contains any whitespaces."); } if (model.Password.Length < UserMinPassword || model.Password.Length > DefaultMaxLength) { errors.Add($"The provided password is not valid. It must be between {UserMinPassword} and {DefaultMaxLength} charecters long."); } if (model.Password != model.ConfirmPassword) { errors.Add($"Password and Confirm Password should be the same."); } return errors; } public ICollection<string> ValidateAddPlayer(AddPlayerModel model) { var errors = new List<string>(); if (model.FullName.Length < PlayerMinFullName || PlayerMaxFullName < model.FullName.Length || model.FullName == null) { errors.Add($"Full name of the player '{model.FullName}' is not valid. It must be between {PlayerMinFullName} and {PlayerMaxFullName} charecters long."); } if (model.Position.Length < PlayerMinPosition || DefaultMaxLength < model.Position.Length || model.Position == null) { errors.Add($"Position '{model.Position}' is not valid. It must be between {PlayerMinPosition} and {DefaultMaxLength} charecters long."); } if (model.Speed < PlayerMinSpeed || PlayerMaxSpeed < model.Speed || model.Speed == null) { errors.Add($"The speed can be between {PlayerMinSpeed} and {PlayerMaxSpeed}. Please enter a valid number."); } if (model.Endurance < PlayerMinEndurance || PlayerMaxEndurance < model.Endurance || model.Endurance == null) { errors.Add($"The endurance can be between {PlayerMinEndurance} and {PlayerMaxEndurance}. Please enter a valid number."); } if (PlayerMaxDescription < model.Description.Length) { errors.Add($"Description of a player can be maximum {PlayerMaxDescription} charecters long."); } if (model.ImageUrl.Length == 0 || string.IsNullOrEmpty(model.ImageUrl)) { errors.Add($"Image should be a valid string format. Please do not enter too big string."); } return errors; } } }
39.27907
168
0.594435
[ "MIT" ]
yanchev93/CSharp-Web
CSharp-Web/FootballManager/FootballManager/Services/Validator.cs
3,380
C#
namespace SimpleRandomWallpaperService { partial class SimpleRandomWallpaperService { /// <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() { // // SimpleRandomWallpaperService // this.ServiceName = "Service1"; } #endregion } }
27.243902
107
0.54521
[ "MIT" ]
fourDotsSoftware/SimpleRandomWallpaper
SimpleRandomWallpaperService/SimpleRandomWallpaperService.Designer.cs
1,119
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; namespace NFine.Code { public class GZip { /// <summary> /// 压缩 /// </summary> /// <param name="text">文本</param> public static string Compress(string text) { if (text.IsEmpty()) return string.Empty; byte[] buffer = Encoding.UTF8.GetBytes(text); return Convert.ToBase64String(Compress(buffer)); } /// <summary> /// 解压缩 /// </summary> /// <param name="text">文本</param> public static string Decompress(string text) { if (text.IsEmpty()) return string.Empty; byte[] buffer = Convert.FromBase64String(text); using (var ms = new MemoryStream(buffer)) { using (var zip = new GZipStream(ms, CompressionMode.Decompress)) { using (var reader = new StreamReader(zip)) { return reader.ReadToEnd(); } } } } /// <summary> /// 压缩 /// </summary> /// <param name="buffer">字节流</param> public static byte[] Compress(byte[] buffer) { if (buffer == null) return null; using (var ms = new MemoryStream()) { using (var zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } return ms.ToArray(); } } /// <summary> /// 解压缩 /// </summary> /// <param name="buffer">字节流</param> public static byte[] Decompress(byte[] buffer) { if (buffer == null) return null; return Decompress(new MemoryStream(buffer)); } /// <summary> /// 压缩 /// </summary> /// <param name="stream">流</param> public static byte[] Compress(Stream stream) { if (stream == null || stream.Length == 0) return null; return Compress(StreamToBytes(stream)); } /// <summary> /// 解压缩 /// </summary> /// <param name="stream">流</param> public static byte[] Decompress(Stream stream) { if (stream == null || stream.Length == 0) return null; using (var zip = new GZipStream(stream, CompressionMode.Decompress)) { using (var reader = new StreamReader(zip)) { return Encoding.UTF8.GetBytes(reader.ReadToEnd()); } } } /// <summary> /// 流转换为字节流 /// </summary> /// <param name="stream">流</param> public static byte[] StreamToBytes(Stream stream) { stream.Seek(0, SeekOrigin.Begin); var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); return buffer; } } }
28.654867
84
0.459234
[ "MIT" ]
Run2948/NFine.Framework.Core
NFine.Core/GZip.cs
3,310
C#
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OpenSkyRestClient.Extensions; using OpenSkyRestClient.Model; using System; using System.Text.Json; namespace OpenSkyRestClient.Parser { public static class StateVectorParser { public static StateVector Parse(JsonElement element) { if(!TryParse(element, out StateVector result)) { return null; } return result; } public static bool TryParse(JsonElement element, out StateVector result) { result = null; if (element.ValueKind != JsonValueKind.Array) { return false; } if (element.GetArrayLength() != 17) { return false; } result = new StateVector { Icao24 = element[0].GetNullableString(), CallSign = element[1].GetNullableString(), OriginCountry = element[2].GetNullableString(), TimePosition = element[3].GetNullableInt32(), LastContact = element[4].GetNullableInt32(), Longitude = element[5].GetNullableFloat(), Latitude = element[6].GetNullableFloat(), BarometricAltitude = element[7].GetNullableFloat(), OnGround = element[8].GetBoolean(), Velocity = element[9].GetNullableFloat(), TrueTrack = element[10].GetNullableFloat(), VerticalRate = element[11].GetNullableFloat(), Sensors = GetIntArray(element[12]), GeometricAltitudeInMeters = element[13].GetNullableFloat(), Squawk = element[14].GetNullableString(), Spi = element[15].GetBoolean(), PositionSource = GetPositionSource(element[16]) }; return true; } private static int[] GetIntArray(JsonElement element) { if (element.ValueKind == JsonValueKind.Null) { return null; } if (element.ValueKind != JsonValueKind.Array) { return null; } int[] result = new int[element.GetArrayLength()]; for (int arrayIdx = 0; arrayIdx < element.GetArrayLength(); arrayIdx++) { result[arrayIdx] = element[arrayIdx].GetInt32(); } return result; } private static PositionSourceEnum? GetPositionSource(JsonElement element) { if (element.ValueKind == JsonValueKind.Null) { return null; } var value = element.GetInt32(); if (!Enum.IsDefined(typeof(PositionSourceEnum), value)) { return null; } return (PositionSourceEnum)Enum.ToObject(typeof(PositionSourceEnum), value); } } }
30.762376
101
0.53814
[ "MIT" ]
bytefish/OpenSkyRestClient
OpenSkyRestClient/OpenSkyRestClient/Parser/StateVectorParser.cs
3,109
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Rudder.Middleware; namespace Rudder { /// <summary> /// Provides the configuration for Rudder library /// </summary> /// <typeparam name="TState">Application state type</typeparam> public interface IRudderOptions<TState> where TState : class { /// <summary> /// Registers a state flow in a container /// </summary> /// <typeparam name="T">IStateFlow implementation</typeparam> IRudderOptions<TState> AddStateFlow<T>() where T : class, IStateFlow<TState>; /// <summary> /// Registers all state flows from calling assembly and additional assemblies /// </summary> /// <typeparam name="TState">Application state type</typeparam> IRudderOptions<TState> AddStateFlows(params Assembly[] additionalAssemblies); /// <summary> /// Registers a logic flow in a container /// </summary> /// <typeparam name="T">ILogicFlow implementation</typeparam> IRudderOptions<TState> AddLogicFlow<T>() where T : class, ILogicFlow; /// <summary> /// Registers all logic flows from calling assembly and additional assemblies /// </summary> /// <typeparam name="TState">Application state type</typeparam> IRudderOptions<TState> AddLogicFlows(params Assembly[] additionalAssemblies); /// <summary> /// Adds JavaScript's console logging of processed actions (experimental) /// </summary> IRudderOptions<TState> AddJsLogging(); /// <summary> /// Registers a StoreMiddleware /// </summary> /// <typeparam name="T">IStoreMiddleware implementation</typeparam> IRudderOptions<TState> AddMiddleware<T>() where T : class, IStoreMiddleware; IRudderOptions<TState> AddStateInitializer<T>() where T : class, IInitialState<TState>; } internal class RudderOptions<TState> : IRudderOptions<TState> where TState : class { private readonly IServiceCollection _services; private readonly Assembly _callingAssembly; internal RudderOptions(IServiceCollection services, Assembly callingAssembly) { _services = services; _callingAssembly = callingAssembly; } public IRudderOptions<TState> AddStateInitializer<T>() where T : class, IInitialState<TState> { _services.AddScoped<IInitialState<TState>, T>(); return this; } public IRudderOptions<TState> AddStateFlow<T>() where T : class, IStateFlow<TState> { _services.AddScoped<IStateFlow<TState>, T>(); return this; } public IRudderOptions<TState> AddStateFlows(params Assembly[] additionalAssemblies) { CombineAssemblies(additionalAssemblies) .SelectMany(GetTypesOf<IStateFlow<TState>>) .ToList() .ForEach(type => _services.AddScoped(typeof(IStateFlow<TState>), type)); return this; } public IRudderOptions<TState> AddLogicFlow<T>() where T : class, ILogicFlow { _services.AddScoped<ILogicFlow, T>(); return this; } public IRudderOptions<TState> AddLogicFlows(params Assembly[] additionalAssemblies) { CombineAssemblies(additionalAssemblies) .SelectMany(GetTypesOf<ILogicFlow>) .ToList() .ForEach(type => _services.AddScoped(typeof(ILogicFlow), type)); return this; } public IRudderOptions<TState> AddMiddleware<T>() where T : class, IStoreMiddleware { _services.AddScoped<IStoreMiddleware, T>(); return this; } public IRudderOptions<TState> AddJsLogging() { AddMiddleware<JsLoggingStoreMiddleware>(); return this; } private IEnumerable<Assembly> CombineAssemblies(Assembly[] additionalAssemblies) => new[] { _callingAssembly }.Union(additionalAssemblies).ToList(); private List<Type> GetTypesOf<T>(Assembly assembly) => assembly .GetTypes() .Where(type => typeof(T).IsAssignableFrom(type)) .ToList(); } }
34.6875
101
0.621847
[ "MIT" ]
kjeske/rudder
src/RudderOptions.cs
4,442
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 namespace Critterpedia.App.UserControls { public sealed partial class MasterDetailControl : UserControl { private ViewModels.ICritterViewModel CViewModel { get; set; } public MasterDetailControl() { this.InitializeComponent(); } } }
27
97
0.754321
[ "MIT" ]
adamhemeon/Critterpedia_UWP
Critterpedia/Critterpedia.App/UserControls/MasterDetailControl.xaml.cs
812
C#
using System; using TwentyOne.Pages; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace TwentyOne { public partial class App : Application { public App() { InitializeComponent(); MainPage = new GameScreenPage(); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
15.9
44
0.536688
[ "MIT" ]
stefanbogaard86/TwentyOne
TwentyOne/App.xaml.cs
479
C#
//----------------------------------------------------------------------- // <copyright file="CatalogContent.cs" company="TelerikAcademy"> // All rights reserved © Telerik Academy 2012-2013 // </copyright> //---------------------------------------------------------------------- namespace CatalogOfFreeContent { using System; using System.Linq; /// <summary> /// Represents the content of a catalog. /// </summary> public class CatalogContent : IComparable, IContent { private string url; public CatalogContent(ContentTypes type, string[] commandParams) { this.Type = type; this.Title = commandParams[(int)ItemData.Title]; this.Author = commandParams[(int)ItemData.Author]; this.Size = long.Parse(commandParams[(int)ItemData.Size]); this.URL = commandParams[(int)ItemData.Url]; } public string Title { get; set; } public string Author { get; set; } public long Size { get; set; } public string URL { get { return this.url; } set { this.url = value; this.TextRepresentation = this.ToString(); } } public ContentTypes Type { get; set; } public string TextRepresentation { get; set; } public int CompareTo(object obj) { if (null == obj) { return 1; } CatalogContent otherContent = obj as CatalogContent; if (otherContent != null) { int comparisonResult = this.TextRepresentation.CompareTo(otherContent.TextRepresentation); return comparisonResult; } throw new ArgumentException("Can not compare object with non-object."); } public override string ToString() { string output = String.Format( "{0}: {1}; {2}; {3}; {4}", this.Type.ToString(), this.Title, this.Author, this.Size, this.URL); return output; } } }
27.349398
87
0.474009
[ "MIT" ]
niki-funky/Telerik_Academy
Programming/High Quality Code/19. Exam preparation/CatalogOfFreeContent/CatalogContent.cs
2,273
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; using Azure.ResourceManager.Sql; namespace Azure.ResourceManager.Sql.Models { /// <summary> A list of long term retention backups for managed database(s). </summary> internal partial class ManagedInstanceLongTermRetentionBackupListResult { /// <summary> Initializes a new instance of ManagedInstanceLongTermRetentionBackupListResult. </summary> internal ManagedInstanceLongTermRetentionBackupListResult() { Value = new ChangeTrackingList<ManagedInstanceLongTermRetentionBackupData>(); } /// <summary> Initializes a new instance of ManagedInstanceLongTermRetentionBackupListResult. </summary> /// <param name="value"> Array of results. </param> /// <param name="nextLink"> Link to retrieve next page of results. </param> internal ManagedInstanceLongTermRetentionBackupListResult(IReadOnlyList<ManagedInstanceLongTermRetentionBackupData> value, string nextLink) { Value = value; NextLink = nextLink; } /// <summary> Array of results. </summary> public IReadOnlyList<ManagedInstanceLongTermRetentionBackupData> Value { get; } /// <summary> Link to retrieve next page of results. </summary> public string NextLink { get; } } }
38.947368
147
0.707432
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ManagedInstanceLongTermRetentionBackupListResult.cs
1,480
C#
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.Journaling.CS { partial class JournalingForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.typeLabel = new System.Windows.Forms.Label(); this.typeComboBox = new System.Windows.Forms.ComboBox(); this.levelLabel = new System.Windows.Forms.Label(); this.levelComboBox = new System.Windows.Forms.ComboBox(); this.locationGroupBox = new System.Windows.Forms.GroupBox(); this.endPointUserControl = new Revit.SDK.Samples.ModelLines.CS.PointUserControl(); this.startPointUserControl = new Revit.SDK.Samples.ModelLines.CS.PointUserControl(); this.endPointLabel = new System.Windows.Forms.Label(); this.startPointLabel = new System.Windows.Forms.Label(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.locationGroupBox.SuspendLayout(); this.SuspendLayout(); // // typeLabel // this.typeLabel.AutoSize = true; this.typeLabel.Location = new System.Drawing.Point(34, 19); this.typeLabel.Name = "typeLabel"; this.typeLabel.Size = new System.Drawing.Size(58, 13); this.typeLabel.TabIndex = 0; this.typeLabel.Text = "Wall Type:"; // // typeComboBox // this.typeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.typeComboBox.FormattingEnabled = true; this.typeComboBox.Location = new System.Drawing.Point(99, 16); this.typeComboBox.Name = "typeComboBox"; this.typeComboBox.Size = new System.Drawing.Size(205, 21); this.typeComboBox.TabIndex = 0; // // levelLabel // this.levelLabel.AutoSize = true; this.levelLabel.Location = new System.Drawing.Point(56, 59); this.levelLabel.Name = "levelLabel"; this.levelLabel.Size = new System.Drawing.Size(36, 13); this.levelLabel.TabIndex = 2; this.levelLabel.Text = "Level:"; // // levelComboBox // this.levelComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.levelComboBox.FormattingEnabled = true; this.levelComboBox.Location = new System.Drawing.Point(99, 56); this.levelComboBox.Name = "levelComboBox"; this.levelComboBox.Size = new System.Drawing.Size(205, 21); this.levelComboBox.TabIndex = 1; // // locationGroupBox // this.locationGroupBox.Controls.Add(this.endPointUserControl); this.locationGroupBox.Controls.Add(this.startPointUserControl); this.locationGroupBox.Controls.Add(this.endPointLabel); this.locationGroupBox.Controls.Add(this.startPointLabel); this.locationGroupBox.Location = new System.Drawing.Point(15, 83); this.locationGroupBox.Name = "locationGroupBox"; this.locationGroupBox.Size = new System.Drawing.Size(289, 86); this.locationGroupBox.TabIndex = 4; this.locationGroupBox.TabStop = false; this.locationGroupBox.Text = "Wall Location Line"; // // endPointUserControl // this.endPointUserControl.Location = new System.Drawing.Point(70, 51); this.endPointUserControl.Name = "endPointUserControl"; this.endPointUserControl.Size = new System.Drawing.Size(213, 28); this.endPointUserControl.TabIndex = 1; // // startPointUserControl // this.startPointUserControl.Location = new System.Drawing.Point(70, 19); this.startPointUserControl.Name = "startPointUserControl"; this.startPointUserControl.Size = new System.Drawing.Size(213, 28); this.startPointUserControl.TabIndex = 0; // // endPointLabel // this.endPointLabel.AutoSize = true; this.endPointLabel.Location = new System.Drawing.Point(19, 57); this.endPointLabel.Name = "endPointLabel"; this.endPointLabel.Size = new System.Drawing.Size(29, 13); this.endPointLabel.TabIndex = 1; this.endPointLabel.Text = "End:"; // // startPointLabel // this.startPointLabel.AutoSize = true; this.startPointLabel.Location = new System.Drawing.Point(19, 29); this.startPointLabel.Name = "startPointLabel"; this.startPointLabel.Size = new System.Drawing.Size(32, 13); this.startPointLabel.TabIndex = 0; this.startPointLabel.Text = "Start:"; // // okButton // this.okButton.Location = new System.Drawing.Point(142, 175); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(79, 23); this.okButton.TabIndex = 2; this.okButton.Text = "&OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(227, 175); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(77, 23); this.cancelButton.TabIndex = 3; this.cancelButton.Text = "&Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // JournalingForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(319, 204); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.locationGroupBox); this.Controls.Add(this.levelComboBox); this.Controls.Add(this.levelLabel); this.Controls.Add(this.typeComboBox); this.Controls.Add(this.typeLabel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "JournalingForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Journaling"; this.locationGroupBox.ResumeLayout(false); this.locationGroupBox.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label typeLabel; private System.Windows.Forms.ComboBox typeComboBox; private System.Windows.Forms.Label levelLabel; private System.Windows.Forms.ComboBox levelComboBox; private System.Windows.Forms.GroupBox locationGroupBox; private System.Windows.Forms.Label endPointLabel; private System.Windows.Forms.Label startPointLabel; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private Revit.SDK.Samples.ModelLines.CS.PointUserControl endPointUserControl; private Revit.SDK.Samples.ModelLines.CS.PointUserControl startPointUserControl; } }
45.834906
107
0.618092
[ "BSD-3-Clause" ]
AMEE/rev
samples/Revit 2012 SDK/Samples/Journaling/CS/JournalingForm.Designer.cs
9,717
C#
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class SimpleFileBrowserItem : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler { #region Constants private const float DOUBLE_CLICK_TIME = 0.5f; #endregion #region Variables protected SimpleFileBrowser fileBrowser; [SerializeField] private Image background; [SerializeField] private Image icon; [SerializeField] private Text nameText; private float prevTouchTime = Mathf.NegativeInfinity; #endregion #region Properties private RectTransform m_transform; public RectTransform transformComponent { get { if( m_transform == null ) m_transform = (RectTransform) transform; return m_transform; } } public string Name { get { return nameText.text; } } private bool m_isDirectory; public bool IsDirectory { get { return m_isDirectory; } } #endregion #region Initialization Functions public void SetFileBrowser( SimpleFileBrowser fileBrowser ) { this.fileBrowser = fileBrowser; } public void SetFile( Sprite icon, string name, bool isDirectory ) { this.icon.sprite = icon; nameText.text = name; m_isDirectory = isDirectory; } #endregion #region Pointer Events public void OnPointerClick( PointerEventData eventData ) { if( Time.realtimeSinceStartup - prevTouchTime < DOUBLE_CLICK_TIME ) { if( fileBrowser.SelectedFile == this ) fileBrowser.OnItemOpened( this ); prevTouchTime = Mathf.NegativeInfinity; } else { fileBrowser.OnItemSelected( this ); prevTouchTime = Time.realtimeSinceStartup; } } public void OnPointerEnter( PointerEventData eventData ) { if( fileBrowser.SelectedFile != this ) background.color = fileBrowser.hoveredFileColor; } public void OnPointerExit( PointerEventData eventData ) { if( fileBrowser.SelectedFile != this ) background.color = fileBrowser.normalFileColor; } #endregion #region Other Events public void Select() { background.color = fileBrowser.selectedFileColor; } public void Deselect() { background.color = fileBrowser.normalFileColor; } #endregion }
22
116
0.720522
[ "MIT" ]
EvanWY/USelfDrivingSimulator
Assets/Plugins/SimpleFileBrowser/Scripts/SimpleFileBrowserItem.cs
2,224
C#
namespace Api.Models { public class EntityModel { public int id { get; set; } public string name { get; set; } } }
13.272727
40
0.541096
[ "MIT" ]
krisk0su/Dynamo
server/Models/EntityModel.cs
148
C#
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; namespace Microsoft.ComponentDetection.Detectors.Pip { /// <summary> /// Represents a package and a list of dependency specifications that the package must be. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PipDependencySpecification { private string DebuggerDisplay => $"{Name} ({string.Join(';', DependencySpecifiers)})"; /// <summary> /// Gets or sets the package <see cref="Name"/> (ex: pyyaml). /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the set of dependency specifications that constrain the overall dependency request (ex: ==1.0, >=2.0). /// </summary> public IList<string> DependencySpecifiers { get; set; } = new List<string>(); /// <summary> /// These are packages that we don't want to evaluate in our graph as they are generally python builtins. /// </summary> private static readonly HashSet<string> PackagesToIgnore = new HashSet<string> { "-markerlib", "pip", "pip-tools", "pip-review", "pkg-resources", "setuptools", "wheel", }; // Extracts abcd from a string like abcd==1.*,!=1.3 private static readonly Regex PipNameExtractionRegex = new Regex( @"^.+?((?=<)|(?=>)|(?=>=)|(?=<=)|(?===)|(?=!=)|(?=~=)|(?====))", RegexOptions.Compiled); // Extracts ==1.*,!=1.3 from a string like abcd==1.*,!=1.3 private static readonly Regex PipVersionExtractionRegex = new Regex( @"((?=<)|(?=>)|(?=>=)|(?=<=)|(?===)|(?=!=)|(?=~=)|(?====))(.*)", RegexOptions.Compiled); // Extracts name and version from a Requires-Dist string that is found in a metadata file public static readonly Regex RequiresDistRegex = new Regex( @"Requires-Dist:\s*(?:(.*?)\s*\((.*?)\)|([^\s;]*))", RegexOptions.Compiled); /// <summary> /// Whether or not the package is safe to resolve based on the packagesToIgnore. /// </summary> /// <returns></returns> public bool PackageIsUnsafe() { return PackagesToIgnore.Contains(Name); } /// <summary> /// This constructor is used in test code. /// </summary> public PipDependencySpecification() { } /// <summary> /// Constructs a dependency specification from a string in one of two formats (Requires-Dist: a (==1.3)) OR a==1.3. /// </summary> /// <param name="packageString">The <see cref="string"/> to parse.</param> /// <param name="requiresDist">The package format.</param> public PipDependencySpecification(string packageString, bool requiresDist = false) { if (requiresDist) { var distMatch = RequiresDistRegex.Match(packageString); for (int i = 1; i < distMatch.Groups.Count; i++) { if (string.IsNullOrWhiteSpace(distMatch.Groups[i].Value)) { continue; } if (string.IsNullOrWhiteSpace(Name)) { Name = distMatch.Groups[i].Value; } else { DependencySpecifiers = distMatch.Groups[i].Value.Split(','); } } } else { var nameMatches = PipNameExtractionRegex.Match(packageString); var versionMatches = PipVersionExtractionRegex.Match(packageString); if (nameMatches.Captures.Count > 0) { Name = nameMatches.Captures[0].Value; } else { Name = packageString; } if (versionMatches.Captures.Count > 0) { DependencySpecifiers = versionMatches.Captures[0].Value.Split(','); } } DependencySpecifiers = DependencySpecifiers.Where(x => !x.Contains("python_version")).ToList(); } } }
36.47541
127
0.513258
[ "MIT" ]
ByAgenT/component-detection
src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs
4,450
C#
using System; using System.Collections.Generic; using System.Linq; namespace MNCD.Extensions { /// <summary> /// List extensions. /// </summary> public static class ListExtensions { private static readonly Random Random = new Random(); /// <summary> /// Creates dictionary that gets index based on list item. /// </summary> /// <typeparam name="T">Type of list item.</typeparam> /// <param name="list">List of items.</param> /// <returns>Dictionary of item and its index.</returns> public static Dictionary<T, int> ToIndexDict<T>(this List<T> list) => list .Select((item, index) => (item, index)) .ToDictionary(pair => pair.item, pair => pair.index); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = Random.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } public static Dictionary<T, int> ToIndexDictionary<T>(this List<T> items) => items .Select((item, index) => (item, index)) .ToDictionary(pair => pair.item, pair => pair.index); } }
32.170732
90
0.523882
[ "MIT" ]
matejkubinec/MN-CD
src/MNCD/Extensions/ListExtensions.cs
1,319
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 05:53:17 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using json = go.encoding.json_package; using fmt = go.fmt_package; using trace = go.@internal.trace_package; using io = go.io_package; using log = go.log_package; using math = go.math_package; using http = go.net.http_package; using filepath = go.path.filepath_package; using runtime = go.runtime_package; using debug = go.runtime.debug_package; using sort = go.sort_package; using strconv = go.strconv_package; using strings = go.strings_package; using time = go.time_package; #nullable enable namespace go { public static partial class main_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct frameNode { // Constructors public frameNode(NilType _) { this.id = default; this.children = default; } public frameNode(long id = default, map<ulong, frameNode> children = default) { this.id = id; this.children = children; } // Enable comparisons between nil and frameNode struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(frameNode value, NilType nil) => value.Equals(default(frameNode)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(frameNode value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, frameNode value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, frameNode value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator frameNode(NilType nil) => default(frameNode); } [GeneratedCode("go2cs", "0.1.0.0")] private static frameNode frameNode_cast(dynamic value) { return new frameNode(value.id, value.children); } } }
34.342105
109
0.621456
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/trace/trace_frameNodeStruct.cs
2,610
C#
using System; using System.Collections.Generic; using System.Text; using JetBrains.Annotations; using JetBrains.Collections; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.Util; using Newtonsoft.Json.Linq; namespace ReSharperPlugin.SpecflowRiderPlugin.Psi { public class GherkinKeywordList { // i18n.json file contains list of keywords and some meta-information about the language. At the moment it's three attributes below. private static readonly string[] GherkinLanguageMetaAttributes = {"name", "native", "encoding"}; private static readonly Dictionary<string, GherkinTokenType> TokenTypes = new Dictionary<string, GherkinTokenType> { {"Feature", GherkinTokenTypes.FEATURE_KEYWORD}, {"Background", GherkinTokenTypes.BACKGROUND_KEYWORD}, {"Scenario", GherkinTokenTypes.SCENARIO_KEYWORD}, {"Rule", GherkinTokenTypes.RULE_KEYWORD}, {"Example", GherkinTokenTypes.EXAMPLE_KEYWORD}, {"Scenario Outline", GherkinTokenTypes.SCENARIO_OUTLINE_KEYWORD}, {"Examples", GherkinTokenTypes.EXAMPLES_KEYWORD}, {"Scenarios", GherkinTokenTypes.EXAMPLES_KEYWORD}, {"Given", GherkinTokenTypes.STEP_KEYWORD}, {"When", GherkinTokenTypes.STEP_KEYWORD}, {"Then", GherkinTokenTypes.STEP_KEYWORD}, {"And", GherkinTokenTypes.STEP_KEYWORD}, {"But", GherkinTokenTypes.STEP_KEYWORD}, {"*", GherkinTokenTypes.STEP_KEYWORD} }; private readonly HashSet<string> _spaceAfterKeywords = new HashSet<string>(); private readonly Dictionary<string, string> _translatedKeywords = new Dictionary<string, string>(); private readonly Dictionary<string, GherkinTokenType> _translatedTokenTypes = new Dictionary<string, GherkinTokenType>(); // Need to use Descending comparer, because long keywords should be first. // For example: "Scenario" keyword is a part of "Scenario Outline" keyword. private readonly SortedSet<string> _allKeywords = new SortedSet<string>(new DescendingComparer<string>()); public GherkinKeywordList(JObject keywords) { foreach (var (key, values) in keywords) { if (GherkinLanguageMetaAttributes.Contains(key)) continue; var keyword = CapitalizeAndFixSpace(key); var tokenType = TokenTypes[keyword]; foreach (var jToken in values) { var translatedKeyword = jToken.Value<string>(); if (translatedKeyword.EndsWith(" ")) { translatedKeyword = translatedKeyword.Substring(0, translatedKeyword.Length - 1); _spaceAfterKeywords.Add(translatedKeyword); } _translatedKeywords[translatedKeyword] = keyword; _translatedTokenTypes[translatedKeyword] = tokenType; _allKeywords.Add(translatedKeyword); } } } private static string CapitalizeAndFixSpace(string keyword) { var result = new StringBuilder(); for (var i = 0; i < keyword.Length; i++) { var c = keyword[i]; if (i == 0) c = char.ToUpper(c); if (char.IsUpper(c) && i > 0) result.Append(' '); result.Append(c); } return result.ToString(); } public IReadOnlyCollection<string> GetAllKeywords() { return _allKeywords; } public bool IsSpaceRequiredAfterKeyword(string keyword) { return _spaceAfterKeywords.Contains(keyword); } public TokenNodeType GetTokenType(string keyword) { return _translatedTokenTypes[keyword]; } [CanBeNull] public string GetEnglishTokenKeyword(string keyword) { if (_translatedKeywords.TryGetValue(keyword, out var englishVersion)) return englishVersion; return null; } private class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return y.CompareTo(x); } } } }
38.361345
141
0.585104
[ "MIT" ]
citizenmatt/SpecFlow.Rider
src/dotnet/ReSharperPlugin.SpecflowRiderPlugin/Psi/GherkinKeywordList.cs
4,565
C#
using System; namespace Lectia16 { namespace ExpresiiFunc { class Program { static void Main() { Func<string, string> func1 = (x) => (x.Remove(x.Length / 2, x.Length / 2)); Console.WriteLine(func1.Invoke("abcdefg")); } } } }
17.526316
91
0.462462
[ "MIT" ]
victordulap/cSharpStudy
stepLessons/Lectia16/Lectia16/Program.cs
335
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ControleLoja.Models { public class VendedorModel { public int Id { get; set; } [Display(Name = "Nome", Prompt = "")] public string Nome { get; set; } [Display(Name = "Email", Prompt = "")] public string Email { get; set; } [Display(Name = "Senha", Prompt = "")] public string Senha { get; set; } [Display(Name = "Tipo", Prompt = "")] public string Tipo { get; set; } } }
22.740741
46
0.592834
[ "MIT" ]
danieltoguti/ControleLoja
ControleLoja/Models/VendedorModel.cs
616
C#
using System; using UnityEngine; using System.Collections.Generic; using System.Linq; public class DaltonImageCreator { public static void CalculateCircles( int numberLeft, int numberRight, List<Circle> circles) { int leftNumber = numberLeft; int rightNumber = numberRight; PiekaImage leftTexture = NumberImages.Left [leftNumber]; PiekaImage rightTexture = NumberImages.Right[rightNumber]; circles.ForEach (c => { if( DoesCircleFitImage( c, leftTexture) || DoesCircleFitImage( c, rightTexture ) ) c.background = false; else c.background = true; }); } public static PiekaImage CreateBWImage(List<Circle> circles) { PiekaImage image = new PiekaImage (Params.w, Params.h); circles.ForEach (c => { if( c.background ) ImageCreator.DrawCircle (image, c, Color.white ); else ImageCreator.DrawCircle (image, c, Color.black ); }); return image; } public static PiekaImage CreateDaltonImage(int easiness, char colorTest, List<Circle> circles) { PiekaImage image = new PiekaImage (Params.w, Params.h); ColorProvider colorProvider = new ColorProvider (easiness, colorTest); circles.ForEach (c => { if( c.background ) ImageCreator.DrawCircle (image, c, colorProvider.GetNumberColor()); else ImageCreator.DrawCircle (image, c, colorProvider.GetBackgroundColor()); }); return image; } private static bool DoesCircleFitImage( Circle circle, PiekaImage tex ) { int fitPixels = 0; int allPixels = 0; for (int i = circle.x - circle.r; i <= circle.x + circle.r; i++) { for (int j = circle.y - circle.r; j <= circle.y + circle.r; j++) { allPixels++; if (tex.GetPixel (i, j) == Color.black) { fitPixels++; } } } if ((float)fitPixels / allPixels >= Params.RequiredFitPercentage) return true; return false; } }
17.416667
95
0.670388
[ "MIT" ]
piekaa/dalton
Assets/Scripts/ImageCreation/DaltonImageCreator.cs
1,883
C#
using DebitOrdersApi.Data; using DebitOrdersApi.Models; using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace DebitOrdersApi.Features.DebitOrders.Commands { public class SaveDebitOrder : IRequest { public string AccountName { get; set; } public string IDNumber { get; set; } public string AccountNumber { get; set; } public string BranchCode { get; set; } public string BankCode { get; set; } public decimal DebitAmount { get; set; } public string DebitNarration { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int ProcessDay { get; set; } public string Creditor { get; set; } } public class SaveOrderHandler : IRequestHandler<SaveDebitOrder> { private readonly DataContext _db; public SaveOrderHandler(DataContext db) { _db = db; } public async Task<Unit> Handle(SaveDebitOrder request, CancellationToken cancellationToken) { var instruction = new DebitInstruction { AccountName = request.AccountName, IDNumber = request.IDNumber, AccountNumber = request.AccountNumber, BranchCode = request.BranchCode, BankCode = request.BankCode, DebitNarration = request.DebitNarration, StartDate = request.StartDate, EndDate = request.EndDate, ProcessingDay = request.ProcessDay, Creditor = request.Creditor }; _db.DebitInstructions.Add(instruction); try { _db.SaveChanges(); } catch (Exception ex) { throw; } return Unit.Value; } } }
28.728571
99
0.577325
[ "MIT" ]
Otis-c/Debit-Orders-Gateway
src/DebitOrdersApi/Features/DebitOrders/Commands/SaveDebitOrder.cs
2,013
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class WordDictionary { static void Main() { Dictionary<string, string> wordExplanation = new Dictionary<string, string>() { {".NET","platform for applications from Microsoft" }, {"CLR", "managed execution environment for .NET"}, {"namespace","hierarchical organization of classes" } }; string word = string.Empty; try { word = Console.ReadLine(); } catch (Exception) { Console.WriteLine("The word is not in the dictionary."); } Console.WriteLine(wordExplanation[word]); } }
24.580645
85
0.580052
[ "MIT" ]
VVoev/Telerik-Academy
03.C#Advanced/06.StringsAndTextProcessing/14.WordDictionary/WordDictionary.cs
764
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace RestaurantWebsite.ViewModels { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ForgotViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } }
27.610619
110
0.589744
[ "MIT" ]
smael123/RestaurantWebsite
RestaurantWebsite/ViewModels/AccountViewModels.cs
3,122
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using System.Net; namespace OpenSim.Region.Framework.Interfaces { public interface IEventQueue { bool Enqueue(OSD o, UUID avatarID); // These are required to decouple Scenes from EventQueueHelper void DisableSimulator(ulong handle, UUID avatarID); void EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY); void EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint, string capsPath, ulong regionHandle, int regionSizeX, int regionSizeY); void TeleportFinishEvent(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL, UUID agentID, int regionSizeX, int regionSizeY); void CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY); void ChatterboxInvitation(UUID sessionID, string sessionName, UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket); void ChatterBoxSessionAgentListUpdates(UUID sessionID, UUID fromAgent, UUID anotherAgent, bool canVoiceChat, bool isModerator, bool textMute); void ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage, UUID avatarID); void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID); OSD ScriptRunningEvent(UUID objectID, UUID itemID, bool running, bool mono); OSD BuildEvent(string eventName, OSD eventBody); void partPhysicsProperties(uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod, UUID avatarID); } }
58.985075
143
0.697874
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/Framework/Interfaces/IEventQueue.cs
3,952
C#
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Ritter.Infra.Crosscutting.Collections; using Ritter.Infra.Crosscutting.Tests.Mocks; using Xunit; namespace Ritter.Infra.Crosscutting.Tests.Paginng { public class Pagination_Paginate { [Fact] public void ReturnPaginatedGivenEmptyConstructor() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(); var paginateResult = values.Paginate(pagination).ToList(); paginateResult.Should().NotBeNull().And.HaveCount(100).And.HaveElementAt(0, values.ElementAt(0)); } [Fact] public void ReturnPaginatedGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10); var paginateResult = values.Paginate(pagination).ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(0)); } [Fact] public void ReturnPaginatedAsyncGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10); var paginateResult = values.PaginateAsync(pagination).GetAwaiter().GetResult().ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(0)); } [Fact] public void ReturnPaginatedGivenPageSizeZero() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 0); var paginateResult = values.Paginate(pagination).ToList(); paginateResult.Should().NotBeNull().And.HaveCount(100); } [Fact] public void ReturnPaginatedAsyncGivenPageSizeZero() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 0); var paginateResult = values.PaginateAsync(pagination) .GetAwaiter() .GetResult() .ToList(); paginateResult.Should().NotBeNull().And.HaveCount(100); } [Fact] public void ThrowExceptionGivenNull() { Action act = () => { IEnumerable<TestObject1> values = GetQuery(); values.Paginate(null); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("page"); } [Fact] public void ReturnPaginatedOrderingAscendingGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10, "Id", true); var paginateResult = values.Paginate(pagination).ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(0)); } [Fact] public void ReturnPaginatedAsyncOrderingAscendingGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10, "Id", true); var paginateResult = values.PaginateAsync(pagination).GetAwaiter().GetResult().ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(0)); } [Fact] public void ReturnPaginatedOrderingDescendingGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10, "Id", false); var paginateResult = values.Paginate(pagination).ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(99)); } [Fact] public void ReturnPaginatedAsyncOrderingDescendingGivenIndexAndSize() { IEnumerable<TestObject1> values = GetQuery(); var pagination = new Pagination(0, 10, "Id", false); var paginateResult = values.PaginateAsync(pagination).GetAwaiter().GetResult().ToList(); paginateResult.Should().NotBeNull().And.HaveCount(10).And.HaveElementAt(0, values.ElementAt(99)); } private static IQueryable<TestObject1> GetQuery() => GetQuery(100); private static IQueryable<TestObject1> GetQuery(int length) { var query = new List<TestObject1>(); for (int i = 1; i <= length; i++) { query.Add(new TestObject1 { Id = i, TestObject2Id = i, TestObject2 = new TestObject2 { Id = i } }); } return query.AsQueryable(); } } }
33.485915
115
0.60715
[ "Apache-2.0" ]
anderson-ritter/Ritter
tests/Infra.Crosscutting.Tests/Paginng/Pagination_Paginate.cs
4,755
C#
using Chloe.Reflection; namespace Chloe.Mapper.Binders { public class ComplexMemberBinder : MemberBinder, IMemberBinder { public ComplexMemberBinder(MemberSetter setter, IObjectActivator activtor) : base(setter, activtor) { } } }
22.333333
107
0.697761
[ "MIT" ]
shuxinqin/Chloe
src/Chloe/Mapper/Binders/ComplexMemberBinder.cs
270
C#
namespace CarcassSpark.Tools { partial class JsonCleaner { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(JsonCleaner)); this.inputBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.outputBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.selectInputFolderButton = new System.Windows.Forms.Button(); this.selectOutputFolderButton = new System.Windows.Forms.Button(); this.inputTextBox = new System.Windows.Forms.TextBox(); this.outputTextBox = new System.Windows.Forms.TextBox(); this.saveButton = new System.Windows.Forms.Button(); this.ToolTip = new System.Windows.Forms.ToolTip(this.components); this.inputLabel = new System.Windows.Forms.Label(); this.outputLabel = new System.Windows.Forms.Label(); this.closeButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // selectInputFolderButton // this.selectInputFolderButton.Location = new System.Drawing.Point(12, 12); this.selectInputFolderButton.Name = "selectInputFolderButton"; this.selectInputFolderButton.Size = new System.Drawing.Size(150, 50); this.selectInputFolderButton.TabIndex = 0; this.selectInputFolderButton.Text = "Select Folder to Clean"; this.ToolTip.SetToolTip(this.selectInputFolderButton, "Select the root folder from which you\'d like to clean JSON files.\r\nAll files will" + " be saved into the same folder structure that they were loaded from."); this.selectInputFolderButton.UseVisualStyleBackColor = true; this.selectInputFolderButton.Click += new System.EventHandler(this.SelectInputFolderButton_Click); // // selectOutputFolderButton // this.selectOutputFolderButton.Enabled = false; this.selectOutputFolderButton.Location = new System.Drawing.Point(12, 68); this.selectOutputFolderButton.Name = "selectOutputFolderButton"; this.selectOutputFolderButton.Size = new System.Drawing.Size(150, 50); this.selectOutputFolderButton.TabIndex = 1; this.selectOutputFolderButton.Text = "Select Folder to Save to"; this.ToolTip.SetToolTip(this.selectOutputFolderButton, "Select a folder to save the cleaned JSON to.\r\nAll files will be saved into the sa" + "me folder structure that they were loaded from."); this.selectOutputFolderButton.UseVisualStyleBackColor = true; this.selectOutputFolderButton.Click += new System.EventHandler(this.SelectOutputFolderButton_Click); // // inputTextBox // this.inputTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.inputTextBox.Location = new System.Drawing.Point(168, 28); this.inputTextBox.Name = "inputTextBox"; this.inputTextBox.ReadOnly = true; this.inputTextBox.Size = new System.Drawing.Size(279, 20); this.inputTextBox.TabIndex = 2; this.ToolTip.SetToolTip(this.inputTextBox, "This is the folder you\'ve selected to clean the JSON in."); // // outputTextBox // this.outputTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.outputTextBox.Location = new System.Drawing.Point(168, 84); this.outputTextBox.Name = "outputTextBox"; this.outputTextBox.ReadOnly = true; this.outputTextBox.Size = new System.Drawing.Size(279, 20); this.outputTextBox.TabIndex = 3; this.ToolTip.SetToolTip(this.outputTextBox, "This is the root directory that you\'re saving the JSON files into."); // // saveButton // this.saveButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.saveButton.Enabled = false; this.saveButton.Location = new System.Drawing.Point(12, 124); this.saveButton.Name = "saveButton"; this.saveButton.Size = new System.Drawing.Size(150, 50); this.saveButton.TabIndex = 4; this.saveButton.Text = "Save Cleaned JSON"; this.ToolTip.SetToolTip(this.saveButton, "This will save the cleaned files and open an instance of Explorer to the output f" + "older."); this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.SaveButton_Click); // // inputLabel // this.inputLabel.AutoSize = true; this.inputLabel.Location = new System.Drawing.Point(168, 12); this.inputLabel.Name = "inputLabel"; this.inputLabel.Size = new System.Drawing.Size(63, 13); this.inputLabel.TabIndex = 5; this.inputLabel.Text = "Input Folder"; // // outputLabel // this.outputLabel.AutoSize = true; this.outputLabel.Location = new System.Drawing.Point(168, 68); this.outputLabel.Name = "outputLabel"; this.outputLabel.Size = new System.Drawing.Size(71, 13); this.outputLabel.TabIndex = 6; this.outputLabel.Text = "Output Folder"; // // closeButton // this.closeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.closeButton.Location = new System.Drawing.Point(372, 151); this.closeButton.Name = "closeButton"; this.closeButton.Size = new System.Drawing.Size(75, 23); this.closeButton.TabIndex = 7; this.closeButton.Text = "Close"; this.closeButton.UseVisualStyleBackColor = true; // // JsonCleaner // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.closeButton; this.ClientSize = new System.Drawing.Size(459, 184); this.Controls.Add(this.closeButton); this.Controls.Add(this.outputLabel); this.Controls.Add(this.inputLabel); this.Controls.Add(this.saveButton); this.Controls.Add(this.outputTextBox); this.Controls.Add(this.inputTextBox); this.Controls.Add(this.selectOutputFolderButton); this.Controls.Add(this.selectInputFolderButton); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(475, 223); this.Name = "JsonCleaner"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Json Cleaner"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.FolderBrowserDialog inputBrowserDialog; private System.Windows.Forms.FolderBrowserDialog outputBrowserDialog; private System.Windows.Forms.Button selectInputFolderButton; private System.Windows.Forms.Button selectOutputFolderButton; private System.Windows.Forms.TextBox inputTextBox; private System.Windows.Forms.TextBox outputTextBox; private System.Windows.Forms.Button saveButton; private System.Windows.Forms.ToolTip ToolTip; private System.Windows.Forms.Label inputLabel; private System.Windows.Forms.Label outputLabel; private System.Windows.Forms.Button closeButton; } }
53.442529
162
0.635552
[ "MIT" ]
SarahKirksey/CarcassSpark
CarcassSpark/Tools/JsonCleaner.Designer.cs
9,301
C#
namespace UrbanIssues.Api.Infrastructure.Mapping { using AutoMapper; public class MappingService: IMappingService { public T Map<T>(object source) { return Mapper.Map<T>(source); } } }
19.833333
49
0.605042
[ "MIT" ]
g-yonchev/UrbanIssues
UrbanIssues.Server/UrbanIssues.Api/Infrastructure/Mapping/MappingService.cs
240
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ZhikeStreet.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.291667
99
0.588336
[ "MIT" ]
zhikecore/zhikestreet
ZhikeStreet.Web/App_Start/RouteConfig.cs
585
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net.Http.Headers; using System.Diagnostics.Contracts; namespace System.Net.Http { public class FormUrlEncodedContent : ByteArrayContent { public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection) : base(GetContentByteArray(nameValueCollection)) { Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection) { if (nameValueCollection == null) { throw new ArgumentNullException(nameof(nameValueCollection)); } Contract.EndContractBlock(); // Encode and concatenate data StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<string, string> pair in nameValueCollection) { if (builder.Length > 0) { builder.Append('&'); } builder.Append(Encode(pair.Key)); builder.Append('='); builder.Append(Encode(pair.Value)); } return HttpRuleParser.DefaultHttpEncoding.GetBytes(builder.ToString()); } private static string Encode(string data) { if (String.IsNullOrEmpty(data)) { return String.Empty; } // Escape spaces as '+'. return Uri.EscapeDataString(data).Replace("%20", "+"); } } }
32.931034
112
0.603665
[ "MIT" ]
Acidburn0zzz/corefx
src/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs
1,910
C#
// // System.Web.UI.HtmlControls.HtmlForm.cs // // Author: // Dick Porter <dick@ximian.com> // // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel; using System.Collections.Specialized; using System.Security.Permissions; using System.Web.Util; using System.Web.UI.WebControls; using System.Web.Configuration; using System.Web.SessionState; namespace System.Web.UI.HtmlControls { // CAS [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] public class HtmlForm : HtmlContainerControl { bool inited; string _defaultfocus; string _defaultbutton; bool submitdisabledcontrols = false; bool? isUplevel; public HtmlForm () : base ("form") { } // LAMESPEC: This is undocumented on MSDN, but apparently it does exist on MS.NET. // See https://bugzilla.novell.com/show_bug.cgi?id=442104 public string Action { get { string action = Attributes ["action"]; if (String.IsNullOrEmpty (action)) return String.Empty; return action; } set { if (String.IsNullOrEmpty (value)) Attributes ["action"] = null; else Attributes ["action"] = value; } } [DefaultValue ("")] public string DefaultButton { get { return _defaultbutton ?? String.Empty; } set { _defaultbutton = value; } } [DefaultValue ("")] public string DefaultFocus { get { return _defaultfocus ?? String.Empty; } set { _defaultfocus = value; } } [DefaultValue ("")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public string Enctype { get { string enc = Attributes["enctype"]; if (enc == null) { return (String.Empty); } return (enc); } set { if (value == null) { Attributes.Remove ("enctype"); } else { Attributes["enctype"] = value; } } } [DefaultValue ("")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public string Method { get { string method = Attributes["method"]; if ((method == null) || (method.Length == 0)) { return ("post"); } return (method); } set { if (value == null) { Attributes.Remove ("method"); } else { Attributes["method"] = value; } } } [DefaultValue ("")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public virtual string Name { get { return UniqueID; } set { /* why am i here? I do nothing. */ } } [DefaultValue (false)] public virtual bool SubmitDisabledControls { get { return submitdisabledcontrols; } set { submitdisabledcontrols = value; } } [DefaultValue ("")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public string Target { get { string target = Attributes["target"]; if (target == null) { return (String.Empty); } return (target); } set { if (value == null) { Attributes.Remove ("target"); } else { Attributes["target"] = value; } } } public override string UniqueID { get { Control container = NamingContainer; if (container == Page) return ID; return "aspnetForm"; } } [MonoTODO ("why override?")] protected override ControlCollection CreateControlCollection () { return base.CreateControlCollection (); } protected internal override void OnInit (EventArgs e) { inited = true; Page page = Page; if (page != null) { page.RegisterViewStateHandler (); page.RegisterForm (this); } base.OnInit (e); } internal bool DetermineRenderUplevel () { if (isUplevel != null) return (bool) isUplevel; isUplevel = UplevelHelper.IsUplevel ( System.Web.Configuration.HttpCapabilitiesBase.GetUserAgentForDetection (HttpContext.Current.Request)); return (bool) isUplevel; } protected internal override void OnPreRender (EventArgs e) { base.OnPreRender(e); } protected override void RenderAttributes (HtmlTextWriter w) { /* Need to always render: method, action and id */ string action; string customAction = Attributes ["action"]; Page page = Page; HttpRequest req = page != null ? page.RequestInternal : null; if (String.IsNullOrEmpty (customAction)) { string file_path = req != null ? req.ClientFilePath : null; string current_path = req != null ? req.CurrentExecutionFilePath : null; if (file_path == null) action = Action; else if (file_path == current_path) { // Just the filename will do action = UrlUtils.GetFile (file_path); } else { // Fun. We need to make cookieless sessions work, so no // absolute paths here. bool cookieless; SessionStateSection sec = WebConfigurationManager.GetSection ("system.web/sessionState") as SessionStateSection; cookieless = sec != null ? sec.Cookieless == HttpCookieMode.UseUri: false; string appVPath = HttpRuntime.AppDomainAppVirtualPath; int appVPathLen = appVPath.Length; if (appVPathLen > 1) { if (cookieless) { if (StrUtils.StartsWith (file_path, appVPath, true)) file_path = file_path.Substring (appVPathLen + 1); } else if (StrUtils.StartsWith (current_path, appVPath, true)) current_path = current_path.Substring (appVPathLen + 1); } if (cookieless) { Uri current_uri = new Uri ("http://host" + current_path); Uri fp_uri = new Uri ("http://host" + file_path); action = fp_uri.MakeRelative (current_uri); } else action = current_path; } } else action = customAction; if (req != null) action += req.QueryStringRaw; if (req != null) { XhtmlConformanceSection xhtml = WebConfigurationManager.GetSection ("system.web/xhtmlConformance") as XhtmlConformanceSection; if (xhtml == null || xhtml.Mode != XhtmlConformanceMode.Strict) if (RenderingCompatibilityLessThan40) // LAMESPEC: MSDN says the 'name' attribute is rendered only in // Legacy mode, this is not true. w.WriteAttribute ("name", Name); } w.WriteAttribute ("method", Method); if (String.IsNullOrEmpty (customAction)) w.WriteAttribute ("action", action, true); /* * This is a hack that guarantees the ID is set properly for HtmlControl to * render it later on. As ugly as it is, we use it here because of the way * the ID, ClientID and UniqueID properties work internally in our Control * code. * * Fixes bug #82596 */ if (ID == null) { #pragma warning disable 219 string client = ClientID; #pragma warning restore 219 } string submit = page != null ? page.GetSubmitStatements () : null; if (!String.IsNullOrEmpty (submit)) { Attributes.Remove ("onsubmit"); w.WriteAttribute ("onsubmit", submit); } /* enctype and target should not be written if * they are empty */ string enctype = Enctype; if (!String.IsNullOrEmpty (enctype)) w.WriteAttribute ("enctype", enctype); string target = Target; if (!String.IsNullOrEmpty (target)) w.WriteAttribute ("target", target); string defaultbutton = DefaultButton; if (!String.IsNullOrEmpty (defaultbutton)) { Control c = FindControl (defaultbutton); if (c == null || !(c is IButtonControl)) throw new InvalidOperationException(String.Format ("The DefaultButton of '{0}' must be the ID of a control of type IButtonControl.", ID)); if (page != null && DetermineRenderUplevel ()) { w.WriteAttribute ( "onkeypress", "javascript:return " + page.WebFormScriptReference + ".WebForm_FireDefaultButton(event, '" + c.ClientID + "')"); } } /* Now remove them from the hash so the base * RenderAttributes can do all the rest */ Attributes.Remove ("method"); Attributes.Remove ("enctype"); Attributes.Remove ("target"); base.RenderAttributes (w); } protected internal override void RenderChildren (HtmlTextWriter w) { Page page = Page; if (!inited && page != null) { page.RegisterViewStateHandler (); page.RegisterForm (this); } if (page != null) page.OnFormRender (w, ClientID); base.RenderChildren (w); if (page != null) page.OnFormPostRender (w, ClientID); } /* According to corcompare */ [MonoTODO ("why override?")] public override void RenderControl (HtmlTextWriter w) { base.RenderControl (w); } protected internal override void Render (HtmlTextWriter w) { base.Render (w); } } }
27.127072
137
0.665886
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlForm.cs
9,820
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 timestream-write-2018-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.TimestreamWrite.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.TimestreamWrite.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for RetentionProperties Object /// </summary> public class RetentionPropertiesUnmarshaller : IUnmarshaller<RetentionProperties, XmlUnmarshallerContext>, IUnmarshaller<RetentionProperties, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> RetentionProperties IUnmarshaller<RetentionProperties, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public RetentionProperties Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; RetentionProperties unmarshalledObject = new RetentionProperties(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("MagneticStoreRetentionPeriodInDays", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.MagneticStoreRetentionPeriodInDays = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MemoryStoreRetentionPeriodInHours", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.MemoryStoreRetentionPeriodInHours = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static RetentionPropertiesUnmarshaller _instance = new RetentionPropertiesUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static RetentionPropertiesUnmarshaller Instance { get { return _instance; } } } }
36.112245
170
0.647075
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/TimestreamWrite/Generated/Model/Internal/MarshallTransformations/RetentionPropertiesUnmarshaller.cs
3,539
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Packaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace OpenExcel { /// <summary> /// Class for Excel Workbook (Consists of Shared Strings too) /// </summary> public class ExcelWorkbook { public string FileName { get; set; } private Package ExcelFile = null; protected XmlDocument workbookDoc = null; private XmlElement sheets { get; set; } private XmlDocument sharedStringsDoc = null; private XmlElement sstNode { get; set; } internal int ssCount { get; set; } public List<ExcelSheet> Sheets { get; set; } #region Constructors /// <summary> /// Default constructor /// </summary> public ExcelWorkbook() { this.FileName = "ExcelWorkbook"; InitializeWorkbook(); InitializeSharedStringDoc(); } //Creates an Excel Workbook by the given name public ExcelWorkbook(string FileName) { this.FileName = FileName; InitializeWorkbook(); InitializeSharedStringDoc(); } #endregion #region Methods private void InitializeWorkbook() //Add a parameter for the location in which the file is saved { Sheets = new List<ExcelSheet>(); workbookDoc = new XmlDocument(); //Obtain a reference to the root node, and then add the XML declaration. XmlElement wbRoot = workbookDoc.DocumentElement; XmlDeclaration wbxmldecl = workbookDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); workbookDoc.InsertBefore(wbxmldecl, wbRoot); //Create and append the workbook node to the document. XmlElement workBook = workbookDoc.CreateElement("workbook"); workBook.SetAttribute("xmlns", "http://schemas.openxmlformats.org/" + "spreadsheetml/2006/main"); workBook.SetAttribute("xmlns:r", "http://schemas.openxmlformats.org/officeDocument/" + "2006/relationships"); workbookDoc.AppendChild(workBook); ////Create and append the workbook node to the document. //XmlElement workbookPr = workbookDoc.CreateElement("workbookPr"); //workbookPr.SetAttribute("defaultThemeVersion", "124226"); //workBook.AppendChild(workbookPr); //// Creating a sheetProctection part for password protection //XmlElement workbookProtection = workbookDoc.CreateElement("workbookProtection"); //workbookProtection.SetAttribute("workbookPassword", "xsd:hexBinary data"); //workbookProtection.SetAttribute("lockStructure", "1"); //workbookProtection.SetAttribute("lockWindows", "1"); //workBook.AppendChild(workbookProtection); ////Create and append the workbook node to the document. //XmlElement bookViews = workbookDoc.CreateElement("bookViews"); //XmlElement workbookView = workbookDoc.CreateElement("workbookView"); //workbookView.SetAttribute("windowHeight", "7365"); //workbookView.SetAttribute("windowWidth", "19815"); //workbookView.SetAttribute("yWindow", "555"); //workbookView.SetAttribute("xWindow", "390"); //bookViews.AppendChild(workbookView); //workBook.AppendChild(bookViews); //Create and append the sheets node to the workBook node. sheets = workbookDoc.CreateElement("sheets"); workBook.AppendChild(sheets); // Creating the file for Excel Package string targetDir = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); FileInfo targetFile = new FileInfo(targetDir + "\\" + FileName + ".xlsx"); if (targetFile.Exists) { FileName = FileName + Path.GetRandomFileName(); } ExcelFile = Package.Open(targetDir + "\\" + FileName + ".xlsx", FileMode.Create, FileAccess.ReadWrite); } private void InitializeSharedStringDoc() { ssCount = 0; sharedStringsDoc = new XmlDocument(); //Get a reference to the root node, and then add the XML declaration. XmlElement ssRoot = sharedStringsDoc.DocumentElement; XmlDeclaration ssxmldecl = sharedStringsDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); sharedStringsDoc.InsertBefore(ssxmldecl, ssRoot); //Create and append the sst node. sstNode = sharedStringsDoc.CreateElement("sst"); sstNode.SetAttribute("xmlns", "http://schemas.openxmlformats.org/" + "spreadsheetml/2006/main"); sharedStringsDoc.AppendChild(sstNode); } public void AddSheet(string SheetName = "Sheet") { Sheets.Add(new ExcelSheet(SheetName)); if (SheetName == "Sheet") { SheetName += Sheets.Count.ToString(); } //Create and append the <sheet> node to the <sheets> node. XmlElement sheet = workbookDoc.CreateElement("sheet"); sheet.SetAttribute("name", SheetName); sheet.SetAttribute("sheetId", Sheets.Count.ToString()); sheet.SetAttribute("id", "http://schemas.openxmlformats.org/" + "officeDocument/2006/relationships", "rId" + Sheets.Count.ToString()); sheets.AppendChild(sheet); } /// <summary> /// Method creates the shared strings document for the excel file generated /// </summary> public void SaveChanges() { foreach (ExcelSheet sheet in Sheets) { int rowCount = 0; if (sheet.autoFilter) { // Adding element for AutoFilter XmlElement autoFilterElement = sheet.workSheetDoc.CreateElement("autoFilter"); string startRange = sheet.Rows.First().Columns.First().cellAddress; string endRange = sheet.Rows.Last().Columns.Last().cellAddress; autoFilterElement.SetAttribute("ref", startRange + ":" + endRange); sheet.workSheetDoc.DocumentElement.AppendChild(autoFilterElement); } foreach (ExcelRow row in sheet.Rows) { rowCount++; int columnCount = 0; foreach (ExcelColumn cell in row.Columns) { columnCount++; //Check for availability of value in a cell if (!string.IsNullOrEmpty(cell.Value)) { //Create the si node XmlElement siNode = sharedStringsDoc.CreateElement("si"); //Create and append the t node. XmlElement tNode = sharedStringsDoc.CreateElement("t"); tNode.InnerText = cell.Value; siNode.AppendChild(tNode); //append the si node to sharedStrings Document sharedStringsDoc.ChildNodes[1].AppendChild(siNode); cell.vNode.InnerText = ssCount.ToString(); row.RowDoc.FirstChild.ReplaceChild(row.RowDoc.ImportNode(cell.ColDoc.FirstChild, true), row.RowDoc.FirstChild.ChildNodes[columnCount - 1]); sheet.workSheetDoc.ChildNodes[1].FirstChild.ReplaceChild(sheet.workSheetDoc.ImportNode(row.RowDoc.FirstChild, true), sheet.workSheetDoc.ChildNodes[1].FirstChild.ChildNodes[rowCount - 1]); ssCount++; } } } } sstNode.SetAttribute("count", ssCount.ToString()); sstNode.SetAttribute("uniqueCount", ssCount.ToString()); XmlDocument tempWorkBook = workbookDoc; XmlDocument tempSharedStrings = sharedStringsDoc; XmlDocument tempWorkSheet = Sheets.Last().workSheetDoc; } public void Download() { SaveChanges(); if (ExcelFile != null) { AddExcelParts(); } if (ExcelFile != null) { ExcelFile.Flush(); ExcelFile.Close(); } } private void AddExcelParts() { #region Add excel part of Workbook string nsWorkbook = "application/vnd.openxmlformats-" + "officedocument.spreadsheetml.sheet.main+xml"; string workbookRelationshipType = "http://schemas.openxmlformats.org/" + "officeDocument/2006/relationships/" + "officeDocument"; Uri workBookUri = PackUriHelper.CreatePartUri(new Uri("xl/workbook.xml", UriKind.Relative)); //Create the workbook part. PackagePart wbPart = ExcelFile.CreatePart(workBookUri, nsWorkbook); //Write the workbook XML to the workbook part. Stream workbookStream = wbPart.GetStream(FileMode.Create, FileAccess.Write); workbookDoc.Save(workbookStream); //Create the relationship for the workbook part. ExcelFile.CreateRelationship(workBookUri, TargetMode.Internal, workbookRelationshipType, "rId1"); #endregion #region Add excel part for Worksheet foreach (ExcelSheet sheet in Sheets) { string nsWorksheet = "application/vnd.openxmlformats-" + "officedocument.spreadsheetml.worksheet+xml"; string worksheetRelationshipType = "http://schemas.openxmlformats.org/" + "officeDocument/2006/relationships/worksheet"; Uri workSheetUri = PackUriHelper.CreatePartUri(new Uri("xl/worksheets/" + sheet.SheetName + ".xml", UriKind.Relative)); //Create the workbook part. PackagePart wsPart = ExcelFile.CreatePart(workSheetUri, nsWorksheet); //Write the workbook XML to the workbook part. Stream worksheetStream = wsPart.GetStream(FileMode.Create, FileAccess.Write); sheet.workSheetDoc.Save(worksheetStream); //Create the relationship for the workbook part. Uri wsworkbookPartUri = PackUriHelper.CreatePartUri(new Uri("xl/workbook.xml", UriKind.Relative)); PackagePart wsworkbookPart = ExcelFile.GetPart(wsworkbookPartUri); wsworkbookPart.CreateRelationship(workSheetUri, TargetMode.Internal, worksheetRelationshipType, "rId1"); } #endregion #region Add excel part for Shared Strings string nsSharedStrings = "application/vnd.openxmlformats-officedocument" + ".spreadsheetml.sharedStrings+xml"; string sharedStringsRelationshipType = "http://schemas.openxmlformats.org" + "/officeDocument/2006/relationships/sharedStrings"; Uri sharedStringsUri = PackUriHelper.CreatePartUri(new Uri("xl/sharedStrings.xml", UriKind.Relative)); //Create the workbook part. PackagePart sharedStringsPart = ExcelFile.CreatePart(sharedStringsUri, nsSharedStrings); //Write the workbook XML to the workbook part. Stream sharedStringsStream = sharedStringsPart.GetStream(FileMode.Create, FileAccess.Write); sharedStringsDoc.Save(sharedStringsStream); //Create the relationship for the workbook part. Uri ssworkbookPartUri = PackUriHelper.CreatePartUri(new Uri("xl/workbook.xml", UriKind.Relative)); PackagePart ssworkbookPart = ExcelFile.GetPart(ssworkbookPartUri); ssworkbookPart.CreateRelationship(sharedStringsUri, TargetMode.Internal, sharedStringsRelationshipType, "rId2"); #endregion } #endregion } }
41.435374
215
0.600148
[ "MIT" ]
Anshul-Chandra/OpenExcel
OpenExcel/Structure/ExcelWorkbook.cs
12,184
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using Entities.Concrete; using Microsoft.EntityFrameworkCore; namespace DataAccess.Concrete.EntityFramework { public class EfBrandDal : EfEntityRepositoryBase<Brand, RecapContext>, IBrandDal { } }
22.388889
84
0.789082
[ "MIT" ]
ErenAri/RecapProject_V2
DataAccess/Concrete/EntityFramework/EfBrandDal.cs
405
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 Sample.Domain.Ordering; namespace Microsoft.Its.Domain.Tests { public class TestConsequenter : IHaveConsequencesWhen<Order.Cancelled>, IHaveConsequencesWhen<Order.Created>, IHaveConsequencesWhen<Order.Delivered> { private readonly Action<Order.Cancelled> onCancelled; private readonly Action<Order.Created> onCreated; private readonly Action<Order.Delivered> onDelivered; public TestConsequenter( Action<Order.Cancelled> onCancelled = null, Action<Order.Created> onCreated = null, Action<Order.Delivered> onDelivered = null) { this.onCancelled = onCancelled ?? (e => { }); this.onCreated = onCreated ?? (e => { }); this.onDelivered = onDelivered ?? (e => { }); } public void HaveConsequences(Order.Cancelled @event) { onCancelled(@event); } public void HaveConsequences(Order.Created @event) { onCreated(@event); } public void HaveConsequences(Order.Delivered @event) { onDelivered(@event); } } }
30.431818
101
0.618372
[ "MIT" ]
gitter-badger/Its.Cqrs
Domain.Tests/Infrastructure/TestConsequenter.cs
1,339
C#
using Cassandra; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenerateData { class OrderDetails { public int orderid { get; set; } public int customerid { get; set; } public LocalDate orderdate { get; set; } public decimal ordervalue { get; set; } } }
22
49
0.638889
[ "MIT" ]
MicrosoftLearning/DP-060T00A-Migrating-your-Database-to-Cosmos-DB
Cassandra/GenerateData/GenerateData/OrderDetails.cs
398
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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; using System.Collections.Generic; using System.Linq; using System.Text; using QuantConnect.Data; using System.Collections.Concurrent; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Util; namespace QuantConnect.Securities { /// <summary> /// Provides a means of keeping track of the different cash holdings of an algorithm /// </summary> public class CashBook : IDictionary<string, Cash>, ICurrencyConverter { private string _accountCurrency; /// <summary> /// Event fired when a <see cref="Cash"/> instance is added or removed, and when /// the <see cref="Cash.Updated"/> is triggered for the currently hold instances /// </summary> public event EventHandler<UpdateType> Updated; /// <summary> /// Gets the base currency used /// </summary> public string AccountCurrency { get { return _accountCurrency; } set { var amount = 0m; Cash accountCurrency; // remove previous account currency if any if (!_accountCurrency.IsNullOrEmpty() && TryGetValue(_accountCurrency, out accountCurrency)) { amount = accountCurrency.Amount; Remove(_accountCurrency); } // add new account currency using same amount as previous _accountCurrency = value.LazyToUpper(); Add(_accountCurrency, new Cash(_accountCurrency, amount, 1.0m)); } } private readonly ConcurrentDictionary<string, Cash> _currencies; /// <summary> /// Gets the total value of the cash book in units of the base currency /// </summary> public decimal TotalValueInAccountCurrency { get { return _currencies.Aggregate(0m, (d, pair) => d + pair.Value.ValueInAccountCurrency); } } /// <summary> /// Initializes a new instance of the <see cref="CashBook"/> class. /// </summary> public CashBook() { _currencies = new ConcurrentDictionary<string, Cash>(); AccountCurrency = Currencies.USD; } /// <summary> /// Adds a new cash of the specified symbol and quantity /// </summary> /// <param name="symbol">The symbol used to reference the new cash</param> /// <param name="quantity">The amount of new cash to start</param> /// <param name="conversionRate">The conversion rate used to determine the initial /// portfolio value/starting capital impact caused by this currency position.</param> public void Add(string symbol, decimal quantity, decimal conversionRate) { var cash = new Cash(symbol, quantity, conversionRate); Add(symbol, cash); } /// <summary> /// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data /// </summary> /// <param name="securities">The SecurityManager for the algorithm</param> /// <param name="subscriptions">The SubscriptionManager for the algorithm</param> /// <param name="marketMap">The market map that decides which market the new security should be in</param> /// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param> /// <param name="securityService">Will be used to create required new <see cref="Security"/></param> /// <returns>Returns a list of added currency <see cref="SubscriptionDataConfig"/></returns> public List<SubscriptionDataConfig> EnsureCurrencyDataFeeds(SecurityManager securities, SubscriptionManager subscriptions, IReadOnlyDictionary<SecurityType, string> marketMap, SecurityChanges changes, ISecurityService securityService) { var addedSubscriptionDataConfigs = new List<SubscriptionDataConfig>(); foreach (var kvp in _currencies) { var cash = kvp.Value; var subscriptionDataConfig = cash.EnsureCurrencyDataFeed( securities, subscriptions, marketMap, changes, securityService, AccountCurrency); if (subscriptionDataConfig != null) { addedSubscriptionDataConfigs.Add(subscriptionDataConfig); } } return addedSubscriptionDataConfigs; } /// <summary> /// Converts a quantity of source currency units into the specified destination currency /// </summary> /// <param name="sourceQuantity">The quantity of source currency to be converted</param> /// <param name="sourceCurrency">The source currency symbol</param> /// <param name="destinationCurrency">The destination currency symbol</param> /// <returns>The converted value</returns> public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency) { if (sourceQuantity == 0) { return 0; } var source = this[sourceCurrency]; var destination = this[destinationCurrency]; if (source.ConversionRate == 0) { throw new Exception($"The conversion rate for {sourceCurrency} is not available."); } if (destination.ConversionRate == 0) { throw new Exception($"The conversion rate for {destinationCurrency} is not available."); } var conversionRate = source.ConversionRate / destination.ConversionRate; return sourceQuantity * conversionRate; } /// <summary> /// Converts a quantity of source currency units into the account currency /// </summary> /// <param name="sourceQuantity">The quantity of source currency to be converted</param> /// <param name="sourceCurrency">The source currency symbol</param> /// <returns>The converted value</returns> public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency) { if (sourceCurrency == AccountCurrency) { return sourceQuantity; } return Convert(sourceQuantity, sourceCurrency, AccountCurrency); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine(string.Format("{0} {1,13} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency)); foreach (var value in _currencies.Select(x => x.Value)) { sb.AppendLine(value.ToString()); } sb.AppendLine("-------------------------------------------------"); sb.AppendLine(string.Format("CashBook Total Value: {0}{1}", Currencies.GetCurrencySymbol(AccountCurrency), Math.Round(TotalValueInAccountCurrency, 2)) ); return sb.ToString(); } #region IDictionary Implementation /// <summary> /// Gets the count of Cash items in this CashBook. /// </summary> /// <value>The count.</value> public int Count => _currencies.Skip(0).Count(); /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; } } /// <summary> /// Add the specified item to this CashBook. /// </summary> /// <param name="item">KeyValuePair of symbol -> Cash item</param> public void Add(KeyValuePair<string, Cash> item) { Add(item.Key, item.Value); } /// <summary> /// Add the specified key and value. /// </summary> /// <param name="symbol">The symbol of the Cash value.</param> /// <param name="value">Value.</param> public void Add(string symbol, Cash value) { if (symbol == Currencies.NullCurrency) { return; } // we link our Updated event with underlying cash instances // so interested listeners just subscribe to our event value.Updated += OnCashUpdate; var alreadyExisted = Remove(symbol, calledInternally: true); _currencies.AddOrUpdate(symbol, value); OnUpdate(alreadyExisted ? UpdateType.Updated : UpdateType.Added); } /// <summary> /// Clear this instance of all Cash entries. /// </summary> public void Clear() { _currencies.Clear(); OnUpdate(UpdateType.Removed); } /// <summary> /// Remove the Cash item corresponding to the specified symbol /// </summary> /// <param name="symbol">The symbolto be removed</param> public bool Remove(string symbol) { return Remove(symbol, calledInternally: false); } /// <summary> /// Remove the specified item. /// </summary> /// <param name="item">Item.</param> public bool Remove(KeyValuePair<string, Cash> item) { return Remove(item.Key); } /// <summary> /// Determines whether the current instance contains an entry with the specified symbol. /// </summary> /// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns> /// <param name="symbol">Key.</param> public bool ContainsKey(string symbol) { return _currencies.ContainsKey(symbol); } /// <summary> /// Try to get the value. /// </summary> /// <remarks>To be added.</remarks> /// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns> /// <param name="symbol">The symbol.</param> /// <param name="value">Value.</param> public bool TryGetValue(string symbol, out Cash value) { return _currencies.TryGetValue(symbol, out value); } /// <summary> /// Determines whether the current collection contains the specified value. /// </summary> /// <param name="item">Item.</param> public bool Contains(KeyValuePair<string, Cash> item) { return _currencies.Contains(item); } /// <summary> /// Copies to the specified array. /// </summary> /// <param name="array">Array.</param> /// <param name="arrayIndex">Array index.</param> public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex) { ((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex); } /// <summary> /// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol. /// </summary> /// <param name="symbol">Symbol.</param> public Cash this[string symbol] { get { if (symbol == Currencies.NullCurrency) { throw new InvalidOperationException( "Unexpected request for NullCurrency Cash instance"); } Cash cash; if (!_currencies.TryGetValue(symbol, out cash)) { throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book."); } return cash; } set { Add(symbol, value); } } /// <summary> /// Gets the keys. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys => _currencies.Select(x => x.Key).ToList(); /// <summary> /// Gets the values. /// </summary> /// <value>The values.</value> public ICollection<Cash> Values => _currencies.Select(x => x.Value).ToList(); /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator() { return _currencies.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _currencies).GetEnumerator(); } #endregion #region ICurrencyConverter Implementation /// <summary> /// Converts a cash amount to the account currency /// </summary> /// <param name="cashAmount">The <see cref="CashAmount"/> instance to convert</param> /// <returns>A new <see cref="CashAmount"/> instance denominated in the account currency</returns> public CashAmount ConvertToAccountCurrency(CashAmount cashAmount) { if (cashAmount.Currency == AccountCurrency) { return cashAmount; } var amount = Convert(cashAmount.Amount, cashAmount.Currency, AccountCurrency); return new CashAmount(amount, AccountCurrency); } #endregion private bool Remove(string symbol, bool calledInternally) { Cash cash = null; var removed = _currencies.TryRemove(symbol, out cash); if (!removed) { if (!calledInternally) { Log.Error($"CashBook.Remove(): Failed to remove the cash book record for symbol {symbol}"); } } else { cash.Updated -= OnCashUpdate; if (!calledInternally) { OnUpdate(UpdateType.Removed); } } return removed; } private void OnCashUpdate(object sender, EventArgs eventArgs) { OnUpdate(UpdateType.Updated); } private void OnUpdate(UpdateType updateType) { Updated?.Invoke(this, updateType); } /// <summary> /// The different types of <see cref="Updated"/> events /// </summary> public enum UpdateType { /// <summary> /// A new <see cref="Cash.Symbol"/> was added /// </summary> Added, /// <summary> /// One or more <see cref="Cash"/> instances were removed /// </summary> Removed, /// <summary> /// An existing <see cref="Cash.Symbol"/> was updated /// </summary> Updated } } }
36.573991
138
0.561121
[ "Apache-2.0" ]
QilongChan/Lean
Common/Securities/CashBook.cs
16,312
C#
using System.Linq; using System.Threading.Tasks; using Equinor.ProCoSys.Preservation.Command.Validators.ResponsibleValidators; using Equinor.ProCoSys.Preservation.Infrastructure; using Equinor.ProCoSys.Preservation.Test.Common; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Equinor.ProCoSys.Preservation.Command.Tests.Validators { [TestClass] public class ResponsibleValidatorTests : ReadOnlyTestsBase { private string _responsibleCode; protected override void SetupNewDatabase(DbContextOptions<PreservationContext> dbContextOptions) { using (var context = new PreservationContext(dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { _responsibleCode = AddResponsible(context, "R").Code; } } [TestMethod] public async Task ExistsAndIsVoidedAsync_KnownCode_Voided_ShouldReturnTrue() { using (var context = new PreservationContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { var responsible = context.Responsibles.Single(r => r.Code == _responsibleCode); responsible.IsVoided = true; context.SaveChangesAsync().Wait(); } using (var context = new PreservationContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { var dut = new ResponsibleValidator(context); var result = await dut.ExistsAndIsVoidedAsync(_responsibleCode, default); Assert.IsTrue(result); } } [TestMethod] public async Task ExistsAndIsVoidedAsync_KnownCode_NotVoided_ShouldReturnFalse() { using (var context = new PreservationContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { var dut = new ResponsibleValidator(context); var result = await dut.ExistsAndIsVoidedAsync(_responsibleCode, default); Assert.IsFalse(result); } } [TestMethod] public async Task ExistsAndIsVoidedAsync_UnknownCode_ShouldReturnFalse() { using (var context = new PreservationContext(_dbContextOptions, _plantProvider, _eventDispatcher, _currentUserProvider)) { var dut = new ResponsibleValidator(context); var result = await dut.ExistsAndIsVoidedAsync("A", default); Assert.IsFalse(result); } } } }
39.376812
132
0.649245
[ "MIT" ]
equinor/pcs-preservation-api
src/tests/Equinor.ProCoSys.Preservation.Command.Tests/Validators/ResponsibleValidatorTests.cs
2,719
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/schannel.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.Versioning; namespace TerraFX.Interop.Windows; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED"]/*' /> [SupportedOSPlatform("windows8.1")] public unsafe partial struct SCHANNEL_CRED { /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwVersion"]/*' /> [NativeTypeName("DWORD")] public uint dwVersion; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.cCreds"]/*' /> [NativeTypeName("DWORD")] public uint cCreds; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.paCred"]/*' /> [NativeTypeName("PCCERT_CONTEXT *")] public CERT_CONTEXT** paCred; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.hRootStore"]/*' /> public HCERTSTORE hRootStore; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.cMappers"]/*' /> [NativeTypeName("DWORD")] public uint cMappers; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.aphMappers"]/*' /> [NativeTypeName("struct _HMAPPER **")] public IntPtr* aphMappers; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.cSupportedAlgs"]/*' /> [NativeTypeName("DWORD")] public uint cSupportedAlgs; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.palgSupportedAlgs"]/*' /> [NativeTypeName("ALG_ID *")] public uint* palgSupportedAlgs; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.grbitEnabledProtocols"]/*' /> [NativeTypeName("DWORD")] public uint grbitEnabledProtocols; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwMinimumCipherStrength"]/*' /> [NativeTypeName("DWORD")] public uint dwMinimumCipherStrength; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwMaximumCipherStrength"]/*' /> [NativeTypeName("DWORD")] public uint dwMaximumCipherStrength; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwSessionLifespan"]/*' /> [NativeTypeName("DWORD")] public uint dwSessionLifespan; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwFlags"]/*' /> [NativeTypeName("DWORD")] public uint dwFlags; /// <include file='SCHANNEL_CRED.xml' path='doc/member[@name="SCHANNEL_CRED.dwCredFormat"]/*' /> [NativeTypeName("DWORD")] public uint dwCredFormat; }
40.742857
145
0.700912
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/schannel/SCHANNEL_CRED.cs
2,854
C#
using System; namespace ContentPatcher.Framework.Conditions { /// <summary>A unique identifier for a contextual condition.</summary> internal struct ConditionKey : IEquatable<ConditionKey> { /********* ** Accessors *********/ /**** ** Predefined keys ****/ /// <summary>A predefined condition key for <see cref="ConditionType.Day"/>.</summary> public static ConditionKey Day { get; } = new ConditionKey(ConditionType.Day); /// <summary>A predefined condition key for <see cref="ConditionType.DayOfWeek"/>.</summary> public static ConditionKey DayOfWeek { get; } = new ConditionKey(ConditionType.DayOfWeek); /// <summary>A predefined condition key for <see cref="ConditionType.DayEvent"/>.</summary> public static ConditionKey DayEvent { get; } = new ConditionKey(ConditionType.DayEvent); /// <summary>A predefined condition key for <see cref="ConditionType.HasFlag"/>.</summary> public static ConditionKey HasFlag { get; } = new ConditionKey(ConditionType.HasFlag); /// <summary>A predefined condition key for <see cref="ConditionType.HasMod"/>.</summary> public static ConditionKey HasMod { get; } = new ConditionKey(ConditionType.HasMod); /// <summary>A predefined condition key for <see cref="ConditionType.HasSeenEvent"/>.</summary> public static ConditionKey HasSeenEvent { get; } = new ConditionKey(ConditionType.HasSeenEvent); /// <summary>A predefined condition key for <see cref="ConditionType.Language"/>.</summary> public static ConditionKey Language { get; } = new ConditionKey(ConditionType.Language); /// <summary>A predefined condition key for <see cref="ConditionType.Season"/>.</summary> public static ConditionKey Season { get; } = new ConditionKey(ConditionType.Season); /// <summary>A predefined condition key for <see cref="ConditionType.Spouse"/>.</summary> public static ConditionKey Spouse { get; } = new ConditionKey(ConditionType.Spouse); /// <summary>A predefined condition key for <see cref="ConditionType.Weather"/>.</summary> public static ConditionKey Weather { get; } = new ConditionKey(ConditionType.Weather); /**** ** Properties ****/ /// <summary>The condition type.</summary> public ConditionType Type { get; } /// <summary>A unique key indicating which in-game object the condition type applies to. For example, the NPC name when <see cref="Type"/> is <see cref="ConditionType.Relationship"/>.</summary> public string ForID { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="type">The condition type.</param> /// <param name="forID">A unique key indicating which in-game object the condition type applies to. For example, the NPC name when <paramref name="type"/> is <see cref="ConditionType.Relationship"/>.</param> public ConditionKey(ConditionType type, string forID = null) { this.Type = type; this.ForID = forID; } /// <summary>Get a string representation for this instance.</summary> public override string ToString() { return this.ForID != null ? $"{this.Type}:{this.ForID}" : this.Type.ToString(); } /**** ** IEquatable ****/ /// <summary>Get whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> public bool Equals(ConditionKey other) { return this.Type == other.Type && this.ForID == other.ForID; } /// <summary>Get whether this instance and a specified object are equal.</summary> /// <param name="obj">The object to compare with the current instance.</param> public override bool Equals(object obj) { return obj is ConditionKey other && this.Equals(other); } /// <summary>Get the hash code for this instance.</summary> public override int GetHashCode() { return this.ToString().GetHashCode(); } /**** ** Static parsing ****/ /// <summary>Parse a raw string into a condition key if it's valid.</summary> /// <param name="raw">The raw string.</param> /// <returns>Returns true if <paramref name="raw"/> was successfully parsed, else false.</returns> public static ConditionKey Parse(string raw) { if (string.IsNullOrWhiteSpace(raw)) throw new ArgumentNullException(nameof(raw)); // extract parts ConditionType type; string forID; { string[] parts = raw.Trim().Split(new[] { ':' }, 2); // condition type if (!Enum.TryParse(parts[0], true, out type)) throw new FormatException($"Can't parse string '{parts[0]}' as a {nameof(ConditionKey)} value."); // for ID forID = parts.Length == 2 ? parts[1].Trim() : null; if (forID == "") forID = null; } // create instance return new ConditionKey(type, forID); } /// <summary>Parse a raw string into a condition key if it's valid.</summary> /// <param name="raw">The raw string.</param> /// <param name="key">The parsed condition key.</param> /// <returns>Returns true if <paramref name="raw"/> was successfully parsed, else false.</returns> public static bool TryParse(string raw, out ConditionKey key) { try { key = ConditionKey.Parse(raw); return true; } catch { key = default(ConditionKey); return false; } } } }
41.302013
215
0.584498
[ "MIT" ]
Sotheros/StardewMods
ContentPatcher/Framework/Conditions/ConditionKey.cs
6,154
C#
using BierFroh.Modules.DependencyGraph.Model; namespace BierFroh.Modules.DependencyGraph; public class DependencyFilter { private readonly HashSet<IDependency> dependencies; public DependencyFilter(HashSet<IDependency> dependencies) { this.dependencies = dependencies; } public bool Contains(IDependency dependency) => dependency is not null && dependencies.Contains(dependency); }
27.6
112
0.770531
[ "BSD-3-Clause" ]
FelixDamrau/BierFroh
src/Modules/DependencyGraph/DependencyFilter.cs
416
C#
using System; using System.Collections.Generic; using System.Text; namespace Hime.Structures { public struct ActionResult { public int Code { get; set; } public byte[] Content { get; set; } public string MIME { get; set; } } }
16.6875
43
0.621723
[ "MIT" ]
naomiEve/hime
Hime/Structures/ActionResult.cs
269
C#
using System; using System.IO; using Cool.AST; using Cool.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest { [TestClass] public class UnitTestAST { [TestMethod] public void ASTBuilderSuccess() { UnitTestParsing testParsing = new UnitTestParsing(); string directorySuccess = "../../../TestCases/Parsing/success/"; DirectoryInfo directory = new DirectoryInfo(directorySuccess); FileInfo[] files = directory.GetFiles(); foreach (var file in files) { testParsing.ParsingFile(file.FullName); var astBuilder = new ASTBuilder(); ASTNode root = astBuilder.Visit(testParsing.tree); Assert.IsFalse(root is null, "AST no created. (root is null)"); Assert.IsTrue(root is ProgramNode, $"AST created with big problems. (root is not a ProgramNode, root is {root})"); } } } }
31.46875
130
0.603774
[ "MIT" ]
Code-distancing/cool
UnitTest/UnitTestAST.cs
1,009
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/dwrite.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IDWriteFontCollection" /> struct.</summary> public static unsafe class IDWriteFontCollectionTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDWriteFontCollection" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IDWriteFontCollection).GUID, Is.EqualTo(IID_IDWriteFontCollection)); } /// <summary>Validates that the <see cref="IDWriteFontCollection" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IDWriteFontCollection>(), Is.EqualTo(sizeof(IDWriteFontCollection))); } /// <summary>Validates that the <see cref="IDWriteFontCollection" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IDWriteFontCollection).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IDWriteFontCollection" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IDWriteFontCollection), Is.EqualTo(8)); } else { Assert.That(sizeof(IDWriteFontCollection), Is.EqualTo(4)); } } } }
38.076923
145
0.64697
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/dwrite/IDWriteFontCollectionTests.cs
1,982
C#
using UnityEngine; namespace UGF.Messages.Runtime.Transform { [AddComponentMenu("Unity Game Framework/Messages/Transform/Message Transform All", 2000)] public class MessageTransformAllReceiver : MonoBehaviour { [SerializeField] private Message m_onBeforeParentChanged = new Message(); [SerializeField] private Message m_onParentChanged = new Message(); [SerializeField] private Message m_onChildrenChanged = new Message(); public Message OnBeforeParentChanged { get { return m_onBeforeParentChanged; } } public Message OnParentChanged { get { return m_onParentChanged; } } public Message OnChildrenChanged { get { return m_onChildrenChanged; } } private void OnBeforeTransformParentChanged() { m_onBeforeParentChanged.Invoke(); } private void OnTransformParentChanged() { m_onParentChanged.Invoke(); } private void OnTransformChildrenChanged() { m_onChildrenChanged.Invoke(); } } }
33.09375
93
0.677998
[ "MIT" ]
unity-game-framework/ugf-messages
Packages/UGF.Messages/Runtime/Transform/MessageTransformAllReceiver.cs
1,059
C#
using System; using System.Collections.Generic; using System.Text; namespace BookApiProject.Dtos.Dtos { public class CategoryDto { public int Id { get; set; } public string Name { get; set; } } }
17.384615
40
0.650442
[ "MIT" ]
CristianSifuentes/BookApiProject
BookApiProject.Dtos/Dtos/CategoryDto.cs
228
C#
using System; namespace Microservice.Entities.MSSQL { /// <summary> /// The interface for audit. /// </summary> public interface IAuditable { /// <summary> /// Id of the user who created record. /// </summary> string CreatedBy { get; set; } /// <summary> /// Date when resource was created (in UTC timezone). /// </summary> DateTime CreatedUtc { get; set; } /// <summary> /// Id of the user who updated record. /// </summary> string LastModifiedBy { get; set; } /// <summary> /// Date when resource was updated (in UTC timezone). /// </summary> DateTime LastModifiedUtc { get; set; } } }
24.032258
61
0.526174
[ "Apache-2.0" ]
ZyshchykMaksim/aspnetcore-microservices.template.net
src/Microservice.Entities.MSSQL/IAuditable.cs
747
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.Media.VideoAnalyzer.Edge.Models { internal partial class PipelineTopologySetRequestBody : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteStringValue(Name); if (Optional.IsDefined(SystemData)) { writer.WritePropertyName("systemData"); writer.WriteObjectValue(SystemData); } if (Optional.IsDefined(Properties)) { writer.WritePropertyName("properties"); writer.WriteObjectValue(Properties); } if (Optional.IsDefined(ApiVersion)) { writer.WritePropertyName("@apiVersion"); writer.WriteStringValue(ApiVersion); } writer.WriteEndObject(); } internal static PipelineTopologySetRequestBody DeserializePipelineTopologySetRequestBody(JsonElement element) { string name = default; Optional<SystemData> systemData = default; Optional<PipelineTopologyProperties> properties = default; string methodName = default; Optional<string> apiVersion = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("systemData")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } systemData = SystemData.DeserializeSystemData(property.Value); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } properties = PipelineTopologyProperties.DeserializePipelineTopologyProperties(property.Value); continue; } if (property.NameEquals("methodName")) { methodName = property.Value.GetString(); continue; } if (property.NameEquals("@apiVersion")) { apiVersion = property.Value.GetString(); continue; } } return new PipelineTopologySetRequestBody(methodName, apiVersion.Value, name, systemData.Value, properties.Value); } } }
36.229885
126
0.527284
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/videoanalyzer/Azure.Media.VideoAnalyzer.Edge/src/Generated/Models/PipelineTopologySetRequestBody.Serialization.cs
3,152
C#