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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// https://www.mshowto.org/yazilim-gelistiriciler-icin-azure-azure-app-configuration-bolum-3.html using Azure.Messaging.EventGrid; using Microsoft.Azure.ServiceBus; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.AzureAppConfiguration; using Microsoft.Extensions.Configuration.AzureAppConfiguration.Extensions; var builder = new ConfigurationBuilder(); IConfigurationRefresher configurationRefresher = null; builder.AddAzureAppConfiguration(options => { options.Connect("Endpoint=https://mshowto-appconfig.azconfig.io;Id=***;Secret=***") .ConfigureRefresh(refresh => refresh.Register("mshowtoconsoleapp:settings:key1")); configurationRefresher = options.GetRefresher(); }); var config = builder.Build(); var subscriptionClient = new SubscriptionClient(connectionString:"Endpoint=sb://mshowto-sbns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=***", topicPath:"appconfig-topic", subscriptionName:"appconfig-sub1"); subscriptionClient.RegisterMessageHandler( handler: (message, cancellationToken) => { var eventGridEvent = EventGridEvent.Parse(BinaryData.FromBytes(message.Body)); eventGridEvent.TryCreatePushNotification(out PushNotification pushNotification); configurationRefresher.ProcessPushNotification(pushNotification); return Task.CompletedTask; }, exceptionReceivedHandler: (exceptionArgs) => { Console.WriteLine($"{exceptionArgs.Exception}"); return Task.CompletedTask; }); Task.Run(async () => { while (true) { Console.WriteLine($"Key1: {config["mshowtoconsoleapp:settings:key1"]}"); await configurationRefresher.TryRefreshAsync(); await Task.Delay(5000); } }).Wait();
37.76
185
0.716102
[ "MIT" ]
mertyeter/azure-for-developers
app-configuration/push-model.cs
1,888
C#
using UnityEngine; using System.Collections.Generic; using Assets.Scripts.Lib.View; using Assets.Scripts.Controller; using Assets.Scripts.View.UIDetail; namespace Assets.Scripts.View.Chat { public class CMDView : ChatUIDetail { public CMDView() : base(200, 30) { } private static CMDView instance; public static CMDView GetInstance() { if (instance == null) instance = new CMDView(); return instance; } protected override void PreInit() { base.PreInit(); } protected override void Init() { SetViewPosition(ViewPosition.BottomLeft); uiPanel.transform.localPosition += new Vector3(5, 0, 0); UIEventListener.Get(Input.gameObject).onSubmit += OnSubmitHandler; } public bool IsEditing() { if (Input == null) return false; return Input.selected; } private void OnSubmitHandler(GameObject go) { string str = inputTxt.text; str = str.Substring(0,str.LastIndexOf('|')); inputTxt.text = ""; ChatController.GetInstance().SendGMMessage(str); } } }
23.818182
78
0.545802
[ "MIT" ]
moto2002/DinaGameClient
Assets/Scripts/View/Chat/CMDView.cs
1,312
C#
using EveMarketProphet.Models; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; namespace EveMarketProphet.Services { public class SdeContext : DbContext { public DbSet<Type> Types { get; set; } public DbSet<ContrabandType> ContrabandTypes { get; set; } public DbSet<Station> Stations { get; set; } public DbSet<Region> Regions { get; set; } public DbSet<SolarSystem> SolarSystems { get; set; } public DbSet<SolarSystemJump> SolarSystemJumps { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Filename=Data/sqlite-latest.sqlite"); optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<SolarSystemJump>().HasKey(t => new { t.fromSolarSystemID, t.toSolarSystemID }); modelBuilder.Entity<ContrabandType>().HasKey(t => new {t.factionID, t.typeID}); } } public class Db { public static Db Instance { get; } = new Db(); public List<Models.Type> Types { get; private set; } public List<ContrabandType> ContrabandTypes { get; private set; } public List<Station> Stations { get; private set; } public List<Region> Regions { get; private set; } public List<SolarSystem> SolarSystems { get; private set; } public List<SolarSystemJump> SolarSystemJumps { get; private set; } private Db() { using (var context = new SdeContext()) { Types = context.Types.ToList(); ContrabandTypes = context.ContrabandTypes.ToList(); Stations = context.Stations.ToList(); Regions = context.Regions.ToList(); SolarSystems = context.SolarSystems.ToList(); SolarSystemJumps = context.SolarSystemJumps.ToList(); } } } }
37.410714
111
0.632936
[ "Apache-2.0" ]
LevWi/EveMarketProphet
EveMarketProphet/Services/DB.cs
2,097
C#
namespace osfDesigner { public enum FlatStyle { Всплывающий = 1, Плоский = 0, Система = 3, Стандартный = 2 } }
14.181818
25
0.50641
[ "MPL-2.0" ]
Nivanchenko/OneScriptFormsDesigner
OneScriptFormsDesigner/OneScriptFormsDesigner/FlatStyle.cs
194
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 route53-2013-04-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.Route53.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Route53.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for TrafficPolicyInstanceAlreadyExistsException operation /// </summary> public class TrafficPolicyInstanceAlreadyExistsExceptionUnmarshaller : IErrorResponseUnmarshaller<TrafficPolicyInstanceAlreadyExistsException, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public TrafficPolicyInstanceAlreadyExistsException Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public TrafficPolicyInstanceAlreadyExistsException Unmarshall(XmlUnmarshallerContext context, ErrorResponse errorResponse) { TrafficPolicyInstanceAlreadyExistsException response = new TrafficPolicyInstanceAlreadyExistsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { } } return response; } private static TrafficPolicyInstanceAlreadyExistsExceptionUnmarshaller _instance = new TrafficPolicyInstanceAlreadyExistsExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static TrafficPolicyInstanceAlreadyExistsExceptionUnmarshaller Instance { get { return _instance; } } } }
36.915663
170
0.682768
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/Internal/MarshallTransformations/TrafficPolicyInstanceAlreadyExistsExceptionUnmarshaller.cs
3,064
C#
namespace SpacechemPatch.Patches { [Decoy("#=q92hEbMwWJAHBnI1OOFNVMfgZTZcBdcobiluEchpymk8=")] internal class WholeUI { [Decoy(".ctor")] public WholeUI(AbstractUI actualUI, bool unused, Optional<AbstractUiElement> elementToFocus, Optional<IScreen> screen) { } } }
28.272727
126
0.672026
[ "MIT" ]
csaboka/spacechempatch
SpacechemPatch/Patches/WholeUI.cs
313
C#
#pragma checksum "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3c60c3212035ffe38a47f6c217e44887d25dc334" // <auto-generated/> #pragma warning disable 1591 namespace HexDataMovies.Client.Shared { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using System.Net.Http.Json; #line default #line hidden #nullable disable #nullable restore #line 3 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 4 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 5 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 6 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.AspNetCore.Components.Web.Virtualization; #line default #line hidden #nullable disable #nullable restore #line 7 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.AspNetCore.Components.WebAssembly.Http; #line default #line hidden #nullable disable #nullable restore #line 8 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 9 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using HexDataMovies.Client; #line default #line hidden #nullable disable #nullable restore #line 10 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using HexDataMovies.Client.Shared; #line default #line hidden #nullable disable #nullable restore #line 11 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using HexDataMovies.Shared.Entity; #line default #line hidden #nullable disable #nullable restore #line 12 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using HexDataMovies.Client.Services; #line default #line hidden #nullable disable #nullable restore #line 13 "/home/saint/Documentos/HexDataMovies/Client/_Imports.razor" using HexDataMovies.Shared.Configuration; #line default #line hidden #nullable disable public partial class NavMenu : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.OpenElement(0, "div"); __builder.AddAttribute(1, "class", "top-row pl-4 navbar navbar-dark"); __builder.AddAttribute(2, "b-ip3k6710ok"); __builder.AddMarkupContent(3, "<img style=\"max-height:48px; margin-top: -4px;\" src=\"/Images/HexData.png\" b-ip3k6710ok>\n "); __builder.AddMarkupContent(4, "<a class=\"navbar-brand\" href b-ip3k6710ok>HexData Movies</a>\n "); __builder.OpenElement(5, "button"); __builder.AddAttribute(6, "class", "navbar-toggler"); __builder.AddAttribute(7, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 4 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" ToggleNavMenu #line default #line hidden #nullable disable )); __builder.AddAttribute(8, "b-ip3k6710ok"); __builder.AddMarkupContent(9, "<span class=\"navbar-toggler-icon\" b-ip3k6710ok></span>"); __builder.CloseElement(); __builder.CloseElement(); __builder.AddMarkupContent(10, "\n\n"); __builder.OpenElement(11, "div"); __builder.AddAttribute(12, "class", #nullable restore #line 9 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavMenuCssClass #line default #line hidden #nullable disable ); __builder.AddAttribute(13, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 9 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" ToggleNavMenu #line default #line hidden #nullable disable )); __builder.AddAttribute(14, "b-ip3k6710ok"); __builder.OpenElement(15, "ul"); __builder.AddAttribute(16, "class", "nav flex-column"); __builder.AddAttribute(17, "b-ip3k6710ok"); __builder.OpenElement(18, "li"); __builder.AddAttribute(19, "class", "nav-item px-3"); __builder.AddAttribute(20, "b-ip3k6710ok"); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(21); __builder.AddAttribute(22, "class", "nav-link"); __builder.AddAttribute(23, "href", ""); __builder.AddAttribute(24, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 12 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(25, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(26, "<span class=\"oi oi-video\" aria-hidden=\"true\" b-ip3k6710ok></span> Películas\n "); } )); __builder.CloseComponent(); __builder.CloseElement(); __builder.AddMarkupContent(27, "\n "); __builder.OpenElement(28, "li"); __builder.AddAttribute(29, "class", "nav-item px-3"); __builder.AddAttribute(30, "b-ip3k6710ok"); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(31); __builder.AddAttribute(32, "class", "nav-link"); __builder.AddAttribute(33, "href", "filmgenres"); __builder.AddAttribute(34, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 17 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(35, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(36, "<span class=\"oi oi-book\" aria-hidden=\"true\" b-ip3k6710ok></span> Categorías\n "); } )); __builder.CloseComponent(); __builder.CloseElement(); __builder.AddMarkupContent(37, "\n "); __builder.OpenElement(38, "li"); __builder.AddAttribute(39, "class", "nav-item px-3"); __builder.AddAttribute(40, "b-ip3k6710ok"); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(41); __builder.AddAttribute(42, "class", "nav-link"); __builder.AddAttribute(43, "href", "actors"); __builder.AddAttribute(44, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 22 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(45, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(46, "<span class=\"oi oi-image\" aria-hidden=\"true\" b-ip3k6710ok></span> Actores\n "); } )); __builder.CloseComponent(); __builder.CloseElement(); __builder.AddMarkupContent(47, "\n "); __builder.OpenElement(48, "li"); __builder.AddAttribute(49, "class", "nav-item px-3"); __builder.AddAttribute(50, "b-ip3k6710ok"); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(51); __builder.AddAttribute(52, "class", "nav-link"); __builder.AddAttribute(53, "href", "movies/create"); __builder.AddAttribute(54, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 27 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(55, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(56, "<span class=\"oi oi-brush\" aria-hidden=\"true\" b-ip3k6710ok></span> Crear Películas\n "); } )); __builder.CloseComponent(); __builder.CloseElement(); __builder.AddMarkupContent(57, "\n "); __builder.OpenElement(58, "li"); __builder.AddAttribute(59, "class", "nav-item px-3"); __builder.AddAttribute(60, "b-ip3k6710ok"); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(61); __builder.AddAttribute(62, "class", "nav-link"); __builder.AddAttribute(63, "href", "actors/create"); __builder.AddAttribute(64, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 37 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(65, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(66, "<span class=\"oi oi-pencil\" aria-hidden=\"true\" b-ip3k6710ok></span> Crear Actores\n "); } )); __builder.CloseComponent(); __builder.CloseElement(); __builder.CloseElement(); __builder.CloseElement(); } #pragma warning restore 1998 #nullable restore #line 59 "/home/saint/Documentos/HexDataMovies/Client/Shared/NavMenu.razor" private bool collapseNavMenu = true; private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } #line default #line hidden #nullable disable } } #pragma warning restore 1591
41.035336
176
0.668992
[ "MIT" ]
toXGet/HexDataMovies
Client/obj/Debug/net5.0/Razor/Shared/NavMenu.razor.g.cs
11,616
C#
using System.IO; using System.Reflection; using MLAPI.Serialization.Pooled; namespace MLAPI.NetworkedVar { internal class SyncedVarContainer { internal SyncedVarAttribute attribute; internal FieldInfo field; internal object fieldInstance; internal object value; internal bool isDirty; internal float lastSyncedTime; internal MethodInfo hookMethod; internal bool IsDirty() { if (attribute.SendTickrate >= 0 && (attribute.SendTickrate == 0 || NetworkingManager.Singleton.NetworkTime - lastSyncedTime >= (1f / attribute.SendTickrate))) { lastSyncedTime = NetworkingManager.Singleton.NetworkTime; object newValue = field.GetValue(fieldInstance); object oldValue = value; if (!Equals(newValue, oldValue) || isDirty) { isDirty = true; value = newValue; return true; } } return false; } internal void ResetDirty() { value = field.GetValue(fieldInstance); isDirty = false; } internal void WriteValue(Stream stream, bool checkDirty = true) { using (PooledBitWriter writer = PooledBitWriter.Get(stream)) { if (checkDirty) { // Trigger a value update IsDirty(); } writer.WriteObjectPacked(value); } } internal void ReadValue(Stream stream) { using (PooledBitReader reader = PooledBitReader.Get(stream)) { value = reader.ReadObjectPacked(field.FieldType); field.SetValue(fieldInstance, value); if (hookMethod != null) hookMethod.Invoke(fieldInstance, null); } } } }
20.90411
161
0.693971
[ "MIT" ]
cakeslice/MLAPI
MLAPI/NetworkedVar/SyncedVarContainer.cs
1,526
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using RssCollection.Models; using RssCollection.Services; namespace RssCollection { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttp, Http>(); //services.Configure<RssDatabaseSettings>(Configuration.GetSection(nameof(RssDatabaseSettings))); //services.AddSingleton<IRssDatabaseSettings>(sp =>sp.GetRequiredService<IOptions<IRssDatabaseSettings>>().Value); IRssDatabaseSettings rssDatabaseSettings = new RssDatabaseSettings(); rssDatabaseSettings.CollectionName = Configuration["RssDatabaseSettings:CollectionName"]; rssDatabaseSettings.ConnectionString = Configuration["RssDatabaseSettings:ConnectionString"]; rssDatabaseSettings.DatabaseName = Configuration["RssDatabaseSettings:DatabaseName"]; services.AddSingleton<IMailing, Mailing>(); services.AddSingleton<IDataBase,DataBase>(sp=>new DataBase(rssDatabaseSettings)); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/home/error"); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
34.283582
126
0.670875
[ "MIT" ]
Dariusz11/rss-collection
RssCollection/Startup.cs
2,297
C#
using BookManagementSystem.Data.BaseEntity; using System.ComponentModel.DataAnnotations.Schema; namespace BookManagementSystem.Data.Model { [Table("Author")] public class Author : BaseEntities { public string AuthorName { get; set; } public bool IsDeleted { get; set; } [ForeignKey("Book")] public int? BookId { get; set; } public virtual Book Book { get; set; } } }
21.45
51
0.648019
[ "MIT" ]
DiyanLyubchev/BookManagementSystem
BookManagementSystem.Data/Model/Author.cs
431
C#
namespace SourceLink.Create.GitHub { public class CreateTask : GitCreateTask { public override string ConvertUrl(string origin) { return UrlConverter.Convert(origin); } } }
20.181818
56
0.621622
[ "MIT" ]
paulomorgado/ctaggart-SourceLink
SourceLink.Create.GitHub/CreateTask.cs
224
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Network; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// State details. /// </summary> public partial class AvailableProvidersListState { /// <summary> /// Initializes a new instance of the AvailableProvidersListState /// class. /// </summary> public AvailableProvidersListState() { CustomInit(); } /// <summary> /// Initializes a new instance of the AvailableProvidersListState /// class. /// </summary> /// <param name="stateName">The state name.</param> /// <param name="providers">A list of Internet service /// providers.</param> /// <param name="cities">List of available cities or towns in the /// state.</param> public AvailableProvidersListState(string stateName = default(string), IList<string> providers = default(IList<string>), IList<AvailableProvidersListCity> cities = default(IList<AvailableProvidersListCity>)) { StateName = stateName; Providers = providers; Cities = cities; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the state name. /// </summary> [JsonProperty(PropertyName = "stateName")] public string StateName { get; set; } /// <summary> /// Gets or sets a list of Internet service providers. /// </summary> [JsonProperty(PropertyName = "providers")] public IList<string> Providers { get; set; } /// <summary> /// Gets or sets list of available cities or towns in the state. /// </summary> [JsonProperty(PropertyName = "cities")] public IList<AvailableProvidersListCity> Cities { get; set; } } }
33.493333
215
0.618232
[ "MIT" ]
thangnguyen2001/azure-sdk-for-net
src/SDKs/Network/Management.Network/Generated/Models/AvailableProvidersListState.cs
2,512
C#
using AoC.Day25; using FluentAssertions; using NUnit.Framework; namespace AoC.Tests.Day25 { public class Day25SolverTests { private readonly Day25Solver _sut = new(); [TestCase(5764801, 8)] [TestCase(17807724, 11)] public void DetermineLoopSize_Tests(int publicKey, int expectedLoopSize) { Day25Solver.DetermineLoopSize(publicKey).Should().Be(expectedLoopSize); } [TestCase(17807724, 8, 14897079)] [TestCase(5764801, 11, 14897079)] public void TransformSubjectNumber_Tests(int subjectNumber, int loopSize, int expectedEncryptionKey) { Day25Solver.TransformSubjectNumber(subjectNumber, loopSize).Should().Be(expectedEncryptionKey); } [Test] public void Part1Example() { // ACT var part1Result = _sut.SolvePart1(@"5764801 17807724"); // ASSERT part1Result.Should().Be(14897079); } [Test] public void Part1ReTest() { // ACT var part1Result = _sut.SolvePart1(); // ASSERT part1Result.Should().Be(1478097); } [Test] public void Part2ReTest() { // ACT var part2Result = _sut.SolvePart2(); // ASSERT part2Result.Should().StartWith("Day 25, part 2, was free :)"); } } }
25.175439
108
0.567247
[ "BSD-3-Clause" ]
robshakespeare/aoc2020
AoC.Tests/Day25/Day25SolverTests.cs
1,435
C#
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.Extensions.SplitPartitionRequest.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.LDAP.VQ.Asn1; using Novell.Directory.LDAP.VQ.Utilclass; namespace Novell.Directory.LDAP.VQ.Extensions { /// <summary> Creates a new partition. /// /// To split a new partition, you must create an instance of this /// class and then call the extendedOperation method with this /// object as the required LdapExtendedOperation parameter. /// /// The SplitPartitionRequest extension uses the following OID: /// 2.16.840.1.113719.1.27.100.3 /// /// The requestValue has the following format: /// /// requestValue ::= /// flags INTEGER /// dn LdapDN /// </summary> public class SplitPartitionRequest:LdapExtendedOperation { /// <summary> /// Constructs an extended operation object for splitting partition. /// /// </summary> /// <param name="dn"> The distinguished name of the container where the new /// partition root should be located. /// /// </param> /// <param name="flags">Specifies whether all servers in the replica ring must be up before /// proceeding. When set to zero, the status of the servers is not /// checked. When set to Ldap_ENSURE_SERVERS_UP, all servers must be up /// for the operation to proceed. /// /// </param> /// <exception> LdapException A general exception which includes an error message /// and an Ldap error code. /// </exception> public SplitPartitionRequest(String dn, int flags):base(ReplicationConstants.CREATE_NAMING_CONTEXT_REQ, null) { try { if ((object) dn == null) throw new ArgumentException(ExceptionMessages.PARAM_ERROR); System.IO.MemoryStream encodedData = new System.IO.MemoryStream(); LBEREncoder encoder = new LBEREncoder(); Asn1Integer asn1_flags = new Asn1Integer(flags); Asn1OctetString asn1_dn = new Asn1OctetString(dn); asn1_flags.encode(encoder, encodedData); asn1_dn.encode(encoder, encodedData); setValue(SupportClass.ToSByteArray(encodedData.ToArray())); } catch (System.IO.IOException ioe) { throw new LdapException(ExceptionMessages.ENCODING_ERROR, LdapException.ENCODING_ERROR, (String) null); } } } }
35.990099
111
0.687483
[ "MIT" ]
VQComms/CsharpLDAP
src/Novell.Directory.LDAP/Extensions/SplitPartitionRequest.cs
3,635
C#
using FluentAssertions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using System; using System.Net.Http; using System.Threading.Tasks; using Xunit; namespace Blaze.SimTainer.Service.Api.Integration.UnitTests.Controllers { public class TestStatusFixture : IDisposable { private readonly TestServer _testServer; public TestStatusFixture() { IWebHostBuilder builder = new WebHostBuilder() .UseEnvironment("Production") .ConfigureServices(ConfigureMockedServices) .UseStartup<Startup>(); _testServer = new TestServer(builder); Client = _testServer.CreateClient(); } public HttpClient Client { get; } [Fact] public void TestStatusEndpointController() { // Arrange & Act Task<string> result = Client.GetStringAsync("/status"); JObject obj = JObject.Parse(result.Result); // Assert obj["status"].ToString().Should().Be("OK"); } public void Dispose() { Client.Dispose(); _testServer.Dispose(); } private void ConfigureMockedServices(IServiceCollection services) { } } }
22.115385
71
0.73913
[ "Apache-2.0" ]
wehkamp/blaze-simtainer-service
test/Blaze.SimTainer.Service.Api.Integration.UnitTests/Controllers/TestStatusFixture.cs
1,150
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.EC2.Inputs { public sealed class LaunchTemplateNetworkInterfaceArgs : Pulumi.ResourceArgs { [Input("associateCarrierIpAddress")] public Input<bool>? AssociateCarrierIpAddress { get; set; } [Input("associatePublicIpAddress")] public Input<bool>? AssociatePublicIpAddress { get; set; } [Input("deleteOnTermination")] public Input<bool>? DeleteOnTermination { get; set; } [Input("description")] public Input<string>? Description { get; set; } [Input("deviceIndex")] public Input<int>? DeviceIndex { get; set; } [Input("groups")] private InputList<string>? _groups; public InputList<string> Groups { get => _groups ?? (_groups = new InputList<string>()); set => _groups = value; } [Input("interfaceType")] public Input<string>? InterfaceType { get; set; } [Input("ipv6AddressCount")] public Input<int>? Ipv6AddressCount { get; set; } [Input("ipv6Addresses")] private InputList<Inputs.LaunchTemplateIpv6AddArgs>? _ipv6Addresses; public InputList<Inputs.LaunchTemplateIpv6AddArgs> Ipv6Addresses { get => _ipv6Addresses ?? (_ipv6Addresses = new InputList<Inputs.LaunchTemplateIpv6AddArgs>()); set => _ipv6Addresses = value; } [Input("networkCardIndex")] public Input<int>? NetworkCardIndex { get; set; } [Input("networkInterfaceId")] public Input<string>? NetworkInterfaceId { get; set; } [Input("privateIpAddress")] public Input<string>? PrivateIpAddress { get; set; } [Input("privateIpAddresses")] private InputList<Inputs.LaunchTemplatePrivateIpAddArgs>? _privateIpAddresses; public InputList<Inputs.LaunchTemplatePrivateIpAddArgs> PrivateIpAddresses { get => _privateIpAddresses ?? (_privateIpAddresses = new InputList<Inputs.LaunchTemplatePrivateIpAddArgs>()); set => _privateIpAddresses = value; } [Input("secondaryPrivateIpAddressCount")] public Input<int>? SecondaryPrivateIpAddressCount { get; set; } [Input("subnetId")] public Input<string>? SubnetId { get; set; } public LaunchTemplateNetworkInterfaceArgs() { } } }
33.525
121
0.644668
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/EC2/Inputs/LaunchTemplateNetworkInterfaceArgs.cs
2,682
C#
using UnityEngine; public class Bomb : MonoBehaviour { private Blows _blows; private void OnEnable() { _blows = FindObjectOfType<Blows>(); } private void OnCollisionEnter2D(Collision2D collision) { GameObject blow = _blows.GetItem(); if (blow != null) { blow.transform.position = transform.position; blow.SetActive(true); } gameObject.SetActive(false); } public void Armed() { GetComponent<Animator>().SetTrigger("BombOn"); } }
18.766667
58
0.575488
[ "MIT" ]
wladweb/Kings-Pigs
Assets/Scripts/Environment/Bomb.cs
565
C#
using System; using System.Collections.Generic; using UnityEngine; namespace UnityARInterface { public class AREditorInterface : ARInterface { float m_LastTime; enum State { Uninitialized, Initialized, WaitingToAddPlane1, WaitingToAddPlane2, Finished } State m_State; BoundedPlane[] m_FakePlanes; Pose m_CameraPose; bool m_WasMouseDownLastFrame; Vector3 m_LastMousePosition; Vector3 m_EulerAngles; Vector3[] m_PointCloud; public override bool StartService(Settings settings) { m_CameraPose = Pose.identity; m_CameraPose.position.Set(0, 0, 0); m_LastTime = Time.time; m_State = State.Initialized; m_FakePlanes = new BoundedPlane[2]; m_FakePlanes[0] = new BoundedPlane() { id = "0x1", extents = new Vector2(2.2f, 2f), //extents = new Vector2(1f, 1f), rotation = Quaternion.AngleAxis(60f, Vector3.up), center = new Vector3(2f, -1f, 3f) //center = new Vector3(1f, 1f, 1f) }; m_FakePlanes[1] = new BoundedPlane() { id = "0x2", extents = new Vector2(2f, 2f), rotation = Quaternion.AngleAxis(200f, Vector3.up), center = new Vector3(3f, 1f, 3f) }; m_PointCloud = new Vector3[20]; for (int i = 0; i < 20; ++i) { m_PointCloud[i] = new Vector3( UnityEngine.Random.Range(-2f, 2f), UnityEngine.Random.Range(-.5f, .5f), UnityEngine.Random.Range(-2f, 2f)); } return true; } public override void StopService() { } public override bool TryGetUnscaledPose(ref Pose pose) { pose = m_CameraPose; return true; } public override bool TryGetCameraImage(ref CameraImage cameraImage) { return false; } public override void SetupCamera(Camera camera) { } public override bool TryGetPointCloud(ref PointCloud pointCloud) { if (pointCloud.points == null) pointCloud.points = new List<Vector3>(); pointCloud.points.Clear(); pointCloud.points.AddRange(m_PointCloud); return true; } public override LightEstimate GetLightEstimate() { return new LightEstimate() { capabilities = LightEstimateCapabilities.None }; } public override Matrix4x4 GetDisplayTransform() { return Matrix4x4.identity; } public override void UpdateCamera(Camera camera) { float speed = camera.transform.parent.localScale.x / 10f; float turnSpeed = 10f; var forward = m_CameraPose.rotation * Vector3.forward; var right = m_CameraPose.rotation * Vector3.right; var up = m_CameraPose.rotation * Vector3.up; if (Input.GetKey(KeyCode.W)) m_CameraPose.position += forward * Time.deltaTime * speed; if (Input.GetKey(KeyCode.S)) m_CameraPose.position -= forward * Time.deltaTime * speed; if (Input.GetKey(KeyCode.A)) m_CameraPose.position -= right * Time.deltaTime * speed; if (Input.GetKey(KeyCode.D)) m_CameraPose.position += right * Time.deltaTime * speed; if (Input.GetKey(KeyCode.Q)) m_CameraPose.position += up * Time.deltaTime * speed; if (Input.GetKey(KeyCode.Z)) m_CameraPose.position -= up * Time.deltaTime * speed; if (Input.GetMouseButton(1)) { if (!m_WasMouseDownLastFrame) m_LastMousePosition = Input.mousePosition; var deltaPosition = Input.mousePosition - m_LastMousePosition; m_EulerAngles.y += Time.deltaTime * turnSpeed * deltaPosition.x; m_EulerAngles.x -= Time.deltaTime * turnSpeed * deltaPosition.y; m_CameraPose.rotation = Quaternion.Euler(m_EulerAngles); m_LastMousePosition = Input.mousePosition; m_WasMouseDownLastFrame = true; } else { m_WasMouseDownLastFrame = false; } } public override void Update() { switch (m_State) { case State.Initialized: m_State = State.WaitingToAddPlane1; m_LastTime = Time.time; break; case State.WaitingToAddPlane1: if (Time.time - m_LastTime > 1f) { OnPlaneAdded(m_FakePlanes[0]); m_LastTime = Time.time; m_State = State.WaitingToAddPlane2; } break; case State.WaitingToAddPlane2: if (Time.time - m_LastTime > 1f) { OnPlaneAdded(m_FakePlanes[1]); m_LastTime = Time.time; m_State = State.Finished; } break; } } } }
30.423913
80
0.50786
[ "MIT" ]
ARUnityBook/ARBook-ARUnity
Assets/UnityARInterface/Scripts/AREditorInterface.cs
5,600
C#
/// Credit Tomasz Schelenz /// Sourced from - https://bitbucket.org/SimonDarksideJ/unity-ui-extensions/issues/81/infinite-scrollrect /// Demo - https://www.youtube.com/watch?v=uVTV7Udx78k - configures automatically. - works in both vertical and horizontal (but not both at the same time) - drag and drop - can be initialized by code (in case you populate your scrollview content from code) /// Updated by Febo Zodiaco - https://bitbucket.org/UnityUIExtensions/unity-ui-extensions/issues/349/magnticinfinitescroll using System.Collections.Generic; namespace UnityEngine.UI.Extensions { /// <summary> /// Infinite scroll view with automatic configuration /// /// Fields /// - InitByUSer - in case your scrollrect is populated from code, you can explicitly Initialize the infinite scroll after your scroll is ready /// by calling Init() method /// /// Notes /// - does not work in both vertical and horizontal orientation at the same time. /// - in order to work it disables layout components and size fitter if present(automatically) /// /// </summary> [AddComponentMenu("UI/Extensions/UI Infinite Scroll")] public class UI_InfiniteScroll : MonoBehaviour { //if true user will need to call Init() method manually (in case the contend of the scrollview is generated from code or requires special initialization) [Tooltip("If false, will Init automatically, otherwise you need to call Init() method")] public bool InitByUser = false; protected ScrollRect _scrollRect; private ContentSizeFitter _contentSizeFitter; private VerticalLayoutGroup _verticalLayoutGroup; private HorizontalLayoutGroup _horizontalLayoutGroup; private GridLayoutGroup _gridLayoutGroup; protected bool _isVertical = false; protected bool _isHorizontal = false; private float _disableMarginX = 0; private float _disableMarginY = 0; private bool _hasDisabledGridComponents = false; protected List<RectTransform> items = new List<RectTransform>(); private Vector2 _newAnchoredPosition = Vector2.zero; //TO DISABLE FLICKERING OBJECT WHEN SCROLL VIEW IS IDLE IN BETWEEN OBJECTS private float _threshold = 100f; private int _itemCount = 0; private float _recordOffsetX = 0; private float _recordOffsetY = 0; protected virtual void Awake() { if (!InitByUser) Init(); } public virtual void SetNewItems(ref List<Transform> newItems) { if (_scrollRect != null) { if (_scrollRect.content == null && newItems == null) { return; } if (items != null) { items.Clear(); } for (int i = _scrollRect.content.childCount - 1; i >= 0; i--) { Transform child = _scrollRect.content.GetChild(i); child.SetParent(null); GameObject.DestroyImmediate(child.gameObject); } foreach (Transform newItem in newItems) { newItem.SetParent(_scrollRect.content); } SetItems(); } } private void SetItems() { for (int i = 0; i < _scrollRect.content.childCount; i++) { items.Add(_scrollRect.content.GetChild(i).GetComponent<RectTransform>()); } _itemCount = _scrollRect.content.childCount; } public void Init() { if (GetComponent<ScrollRect>() != null) { _scrollRect = GetComponent<ScrollRect>(); _scrollRect.onValueChanged.AddListener(OnScroll); _scrollRect.movementType = ScrollRect.MovementType.Unrestricted; if (_scrollRect.content.GetComponent<VerticalLayoutGroup>() != null) { _verticalLayoutGroup = _scrollRect.content.GetComponent<VerticalLayoutGroup>(); } if (_scrollRect.content.GetComponent<HorizontalLayoutGroup>() != null) { _horizontalLayoutGroup = _scrollRect.content.GetComponent<HorizontalLayoutGroup>(); } if (_scrollRect.content.GetComponent<GridLayoutGroup>() != null) { _gridLayoutGroup = _scrollRect.content.GetComponent<GridLayoutGroup>(); } if (_scrollRect.content.GetComponent<ContentSizeFitter>() != null) { _contentSizeFitter = _scrollRect.content.GetComponent<ContentSizeFitter>(); } _isHorizontal = _scrollRect.horizontal; _isVertical = _scrollRect.vertical; if (_isHorizontal && _isVertical) { Debug.LogError("UI_InfiniteScroll doesn't support scrolling in both directions, please choose one direction (horizontal or vertical)"); } SetItems(); } else { Debug.LogError("UI_InfiniteScroll => No ScrollRect component found"); } } void DisableGridComponents() { if (_isVertical) { _recordOffsetY = items[1].GetComponent<RectTransform>().anchoredPosition.y - items[0].GetComponent<RectTransform>().anchoredPosition.y; if (_recordOffsetY < 0) { _recordOffsetY *= -1; } _disableMarginY = _recordOffsetY * _itemCount / 2; } if (_isHorizontal) { _recordOffsetX = items[1].GetComponent<RectTransform>().anchoredPosition.x - items[0].GetComponent<RectTransform>().anchoredPosition.x; if (_recordOffsetX < 0) { _recordOffsetX *= -1; } _disableMarginX = _recordOffsetX * _itemCount / 2; } if (_verticalLayoutGroup) { _verticalLayoutGroup.enabled = false; } if (_horizontalLayoutGroup) { _horizontalLayoutGroup.enabled = false; } if (_contentSizeFitter) { _contentSizeFitter.enabled = false; } if (_gridLayoutGroup) { _gridLayoutGroup.enabled = false; } _hasDisabledGridComponents = true; } public void OnScroll(Vector2 pos) { if (!_hasDisabledGridComponents) DisableGridComponents(); for (int i = 0; i < items.Count; i++) { if (_isHorizontal) { if (_scrollRect.transform.InverseTransformPoint(items[i].gameObject.transform.position).x > _disableMarginX + _threshold) { _newAnchoredPosition = items[i].anchoredPosition; _newAnchoredPosition.x -= _itemCount * _recordOffsetX; items[i].anchoredPosition = _newAnchoredPosition; _scrollRect.content.GetChild(_itemCount - 1).transform.SetAsFirstSibling(); } else if (_scrollRect.transform.InverseTransformPoint(items[i].gameObject.transform.position).x < -_disableMarginX) { _newAnchoredPosition = items[i].anchoredPosition; _newAnchoredPosition.x += _itemCount * _recordOffsetX; items[i].anchoredPosition = _newAnchoredPosition; _scrollRect.content.GetChild(0).transform.SetAsLastSibling(); } } if (_isVertical) { if (_scrollRect.transform.InverseTransformPoint(items[i].gameObject.transform.position).y > _disableMarginY + _threshold) { _newAnchoredPosition = items[i].anchoredPosition; _newAnchoredPosition.y -= _itemCount * _recordOffsetY; items[i].anchoredPosition = _newAnchoredPosition; _scrollRect.content.GetChild(_itemCount - 1).transform.SetAsFirstSibling(); } else if (_scrollRect.transform.InverseTransformPoint(items[i].gameObject.transform.position).y < -_disableMarginY) { _newAnchoredPosition = items[i].anchoredPosition; _newAnchoredPosition.y += _itemCount * _recordOffsetY; items[i].anchoredPosition = _newAnchoredPosition; _scrollRect.content.GetChild(0).transform.SetAsLastSibling(); } } } } } }
42.055046
260
0.558137
[ "MIT" ]
AustinDreak/Dieselpunk-Audio-Player
Assets/com.unity.uiextensions/Runtime/Scripts/Utilities/UI_InfiniteScroll.cs
9,170
C#
//////////////////////////////////////////////////////////////////////////////// // // @module Common Android Native Lib // @author Osipov Stanislav (Stan's Assets) // @support [email protected] // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System; using System.Collections; public class TwitterUserInfo { public event Action<Texture2D> ActionProfileImageLoaded = delegate{}; public event Action<Texture2D> ActionProfileBackgroundImageLoaded = delegate{}; private string _id; private string _description; private string _name; private string _screen_name; private string _location; private string _lang; private string _rawJSON; private string _profile_image_url; private string _profile_image_url_https; private string _profile_background_image_url; private string _profile_background_image_url_https; private Texture2D _profile_image = null; private Texture2D _profile_background = null; private Color _profile_background_color = Color.clear; private Color _profile_text_color = Color.clear; private int _friends_count; private int _statuses_count; private TwitterStatus _status; //-------------------------------------- // INITIALIZE //-------------------------------------- public TwitterUserInfo(string data) { _rawJSON = data; IDictionary JSON = ANMiniJSON.Json.Deserialize(_rawJSON) as IDictionary; _id = System.Convert.ToString(JSON["id"]); _name = System.Convert.ToString(JSON["name"]); _description = System.Convert.ToString(JSON["description"]); _screen_name = System.Convert.ToString(JSON["screen_name"]); _lang = System.Convert.ToString(JSON["lang"]); _location = System.Convert.ToString(JSON["location"]); _profile_image_url = System.Convert.ToString(JSON["profile_image_url"]); _profile_image_url_https = System.Convert.ToString(JSON["profile_image_url_https"]); _profile_background_image_url = System.Convert.ToString(JSON["profile_background_image_url"]); _profile_background_image_url_https = System.Convert.ToString(JSON["profile_background_image_url_https"]); _friends_count = System.Convert.ToInt32(JSON["friends_count"]); _statuses_count = System.Convert.ToInt32(JSON["statuses_count"]); _profile_text_color = HexToColor(System.Convert.ToString(JSON["profile_text_color"])); _profile_background_color = HexToColor(System.Convert.ToString(JSON["profile_background_color"])); _status = new TwitterStatus(JSON["status"] as IDictionary); } public TwitterUserInfo(IDictionary JSON) { _id = System.Convert.ToString(JSON["id"]); _name = System.Convert.ToString(JSON["name"]); _description = System.Convert.ToString(JSON["description"]); _screen_name = System.Convert.ToString(JSON["screen_name"]); _lang = System.Convert.ToString(JSON["lang"]); _location = System.Convert.ToString(JSON["location"]); _profile_image_url = System.Convert.ToString(JSON["profile_image_url"]); _profile_image_url_https = System.Convert.ToString(JSON["profile_image_url_https"]); _profile_background_image_url = System.Convert.ToString(JSON["profile_background_image_url"]); _profile_background_image_url_https = System.Convert.ToString(JSON["profile_background_image_url_https"]); _friends_count = System.Convert.ToInt32(JSON["friends_count"]); _statuses_count = System.Convert.ToInt32(JSON["statuses_count"]); _profile_text_color = HexToColor(System.Convert.ToString(JSON["profile_text_color"])); _profile_background_color = HexToColor(System.Convert.ToString(JSON["profile_background_color"])); } //-------------------------------------- // PUBLI METHODS //-------------------------------------- public void LoadProfileImage() { if(_profile_image != null) { ActionProfileImageLoaded(_profile_image); return; } SA.Common.Util.Loader.LoadWebTexture(_profile_image_url_https, OnProfileImageLoaded); } public void LoadBackgroundImage() { if(_profile_background != null) { ActionProfileBackgroundImageLoaded(_profile_background); return; } SA.Common.Util.Loader.LoadWebTexture(_profile_background_image_url_https, OnProfileBackgroundLoaded); } //-------------------------------------- // GET / SET //-------------------------------------- public string rawJSON { get { return _rawJSON; } } public string id { get { return _id; } } public string name { get { return _name; } } public string description { get { return _description; } } public string screen_name { get { return _screen_name; } } public string location { get { return _location; } } public string lang { get { return _lang; } } public string profile_image_url { get { return _profile_image_url; } } public string profile_image_url_https { get { return _profile_image_url_https; } } public string profile_background_image_url { get { return _profile_background_image_url; } } public string profile_background_image_url_https { get { return _profile_background_image_url_https; } } public int friends_count { get { return _friends_count; } } public int statuses_count { get { return _statuses_count; } } public TwitterStatus status { get { return _status; } } public Texture2D profile_image { get { return _profile_image; } } public Texture2D profile_background { get { return _profile_background; } } public Color profile_background_color { get { return _profile_background_color; } } public Color profile_text_color { get { return _profile_text_color; } } //-------------------------------------- // EVENTS //-------------------------------------- private void OnProfileImageLoaded(Texture2D img) { if(this == null) {return;} _profile_image = img; ActionProfileImageLoaded(_profile_image); } private void OnProfileBackgroundLoaded(Texture2D img) { if(this == null) {return;} _profile_background = img; ActionProfileBackgroundImageLoaded(_profile_background); } //-------------------------------------- // PRIVATE METHODS //-------------------------------------- private Color HexToColor(string hex) { byte r = byte.Parse(hex.Substring(0,2), System.Globalization.NumberStyles.HexNumber); byte g = byte.Parse(hex.Substring(2,2), System.Globalization.NumberStyles.HexNumber); byte b = byte.Parse(hex.Substring(4,2), System.Globalization.NumberStyles.HexNumber); return new Color32(r,g,b, 255); } }
22.205298
108
0.665225
[ "MIT" ]
KingOfFawns/Special_Course
Special Course/Assets/Plugins/StansAssets/Modules/AndroidNative/Scripts/Social/Twitter/Models/TwitterUserInfo.cs
6,706
C#
#region License // Copyright (c) Amos Voron. All rights reserved. // Licensed under the Apache 2.0 License. See LICENSE in the project root for license information. #endregion using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Reflection; using System.Diagnostics; using QueryTalk.Wall; namespace QueryTalk { /// <summary> /// Encapsulates the public static members of the QueryTalk's designer. /// </summary> public abstract partial class Designer : Chainer, INonPredecessor, IName { #region Internal Designer // creates new designer (safe) internal static NameChainer GetNewDesigner(string name = null) { return GetNewDesigner(name, false, true); } // creates new designer with arguments (safe) internal static NameChainer GetNewDesigner( string name, bool isEmbeddedTransaction, bool isEmbeddedTryCatch, Designer.IsolationLevel isolationLevel = IsolationLevel.Default) { var root = new InternalRoot(isEmbeddedTransaction); root.IsEmbeddedTryCatch = isEmbeddedTryCatch; root.Name = name; return new NameChainer(root, isolationLevel); } // gets the designer of this root (unsafe) // note: This designer is not safe because the root can be used only once. internal NameChainer GetDesigner() { return new NameChainer(this); } internal Designer.IsolationLevel EmbeddedTransactionIsolationLevel { get; set; } private bool _isUsed; internal bool IsUsed { get { return _isUsed; } } internal void SetAsUsed() { _isUsed = true; } #endregion #region Properties // compilable type // note: The CompilableType is set at the end of chaining! internal Nullable<Compilable.ObjectType> CompilableType { get; set; } // first query (for views) internal new Query Query { get { var node = Next; while (node != null) { if (node.IsQuery) { return node.Query; } node = node.Next; } return null; } } private string _rootName; /// <summary> /// A name of the QueryTalk object. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string Name { get { return _rootName; } internal set { _rootName = value ?? Wall.Text.NotAvailable; } } // root node internal DbNode Node { get; set; } internal void CheckNodeReuseAndThrow() { if (Node != null) { Node.CheckReuseAndThrow(); } } private bool _isEmbeddedTransaction = true; /// <summary> /// Indicates whether the procedure is wrapped by the transaction block. /// </summary> internal protected bool IsEmbeddedTransaction { get { return _isEmbeddedTransaction; } set { _isEmbeddedTransaction = value; } } private bool _isEmbeddedTryCatch = true; /// <summary> /// Indicates whether the procedure is wrapped by the try-catch block. /// </summary> internal protected bool IsEmbeddedTryCatch { get { return _isEmbeddedTryCatch; } set { _isEmbeddedTryCatch = value; } } internal ConnectionKey ConnectionKey { get; set; } #region Statements private List<Statement> _statements = new List<Statement>(); internal List<Statement> Statements { get { return _statements; } } // auto-incremental statement index private int _statementIndex = 0; internal int GetStatementIndex() { ++_statementIndex; // auto-increment return _statementIndex - 1; } #endregion #region Params // collection of all params (explicit+implicit) private List<Variable> _params = new List<Variable>(); internal List<Variable> AllParams { get { return _params; } } // collection of explicit params only internal List<Variable> ExplicitParams { get { return _params.Where(p => !p.IsParameterized).ToList(); } } // collection of optional params only internal List<Variable> OptionalParams { get { return _params.Where(p => p.IsOptional).ToList(); } } // collection of implicit params only internal List<Variable> ImplicitParams { get { return _params.Where(p => p.IsParameterized).ToList(); } } // is object parameterized internal bool HasParams { get { return _params.Count > 0; } } // returns true if argumentsCount is valid (considering the optional arguments) internal bool ParamCountCheck(int argumentsCount) { return (argumentsCount <= ExplicitParams.Count) && (argumentsCount + OptionalParams.Count >= ExplicitParams.Count); } // general lookup method for checking the param existence internal bool ParamExists(string param) { return _params.Where(p => p.Name.EqualsCS(param)).Any(); } // The central method for adding the params. internal void TryAddParamOrThrow(Variable param, bool isAuto) { // check variable format (only if given by user) if (!isAuto) { Variable.CheckNameFormat(param.Name, out chainException); TryThrow(Wall.Text.Method.Param); } if (ParamExists(param.Name)) { Throw(QueryTalkExceptionType.ParamOrVariableAlreadyDeclared, String.Format("param = {0}", param.Name), Wall.Text.Method.Param); } // check size declaration if (param.DT.IsDataType()) { var info = Mapping.SqlMapping[param.DT]; if ((info.SizeType == Mapping.SizeType.None && param.DataType.Length + param.DataType.Precision + param.DataType.Scale > 0) || (info.SizeType == Mapping.SizeType.Length && param.DataType.Precision + param.DataType.Scale > 0) || (info.SizeType == Mapping.SizeType.Precision && param.DataType.Length > 0)) { Throw(QueryTalkExceptionType.InvalidDbTypeDeclaration, String.Format("param = {0}{1} " + "db type = {2}{3} " + "length = {4}{5} " + "precision = {6}{7} " + "scale = {8}", param.Name, Environment.NewLine, info.SqlPlain, Environment.NewLine, param.DataType.Length, Environment.NewLine, param.DataType.Precision, Environment.NewLine, param.DataType.Scale), Wall.Text.Method.Pass); } // check size components if (param.DataType.Scale > param.DataType.Precision || param.DataType.Length < 0 || param.DataType.Precision < 0 || param.DataType.Scale < 0) { Throw(QueryTalkExceptionType.InvalidDbTypeDeclaration, String.Format("param = {0}{1} " + "db type = {2}{3} " + "length = {4}{5} " + "precision = {6}{7} " + "scale = {8}", param.Name, Environment.NewLine, info.SqlPlain, Environment.NewLine, param.DataType.Length, Environment.NewLine, param.DataType.Precision, Environment.NewLine, param.DataType.Scale), Wall.Text.Method.Pass); } } _params.Add(param); // add non-inline param to the variable collection if (param.DT.IsNotInliner()) { TryAddVariableOrThrow(param, Wall.Text.Method.ParamOrTableParam, isAuto, false); } } #endregion #region Variables // collection of names of the parameters and variables together private List<Variable> _variables = new List<Variable>(); internal List<Variable> Variables { get { return _variables; } } // attention: // If root object is accessed through the BuildContext object, use buildContext.TryGetVariable method instead. internal Variable TryGetVariable( string variableName, out QueryTalkException exception, Variable.SearchType searchType = Variable.SearchType.Any) { exception = null; if (variableName == null) { exception = Variable.InvalidVariableException(variableName, QueryTalkExceptionType.ArgumentNull); return null; } Variable param; Variable variable; // try get param param = AllParams.Where(p => p.Name.EqualsCS(variableName)) .FirstOrDefault(); // try get non-param variable = _variables.Where(v => v.Name.EqualsCS(variableName)) .FirstOrDefault(); if (searchType == Variable.SearchType.Any) { return param ?? variable; } if (searchType == Variable.SearchType.Inliner && (param == null || param.DT.IsNotInliner())) { exception = Variable.InvalidVariableException(variableName, QueryTalkExceptionType.InlinerNotFound); return null; } // param/variable should exists if (searchType != Variable.SearchType.Any && (param == null && variable == null)) { exception = Variable.InvalidVariableException(variableName, QueryTalkExceptionType.ParamOrVariableNotDeclared); return null; } return param ?? variable; } // general lookup method for checking the variable existence // returns: // true : it exists // false: not exists // null : check not needed (it is a snippet) internal Nullable<bool> VariableExists(string variable) { // do not check the snippet neither the view if (CompilableType.IsViewOrSnippet()) { return null; } return _variables.Where(v => v.Name.EqualsCS(variable)).Any(); } // add method that throws exception if variable/param already exists internal void TryAddVariableOrThrow(Variable variable, string method, bool isAuto, bool checkParams = true) // if false then the variable is not checked in the params collection // (in case when already added param is to be added to the variable collection as well) { // check variable format if (!isAuto) { Variable.CheckNameFormat(variable.Name, out chainException); TryThrow(method); } // check variable in param collection if (checkParams) { if (ParamExists(variable.Name)) { Throw(QueryTalkExceptionType.ParamOrVariableAlreadyDeclared, String.Format("{0} = {1}", Wall.Text.Free.Variable, variable.Name), method); } } // check variable in variable collection if (VariableExists(variable.Name) == true) { Throw(QueryTalkExceptionType.ParamOrVariableAlreadyDeclared, String.Format("{0} = {1}", Wall.Text.Free.Variable, variable.Name), method); } _variables.Add(variable); } // return true if an argument exists as a param or variable internal Nullable<bool> ParamOrVariableExists(string paramOrVariable) { // do not check the snippet if (CompilableType.IsViewOrSnippet()) { return null; } // check params bool exists = ParamExists(paramOrVariable); if (exists) { return true; } // check variables exists = VariableExists(paramOrVariable) == true; if (exists) { return true; } // neither param nor variable return false; } // copy variables from snippet's root internal void TakeVariables(Snippet snippet) { foreach (var variable in snippet.GetRoot().Variables) { TryAddVariableOrThrow(variable, QueryTalk.Wall.Text.Method.Inject, false); } } #endregion #region Labels // collection of labels private List<string> _labels = new List<string>(); // add method that throws exception if label already exists internal void TryAddLabelOrThrow(string label) { if (_labels.Contains(label.ToUpperCS())) { Throw(QueryTalkExceptionType.LabelAlreadyDeclared, ArgVal(() => label, label), ".Label"); } _labels.Add(label.ToUpperCS()); } #endregion #region Temp tables // collection of temp tables private List<string> _tempTables = new List<string>(); internal void TryAddTempTable(string tempTable) { if (!_tempTables.Contains(tempTable.ToUpperCS())) { _tempTables.Add(tempTable.ToUpperCS()); } } // general lookup method for checking temp table existence internal bool TempTableExists(string table, bool remove = false) { var exists = _tempTables.Where(tt => tt.EqualsCS(table)).Any(); if (exists && remove) { _tempTables.Remove(table.ToUpperCS()); } return exists; } #endregion // auto-incremental 1-based variable index private long _variableIndex = 0; // variable index provider method internal long GetVariableIndex() { return ++_variableIndex; } // variable unique index based on System.Guid // To avoid collisions when the data views are passed directly to the stored proc or function inside the .Exec method. internal static long GetVariableGuid() { return Math.Abs(BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0)); } // auto-incremental 1-based column index private int _colIndex = 0; internal int ColIndex { get { return ++_colIndex; } } internal int IfCounter { get; set; } internal int WhileCounter { get; set; } internal int TryCatchCounter { get; set; } internal int CursorCounter { get; set; } internal int TranCounter { get; set; } private int _uniqueIndex = 0; internal int GetUniqueIndex() { return ++_uniqueIndex; } #endregion #region Constructor /// <summary> /// This constructor is not intended for public use. /// </summary> protected Designer() : base(null) { } #endregion #region ClearForReuse // prepare root for reuse (for Testing Environment only) internal void ClearForReuse() { Statements.Clear(); _isUsed = false; _params.Clear(); _variables.Clear(); _labels.Clear(); _tempTables.Clear(); _statementIndex = 0; _uniqueIndex = 0; _colIndex = 0; _variableIndex = 0; TranCounter = 0; CursorCounter = 0; TryCatchCounter = 0; WhileCounter = 0; IfCounter = 0; } #endregion #region Helper methods private static void Call(Assembly callingAssembly, Action<Assembly> method) { try { method(callingAssembly); } catch (QueryTalkException) { throw; } catch (System.Exception ex) { if (ex.InnerException is QueryTalkException) { var ex2 = (QueryTalkException)ex; if (ex2.ClrException != null) { throw ex2.ClrException; } throw ex.InnerException; } throw; } } private static T Call<T>(Assembly callingAssembly, Func<Assembly, T> method) { try { return method(callingAssembly); } catch (QueryTalkException) { throw; } catch (System.Exception ex) { if (ex.InnerException is QueryTalkException) { var ex2 = (QueryTalkException)ex; if (ex2.ClrException != null) { throw ex2.ClrException; } throw ex.InnerException; } throw; } } private static T[] MergeArrays<T>(T firstColumn, IEnumerable<T> otherColumns) { T[] merged = new T[otherColumns.Count() + 1]; merged[0] = firstColumn; otherColumns.ToArray<T>().CopyTo(merged, 1); return merged; } private static void _Throw(QueryTalkExceptionType exceptionType, string arguments, string method) { throw new QueryTalkException("d.Throw", exceptionType, arguments, method); } #endregion #region Hidden base methods /// <summary> /// Not intended for public use. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object objA, object objB) { throw new System.NotImplementedException("Equals method of QueryTalk.Wall.Designer type is not allowed."); } /// <summary> /// Not intended for public use. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool ReferenceEquals(object objA, object objB) { throw new System.NotImplementedException("ReferenceEquals method of QueryTalk.Wall.Designer type is not allowed."); } #endregion #region ToString /// <summary> /// Returns the string representation of this instance. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return String.Format("Designer ({0})", Name); } #endregion } }
30.764359
157
0.508832
[ "MIT" ]
amosvoron/QueryTalk
lib/designer/Constructor.cs
20,891
C#
using System; using System.Collections.Generic; using NUnit.Framework; namespace addressbook_tests_autoit { [TestFixture] public class GroupCreationTests : TestBase { [Test] public void TestGroupCreation() { List<GroupData> oldGroups = app.Groups.GetGroupList(); GroupData newGroup = new GroupData() { Name = "test" }; app.Groups.Add(newGroup); List<GroupData> newGroups = app.Groups.GetGroupList(); oldGroups.Add(newGroup); oldGroups.Sort(); newGroups.Sort(); Assert.AreEqual(oldGroups, newGroups); } } }
21.818182
66
0.544444
[ "Apache-2.0" ]
hatshepsutb/csharp_training
addressbook_tests_autoit/addressbook_tests_autoit/tests/GroupCreationTests.cs
722
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 iotwireless-2020-11-22.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.IoTWireless.Model { /// <summary> /// LoRaWAN object for list functions. /// </summary> public partial class LoRaWANListDevice { private string _devEui; /// <summary> /// Gets and sets the property DevEui. /// <para> /// The DevEUI value. /// </para> /// </summary> public string DevEui { get { return this._devEui; } set { this._devEui = value; } } // Check to see if DevEui property is set internal bool IsSetDevEui() { return this._devEui != null; } } }
27.894737
110
0.619497
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/Model/LoRaWANListDevice.cs
1,590
C#
namespace KitchenPC.DB.Models { using System; using FluentNHibernate.Mapping; public class QueuedRecipesMap : ClassMap<QueuedRecipes> { public QueuedRecipesMap() { this.Id(x => x.QueueId) .GeneratedBy.GuidComb() .UnsavedValue(Guid.Empty); this.Map(x => x.UserId).Not.Nullable().Index("IDX_QueuedRecipes_UserId").UniqueKey("UniqueRecipe"); this.Map(x => x.QueuedDate).Not.Nullable(); this.References(x => x.Recipe).Not.Nullable().UniqueKey("UniqueRecipe"); } } }
29.047619
112
0.57377
[ "MIT" ]
Derneuca/KitchenPCTeamwork
KitchenPC/DB/Models/QueuedRecipesMap.cs
612
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace DotNet.VersionSweeper; public enum ActionType { CreateIssue, PullRequest, DryRun }
21.333333
72
0.710938
[ "MIT" ]
dotnet/versionsweeper
src/DotNet.VersionSweeper/ActionType.cs
258
C#
using System; namespace PerformanceEf3.EFCore.Models { public partial class ProductReview { public int ProductReviewID { get; set; } public int ProductID { get; set; } public string ReviewerName { get; set; } public DateTime ReviewDate { get; set; } public string EmailAddress { get; set; } public int Rating { get; set; } public string Comments { get; set; } public DateTime ModifiedDate { get; set; } public virtual Product Product { get; set; } } }
28.368421
52
0.617811
[ "BSD-3-Clause" ]
VDSnuff/presentations
DOTNETCORE/EFCoreSamples/01_PerformanceEF3/EFCore/Models/ProductReview.cs
541
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.MultiTenancy; using maarif.myproject.Authorization; using maarif.myproject.Authorization.Roles; using maarif.myproject.Authorization.Users; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace maarif.myproject.EntityFrameworkCore.Seed.Host { public class HostRoleAndUserCreator { private readonly myprojectDbContext _context; public HostRoleAndUserCreator(myprojectDbContext context) { _context = context; } public void Create() { CreateHostRoleAndUsers(); } private void CreateHostRoleAndUsers() { // Admin role for host var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin); if (adminRoleForHost == null) { adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin) { IsStatic = true, IsDefault = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role for host var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType<RolePermissionSetting>() .Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new myprojectAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = null, Name = permission.Name, IsGranted = true, RoleId = adminRoleForHost.Id }) ); _context.SaveChanges(); } // Admin user for host var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName); if (adminUserForHost == null) { var user = new User { TenantId = null, UserName = AbpUserBase.AdminUserName, Name = "admin", Surname = "admin", EmailAddress = "[email protected]", IsEmailConfirmed = true, IsActive = true }; user.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe"); user.SetNormalizedNames(); adminUserForHost = _context.Users.Add(user).Entity; _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id)); _context.SaveChanges(); _context.SaveChanges(); } } } }
36.252525
171
0.56506
[ "MIT" ]
eminekiricii/maarifProject
aspnet-core/src/maarif.myproject.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/HostRoleAndUserCreator.cs
3,589
C#
namespace DataFlow.EdFi.Models.Resources { public class StudentDisciplineIncidentAssociationBehavior { /// <summary> /// A unique identifier used as Primary Key, not derived from business logic, when acting as Foreign Key, references the parent table. /// </summary> public string behaviorDescriptor { get; set; } /// <summary> /// Specifies a more granular level of detail of a behavior involved in the incident. /// </summary> public string behaviorDetailedDescription { get; set; } } }
31.888889
142
0.649826
[ "Apache-2.0" ]
schoolstacks/dataflow
DataFlow.EdFi/Models/Resources/StudentDisciplineIncidentAssociationBehavior.cs
574
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; internal static partial class Interop { internal static partial class User32 { public static class OBJID { public const int WINDOW = 0x00000000; public const int NATIVEOM = unchecked((int)0xFFFFFFF0); public const int QUERYCLASSNAMEIDX = unchecked((int)0xFFFFFFF4); public const int SOUND = unchecked((int)0xFFFFFFF5); public const int ALERT = unchecked((int)0xFFFFFFF6); public const int CURSOR = unchecked((int)0xFFFFFFF7); public const int CARET = unchecked((int)0xFFFFFFF8); public const int SIZEGRIP = unchecked((int)0xFFFFFFF9); public const int HSCROLL = unchecked((int)0xFFFFFFFA); public const int VSCROLL = unchecked((int)0xFFFFFFFB); public const int CLIENT = unchecked((int)0xFFFFFFFC); public const int MENU = unchecked((int)0xFFFFFFFD); public const int TITLEBAR = unchecked((int)0xFFFFFFFE); public const int SYSMENU = unchecked((int)0xFFFFFFFF); } } }
43.066667
76
0.654025
[ "MIT" ]
AArnott/winforms
src/System.Windows.Forms.Primitives/src/Interop/User32/Interop.OBJID.cs
1,294
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; #if SUPPORT_JIT using Internal.Runtime.CompilerServices; #endif using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.CorConstants; using ILCompiler; using ILCompiler.DependencyAnalysis; #if READYTORUN using System.Reflection.Metadata.Ecma335; using ILCompiler.DependencyAnalysis.ReadyToRun; #endif namespace Internal.JitInterface { internal unsafe sealed partial class CorInfoImpl { // // Global initialization and state // private enum ImageFileMachine { I386 = 0x014c, IA64 = 0x0200, AMD64 = 0x8664, ARM = 0x01c4, ARM64 = 0xaa64, } internal const string JitLibrary = "clrjitilc"; #if SUPPORT_JIT private const string JitSupportLibrary = "*"; #else private const string JitSupportLibrary = "jitinterface"; #endif private IntPtr _jit; private IntPtr _unmanagedCallbacks; // array of pointers to JIT-EE interface callbacks private Object _keepAlive; // Keeps delegates for the callbacks alive private ExceptionDispatchInfo _lastException; [DllImport(JitLibrary, CallingConvention=CallingConvention.StdCall)] // stdcall in CoreCLR! private extern static IntPtr jitStartup(IntPtr host); [DllImport(JitLibrary, CallingConvention=CallingConvention.StdCall)] private extern static IntPtr getJit(); [DllImport(JitSupportLibrary)] private extern static IntPtr GetJitHost(IntPtr configProvider); // // Per-method initialization and state // private static CorInfoImpl GetThis(IntPtr thisHandle) { CorInfoImpl _this = Unsafe.Read<CorInfoImpl>((void*)thisHandle); Debug.Assert(_this is CorInfoImpl); return _this; } [DllImport(JitSupportLibrary)] private extern static CorJitResult JitCompileMethod(out IntPtr exception, IntPtr jit, IntPtr thisHandle, IntPtr callbacks, ref CORINFO_METHOD_INFO info, uint flags, out IntPtr nativeEntry, out uint codeSize); [DllImport(JitSupportLibrary)] private extern static uint GetMaxIntrinsicSIMDVectorLength(IntPtr jit, CORJIT_FLAGS* flags); [DllImport(JitSupportLibrary)] private extern static IntPtr AllocException([MarshalAs(UnmanagedType.LPWStr)]string message, int messageLength); private IntPtr AllocException(Exception ex) { _lastException = ExceptionDispatchInfo.Capture(ex); string exString = ex.ToString(); IntPtr nativeException = AllocException(exString, exString.Length); if (_nativeExceptions == null) { _nativeExceptions = new List<IntPtr>(); } _nativeExceptions.Add(nativeException); return nativeException; } [DllImport(JitSupportLibrary)] private extern static void FreeException(IntPtr obj); [DllImport(JitSupportLibrary)] private extern static char* GetExceptionMessage(IntPtr obj); private readonly UnboxingMethodDescFactory _unboxingThunkFactory; public static void Startup() { jitStartup(GetJitHost(JitConfigProvider.Instance.UnmanagedInstance)); } public CorInfoImpl() { _jit = getJit(); if (_jit == IntPtr.Zero) { throw new IOException("Failed to initialize JIT"); } _unmanagedCallbacks = GetUnmanagedCallbacks(out _keepAlive); _unboxingThunkFactory = new UnboxingMethodDescFactory(); } public TextWriter Log { get { return _compilation.Logger.Writer; } } private CORINFO_MODULE_STRUCT_* _methodScope; // Needed to resolve CORINFO_EH_CLAUSE tokens private bool _isFallbackBodyCompilation; // True if we're compiling a fallback method body after compiling the real body failed private void CompileMethodInternal(IMethodNode methodCodeNodeNeedingCode, MethodIL methodIL = null) { _isFallbackBodyCompilation = methodIL != null; CORINFO_METHOD_INFO methodInfo; methodIL = Get_CORINFO_METHOD_INFO(MethodBeingCompiled, methodIL, &methodInfo); // This is e.g. an "extern" method in C# without a DllImport or InternalCall. if (methodIL == null) { ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, MethodBeingCompiled); } _methodScope = methodInfo.scope; #if !READYTORUN SetDebugInformation(methodCodeNodeNeedingCode, methodIL); #endif CorInfoImpl _this = this; IntPtr exception; IntPtr nativeEntry; uint codeSize; var result = JitCompileMethod(out exception, _jit, (IntPtr)Unsafe.AsPointer(ref _this), _unmanagedCallbacks, ref methodInfo, (uint)CorJitFlag.CORJIT_FLAG_CALL_GETJITFLAGS, out nativeEntry, out codeSize); if (exception != IntPtr.Zero) { if (_lastException != null) { // If we captured a managed exception, rethrow that. // TODO: might not actually be the real reason. It could be e.g. a JIT failure/bad IL that followed // an inlining attempt with a type system problem in it... #if SUPPORT_JIT _lastException.Throw(); #else if (_lastException.SourceException is TypeSystemException) { // Type system exceptions can be turned into code that throws the exception at runtime. _lastException.Throw(); } #if READYTORUN else if (_lastException.SourceException is RequiresRuntimeJitException) { // Runtime JIT requirement is not a cause for failure, we just mustn't JIT a particular method _lastException.Throw(); } #endif else { // This is just a bug somewhere. throw new CodeGenerationFailedException(_methodCodeNode.Method, _lastException.SourceException); } #endif } // This is a failure we don't know much about. char* szMessage = GetExceptionMessage(exception); string message = szMessage != null ? new string(szMessage) : "JIT Exception"; throw new Exception(message); } if (result == CorJitResult.CORJIT_BADCODE) { ThrowHelper.ThrowInvalidProgramException(); } if (result != CorJitResult.CORJIT_OK) { #if SUPPORT_JIT // FailFast? throw new Exception("JIT failed"); #else throw new CodeGenerationFailedException(_methodCodeNode.Method); #endif } PublishCode(); } private void PublishCode() { var relocs = _relocs.ToArray(); Array.Sort(relocs, (x, y) => (x.Offset - y.Offset)); int alignment = JitConfigProvider.Instance.HasFlag(CorJitFlag.CORJIT_FLAG_SIZE_OPT) ? _compilation.NodeFactory.Target.MinimumFunctionAlignment : _compilation.NodeFactory.Target.OptimumFunctionAlignment; var objectData = new ObjectNode.ObjectData(_code, relocs, alignment, new ISymbolDefinitionNode[] { _methodCodeNode }); ObjectNode.ObjectData ehInfo = _ehClauses != null ? EncodeEHInfo() : null; DebugEHClauseInfo[] debugEHClauseInfos = null; if (_ehClauses != null) { debugEHClauseInfos = new DebugEHClauseInfo[_ehClauses.Length]; for (int i = 0; i < _ehClauses.Length; i++) { var clause = _ehClauses[i]; debugEHClauseInfos[i] = new DebugEHClauseInfo(clause.TryOffset, clause.TryLength, clause.HandlerOffset, clause.HandlerLength); } } _methodCodeNode.SetCode(objectData #if !SUPPORT_JIT && !READYTORUN , isFoldable: (_compilation._compilationOptions & RyuJitCompilationOptions.MethodBodyFolding) != 0 #endif ); _methodCodeNode.InitializeFrameInfos(_frameInfos); _methodCodeNode.InitializeDebugEHClauseInfos(debugEHClauseInfos); _methodCodeNode.InitializeGCInfo(_gcInfo); _methodCodeNode.InitializeEHInfo(ehInfo); _methodCodeNode.InitializeDebugLocInfos(_debugLocInfos); _methodCodeNode.InitializeDebugVarInfos(_debugVarInfos); #if READYTORUN _methodCodeNode.InitializeInliningInfo(_inlinedMethods.ToArray()); #endif PublishProfileData(); } partial void PublishProfileData(); private MethodDesc MethodBeingCompiled { get { return _methodCodeNode.Method; } } private int PointerSize { get { return _compilation.TypeSystemContext.Target.PointerSize; } } private Dictionary<Object, GCHandle> _pins = new Dictionary<object, GCHandle>(); private IntPtr GetPin(Object obj) { GCHandle handle; if (!_pins.TryGetValue(obj, out handle)) { handle = GCHandle.Alloc(obj, GCHandleType.Pinned); _pins.Add(obj, handle); } return handle.AddrOfPinnedObject(); } private List<IntPtr> _nativeExceptions; private void CompileMethodCleanup() { foreach (var pin in _pins) pin.Value.Free(); _pins.Clear(); if (_nativeExceptions != null) { foreach (IntPtr ex in _nativeExceptions) FreeException(ex); _nativeExceptions = null; } _methodCodeNode = null; _code = null; _coldCode = null; _roData = null; _roDataBlob = null; _relocs = new ArrayBuilder<Relocation>(); _numFrameInfos = 0; _usedFrameInfos = 0; _frameInfos = null; _gcInfo = null; _ehClauses = null; #if !READYTORUN _sequencePoints = null; _variableToTypeDesc = null; _parameterIndexToNameMap = null; _localSlotToInfoMap = null; #endif _debugLocInfos = null; _debugVarInfos = null; _lastException = null; #if READYTORUN _profileDataNode = null; _inlinedMethods = new ArrayBuilder<MethodDesc>(); #endif } private Dictionary<Object, IntPtr> _objectToHandle = new Dictionary<Object, IntPtr>(); private List<Object> _handleToObject = new List<Object>(); private const int handleMultipler = 8; private const int handleBase = 0x420000; private IntPtr ObjectToHandle(Object obj) { IntPtr handle; if (!_objectToHandle.TryGetValue(obj, out handle)) { handle = (IntPtr)(handleMultipler * _handleToObject.Count + handleBase); _handleToObject.Add(obj); _objectToHandle.Add(obj, handle); } return handle; } private Object HandleToObject(IntPtr handle) { int index = ((int)handle - handleBase) / handleMultipler; return _handleToObject[index]; } private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) { return (MethodDesc)HandleToObject((IntPtr)method); } private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) { return (CORINFO_METHOD_STRUCT_*)ObjectToHandle((Object)method); } private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) { return (TypeDesc)HandleToObject((IntPtr)type); } private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) { return (CORINFO_CLASS_STRUCT_*)ObjectToHandle((Object)type); } private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) { return (FieldDesc)HandleToObject((IntPtr)field); } private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) { return (CORINFO_FIELD_STRUCT_*)ObjectToHandle((Object)field); } private MethodIL Get_CORINFO_METHOD_INFO(MethodDesc method, MethodIL methodIL, CORINFO_METHOD_INFO* methodInfo) { // MethodIL can be provided externally for the case of a method whose IL was replaced because we couldn't compile it. if (methodIL == null) methodIL = _compilation.GetMethodIL(method); if (methodIL == null) { *methodInfo = default(CORINFO_METHOD_INFO); return null; } methodInfo->ftn = ObjectToHandle(method); methodInfo->scope = (CORINFO_MODULE_STRUCT_*)ObjectToHandle(methodIL); var ilCode = methodIL.GetILBytes(); methodInfo->ILCode = (byte*)GetPin(ilCode); methodInfo->ILCodeSize = (uint)ilCode.Length; methodInfo->maxStack = (uint)methodIL.MaxStack; methodInfo->EHcount = (uint)methodIL.GetExceptionRegions().Length; methodInfo->options = methodIL.IsInitLocals ? CorInfoOptions.CORINFO_OPT_INIT_LOCALS : (CorInfoOptions)0; if (method.AcquiresInstMethodTableFromThis()) { methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_THIS; } else if (method.RequiresInstMethodDescArg()) { methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODDESC; } else if (method.RequiresInstMethodTableArg()) { methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODTABLE; } methodInfo->regionKind = CorInfoRegionKind.CORINFO_REGION_NONE; Get_CORINFO_SIG_INFO(method, &methodInfo->args); Get_CORINFO_SIG_INFO(methodIL.GetLocals(), &methodInfo->locals); return methodIL; } private void Get_CORINFO_SIG_INFO(MethodDesc method, CORINFO_SIG_INFO* sig, bool suppressHiddenArgument = false) { Get_CORINFO_SIG_INFO(method.Signature, sig); if (method.IsPInvoke && method.IsSuppressGCTransition()) { sig->flags |= CorInfoSigInfoFlags.CORINFO_SIGFLAG_SUPPRESS_GC_TRANSITION; } // Does the method have a hidden parameter? bool hasHiddenParameter = !suppressHiddenArgument && method.RequiresInstArg(); if (method.IsIntrinsic) { // Some intrinsics will beg to differ about the hasHiddenParameter decision #if !READYTORUN if (_compilation.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method)) hasHiddenParameter = false; #endif if (method.IsArrayAddressMethod()) hasHiddenParameter = true; // We only populate sigInst for intrinsic methods because most of the time, // JIT doesn't care what the instantiation is and this is expensive. Instantiation owningTypeInst = method.OwningType.Instantiation; sig->sigInst.classInstCount = (uint)owningTypeInst.Length; if (owningTypeInst.Length > 0) { var classInst = new IntPtr[owningTypeInst.Length]; for (int i = 0; i < owningTypeInst.Length; i++) classInst[i] = (IntPtr)ObjectToHandle(owningTypeInst[i]); sig->sigInst.classInst = (CORINFO_CLASS_STRUCT_**)GetPin(classInst); } } if (hasHiddenParameter) { sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE; } } private void Get_CORINFO_SIG_INFO(MethodSignature signature, CORINFO_SIG_INFO* sig) { sig->callConv = (CorInfoCallConv)(signature.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask); // Varargs are not supported in .NET Core if (sig->callConv == CorInfoCallConv.CORINFO_CALLCONV_VARARG) ThrowHelper.ThrowBadImageFormatException(); if (!signature.IsStatic) sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_HASTHIS; TypeDesc returnType = signature.ReturnType; CorInfoType corInfoRetType = asCorInfoType(signature.ReturnType, &sig->retTypeClass); sig->_retType = (byte)corInfoRetType; sig->retTypeSigClass = ObjectToHandle(signature.ReturnType); sig->flags = 0; // used by IL stubs code sig->numArgs = (ushort)signature.Length; sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index sig->sigInst.classInst = null; // Not used by the JIT sig->sigInst.classInstCount = 0; // Not used by the JIT sig->sigInst.methInst = null; // Not used by the JIT sig->sigInst.methInstCount = (uint)signature.GenericParameterCount; sig->pSig = (byte*)ObjectToHandle(signature); sig->cbSig = 0; // Not used by the JIT sig->scope = null; // Not used by the JIT sig->token = 0; // Not used by the JIT } private void Get_CORINFO_SIG_INFO(LocalVariableDefinition[] locals, CORINFO_SIG_INFO* sig) { sig->callConv = CorInfoCallConv.CORINFO_CALLCONV_DEFAULT; sig->_retType = (byte)CorInfoType.CORINFO_TYPE_VOID; sig->retTypeClass = null; sig->retTypeSigClass = null; sig->flags = CorInfoSigInfoFlags.CORINFO_SIGFLAG_IS_LOCAL_SIG; sig->numArgs = (ushort)locals.Length; sig->sigInst.classInst = null; sig->sigInst.classInstCount = 0; sig->sigInst.methInst = null; sig->sigInst.methInstCount = 0; sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index sig->pSig = (byte*)ObjectToHandle(locals); sig->cbSig = 0; // Not used by the JIT sig->scope = null; // Not used by the JIT sig->token = 0; // Not used by the JIT } private CorInfoType asCorInfoType(TypeDesc type) { if (type.IsEnum) { type = type.UnderlyingType; } if (type.IsPrimitive) { Debug.Assert((CorInfoType)TypeFlags.Void == CorInfoType.CORINFO_TYPE_VOID); Debug.Assert((CorInfoType)TypeFlags.Double == CorInfoType.CORINFO_TYPE_DOUBLE); return (CorInfoType)type.Category; } if (type.IsPointer || type.IsFunctionPointer) { return CorInfoType.CORINFO_TYPE_PTR; } if (type.IsByRef) { return CorInfoType.CORINFO_TYPE_BYREF; } if (type.IsValueType) { return CorInfoType.CORINFO_TYPE_VALUECLASS; } return CorInfoType.CORINFO_TYPE_CLASS; } private CorInfoType asCorInfoType(TypeDesc type, CORINFO_CLASS_STRUCT_** structType) { var corInfoType = asCorInfoType(type); *structType = ((corInfoType == CorInfoType.CORINFO_TYPE_CLASS) || (corInfoType == CorInfoType.CORINFO_TYPE_VALUECLASS) || (corInfoType == CorInfoType.CORINFO_TYPE_BYREF)) ? ObjectToHandle(type) : null; return corInfoType; } private CORINFO_CONTEXT_STRUCT* contextFromMethod(MethodDesc method) { return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(method)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD); } private CORINFO_CONTEXT_STRUCT* contextFromType(TypeDesc type) { return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(type)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS); } private MethodDesc methodFromContext(CORINFO_CONTEXT_STRUCT* contextStruct) { if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS) { return null; } else { return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)); } } private TypeDesc typeFromContext(CORINFO_CONTEXT_STRUCT* contextStruct) { if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS) { return HandleToObject((CORINFO_CLASS_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)); } else { return methodFromContext(contextStruct).OwningType; } } private TypeSystemEntity entityFromContext(CORINFO_CONTEXT_STRUCT* contextStruct) { return (TypeSystemEntity)HandleToObject((IntPtr)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)); } private uint getMethodAttribsInternal(MethodDesc method) { CorInfoFlag result = 0; // CORINFO_FLG_PROTECTED - verification only if (method.Signature.IsStatic) result |= CorInfoFlag.CORINFO_FLG_STATIC; if (method.IsSynchronized) result |= CorInfoFlag.CORINFO_FLG_SYNCH; if (method.IsIntrinsic) result |= CorInfoFlag.CORINFO_FLG_INTRINSIC | CorInfoFlag.CORINFO_FLG_JIT_INTRINSIC; if (method.IsVirtual) result |= CorInfoFlag.CORINFO_FLG_VIRTUAL; if (method.IsAbstract) result |= CorInfoFlag.CORINFO_FLG_ABSTRACT; if (method.IsConstructor || method.IsStaticConstructor) result |= CorInfoFlag.CORINFO_FLG_CONSTRUCTOR; // // See if we need to embed a .cctor call at the head of the // method body. // // method or class might have the final bit if (_compilation.IsEffectivelySealed(method)) result |= CorInfoFlag.CORINFO_FLG_FINAL; if (method.IsSharedByGenericInstantiations) result |= CorInfoFlag.CORINFO_FLG_SHAREDINST; if (method.IsPInvoke) result |= CorInfoFlag.CORINFO_FLG_PINVOKE; #if READYTORUN if (method.RequireSecObject) { result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE_CALLER; } #endif if (method.IsAggressiveOptimization) { result |= CorInfoFlag.CORINFO_FLG_AGGRESSIVE_OPT; } // TODO: Cache inlining hits // Check for an inlining directive. if (method.IsNoInlining) { /* Function marked as not inlineable */ result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE; } else if (method.IsAggressiveInlining) { result |= CorInfoFlag.CORINFO_FLG_FORCEINLINE; } if (method.OwningType.IsDelegate && method.Name == "Invoke") { // This is now used to emit efficient invoke code for any delegate invoke, // including multicast. result |= CorInfoFlag.CORINFO_FLG_DELEGATE_INVOKE; // RyuJIT special cases this method; it would assert if it's not final // and we might not have set the bit in the code above. result |= CorInfoFlag.CORINFO_FLG_FINAL; } #if READYTORUN // Check for SIMD intrinsics DefType owningDefType = method.OwningType as DefType; if (owningDefType != null && VectorOfTFieldLayoutAlgorithm.IsVectorOfTType(owningDefType)) { throw new RequiresRuntimeJitException("This function is using SIMD intrinsics, their size is machine specific"); } #endif // Check for hardware intrinsics if (HardwareIntrinsicHelpers.IsHardwareIntrinsic(method)) { #if READYTORUN if (!isMethodDefinedInCoreLib()) { throw new RequiresRuntimeJitException("This function is not defined in CoreLib and it is using hardware intrinsics."); } #endif #if !READYTORUN // Do not report the get_IsSupported method as an intrinsic - RyuJIT would expand it to // a constant depending on the code generation flags passed to it, but we would like to // do a dynamic check instead. if (!HardwareIntrinsicHelpers.IsIsSupportedMethod(method) || HardwareIntrinsicHelpers.IsKnownSupportedIntrinsicAtCompileTime(method)) #endif { result |= CorInfoFlag.CORINFO_FLG_JIT_INTRINSIC; } } result |= CorInfoFlag.CORINFO_FLG_NOSECURITYWRAP; return (uint)result; } private void setMethodAttribs(CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs) { // TODO: Inlining } private void getMethodSig(CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent) { MethodDesc method = HandleToObject(ftn); // There might be a more concrete parent type specified - this can happen when inlining. if (memberParent != null) { TypeDesc type = HandleToObject(memberParent); // Typically, the owning type of the method is a canonical type and the member parent // supplied by RyuJIT is a concrete instantiation. if (type != method.OwningType) { Debug.Assert(type.HasSameTypeDefinition(method.OwningType)); Instantiation methodInst = method.Instantiation; method = _compilation.TypeSystemContext.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)type); if (methodInst.Length > 0) { method = method.MakeInstantiatedMethod(methodInst); } } } Get_CORINFO_SIG_INFO(method, sig); } private bool getMethodInfo(CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info) { MethodIL methodIL = Get_CORINFO_METHOD_INFO(HandleToObject(ftn), null, info); return methodIL != null; } private CorInfoInline canInline(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, ref uint pRestrictions) { MethodDesc callerMethod = HandleToObject(callerHnd); MethodDesc calleeMethod = HandleToObject(calleeHnd); if (_compilation.CanInline(callerMethod, calleeMethod)) { // No restrictions on inlining return CorInfoInline.INLINE_PASS; } else { // Call may not be inlined return CorInfoInline.INLINE_NEVER; } } private void reportTailCallDecision(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason) { } private void getEHinfo(CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, ref CORINFO_EH_CLAUSE clause) { var methodIL = _compilation.GetMethodIL(HandleToObject(ftn)); var ehRegion = methodIL.GetExceptionRegions()[EHnumber]; clause.Flags = (CORINFO_EH_CLAUSE_FLAGS)ehRegion.Kind; clause.TryOffset = (uint)ehRegion.TryOffset; clause.TryLength = (uint)ehRegion.TryLength; clause.HandlerOffset = (uint)ehRegion.HandlerOffset; clause.HandlerLength = (uint)ehRegion.HandlerLength; clause.ClassTokenOrOffset = (uint)((ehRegion.Kind == ILExceptionRegionKind.Filter) ? ehRegion.FilterOffset : ehRegion.ClassToken); } private CORINFO_CLASS_STRUCT_* getMethodClass(CORINFO_METHOD_STRUCT_* method) { var m = HandleToObject(method); return ObjectToHandle(m.OwningType); } private CORINFO_MODULE_STRUCT_* getMethodModule(CORINFO_METHOD_STRUCT_* method) { MethodDesc m = HandleToObject(method); if (m is UnboxingMethodDesc unboxingMethodDesc) { m = unboxingMethodDesc.Target; } MethodIL methodIL = _compilation.GetMethodIL(m); if (methodIL == null) { return null; } return (CORINFO_MODULE_STRUCT_*)ObjectToHandle(methodIL); } private CORINFO_METHOD_STRUCT_* resolveVirtualMethod(CORINFO_METHOD_STRUCT_* baseMethod, CORINFO_CLASS_STRUCT_* derivedClass, CORINFO_CONTEXT_STRUCT* ownerType) { TypeDesc implType = HandleToObject(derivedClass); // __Canon cannot be devirtualized if (implType.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { return null; } MethodDesc decl = HandleToObject(baseMethod); Debug.Assert(!decl.HasInstantiation); if (ownerType != null) { TypeDesc ownerTypeDesc = typeFromContext(ownerType); if (decl.OwningType != ownerTypeDesc) { Debug.Assert(ownerTypeDesc is InstantiatedType); decl = _compilation.TypeSystemContext.GetMethodForInstantiatedType(decl.GetTypicalMethodDefinition(), (InstantiatedType)ownerTypeDesc); } } MethodDesc impl = _compilation.ResolveVirtualMethod(decl, implType); if (impl != null) { if (impl.OwningType.IsValueType) { impl = _unboxingThunkFactory.GetUnboxingMethod(impl); } return ObjectToHandle(impl); } return null; } private CORINFO_METHOD_STRUCT_* getUnboxedEntry(CORINFO_METHOD_STRUCT_* ftn, byte* requiresInstMethodTableArg) { MethodDesc result = null; bool requiresInstMTArg = false; MethodDesc method = HandleToObject(ftn); if (method.IsUnboxingThunk()) { result = method.GetUnboxedMethod(); requiresInstMTArg = method.RequiresInstMethodTableArg(); } if (requiresInstMethodTableArg != null) { *requiresInstMethodTableArg = requiresInstMTArg ? (byte)1 : (byte)0; } return result != null ? ObjectToHandle(result) : null; } private CORINFO_CLASS_STRUCT_* getDefaultEqualityComparerClass(CORINFO_CLASS_STRUCT_* elemType) { TypeDesc comparand = HandleToObject(elemType); TypeDesc comparer = IL.Stubs.ComparerIntrinsics.GetEqualityComparerForType(comparand); return comparer != null ? ObjectToHandle(comparer) : null; } private bool isIntrinsicType(CORINFO_CLASS_STRUCT_* classHnd) { TypeDesc type = HandleToObject(classHnd); return type.IsIntrinsic; } private CorInfoUnmanagedCallConv getUnmanagedCallConv(CORINFO_METHOD_STRUCT_* method) { MethodSignatureFlags unmanagedCallConv = HandleToObject(method).GetPInvokeMethodMetadata().Flags.UnmanagedCallingConvention; // Verify that it is safe to convert MethodSignatureFlags.UnmanagedCallingConvention to CorInfoUnmanagedCallConv via a simple cast Debug.Assert((int)CorInfoUnmanagedCallConv.CORINFO_UNMANAGED_CALLCONV_C == (int)MethodSignatureFlags.UnmanagedCallingConventionCdecl); Debug.Assert((int)CorInfoUnmanagedCallConv.CORINFO_UNMANAGED_CALLCONV_STDCALL == (int)MethodSignatureFlags.UnmanagedCallingConventionStdCall); Debug.Assert((int)CorInfoUnmanagedCallConv.CORINFO_UNMANAGED_CALLCONV_THISCALL == (int)MethodSignatureFlags.UnmanagedCallingConventionThisCall); return (CorInfoUnmanagedCallConv)unmanagedCallConv; } private bool satisfiesMethodConstraints(CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method) { throw new NotImplementedException("satisfiesMethodConstraints"); } private bool isCompatibleDelegate(CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, ref bool pfIsOpenDelegate) { throw new NotImplementedException("isCompatibleDelegate"); } private CorInfoInstantiationVerification isInstantiationOfVerifiedGeneric(CORINFO_METHOD_STRUCT_* method) { throw new NotImplementedException("isInstantiationOfVerifiedGeneric"); } private void initConstraintsForVerification(CORINFO_METHOD_STRUCT_* method, ref bool pfHasCircularClassConstraints, ref bool pfHasCircularMethodConstraint) { throw new NotImplementedException("isInstantiationOfVerifiedGeneric"); } private CorInfoCanSkipVerificationResult canSkipMethodVerification(CORINFO_METHOD_STRUCT_* ftnHandle) { return CorInfoCanSkipVerificationResult.CORINFO_VERIFICATION_CAN_SKIP; } private void methodMustBeLoadedBeforeCodeIsRun(CORINFO_METHOD_STRUCT_* method) { } private CORINFO_METHOD_STRUCT_* mapMethodDeclToMethodImpl(CORINFO_METHOD_STRUCT_* method) { throw new NotImplementedException("mapMethodDeclToMethodImpl"); } private static object ResolveTokenWithSubstitution(MethodIL methodIL, mdToken token, Instantiation typeInst, Instantiation methodInst) { // Grab the generic definition of the method IL, resolve the token within the definition, // and instantiate it with the given context. object result = methodIL.GetMethodILDefinition().GetObject((int)token); if (result is MethodDesc methodResult) { result = methodResult.InstantiateSignature(typeInst, methodInst); } else if (result is FieldDesc fieldResult) { result = fieldResult.InstantiateSignature(typeInst, methodInst); } else { result = ((TypeDesc)result).InstantiateSignature(typeInst, methodInst); } return result; } private static object ResolveTokenInScope(MethodIL methodIL, object typeOrMethodContext, mdToken token) { MethodDesc owningMethod = methodIL.OwningMethod; // If token context differs from the scope, it means we're inlining. // If we're inlining a shared method body, we might be able to un-share // the referenced token and avoid runtime lookups. // Resolve the token in the inlining context. object result; if (owningMethod != typeOrMethodContext && owningMethod.IsCanonicalMethod(CanonicalFormKind.Any)) { Instantiation typeInst = default; Instantiation methodInst = default; if (typeOrMethodContext is TypeDesc typeContext) { Debug.Assert(typeContext.HasSameTypeDefinition(owningMethod.OwningType)); typeInst = typeContext.Instantiation; } else { var methodContext = (MethodDesc)typeOrMethodContext; Debug.Assert(methodContext.GetTypicalMethodDefinition() == owningMethod.GetTypicalMethodDefinition() || (owningMethod.Name == "CreateDefaultInstance" && methodContext.Name == "CreateInstance")); typeInst = methodContext.OwningType.Instantiation; methodInst = methodContext.Instantiation; } result = ResolveTokenWithSubstitution(methodIL, token, typeInst, methodInst); } else { // Not inlining - just resolve the token within the methodIL result = methodIL.GetObject((int)token); } return result; } private object GetRuntimeDeterminedObjectForToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken) { // Since RyuJIT operates on canonical types (as opposed to runtime determined ones), but the // dependency analysis operates on runtime determined ones, we convert the resolved token // to the runtime determined form (e.g. Foo<__Canon> becomes Foo<T__Canon>). var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope); var typeOrMethodContext = HandleToObject((IntPtr)pResolvedToken.tokenContext); object result = ResolveTokenInScope(methodIL, typeOrMethodContext, pResolvedToken.token); if (result is MethodDesc method) { if (method.IsSharedByGenericInstantiations) { MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget(); result = ResolveTokenWithSubstitution(methodIL, pResolvedToken.token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation); Debug.Assert(((MethodDesc)result).IsRuntimeDeterminedExactMethod); } } else if (result is FieldDesc field) { if (field.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any)) { MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget(); result = ResolveTokenWithSubstitution(methodIL, pResolvedToken.token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation); Debug.Assert(((FieldDesc)result).OwningType.IsRuntimeDeterminedSubtype); } } else { TypeDesc type = (TypeDesc)result; if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) { MethodDesc sharedMethod = methodIL.OwningMethod.GetSharedRuntimeFormMethodTarget(); result = ResolveTokenWithSubstitution(methodIL, pResolvedToken.token, sharedMethod.OwningType.Instantiation, sharedMethod.Instantiation); Debug.Assert(((TypeDesc)result).IsRuntimeDeterminedSubtype || /* If the resolved type is not runtime determined there's a chance we went down this path because there was a literal typeof(__Canon) in the compiled IL - check for that by resolving the token in the definition. */ ((TypeDesc)methodIL.GetMethodILDefinition().GetObject((int)pResolvedToken.token)).IsCanonicalDefinitionType(CanonicalFormKind.Any)); } if (pResolvedToken.tokenType == CorInfoTokenKind.CORINFO_TOKENKIND_Newarr) result = ((TypeDesc)result).MakeArrayType(); } return result; } private void resolveToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken) { var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope); var typeOrMethodContext = HandleToObject((IntPtr)pResolvedToken.tokenContext); object result = ResolveTokenInScope(methodIL, typeOrMethodContext, pResolvedToken.token); pResolvedToken.hClass = null; pResolvedToken.hMethod = null; pResolvedToken.hField = null; #if READYTORUN TypeDesc owningType = methodIL.OwningMethod.GetTypicalMethodDefinition().OwningType; bool recordToken = _compilation.NodeFactory.CompilationModuleGroup.VersionsWithType(owningType) && owningType is EcmaType; #endif if (result is MethodDesc) { MethodDesc method = result as MethodDesc; pResolvedToken.hMethod = ObjectToHandle(method); TypeDesc owningClass = method.OwningType; pResolvedToken.hClass = ObjectToHandle(owningClass); #if !SUPPORT_JIT _compilation.TypeSystemContext.EnsureLoadableType(owningClass); #endif #if READYTORUN if (recordToken) { _compilation.NodeFactory.Resolver.AddModuleTokenForMethod(method, HandleToModuleToken(ref pResolvedToken)); } #endif } else if (result is FieldDesc) { FieldDesc field = result as FieldDesc; // References to literal fields from IL body should never resolve. // The CLR would throw a MissingFieldException while jitting and so should we. if (field.IsLiteral) ThrowHelper.ThrowMissingFieldException(field.OwningType, field.Name); pResolvedToken.hField = ObjectToHandle(field); TypeDesc owningClass = field.OwningType; pResolvedToken.hClass = ObjectToHandle(owningClass); #if !SUPPORT_JIT _compilation.TypeSystemContext.EnsureLoadableType(owningClass); #endif #if READYTORUN if (recordToken) { _compilation.NodeFactory.Resolver.AddModuleTokenForField(field, HandleToModuleToken(ref pResolvedToken)); } #endif } else { TypeDesc type = (TypeDesc)result; #if READYTORUN if (recordToken) { _compilation.NodeFactory.Resolver.AddModuleTokenForType(type, HandleToModuleToken(ref pResolvedToken)); } #endif if (pResolvedToken.tokenType == CorInfoTokenKind.CORINFO_TOKENKIND_Newarr) { if (type.IsVoid) ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, methodIL.OwningMethod); type = type.MakeArrayType(); } pResolvedToken.hClass = ObjectToHandle(type); #if !SUPPORT_JIT _compilation.TypeSystemContext.EnsureLoadableType(type); #endif } pResolvedToken.pTypeSpec = null; pResolvedToken.cbTypeSpec = 0; pResolvedToken.pMethodSpec = null; pResolvedToken.cbMethodSpec = 0; } private bool tryResolveToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken) { resolveToken(ref pResolvedToken); return true; } private void findSig(CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) { var methodIL = (MethodIL)HandleToObject((IntPtr)module); Get_CORINFO_SIG_INFO((MethodSignature)methodIL.GetObject((int)sigTOK), sig); } private void findCallSiteSig(CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) { var methodIL = (MethodIL)HandleToObject((IntPtr)module); Get_CORINFO_SIG_INFO(((MethodDesc)methodIL.GetObject((int)methTOK)), sig); } private CORINFO_CLASS_STRUCT_* getTokenTypeAsHandle(ref CORINFO_RESOLVED_TOKEN pResolvedToken) { WellKnownType result = WellKnownType.RuntimeTypeHandle; if (pResolvedToken.hMethod != null) { result = WellKnownType.RuntimeMethodHandle; } else if (pResolvedToken.hField != null) { result = WellKnownType.RuntimeFieldHandle; } return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(result)); } private CorInfoCanSkipVerificationResult canSkipVerification(CORINFO_MODULE_STRUCT_* module) { return CorInfoCanSkipVerificationResult.CORINFO_VERIFICATION_CAN_SKIP; } private bool isValidToken(CORINFO_MODULE_STRUCT_* module, uint metaTOK) { throw new NotImplementedException("isValidToken"); } private bool isValidStringRef(CORINFO_MODULE_STRUCT_* module, uint metaTOK) { throw new NotImplementedException("isValidStringRef"); } private bool shouldEnforceCallvirtRestriction(CORINFO_MODULE_STRUCT_* scope) { throw new NotImplementedException("shouldEnforceCallvirtRestriction"); } private char* getStringLiteral(CORINFO_MODULE_STRUCT_* module, uint metaTOK, ref int length) { MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)module); string s = (string)methodIL.GetObject((int)metaTOK); length = (int)s.Length; return (char*)GetPin(s); } private CorInfoType asCorInfoType(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); return asCorInfoType(type); } private byte* getClassName(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); return (byte*)GetPin(StringToUTF8(type.ToString())); } private byte* getClassNameFromMetadata(CORINFO_CLASS_STRUCT_* cls, byte** namespaceName) { var type = HandleToObject(cls) as MetadataType; if (type != null) { if (namespaceName != null) *namespaceName = (byte*)GetPin(StringToUTF8(type.Namespace)); return (byte*)GetPin(StringToUTF8(type.Name)); } if (namespaceName != null) *namespaceName = null; return null; } private CORINFO_CLASS_STRUCT_* getTypeInstantiationArgument(CORINFO_CLASS_STRUCT_* cls, uint index) { TypeDesc type = HandleToObject(cls); Instantiation inst = type.Instantiation; return index < (uint)inst.Length ? ObjectToHandle(inst[(int)index]) : null; } private int appendClassName(char** ppBuf, ref int pnBufLen, CORINFO_CLASS_STRUCT_* cls, bool fNamespace, bool fFullInst, bool fAssembly) { // We support enough of this to make SIMD work, but not much else. Debug.Assert(fNamespace && !fFullInst && !fAssembly); var type = HandleToObject(cls); string name = TypeString.Instance.FormatName(type); int length = name.Length; if (pnBufLen > 0) { char* buffer = *ppBuf; for (int i = 0; i < Math.Min(name.Length, pnBufLen); i++) buffer[i] = name[i]; if (name.Length < pnBufLen) buffer[name.Length] = (char)0; else buffer[pnBufLen - 1] = (char)0; pnBufLen -= length; *ppBuf = buffer + length; } return length; } private bool isValueClass(CORINFO_CLASS_STRUCT_* cls) { return HandleToObject(cls).IsValueType; } private CorInfoInlineTypeCheck canInlineTypeCheck(CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source) { // TODO: when we support multiple modules at runtime, this will need to do more work // NOTE: cls can be null return CorInfoInlineTypeCheck.CORINFO_INLINE_TYPECHECK_PASS; } private bool canInlineTypeCheckWithObjectVTable(CORINFO_CLASS_STRUCT_* cls) { throw new NotImplementedException(); } private uint getClassAttribs(CORINFO_CLASS_STRUCT_* cls) { TypeDesc type = HandleToObject(cls); return getClassAttribsInternal(type); } private uint getClassAttribsInternal(TypeDesc type) { // TODO: Support for verification (CORINFO_FLG_GENERIC_TYPE_VARIABLE) CorInfoFlag result = (CorInfoFlag)0; var metadataType = type as MetadataType; // The array flag is used to identify the faked-up methods on // array types, i.e. .ctor, Get, Set and Address if (type.IsArray) result |= CorInfoFlag.CORINFO_FLG_ARRAY; if (type.IsInterface) result |= CorInfoFlag.CORINFO_FLG_INTERFACE; if (type.IsArray || type.IsString) result |= CorInfoFlag.CORINFO_FLG_VAROBJSIZE; if (type.IsValueType) { result |= CorInfoFlag.CORINFO_FLG_VALUECLASS; if (metadataType.IsByRefLike) result |= CorInfoFlag.CORINFO_FLG_CONTAINS_STACK_PTR; // The CLR has more complicated rules around CUSTOMLAYOUT, but this will do. if (metadataType.IsExplicitLayout || (metadataType.IsSequentialLayout && metadataType.GetClassLayout().Size != 0) || metadataType.IsWellKnownType(WellKnownType.TypedReference)) result |= CorInfoFlag.CORINFO_FLG_CUSTOMLAYOUT; // TODO // if (type.IsUnsafeValueType) // result |= CorInfoFlag.CORINFO_FLG_UNSAFE_VALUECLASS; } if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) result |= CorInfoFlag.CORINFO_FLG_SHAREDINST; if (type.HasVariance) result |= CorInfoFlag.CORINFO_FLG_VARIANCE; if (type.IsDelegate) result |= CorInfoFlag.CORINFO_FLG_DELEGATE; if (_compilation.IsEffectivelySealed(type)) result |= CorInfoFlag.CORINFO_FLG_FINAL; if (type.IsIntrinsic) result |= CorInfoFlag.CORINFO_FLG_INTRINSIC_TYPE; if (metadataType != null) { if (metadataType.ContainsGCPointers) result |= CorInfoFlag.CORINFO_FLG_CONTAINS_GC_PTR; if (metadataType.IsBeforeFieldInit) result |= CorInfoFlag.CORINFO_FLG_BEFOREFIELDINIT; // Assume overlapping fields for explicit layout. if (metadataType.IsExplicitLayout) result |= CorInfoFlag.CORINFO_FLG_OVERLAPPING_FIELDS; if (metadataType.IsAbstract) result |= CorInfoFlag.CORINFO_FLG_ABSTRACT; } return (uint)result; } private bool isStructRequiringStackAllocRetBuf(CORINFO_CLASS_STRUCT_* cls) { // Disable this optimization. It has limited value (only kicks in on x86, and only for less common structs), // causes bugs and introduces odd ABI differences not compatible with ReadyToRun. return false; } private CORINFO_MODULE_STRUCT_* getClassModule(CORINFO_CLASS_STRUCT_* cls) { throw new NotImplementedException("getClassModule"); } private CORINFO_ASSEMBLY_STRUCT_* getModuleAssembly(CORINFO_MODULE_STRUCT_* mod) { throw new NotImplementedException("getModuleAssembly"); } private byte* getAssemblyName(CORINFO_ASSEMBLY_STRUCT_* assem) { throw new NotImplementedException("getAssemblyName"); } private void* LongLifetimeMalloc(UIntPtr sz) { return (void*)Marshal.AllocCoTaskMem((int)sz); } private void LongLifetimeFree(void* obj) { Marshal.FreeCoTaskMem((IntPtr)obj); } private byte* getClassModuleIdForStatics(CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection) { throw new NotImplementedException("getClassModuleIdForStatics"); } private uint getClassSize(CORINFO_CLASS_STRUCT_* cls) { TypeDesc type = HandleToObject(cls); LayoutInt classSize = type.GetElementSize(); #if READYTORUN if (classSize.IsIndeterminate) { throw new RequiresRuntimeJitException(type); } #endif return (uint)classSize.AsInt; } private uint getHeapClassSize(CORINFO_CLASS_STRUCT_* cls) { TypeDesc type = HandleToObject(cls); Debug.Assert(!type.IsValueType); Debug.Assert(type.IsDefType); Debug.Assert(!type.IsString); #if READYTORUN Debug.Assert(_compilation.IsInheritanceChainLayoutFixedInCurrentVersionBubble(type)); #endif return (uint)((DefType)type).InstanceByteCount.AsInt; } private bool canAllocateOnStack(CORINFO_CLASS_STRUCT_* cls) { TypeDesc type = HandleToObject(cls); Debug.Assert(!type.IsValueType); Debug.Assert(type.IsDefType); bool result = !type.HasFinalizer; #if READYTORUN if (!_compilation.IsInheritanceChainLayoutFixedInCurrentVersionBubble(type)) result = false; #endif return result; } private uint getClassAlignmentRequirement(CORINFO_CLASS_STRUCT_* cls, bool fDoubleAlignHint) { DefType type = (DefType)HandleToObject(cls); return (uint)type.InstanceFieldAlignment.AsInt; } private int MarkGcField(byte* gcPtrs, CorInfoGCType gcType) { // Ensure that if we have multiple fields with the same offset, // that we don't double count the data in the gc layout. if (*gcPtrs == (byte)CorInfoGCType.TYPE_GC_NONE) { *gcPtrs = (byte)gcType; return 1; } else { Debug.Assert(*gcPtrs == (byte)gcType); return 0; } } private int GatherClassGCLayout(TypeDesc type, byte* gcPtrs) { int result = 0; if (type.IsByReferenceOfT) { return MarkGcField(gcPtrs, CorInfoGCType.TYPE_GC_BYREF); } foreach (var field in type.GetFields()) { if (field.IsStatic) continue; CorInfoGCType gcType = CorInfoGCType.TYPE_GC_NONE; var fieldType = field.FieldType; if (fieldType.IsValueType) { var fieldDefType = (DefType)fieldType; if (!fieldDefType.ContainsGCPointers && !fieldDefType.IsByRefLike) continue; gcType = CorInfoGCType.TYPE_GC_OTHER; } else if (fieldType.IsGCPointer) { gcType = CorInfoGCType.TYPE_GC_REF; } else if (fieldType.IsByRef) { gcType = CorInfoGCType.TYPE_GC_BYREF; } else { continue; } Debug.Assert(field.Offset.AsInt % PointerSize == 0); byte* fieldGcPtrs = gcPtrs + field.Offset.AsInt / PointerSize; if (gcType == CorInfoGCType.TYPE_GC_OTHER) { result += GatherClassGCLayout(fieldType, fieldGcPtrs); } else { result += MarkGcField(fieldGcPtrs, gcType); } } return result; } private uint getClassGClayout(CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs) { uint result = 0; DefType type = (DefType)HandleToObject(cls); int pointerSize = PointerSize; int ptrsCount = AlignmentHelper.AlignUp(type.InstanceFieldSize.AsInt, pointerSize) / pointerSize; // Assume no GC pointers at first for (int i = 0; i < ptrsCount; i++) gcPtrs[i] = (byte)CorInfoGCType.TYPE_GC_NONE; if (type.ContainsGCPointers || type.IsByRefLike) { result = (uint)GatherClassGCLayout(type, gcPtrs); } return result; } private uint getClassNumInstanceFields(CORINFO_CLASS_STRUCT_* cls) { TypeDesc type = HandleToObject(cls); uint result = 0; foreach (var field in type.GetFields()) { if (!field.IsStatic) result++; } return result; } private CORINFO_FIELD_STRUCT_* getFieldInClass(CORINFO_CLASS_STRUCT_* clsHnd, int num) { TypeDesc classWithFields = HandleToObject(clsHnd); int iCurrentFoundField = -1; foreach (var field in classWithFields.GetFields()) { if (field.IsStatic) continue; ++iCurrentFoundField; if (iCurrentFoundField == num) { return ObjectToHandle(field); } } // We could not find the field that was searched for. throw new InvalidOperationException(); } private bool checkMethodModifier(CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, bool fOptional) { throw new NotImplementedException("checkMethodModifier"); } private CorInfoHelpFunc getSharedCCtorHelper(CORINFO_CLASS_STRUCT_* clsHnd) { throw new NotImplementedException("getSharedCCtorHelper"); } private CorInfoHelpFunc getSecurityPrologHelper(CORINFO_METHOD_STRUCT_* ftn) { throw new NotImplementedException("getSecurityPrologHelper"); } private CORINFO_CLASS_STRUCT_* getTypeForBox(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); var typeForBox = type.IsNullable ? type.Instantiation[0] : type; return ObjectToHandle(typeForBox); } private CorInfoHelpFunc getBoxHelper(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); // we shouldn't allow boxing of types that contains stack pointers // csc and vbc already disallow it. if (type.IsByRefLike) ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, MethodBeingCompiled); return type.IsNullable ? CorInfoHelpFunc.CORINFO_HELP_BOX_NULLABLE : CorInfoHelpFunc.CORINFO_HELP_BOX; } private CorInfoHelpFunc getUnBoxHelper(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); return type.IsNullable ? CorInfoHelpFunc.CORINFO_HELP_UNBOX_NULLABLE : CorInfoHelpFunc.CORINFO_HELP_UNBOX; } private byte* getHelperName(CorInfoHelpFunc helpFunc) { return (byte*)GetPin(StringToUTF8(helpFunc.ToString())); } private CorInfoInitClassResult initClass(CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context, bool speculative) { FieldDesc fd = field == null ? null : HandleToObject(field); Debug.Assert(fd == null || fd.IsStatic); MethodDesc md = HandleToObject(method); TypeDesc type = fd != null ? fd.OwningType : typeFromContext(context); if (_isFallbackBodyCompilation || #if READYTORUN IsClassPreInited(type) #else !_compilation.HasLazyStaticConstructor(type) #endif ) { return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } MetadataType typeToInit = (MetadataType)type; if (fd == null) { if (typeToInit.IsBeforeFieldInit) { // We can wait for field accesses to run .cctor return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } // Run .cctor on statics & constructors if (md.Signature.IsStatic) { // Except don't class construct on .cctor - it would be circular if (md.IsStaticConstructor) { return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } } else if (!md.IsConstructor && !typeToInit.IsValueType && !typeToInit.IsInterface) { // According to the spec, we should be able to do this optimization for both reference and valuetypes. // To maintain backward compatibility, we are doing it for reference types only. // We don't do this for interfaces though, as those don't have instance constructors. // For instance methods of types with precise-initialization // semantics, we can assume that the .ctor triggerred the // type initialization. // This does not hold for NULL "this" object. However, the spec does // not require that case to work. return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } } if (typeToInit.IsCanonicalSubtype(CanonicalFormKind.Any)) { // Shared generic code has to use helper. Moreover, tell JIT not to inline since // inlining of generic dictionary lookups is not supported. return CorInfoInitClassResult.CORINFO_INITCLASS_USE_HELPER | CorInfoInitClassResult.CORINFO_INITCLASS_DONT_INLINE; } // // Try to prove that the initialization is not necessary because of nesting // if (fd == null) { // Handled above Debug.Assert(!typeToInit.IsBeforeFieldInit); // Note that jit has both methods the same if asking whether to emit cctor // for a given method's code (as opposed to inlining codegen). MethodDesc contextMethod = methodFromContext(context); if (contextMethod != MethodBeingCompiled && typeToInit == MethodBeingCompiled.OwningType) { // If we're inling a call to a method in our own type, then we should already // have triggered the .cctor when caller was itself called. return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } } else { // This optimization may cause static fields in reference types to be accessed without cctor being triggered // for NULL "this" object. It does not conform with what the spec says. However, we have been historically // doing it for perf reasons. if (!typeToInit.IsValueType && ! typeToInit.IsInterface && !typeToInit.IsBeforeFieldInit) { if (typeToInit == typeFromContext(context) || typeToInit == MethodBeingCompiled.OwningType) { // The class will be initialized by the time we access the field. return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } } // If we are currently compiling the class constructor for this static field access then we can skip the initClass if (MethodBeingCompiled.OwningType == typeToInit && MethodBeingCompiled.IsStaticConstructor) { // The class will be initialized by the time we access the field. return CorInfoInitClassResult.CORINFO_INITCLASS_NOT_REQUIRED; } } return CorInfoInitClassResult.CORINFO_INITCLASS_USE_HELPER; } private CORINFO_CLASS_STRUCT_* getBuiltinClass(CorInfoClassId classId) { switch (classId) { case CorInfoClassId.CLASSID_SYSTEM_OBJECT: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Object)); case CorInfoClassId.CLASSID_TYPED_BYREF: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.TypedReference)); case CorInfoClassId.CLASSID_TYPE_HANDLE: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeTypeHandle)); case CorInfoClassId.CLASSID_FIELD_HANDLE: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeFieldHandle)); case CorInfoClassId.CLASSID_METHOD_HANDLE: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.RuntimeMethodHandle)); case CorInfoClassId.CLASSID_ARGUMENT_HANDLE: ThrowHelper.ThrowTypeLoadException("System", "RuntimeArgumentHandle", _compilation.TypeSystemContext.SystemModule); return null; case CorInfoClassId.CLASSID_STRING: return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.String)); case CorInfoClassId.CLASSID_RUNTIME_TYPE: TypeDesc typeOfRuntimeType = _compilation.GetTypeOfRuntimeType(); return typeOfRuntimeType != null ? ObjectToHandle(typeOfRuntimeType) : null; default: throw new NotImplementedException(); } } private CorInfoType getTypeForPrimitiveValueClass(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); if (!type.IsPrimitive && !type.IsEnum) return CorInfoType.CORINFO_TYPE_UNDEF; return asCorInfoType(type); } private CorInfoType getTypeForPrimitiveNumericClass(CORINFO_CLASS_STRUCT_* cls) { var type = HandleToObject(cls); switch (type.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.UInt16: case TypeFlags.Int16: case TypeFlags.UInt32: case TypeFlags.Int32: case TypeFlags.UInt64: case TypeFlags.Int64: case TypeFlags.Single: case TypeFlags.Double: return asCorInfoType(type); default: return CorInfoType.CORINFO_TYPE_UNDEF; } } private bool canCast(CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent) { throw new NotImplementedException("canCast"); } private bool areTypesEquivalent(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { throw new NotImplementedException("areTypesEquivalent"); } private TypeCompareState compareTypesForCast(CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass) { TypeDesc fromType = HandleToObject(fromClass); TypeDesc toType = HandleToObject(toClass); TypeCompareState result = TypeCompareState.May; if (toType.IsNullable) { // If casting to Nullable<T>, don't try to optimize result = TypeCompareState.May; } else if (!fromType.IsCanonicalSubtype(CanonicalFormKind.Any) && !toType.IsCanonicalSubtype(CanonicalFormKind.Any)) { // If the types are not shared, we can check directly. if (fromType.CanCastTo(toType)) result = TypeCompareState.Must; else result = TypeCompareState.MustNot; } else if (fromType.IsCanonicalSubtype(CanonicalFormKind.Any) && !toType.IsCanonicalSubtype(CanonicalFormKind.Any)) { // Casting from a shared type to an unshared type. // Only handle casts to interface types for now if (toType.IsInterface) { // Do a preliminary check. bool canCast = fromType.CanCastTo(toType); // Pass back positive results unfiltered. The unknown type // parameters in fromClass did not come into play. if (canCast) { result = TypeCompareState.Must; } // We have __Canon parameter(s) in fromClass, somewhere. // // In CanCastTo, these __Canon(s) won't match the interface or // instantiated types on the interface, so CanCastTo may // return false negatives. // // Only report MustNot if the fromClass is not __Canon // and the interface is not instantiated; then there is // no way for the fromClass __Canon(s) to confuse things. // // __Canon -> IBar May // IFoo<__Canon> -> IFoo<string> May // IFoo<__Canon> -> IBar MustNot // else if (fromType.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { result = TypeCompareState.May; } else if (toType.HasInstantiation) { result = TypeCompareState.May; } else { result = TypeCompareState.MustNot; } } } #if READYTORUN // In R2R it is a breaking change for a previously positive // cast to become negative, but not for a previously negative // cast to become positive. So in R2R a negative result is // always reported back as May. if (result == TypeCompareState.MustNot) { result = TypeCompareState.May; } #endif return result; } private TypeCompareState compareTypesForEquality(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { TypeCompareState result = TypeCompareState.May; TypeDesc type1 = HandleToObject(cls1); TypeDesc type2 = HandleToObject(cls2); // If neither type is a canonical subtype, type handle comparison suffices if (!type1.IsCanonicalSubtype(CanonicalFormKind.Any) && !type2.IsCanonicalSubtype(CanonicalFormKind.Any)) { result = (type1 == type2 ? TypeCompareState.Must : TypeCompareState.MustNot); } // If either or both types are canonical subtypes, we can sometimes prove inequality. else { // If either is a value type then the types cannot // be equal unless the type defs are the same. if (type1.IsValueType || type2.IsValueType) { if (!type1.IsCanonicalDefinitionType(CanonicalFormKind.Universal) && !type2.IsCanonicalDefinitionType(CanonicalFormKind.Universal)) { if (!type1.HasSameTypeDefinition(type2)) { result = TypeCompareState.MustNot; } } } // If we have two ref types that are not __Canon, then the // types cannot be equal unless the type defs are the same. else { if (!type1.IsCanonicalDefinitionType(CanonicalFormKind.Any) && !type2.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { if (!type1.HasSameTypeDefinition(type2)) { result = TypeCompareState.MustNot; } } } } return result; } private CORINFO_CLASS_STRUCT_* mergeClasses(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { TypeDesc type1 = HandleToObject(cls1); TypeDesc type2 = HandleToObject(cls2); TypeDesc merged = TypeExtensions.MergeTypesToCommonParent(type1, type2); #if DEBUG // Make sure the merge is reflexive in the cases we "support". TypeDesc reflexive = TypeExtensions.MergeTypesToCommonParent(type2, type1); // If both sides are classes than either they have a common non-interface parent (in which case it is // reflexive) // OR they share a common interface, and it can be order dependent (if they share multiple interfaces // in common) if (!type1.IsInterface && !type2.IsInterface) { if (merged.IsInterface) { Debug.Assert(reflexive.IsInterface); } else { Debug.Assert(merged == reflexive); } } // Both results must either be interfaces or classes. They cannot be mixed. Debug.Assert(merged.IsInterface == reflexive.IsInterface); // If the result of the merge was a class, then the result of the reflexive merge was the same class. if (!merged.IsInterface) { Debug.Assert(merged == reflexive); } // If both sides are arrays, then the result is either an array or g_pArrayClass. The above is // actually true about the element type for references types, but I think that that is a little // excessive for sanity. if (type1.IsArray && type2.IsArray) { TypeDesc arrayClass = _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Array); Debug.Assert((merged.IsArray && reflexive.IsArray) || ((merged == arrayClass) && (reflexive == arrayClass))); } // The results must always be assignable Debug.Assert(type1.CanCastTo(merged) && type2.CanCastTo(merged) && type1.CanCastTo(reflexive) && type2.CanCastTo(reflexive)); #endif return ObjectToHandle(merged); } private bool isMoreSpecificType(CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { TypeDesc type1 = HandleToObject(cls1); TypeDesc type2 = HandleToObject(cls2); // If we have a mixture of shared and unshared types, // consider the unshared type as more specific. bool isType1CanonSubtype = type1.IsCanonicalSubtype(CanonicalFormKind.Any); bool isType2CanonSubtype = type2.IsCanonicalSubtype(CanonicalFormKind.Any); if (isType1CanonSubtype != isType2CanonSubtype) { // Only one of type1 and type2 is shared. // type2 is more specific if type1 is the shared type. return isType1CanonSubtype; } // Otherwise both types are either shared or not shared. // Look for a common parent type. TypeDesc merged = TypeExtensions.MergeTypesToCommonParent(type1, type2); // If the common parent is type1, then type2 is more specific. return merged == type1; } private CORINFO_CLASS_STRUCT_* getParentType(CORINFO_CLASS_STRUCT_* cls) { throw new NotImplementedException("getParentType"); } private CorInfoType getChildType(CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet) { CorInfoType result = CorInfoType.CORINFO_TYPE_UNDEF; var td = HandleToObject(clsHnd); if (td.IsArray || td.IsByRef) { TypeDesc returnType = ((ParameterizedType)td).ParameterType; result = asCorInfoType(returnType, clsRet); } else clsRet = null; return result; } private bool satisfiesClassConstraints(CORINFO_CLASS_STRUCT_* cls) { throw new NotImplementedException("satisfiesClassConstraints"); } private bool isSDArray(CORINFO_CLASS_STRUCT_* cls) { var td = HandleToObject(cls); return td.IsSzArray; } private uint getArrayRank(CORINFO_CLASS_STRUCT_* cls) { var td = HandleToObject(cls) as ArrayType; Debug.Assert(td != null); return (uint) td.Rank; } private void* getArrayInitializationData(CORINFO_FIELD_STRUCT_* field, uint size) { var fd = HandleToObject(field); // Check for invalid arguments passed to InitializeArray intrinsic if (!fd.HasRva || size > fd.FieldType.GetElementSize().AsInt) { return null; } return (void*)ObjectToHandle(_compilation.GetFieldRvaData(fd)); } private CorInfoIsAccessAllowedResult canAccessClass(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, ref CORINFO_HELPER_DESC pAccessHelper) { // TODO: Access check return CorInfoIsAccessAllowedResult.CORINFO_ACCESS_ALLOWED; } private byte* getFieldName(CORINFO_FIELD_STRUCT_* ftn, byte** moduleName) { var field = HandleToObject(ftn); if (moduleName != null) { MetadataType typeDef = field.OwningType.GetTypeDefinition() as MetadataType; if (typeDef != null) *moduleName = (byte*)GetPin(StringToUTF8(typeDef.GetFullName())); else *moduleName = (byte*)GetPin(StringToUTF8("unknown")); } return (byte*)GetPin(StringToUTF8(field.Name)); } private CORINFO_CLASS_STRUCT_* getFieldClass(CORINFO_FIELD_STRUCT_* field) { var fieldDesc = HandleToObject(field); return ObjectToHandle(fieldDesc.OwningType); } private CorInfoType getFieldType(CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent) { FieldDesc fieldDesc = HandleToObject(field); TypeDesc fieldType = fieldDesc.FieldType; CorInfoType type; if (structType != null) { type = asCorInfoType(fieldType, structType); } else { type = asCorInfoType(fieldType); } Debug.Assert(!fieldDesc.OwningType.IsByReferenceOfT || fieldDesc.OwningType.GetKnownField("_value").FieldType.Category == TypeFlags.IntPtr); if (type == CorInfoType.CORINFO_TYPE_NATIVEINT && fieldDesc.OwningType.IsByReferenceOfT) { Debug.Assert(structType == null || *structType == null); Debug.Assert(fieldDesc.Offset.AsInt == 0); type = CorInfoType.CORINFO_TYPE_BYREF; } return type; } private uint getFieldOffset(CORINFO_FIELD_STRUCT_* field) { var fieldDesc = HandleToObject(field); Debug.Assert(fieldDesc.Offset != FieldAndOffset.InvalidOffset); return (uint)fieldDesc.Offset.AsInt; } private bool isWriteBarrierHelperRequired(CORINFO_FIELD_STRUCT_* field) { throw new NotImplementedException("isWriteBarrierHelperRequired"); } private CORINFO_FIELD_ACCESSOR getFieldIntrinsic(FieldDesc field) { Debug.Assert(field.IsIntrinsic); var owningType = field.OwningType; if ((owningType.IsWellKnownType(WellKnownType.IntPtr) || owningType.IsWellKnownType(WellKnownType.UIntPtr)) && field.Name == "Zero") { return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_ZERO; } else if (owningType.IsString && field.Name == "Empty") { return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_EMPTY_STRING; } else if (owningType.Name == "BitConverter" && owningType.Namespace == "System" && field.Name == "IsLittleEndian") { return CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INTRINSIC_ISLITTLEENDIAN; } return (CORINFO_FIELD_ACCESSOR)(-1); } private bool isFieldStatic(CORINFO_FIELD_STRUCT_* fldHnd) { return HandleToObject(fldHnd).IsStatic; } private void getBoundaries(CORINFO_METHOD_STRUCT_* ftn, ref uint cILOffsets, ref uint* pILOffsets, BoundaryTypes* implicitBoundaries) { // TODO: Debugging cILOffsets = 0; pILOffsets = null; *implicitBoundaries = BoundaryTypes.DEFAULT_BOUNDARIES; } private void getVars(CORINFO_METHOD_STRUCT_* ftn, ref uint cVars, ILVarInfo** vars, ref bool extendOthers) { // TODO: Debugging cVars = 0; *vars = null; // Just tell the JIT to extend everything. extendOthers = true; } private void* allocateArray(uint cBytes) { return (void*)Marshal.AllocCoTaskMem((int)cBytes); } private void freeArray(void* array) { Marshal.FreeCoTaskMem((IntPtr)array); } private CORINFO_ARG_LIST_STRUCT_* getArgNext(CORINFO_ARG_LIST_STRUCT_* args) { return (CORINFO_ARG_LIST_STRUCT_*)((int)args + 1); } private CorInfoTypeWithMod getArgType(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet) { int index = (int)args; Object sigObj = HandleToObject((IntPtr)sig->pSig); MethodSignature methodSig = sigObj as MethodSignature; if (methodSig != null) { TypeDesc type = methodSig[index]; CorInfoType corInfoType = asCorInfoType(type, vcTypeRet); return (CorInfoTypeWithMod)corInfoType; } else { LocalVariableDefinition[] locals = (LocalVariableDefinition[])sigObj; TypeDesc type = locals[index].Type; CorInfoType corInfoType = asCorInfoType(type, vcTypeRet); return (CorInfoTypeWithMod)corInfoType | (locals[index].IsPinned ? CorInfoTypeWithMod.CORINFO_TYPE_MOD_PINNED : 0); } } private CORINFO_CLASS_STRUCT_* getArgClass(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args) { int index = (int)args; Object sigObj = HandleToObject((IntPtr)sig->pSig); MethodSignature methodSig = sigObj as MethodSignature; if (methodSig != null) { TypeDesc type = methodSig[index]; return ObjectToHandle(type); } else { LocalVariableDefinition[] locals = (LocalVariableDefinition[])sigObj; TypeDesc type = locals[index].Type; return ObjectToHandle(type); } } private CorInfoType getHFAType(CORINFO_CLASS_STRUCT_* hClass) { var type = (DefType)HandleToObject(hClass); return type.IsHfa ? asCorInfoType(type.HfaElementType) : CorInfoType.CORINFO_TYPE_UNDEF; } private HRESULT GetErrorHRESULT(_EXCEPTION_POINTERS* pExceptionPointers) { throw new NotImplementedException("GetErrorHRESULT"); } private uint GetErrorMessage(char* buffer, uint bufferLength) { throw new NotImplementedException("GetErrorMessage"); } private int FilterException(_EXCEPTION_POINTERS* pExceptionPointers) { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. Debug.Fail("CorInfoImpl.FilterException should not be called"); throw new NotSupportedException("FilterException"); } private void HandleException(_EXCEPTION_POINTERS* pExceptionPointers) { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. Debug.Fail("CorInfoImpl.HandleException should not be called"); throw new NotSupportedException("HandleException"); } private bool runWithErrorTrap(void* function, void* parameter) { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. Debug.Fail("CorInfoImpl.runWithErrorTrap should not be called"); throw new NotSupportedException("runWithErrorTrap"); } private void ThrowExceptionForJitResult(HRESULT result) { throw new NotImplementedException("ThrowExceptionForJitResult"); } private void ThrowExceptionForHelper(ref CORINFO_HELPER_DESC throwHelper) { throw new NotImplementedException("ThrowExceptionForHelper"); } private void getEEInfo(ref CORINFO_EE_INFO pEEInfoOut) { pEEInfoOut = new CORINFO_EE_INFO(); #if DEBUG // In debug, write some bogus data to the struct to ensure we have filled everything // properly. fixed (CORINFO_EE_INFO* tmp = &pEEInfoOut) MemoryHelper.FillMemory((byte*)tmp, 0xcc, Marshal.SizeOf<CORINFO_EE_INFO>()); #endif int pointerSize = this.PointerSize; pEEInfoOut.inlinedCallFrameInfo.size = (uint)SizeOfPInvokeTransitionFrame; pEEInfoOut.offsetOfDelegateInstance = (uint)pointerSize; // Delegate::m_firstParameter pEEInfoOut.offsetOfDelegateFirstTarget = OffsetOfDelegateFirstTarget; pEEInfoOut.offsetOfObjArrayData = (uint)(2 * pointerSize); pEEInfoOut.sizeOfReversePInvokeFrame = (uint)(2 * pointerSize); pEEInfoOut.osPageSize = new UIntPtr(0x1000); pEEInfoOut.maxUncheckedOffsetForNullObject = (_compilation.NodeFactory.Target.IsWindows) ? new UIntPtr(32 * 1024 - 1) : new UIntPtr((uint)pEEInfoOut.osPageSize / 2 - 1); pEEInfoOut.targetAbi = TargetABI; pEEInfoOut.osType = _compilation.NodeFactory.Target.IsWindows ? CORINFO_OS.CORINFO_WINNT : CORINFO_OS.CORINFO_UNIX; } private char* getJitTimeLogFilename() { return null; } private mdToken getMethodDefFromMethod(CORINFO_METHOD_STRUCT_* hMethod) { MethodDesc method = HandleToObject(hMethod); #if READYTORUN if (method is UnboxingMethodDesc unboxingMethodDesc) { method = unboxingMethodDesc.Target; } #endif MethodDesc methodDefinition = method.GetTypicalMethodDefinition(); // Need to cast down to EcmaMethod. Do not use this as a precedent that casting to Ecma* // within the JitInterface is fine. We might want to consider moving this to Compilation. TypeSystem.Ecma.EcmaMethod ecmaMethodDefinition = methodDefinition as TypeSystem.Ecma.EcmaMethod; if (ecmaMethodDefinition != null) { return (mdToken)System.Reflection.Metadata.Ecma335.MetadataTokens.GetToken(ecmaMethodDefinition.Handle); } return 0; } private static byte[] StringToUTF8(string s) { int byteCount = Encoding.UTF8.GetByteCount(s); byte[] bytes = new byte[byteCount + 1]; Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); return bytes; } private byte* getMethodName(CORINFO_METHOD_STRUCT_* ftn, byte** moduleName) { MethodDesc method = HandleToObject(ftn); if (moduleName != null) { MetadataType typeDef = method.OwningType.GetTypeDefinition() as MetadataType; if (typeDef != null) *moduleName = (byte*)GetPin(StringToUTF8(typeDef.GetFullName())); else *moduleName = (byte*)GetPin(StringToUTF8("unknown")); } return (byte*)GetPin(StringToUTF8(method.Name)); } private String getMethodNameFromMetadataImpl(MethodDesc method, out string className, out string namespaceName, out string enclosingClassName) { string result = null; className = null; namespaceName = null; enclosingClassName = null; result = method.Name; MetadataType owningType = method.OwningType as MetadataType; if (owningType != null) { className = owningType.Name; namespaceName = owningType.Namespace; // Query enclosingClassName when the method is in a nested class // and get the namespace of enclosing classes (nested class's namespace is empty) var containingType = owningType.ContainingType; if (containingType != null) { enclosingClassName = containingType.Name; namespaceName = containingType.Namespace; } } return result; } private byte* getMethodNameFromMetadata(CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName) { MethodDesc method = HandleToObject(ftn); string result; string classResult; string namespaceResult; string enclosingResult; result = getMethodNameFromMetadataImpl(method, out classResult, out namespaceResult, out enclosingResult); if (className != null) *className = classResult != null ? (byte*)GetPin(StringToUTF8(classResult)) : null; if (namespaceName != null) *namespaceName = namespaceResult != null ? (byte*)GetPin(StringToUTF8(namespaceResult)) : null; if (enclosingClassName != null) *enclosingClassName = enclosingResult != null ? (byte*)GetPin(StringToUTF8(enclosingResult)) : null; return result != null ? (byte*)GetPin(StringToUTF8(result)) : null; } private uint getMethodHash(CORINFO_METHOD_STRUCT_* ftn) { return (uint)HandleToObject(ftn).GetHashCode(); } private byte* findNameOfToken(CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity) { throw new NotImplementedException("findNameOfToken"); } private bool getSystemVAmd64PassStructInRegisterDescriptor(CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr) { TypeDesc typeDesc = HandleToObject(structHnd); SystemVStructClassificator.GetSystemVAmd64PassStructInRegisterDescriptor(typeDesc, out *structPassInRegDescPtr); return true; } private uint getThreadTLSIndex(ref void* ppIndirection) { throw new NotImplementedException("getThreadTLSIndex"); } private void* getInlinedCallFrameVptr(ref void* ppIndirection) { throw new NotImplementedException("getInlinedCallFrameVptr"); } private int* getAddrOfCaptureThreadGlobal(ref void* ppIndirection) { ppIndirection = null; return null; } private Dictionary<CorInfoHelpFunc, ISymbolNode> _helperCache = new Dictionary<CorInfoHelpFunc, ISymbolNode>(); private void* getHelperFtn(CorInfoHelpFunc ftnNum, ref void* ppIndirection) { ISymbolNode entryPoint; if (!_helperCache.TryGetValue(ftnNum, out entryPoint)) { entryPoint = GetHelperFtnUncached(ftnNum); _helperCache.Add(ftnNum, entryPoint); } if (entryPoint.RepresentsIndirectionCell) { ppIndirection = (void*)ObjectToHandle(entryPoint); return null; } else { ppIndirection = null; return (void*)ObjectToHandle(entryPoint); } } private void getFunctionFixedEntryPoint(CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult) { throw new NotImplementedException("getFunctionFixedEntryPoint"); } private CorInfoHelpFunc getLazyStringLiteralHelper(CORINFO_MODULE_STRUCT_* handle) { // TODO: Lazy string literal helper return CorInfoHelpFunc.CORINFO_HELP_UNDEF; } private CORINFO_MODULE_STRUCT_* embedModuleHandle(CORINFO_MODULE_STRUCT_* handle, ref void* ppIndirection) { throw new NotImplementedException("embedModuleHandle"); } private CORINFO_CLASS_STRUCT_* embedClassHandle(CORINFO_CLASS_STRUCT_* handle, ref void* ppIndirection) { throw new NotImplementedException("embedClassHandle"); } private CORINFO_FIELD_STRUCT_* embedFieldHandle(CORINFO_FIELD_STRUCT_* handle, ref void* ppIndirection) { throw new NotImplementedException("embedFieldHandle"); } private CORINFO_RUNTIME_LOOKUP_KIND GetGenericRuntimeLookupKind(MethodDesc method) { if (method.RequiresInstMethodDescArg()) return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_METHODPARAM; else if (method.RequiresInstMethodTableArg()) return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_CLASSPARAM; else { Debug.Assert(method.AcquiresInstMethodTableFromThis()); return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_THISOBJ; } } private void getLocationOfThisType(out CORINFO_LOOKUP_KIND result, CORINFO_METHOD_STRUCT_* context) { result = new CORINFO_LOOKUP_KIND(); MethodDesc method = HandleToObject(context); if (method.IsSharedByGenericInstantiations) { result.needsRuntimeLookup = true; result.runtimeLookupKind = GetGenericRuntimeLookupKind(method); } else { result.needsRuntimeLookup = false; result.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_THISOBJ; } } private void* getPInvokeUnmanagedTarget(CORINFO_METHOD_STRUCT_* method, ref void* ppIndirection) { throw new NotImplementedException("getPInvokeUnmanagedTarget"); } private void* getAddressOfPInvokeFixup(CORINFO_METHOD_STRUCT_* method, ref void* ppIndirection) { throw new NotImplementedException("getAddressOfPInvokeFixup"); } private void* GetCookieForPInvokeCalliSig(CORINFO_SIG_INFO* szMetaSig, ref void* ppIndirection) { throw new NotImplementedException("GetCookieForPInvokeCalliSig"); } private CORINFO_JUST_MY_CODE_HANDLE_* getJustMyCodeHandle(CORINFO_METHOD_STRUCT_* method, ref CORINFO_JUST_MY_CODE_HANDLE_* ppIndirection) { ppIndirection = null; return null; } private void GetProfilingHandle(ref bool pbHookFunction, ref void* pProfilerHandle, ref bool pbIndirectedHandles) { throw new NotImplementedException("GetProfilingHandle"); } /// <summary> /// Create a CORINFO_CONST_LOOKUP to a symbol and put the address into the addr field /// </summary> private CORINFO_CONST_LOOKUP CreateConstLookupToSymbol(ISymbolNode symbol) { CORINFO_CONST_LOOKUP constLookup = new CORINFO_CONST_LOOKUP(); constLookup.addr = (void*)ObjectToHandle(symbol); constLookup.accessType = symbol.RepresentsIndirectionCell ? InfoAccessType.IAT_PVALUE : InfoAccessType.IAT_VALUE; return constLookup; } private bool canAccessFamily(CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType) { throw new NotImplementedException("canAccessFamily"); } private bool isRIDClassDomainID(CORINFO_CLASS_STRUCT_* cls) { throw new NotImplementedException("isRIDClassDomainID"); } private uint getClassDomainID(CORINFO_CLASS_STRUCT_* cls, ref void* ppIndirection) { throw new NotImplementedException("getClassDomainID"); } private void* getFieldAddress(CORINFO_FIELD_STRUCT_* field, void** ppIndirection) { FieldDesc fieldDesc = HandleToObject(field); Debug.Assert(fieldDesc.HasRva); ISymbolNode node = _compilation.GetFieldRvaData(fieldDesc); void *handle = (void *)ObjectToHandle(node); if (node.RepresentsIndirectionCell) { *ppIndirection = handle; return null; } else { if (ppIndirection != null) *ppIndirection = null; return handle; } } private CORINFO_CLASS_STRUCT_* getStaticFieldCurrentClass(CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative) { if (pIsSpeculative != null) *pIsSpeculative = 1; return null; } private IntPtr getVarArgsHandle(CORINFO_SIG_INFO* pSig, ref void* ppIndirection) { throw new NotImplementedException("getVarArgsHandle"); } private bool canGetVarArgsHandle(CORINFO_SIG_INFO* pSig) { throw new NotImplementedException("canGetVarArgsHandle"); } private InfoAccessType emptyStringLiteral(ref void* ppValue) { return constructStringLiteral(_methodScope, (mdToken)CorTokenType.mdtString, ref ppValue); } private uint getFieldThreadLocalStoreID(CORINFO_FIELD_STRUCT_* field, ref void* ppIndirection) { throw new NotImplementedException("getFieldThreadLocalStoreID"); } private void setOverride(IntPtr pOverride, CORINFO_METHOD_STRUCT_* currentMethod) { throw new NotImplementedException("setOverride"); } private void addActiveDependency(CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo) { throw new NotImplementedException("addActiveDependency"); } private CORINFO_METHOD_STRUCT_* GetDelegateCtor(CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, ref DelegateCtorArgs pCtorData) { throw new NotImplementedException("GetDelegateCtor"); } private void MethodCompileComplete(CORINFO_METHOD_STRUCT_* methHnd) { throw new NotImplementedException("MethodCompileComplete"); } private void* getTailCallCopyArgsThunk(CORINFO_SIG_INFO* pSig, CorInfoHelperTailCallSpecialHandling flags) { // Slow tailcalls are not supported yet // https://github.com/dotnet/corert/issues/1683 return null; } private void* getMemoryManager() { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. Debug.Fail("CorInfoImpl.getMemoryManager should not be called"); throw new NotSupportedException("getMemoryManager"); } private byte[] _code; private byte[] _coldCode; private byte[] _roData; private BlobNode _roDataBlob; private int _numFrameInfos; private int _usedFrameInfos; private FrameInfo[] _frameInfos; private byte[] _gcInfo; private CORINFO_EH_CLAUSE[] _ehClauses; private void allocMem(uint hotCodeSize, uint coldCodeSize, uint roDataSize, uint xcptnsCount, CorJitAllocMemFlag flag, ref void* hotCodeBlock, ref void* coldCodeBlock, ref void* roDataBlock) { hotCodeBlock = (void*)GetPin(_code = new byte[hotCodeSize]); if (coldCodeSize != 0) coldCodeBlock = (void*)GetPin(_coldCode = new byte[coldCodeSize]); if (roDataSize != 0) { int alignment = 8; if ((flag & CorJitAllocMemFlag.CORJIT_ALLOCMEM_FLG_RODATA_16BYTE_ALIGN) != 0) { alignment = 16; } else if (roDataSize < 8) { alignment = PointerSize; } _roData = new byte[roDataSize]; _roDataBlob = _compilation.NodeFactory.ReadOnlyDataBlob( "__readonlydata_" + _compilation.NameMangler.GetMangledMethodName(MethodBeingCompiled), _roData, alignment); roDataBlock = (void*)GetPin(_roData); } if (_numFrameInfos > 0) { _frameInfos = new FrameInfo[_numFrameInfos]; } } private void reserveUnwindInfo(bool isFunclet, bool isColdCode, uint unwindSize) { _numFrameInfos++; } private void allocUnwindInfo(byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) { Debug.Assert(FrameInfoFlags.Filter == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_FILTER); Debug.Assert(FrameInfoFlags.Handler == (FrameInfoFlags)CorJitFuncKind.CORJIT_FUNC_HANDLER); FrameInfoFlags flags = (FrameInfoFlags)funcKind; if (funcKind == CorJitFuncKind.CORJIT_FUNC_ROOT) { if (this.MethodBeingCompiled.IsNativeCallable) flags |= FrameInfoFlags.ReversePInvoke; } byte[] blobData = new byte[unwindSize]; for (uint i = 0; i < unwindSize; i++) { blobData[i] = pUnwindBlock[i]; } _frameInfos[_usedFrameInfos++] = new FrameInfo(flags, (int)startOffset, (int)endOffset, blobData); } private void* allocGCInfo(UIntPtr size) { _gcInfo = new byte[(int)size]; return (void*)GetPin(_gcInfo); } private void yieldExecution() { // Nothing to do } private bool logMsg(uint level, byte* fmt, IntPtr args) { // Console.WriteLine(Marshal.PtrToStringAnsi((IntPtr)fmt)); return false; } private int doAssert(byte* szFile, int iLine, byte* szExpr) { Log.WriteLine(Marshal.PtrToStringAnsi((IntPtr)szFile) + ":" + iLine); Log.WriteLine(Marshal.PtrToStringAnsi((IntPtr)szExpr)); return 1; } private void reportFatalError(CorJitResult result) { // We could add some logging here, but for now it's unnecessary. // CompileMethod is going to fail with this CorJitResult anyway. } private void recordCallSite(uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle) { } private ArrayBuilder<Relocation> _relocs; /// <summary> /// Various type of block. /// </summary> public enum BlockType : sbyte { /// <summary>Not a generated block.</summary> Unknown = -1, /// <summary>Represent code.</summary> Code = 0, /// <summary>Represent cold code (i.e. code not called frequently).</summary> ColdCode = 1, /// <summary>Read-only data.</summary> ROData = 2, /// <summary>Instrumented Block Count Data</summary> BBCounts = 3 } private BlockType findKnownBlock(void* location, out int offset) { fixed (byte* pCode = _code) { if (pCode <= (byte*)location && (byte*)location < pCode + _code.Length) { offset = (int)((byte*)location - pCode); return BlockType.Code; } } if (_coldCode != null) { fixed (byte* pColdCode = _coldCode) { if (pColdCode <= (byte*)location && (byte*)location < pColdCode + _coldCode.Length) { offset = (int)((byte*)location - pColdCode); return BlockType.ColdCode; } } } if (_roData != null) { fixed (byte* pROData = _roData) { if (pROData <= (byte*)location && (byte*)location < pROData + _roData.Length) { offset = (int)((byte*)location - pROData); return BlockType.ROData; } } } { BlockType retBlockType = BlockType.Unknown; offset = 0; findKnownBBCountBlock(ref retBlockType, location, ref offset); if (retBlockType == BlockType.BBCounts) return retBlockType; } offset = 0; return BlockType.Unknown; } partial void findKnownBBCountBlock(ref BlockType blockType, void* location, ref int offset); // Translates relocation type constants used by JIT (defined in winnt.h) to RelocType enumeration private static RelocType GetRelocType(TargetArchitecture targetArchitecture, ushort fRelocType) { if (targetArchitecture != TargetArchitecture.ARM64) return (RelocType)fRelocType; const ushort IMAGE_REL_ARM64_PAGEBASE_REL21 = 4; const ushort IMAGE_REL_ARM64_PAGEOFFSET_12A = 6; switch (fRelocType) { case IMAGE_REL_ARM64_PAGEBASE_REL21: return RelocType.IMAGE_REL_BASED_ARM64_PAGEBASE_REL21; case IMAGE_REL_ARM64_PAGEOFFSET_12A: return RelocType.IMAGE_REL_BASED_ARM64_PAGEOFFSET_12A; default: Debug.Fail("Invalid RelocType: " + fRelocType); return 0; }; } private void recordRelocation(void* location, void* target, ushort fRelocType, ushort slotNum, int addlDelta) { // slotNum is not used Debug.Assert(slotNum == 0); int relocOffset; BlockType locationBlock = findKnownBlock(location, out relocOffset); Debug.Assert(locationBlock != BlockType.Unknown, "BlockType.Unknown not expected"); TargetArchitecture targetArchitecture = _compilation.TypeSystemContext.Target.Architecture; if (locationBlock != BlockType.Code) { // TODO: https://github.com/dotnet/corert/issues/3877 if (targetArchitecture == TargetArchitecture.ARM) return; throw new NotImplementedException("Arbitrary relocs"); } int relocDelta; BlockType targetBlock = findKnownBlock(target, out relocDelta); ISymbolNode relocTarget; switch (targetBlock) { case BlockType.Code: relocTarget = _methodCodeNode; break; case BlockType.ColdCode: // TODO: Arbitrary relocs throw new NotImplementedException("ColdCode relocs"); case BlockType.ROData: relocTarget = _roDataBlob; break; #if READYTORUN case BlockType.BBCounts: relocTarget = _profileDataNode; break; #endif default: // Reloc points to something outside of the generated blocks var targetObject = HandleToObject((IntPtr)target); relocTarget = (ISymbolNode)targetObject; break; } relocDelta += addlDelta; RelocType relocType = GetRelocType(targetArchitecture, fRelocType); // relocDelta is stored as the value Relocation.WriteValue(relocType, location, relocDelta); if (_relocs.Count == 0) _relocs.EnsureCapacity(_code.Length / 32 + 1); _relocs.Add(new Relocation(relocType, relocOffset, relocTarget)); } private ushort getRelocTypeHint(void* target) { switch (_compilation.TypeSystemContext.Target.Architecture) { case TargetArchitecture.X64: return (ushort)ILCompiler.DependencyAnalysis.RelocType.IMAGE_REL_BASED_REL32; case TargetArchitecture.ARM: return (ushort)ILCompiler.DependencyAnalysis.RelocType.IMAGE_REL_BASED_THUMB_BRANCH24; default: return UInt16.MaxValue; } } private void getModuleNativeEntryPointRange(ref void* pStart, ref void* pEnd) { throw new NotImplementedException("getModuleNativeEntryPointRange"); } private uint getExpectedTargetArchitecture() { TargetArchitecture arch = _compilation.TypeSystemContext.Target.Architecture; switch (arch) { case TargetArchitecture.X86: return (uint)ImageFileMachine.I386; case TargetArchitecture.X64: return (uint)ImageFileMachine.AMD64; case TargetArchitecture.ARM: return (uint)ImageFileMachine.ARM; case TargetArchitecture.ARM64: return (uint)ImageFileMachine.ARM64; default: throw new NotImplementedException("Expected target architecture is not supported"); } } private bool isMethodDefinedInCoreLib() { TypeDesc owningType = MethodBeingCompiled.OwningType; MetadataType owningMetadataType = owningType as MetadataType; if (owningMetadataType == null) { return false; } return owningMetadataType.Module == _compilation.TypeSystemContext.SystemModule; } private uint getJitFlags(ref CORJIT_FLAGS flags, uint sizeInBytes) { // Read the user-defined configuration options. foreach (var flag in JitConfigProvider.Instance.Flags) flags.Set(flag); // Set the rest of the flags that don't make sense to expose publically. flags.Set(CorJitFlag.CORJIT_FLAG_SKIP_VERIFICATION); flags.Set(CorJitFlag.CORJIT_FLAG_READYTORUN); flags.Set(CorJitFlag.CORJIT_FLAG_RELOC); flags.Set(CorJitFlag.CORJIT_FLAG_PREJIT); flags.Set(CorJitFlag.CORJIT_FLAG_USE_PINVOKE_HELPERS); if ((_compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.X86 || _compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.X64) #if READYTORUN && isMethodDefinedInCoreLib() #endif ) { // This list needs to match the list of intrinsics we can generate detection code for // in HardwareIntrinsicHelpers.EmitIsSupportedIL. flags.Set(CorJitFlag.CORJIT_FLAG_USE_AES); flags.Set(CorJitFlag.CORJIT_FLAG_USE_PCLMULQDQ); flags.Set(CorJitFlag.CORJIT_FLAG_USE_SSE3); flags.Set(CorJitFlag.CORJIT_FLAG_USE_SSSE3); flags.Set(CorJitFlag.CORJIT_FLAG_USE_LZCNT); } if (this.MethodBeingCompiled.IsNativeCallable) flags.Set(CorJitFlag.CORJIT_FLAG_REVERSE_PINVOKE); if (this.MethodBeingCompiled.IsPInvoke) { flags.Set(CorJitFlag.CORJIT_FLAG_IL_STUB); } if (this.MethodBeingCompiled.IsNoOptimization) flags.Set(CorJitFlag.CORJIT_FLAG_MIN_OPT); return (uint)sizeof(CORJIT_FLAGS); } } }
40.07837
207
0.600834
[ "MIT" ]
Drawaes/runtime
src/coreclr/src/tools/Common/JitInterface/CorInfoImpl.cs
115,065
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("CH07_DependencyInjection.Tests")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("CH07_DependencyInjection.Tests")] [assembly: System.Reflection.AssemblyTitleAttribute("CH07_DependencyInjection.Tests")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
43.333333
88
0.664423
[ "MIT" ]
PacktPublishing/Clean-Code-in-C-
CH07/backup/CH07_DependencyInjection.Tests/obj/Debug/netcoreapp3.1/CH07_DependencyInjection.Tests.AssemblyInfo.cs
1,040
C#
using System.Collections.Generic; namespace AntProVue.Admin.Api.Dtos.Users { public class UserRolesApiDto<TRoleDto> { public UserRolesApiDto() { Roles = new List<TRoleDto>(); } public List<TRoleDto> Roles { get; set; } public int PageSize { get; set; } public int TotalCount { get; set; } } }
15.583333
49
0.57754
[ "MIT" ]
gnsilence/AntdPro-Vue-id4
AntProVue/src/AntProVue.Admin.Api/Dtos/Users/UserRolesApiDto.cs
374
C#
using System; using System.Collections.Generic; using Microsoft.ML; using Microsoft.ML.Transforms.TimeSeries; using System.IO; namespace Samples.Dynamic { public static class ForecastingWithConfidenceInternal { // This example creates a time series (list of Data with the i-th element // corresponding to the i-th time slot) and then does forecasting. public static void Example() { // Create a new ML context, for ML.NET operations. It can be used for // exception tracking and logging, as well as the source of randomness. var ml = new MLContext(); // Generate sample series data with a recurring pattern. var data = new List<TimeSeriesData>() { new TimeSeriesData(0), new TimeSeriesData(1), new TimeSeriesData(2), new TimeSeriesData(3), new TimeSeriesData(4), new TimeSeriesData(0), new TimeSeriesData(1), new TimeSeriesData(2), new TimeSeriesData(3), new TimeSeriesData(4), new TimeSeriesData(0), new TimeSeriesData(1), new TimeSeriesData(2), new TimeSeriesData(3), new TimeSeriesData(4), }; // Convert data to IDataView. var dataView = ml.Data.LoadFromEnumerable(data); // Setup arguments. var inputColumnName = nameof(TimeSeriesData.Value); var outputColumnName = nameof(ForecastResult.Forecast); // Instantiate the forecasting model. var model = ml.Forecasting.ForecastBySsa(outputColumnName, inputColumnName, 5, 11, data.Count, 5, confidenceLevel: 0.95f, confidenceLowerBoundColumn: "ConfidenceLowerBound", confidenceUpperBoundColumn: "ConfidenceUpperBound"); // Train. var transformer = model.Fit(dataView); // Forecast next five values. var forecastEngine = transformer.CreateTimeSeriesEngine<TimeSeriesData, ForecastResult>(ml); var forecast = forecastEngine.Predict(); PrintForecastValuesAndIntervals(forecast.Forecast, forecast .ConfidenceLowerBound, forecast.ConfidenceUpperBound); // Forecasted values: // [1.977226, 1.020494, 1.760543, 3.437509, 4.266461] // Confidence intervals: // [0.3451088 - 3.609343] [-0.7967533 - 2.83774] [-0.058467 - 3.579552] [1.61505 - 5.259968] [2.349299 - 6.183623] // Update with new observations. forecastEngine.Predict(new TimeSeriesData(0)); forecastEngine.Predict(new TimeSeriesData(0)); forecastEngine.Predict(new TimeSeriesData(0)); forecastEngine.Predict(new TimeSeriesData(0)); // Checkpoint. forecastEngine.CheckPoint(ml, "model.zip"); // Load the checkpointed model from disk. // Load the model. ITransformer modelCopy; using (var file = File.OpenRead("model.zip")) modelCopy = ml.Model.Load(file, out DataViewSchema schema); // We must create a new prediction engine from the persisted model. var forecastEngineCopy = modelCopy.CreateTimeSeriesEngine< TimeSeriesData, ForecastResult>(ml); // Forecast with the checkpointed model loaded from disk. forecast = forecastEngineCopy.Predict(); PrintForecastValuesAndIntervals(forecast.Forecast, forecast .ConfidenceLowerBound, forecast.ConfidenceUpperBound); // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795] // Confidence intervals: // [0.1592142 - 3.423448] [-0.5617217 - 3.072772] [-1.512994 - 2.125025] [-2.022905 - 1.622013] [-1.351382 - 2.482941] // Forecast with the original model(that was checkpointed to disk). forecast = forecastEngine.Predict(); PrintForecastValuesAndIntervals(forecast.Forecast, forecast.ConfidenceLowerBound, forecast.ConfidenceUpperBound); // [1.791331, 1.255525, 0.3060154, -0.200446, 0.5657795] // Confidence intervals: // [0.1592142 - 3.423448] [-0.5617217 - 3.072772] [-1.512994 - 2.125025] [-2.022905 - 1.622013] [-1.351382 - 2.482941] } static void PrintForecastValuesAndIntervals(float[] forecast, float[] confidenceIntervalLowerBounds, float[] confidenceIntervalUpperBounds) { Console.WriteLine($"Forecasted values:"); Console.WriteLine("[{0}]", string.Join(", ", forecast)); Console.WriteLine($"Confidence intervals:"); for (int index = 0; index < forecast.Length; index++) Console.Write($"[{confidenceIntervalLowerBounds[index]} -" + $" {confidenceIntervalUpperBounds[index]}] "); Console.WriteLine(); } class ForecastResult { public float[] Forecast { get; set; } public float[] ConfidenceLowerBound { get; set; } public float[] ConfidenceUpperBound { get; set; } } class TimeSeriesData { public float Value; public TimeSeriesData(float value) { Value = value; } } } }
40.035971
130
0.583468
[ "MIT" ]
1Crazymoney/machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/TimeSeries/ForecastingWithConfidenceInterval.cs
5,565
C#
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; namespace NMock { public class MockUserRepository : IUserRepository { private List<User> _users = JsonConvert.DeserializeObject<List<User>>(@" [{""id"":""1"",""createdAt"":""2019-05-06T19:32:07.034Z"",""name"":""Rosario Beier"",""avatar"":""https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg""},{""id"":""2"",""createdAt"":""2019-05-07T10:28:32.699Z"",""name"":""Rocio Gibson DVM"",""avatar"":""https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg""},{""id"":""3"",""createdAt"":""2019-05-06T17:00:24.825Z"",""name"":""Adeline Torphy"",""avatar"":""https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg""}] "); public User this[int index] => _users.FirstOrDefault(x => x.Id == index); public List<User> GetAllUsers() => _users; } }
49.888889
497
0.642539
[ "MIT" ]
guneysus/dotnet-mock-server
src/dotnet-mock-server/NMock/MockUserRepository.cs
900
C#
using System; using System.Collections.Generic; using System.Text; namespace SageOne.Entities { public class BankAccountNote : Entity<BankAccountNote> { } }
17
58
0.741176
[ "MIT" ]
gvanderberg/sageone-dotnet
src/SageOne/Entities/BankAccountNote.cs
172
C#
using System; using System.Reflection; using Hik.Communication.Mbt.Client; using Hik.Communication.Mbt.Communication; using Hik.Communication.Mbt.Communication.Messages; using Hik.Communication.Mbt.Communication.Messengers; using Hik.Communication.MbtServices.Communication; using Hik.Communication.MbtServices.Communication.Messages; namespace Hik.Communication.MbtServices.Client { /// <summary> /// Represents a service client that consumes a MBT service. /// </summary> /// <typeparam name="T">Type of service interface</typeparam> internal class MbtServiceClient<T> : IMbtServiceClient<T> where T : class { #region Public events /// <summary> /// This event is raised when client connected to server. /// </summary> public event EventHandler Connected; /// <summary> /// This event is raised when client disconnected from server. /// </summary> public event EventHandler Disconnected; #endregion #region Public properties /// <summary> /// Timeout for connecting to a server (as milliseconds). /// Default value: 15 seconds (15000 ms). /// </summary> public int ConnectTimeout { get { return _client.ConnectTimeout; } set { _client.ConnectTimeout = value; } } /// <summary> /// Gets the current communication state. /// </summary> public CommunicationStates CommunicationState { get { return _client.CommunicationState; } } /// <summary> /// Reference to the service proxy to invoke remote service methods. /// </summary> public T ServiceProxy { get; private set; } /// <summary> /// Timeout value when invoking a service method. /// If timeout occurs before end of remote method call, an exception is thrown. /// Use -1 for no timeout (wait indefinite). /// Default value: 60000 (1 minute). /// </summary> public int Timeout { get { return _requestReplyMessenger.Timeout; } set { _requestReplyMessenger.Timeout = value; } } #endregion #region Private fields /// <summary> /// Underlying IMbtClient object to communicate with server. /// </summary> private readonly IMbtClient _client; /// <summary> /// Messenger object to send/receive messages over _client. /// </summary> private readonly RequestReplyMessenger<IMbtClient> _requestReplyMessenger; /// <summary> /// This object is used to create a transparent proxy to invoke remote methods on server. /// </summary> private readonly AutoConnectRemoteInvokeProxy<T, IMbtClient> _realServiceProxy; /// <summary> /// The client object that is used to call method invokes in client side. /// May be null if client has no methods to be invoked by server. /// </summary> private readonly object _clientObject; #endregion #region Constructor /// <summary> /// Creates a new MbtServiceClient object. /// </summary> /// <param name="client">Underlying IMbtClient object to communicate with server</param> /// <param name="clientObject">The client object that is used to call method invokes in client side. /// May be null if client has no methods to be invoked by server.</param> public MbtServiceClient(IMbtClient client, object clientObject) { _client = client; _clientObject = clientObject; _client.Connected += Client_Connected; _client.Disconnected += Client_Disconnected; _requestReplyMessenger = new RequestReplyMessenger<IMbtClient>(client); _requestReplyMessenger.MessageReceived += RequestReplyMessenger_MessageReceived; _realServiceProxy = new AutoConnectRemoteInvokeProxy<T, IMbtClient>(_requestReplyMessenger, this); ServiceProxy = (T)_realServiceProxy.GetTransparentProxy(); } #endregion #region Public methods /// <summary> /// Connects to server. /// </summary> public void Connect() { _client.Connect(); } /// <summary> /// Disconnects from server. /// Does nothing if already disconnected. /// </summary> public void Disconnect() { _client.Disconnect(); } /// <summary> /// Calls Disconnect method. /// </summary> public void Dispose() { Disconnect(); } #endregion #region Private methods /// <summary> /// Handles MessageReceived event of messenger. /// It gets messages from server and invokes appropriate method. /// </summary> /// <param name="sender">Source of event</param> /// <param name="e">Event arguments</param> private void RequestReplyMessenger_MessageReceived(object sender, MessageEventArgs e) { //Cast message to MbtRemoteInvokeMessage and check it var invokeMessage = e.Message as MbtRemoteInvokeMessage; if (invokeMessage == null) { return; } //Check client object. if (_clientObject == null) { SendInvokeResponse(invokeMessage, null, new MbtRemoteException("Client does not wait for method invocations by server.")); return; } //Invoke method object returnValue; try { var type = _clientObject.GetType(); var method = type.GetMethod(invokeMessage.MethodName); returnValue = method.Invoke(_clientObject, invokeMessage.Parameters); } catch (TargetInvocationException ex) { var innerEx = ex.InnerException; SendInvokeResponse(invokeMessage, null, new MbtRemoteException(innerEx.Message, innerEx)); return; } catch (Exception ex) { SendInvokeResponse(invokeMessage, null, new MbtRemoteException(ex.Message, ex)); return; } //Send return value SendInvokeResponse(invokeMessage, returnValue, null); } /// <summary> /// Sends response to the remote application that invoked a service method. /// </summary> /// <param name="requestMessage">Request message</param> /// <param name="returnValue">Return value to send</param> /// <param name="exception">Exception to send</param> private void SendInvokeResponse(IMbtMessage requestMessage, object returnValue, MbtRemoteException exception) { try { _requestReplyMessenger.SendMessage( new MbtRemoteInvokeReturnMessage { RepliedMessageId = requestMessage.MessageId, ReturnValue = returnValue, RemoteException = exception }); } catch (Exception ex) { System.Diagnostics.Trace.Write($"SendInvokeResponse: {ex}"); } } /// <summary> /// Handles Connected event of _client object. /// </summary> /// <param name="sender">Source of object</param> /// <param name="e">Event arguments</param> private void Client_Connected(object sender, EventArgs e) { _requestReplyMessenger.Start(); OnConnected(); } /// <summary> /// Handles Disconnected event of _client object. /// </summary> /// <param name="sender">Source of object</param> /// <param name="e">Event arguments</param> private void Client_Disconnected(object sender, EventArgs e) { _requestReplyMessenger.Stop(); OnDisconnected(); } #endregion #region Private methods /// <summary> /// Raises Connected event. /// </summary> private void OnConnected() { var handler = Connected; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Raises Disconnected event. /// </summary> private void OnDisconnected() { var handler = Disconnected; if (handler != null) { handler(this, EventArgs.Empty); } } #endregion } }
32.587591
138
0.568597
[ "MIT" ]
majidbigdeli/MBT
src/Mbt/Communication/MbtServices/Client/MbtServiceClient.cs
8,931
C#
using System.Collections.Generic; using System.Linq; using FormEditor.Fields.Statistics; using Newtonsoft.Json; using Umbraco.Core.Models; namespace FormEditor.Fields { public abstract class FieldWithFieldValues : FieldWithMandatoryValidation, IValueFrequencyStatisticsField { public FieldValue[] FieldValues { get; set; } protected internal override void CollectSubmittedValue(Dictionary<string, string> allSubmittedValues, IPublishedContent content) { base.CollectSubmittedValue(allSubmittedValues, content); if(string.IsNullOrEmpty(SubmittedValue)) { return; } if(SubmittedValue.StartsWith("[\"") && SubmittedValue.EndsWith("\"]")) { // #168: if the submitted value is a JSON string array, parse it to the expected CSV format SubmittedValue = string.Join(",", JsonConvert.DeserializeObject<string[]>(SubmittedValue)); } } protected internal override bool ValidateSubmittedValue(IEnumerable<Field> allCollectedValues, IPublishedContent content) { if(base.ValidateSubmittedValue(allCollectedValues, content) == false) { return false; } if(string.IsNullOrEmpty(SubmittedValue)) { // nothing selected => valid (mandatory validation is handled by base class) return true; } var submittedFieldValues = ExtractSubmittedValues(); FieldValues.ToList().ForEach(f => f.Selected = submittedFieldValues.Contains(f.Value)); // make sure all submitted values are actually defined as a field value (maybe some schmuck tampered with the options client side) if (submittedFieldValues.Any()) { return submittedFieldValues.All(v => FieldValues.Any(f => f.Value == v)); } return true; } public virtual bool IsMultiSelectEnabled => false; [JsonIgnore] public IEnumerable<string> SubmittedValues => ExtractSubmittedValues(); private string[] ExtractSubmittedValues() { return SubmittedValue != null ? IsMultiSelectEnabled ? SubmittedValue.Split(',') : new[] {SubmittedValue} : new string[] {}; } public virtual bool MultipleValuesPerEntry => IsMultiSelectEnabled; } }
31.328358
133
0.737018
[ "MIT" ]
generike/FormEditor
Source/Solution/FormEditor/Fields/FieldWithFieldValues.cs
2,101
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ContainerRegistry { /// <summary> /// An object that represents a connected registry for a container registry. /// API Version: 2020-11-01-preview. /// </summary> [AzureNextGenResourceType("azure-nextgen:containerregistry:ConnectedRegistry")] public partial class ConnectedRegistry : Pulumi.CustomResource { /// <summary> /// The activation properties of the connected registry. /// </summary> [Output("activation")] public Output<Outputs.ActivationPropertiesResponse> Activation { get; private set; } = null!; /// <summary> /// The list of the ACR token resource IDs used to authenticate clients to the connected registry. /// </summary> [Output("clientTokenIds")] public Output<ImmutableArray<string>> ClientTokenIds { get; private set; } = null!; /// <summary> /// The current connection state of the connected registry. /// </summary> [Output("connectionState")] public Output<string> ConnectionState { get; private set; } = null!; /// <summary> /// The last activity time of the connected registry. /// </summary> [Output("lastActivityTime")] public Output<string> LastActivityTime { get; private set; } = null!; /// <summary> /// The logging properties of the connected registry. /// </summary> [Output("logging")] public Output<Outputs.LoggingPropertiesResponse?> Logging { get; private set; } = null!; /// <summary> /// The login server properties of the connected registry. /// </summary> [Output("loginServer")] public Output<Outputs.LoginServerPropertiesResponse?> LoginServer { get; private set; } = null!; /// <summary> /// The mode of the connected registry resource that indicates the permissions of the registry. /// </summary> [Output("mode")] public Output<string> Mode { get; private set; } = null!; /// <summary> /// The name of the resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The parent of the connected registry. /// </summary> [Output("parent")] public Output<Outputs.ParentPropertiesResponse> Parent { get; private set; } = null!; /// <summary> /// Provisioning state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The list of current statuses of the connected registry. /// </summary> [Output("statusDetails")] public Output<ImmutableArray<Outputs.StatusDetailPropertiesResponse>> StatusDetails { get; private set; } = null!; /// <summary> /// Metadata pertaining to creation and last modification of the resource. /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// The type of the resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The current version of ACR runtime on the connected registry. /// </summary> [Output("version")] public Output<string> Version { get; private set; } = null!; /// <summary> /// Create a ConnectedRegistry resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ConnectedRegistry(string name, ConnectedRegistryArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:containerregistry:ConnectedRegistry", name, args ?? new ConnectedRegistryArgs(), MakeResourceOptions(options, "")) { } private ConnectedRegistry(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:containerregistry:ConnectedRegistry", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:containerregistry/v20201101preview:ConnectedRegistry"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ConnectedRegistry resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ConnectedRegistry Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ConnectedRegistry(name, id, options); } } public sealed class ConnectedRegistryArgs : Pulumi.ResourceArgs { [Input("clientTokenIds")] private InputList<string>? _clientTokenIds; /// <summary> /// The list of the ACR token resource IDs used to authenticate clients to the connected registry. /// </summary> public InputList<string> ClientTokenIds { get => _clientTokenIds ?? (_clientTokenIds = new InputList<string>()); set => _clientTokenIds = value; } /// <summary> /// The name of the connected registry. /// </summary> [Input("connectedRegistryName")] public Input<string>? ConnectedRegistryName { get; set; } /// <summary> /// The logging properties of the connected registry. /// </summary> [Input("logging")] public Input<Inputs.LoggingPropertiesArgs>? Logging { get; set; } /// <summary> /// The mode of the connected registry resource that indicates the permissions of the registry. /// </summary> [Input("mode", required: true)] public InputUnion<string, Pulumi.AzureNextGen.ContainerRegistry.ConnectedRegistryMode> Mode { get; set; } = null!; /// <summary> /// The parent of the connected registry. /// </summary> [Input("parent", required: true)] public Input<Inputs.ParentPropertiesArgs> Parent { get; set; } = null!; /// <summary> /// The name of the container registry. /// </summary> [Input("registryName", required: true)] public Input<string> RegistryName { get; set; } = null!; /// <summary> /// The name of the resource group to which the container registry belongs. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public ConnectedRegistryArgs() { } } }
39.902439
148
0.607457
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ContainerRegistry/ConnectedRegistry.cs
8,180
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PieceScript : MonoBehaviour { public int ID; public bool enemy; public GameObject SFX; public GameObject evolveSound; public GameObject mergeSound; public GameObject particle; Ray ray; Ray moveRay; Ray touchRay; Ray moveTouchRay; RaycastHit hit; RaycastHit moveHit; RaycastHit touchHit; RaycastHit touchMovehit; public LayerMask moveMask; public GameObject evolutionTarget; public GameObject moveOptions; public bool selected; public List<Vector3> path; public List<bool> reachedPath; public float selectedOffset; public bool pathFound; bool executeOnce; public float lerpTime; public static float moveVelocity; public static bool willSmooth; Vector3 zeroVel = Vector3.zero; public float marginOfError; public float mergeTime = 0.5F; public MaterialScript materialScript; public GameObject selectLight; // Start is called before the first frame update void Start() { materialScript = transform.GetChild(0).GetComponent<MaterialScript>(); GameDataManager.saveGame = true; } // Update is called once per frame void Update() { if (!enemy) { if (selected && !pathFound) { moveOptions.SetActive(true); selectLight.SetActive(true); if (materialScript != null) materialScript.selected = true; } else { moveOptions.SetActive(false); selectLight.SetActive(false); if (materialScript != null) materialScript.selected = false; } ray = Camera.main.ScreenPointToRay(Input.mousePosition); moveRay = Camera.main.ScreenPointToRay(Input.mousePosition); //Touch input if (SpawnScript.touchInput && Input.touchCount > 0) { touchRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); moveTouchRay = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); if (Input.touchCount == 1) { if (Physics.Raycast(moveTouchRay, out touchMovehit, 100f, moveMask) && selected) { if (touchMovehit.collider.CompareTag("MoveOption")) { if (touchMovehit.collider.gameObject.GetComponent<MoveOptions>().isActive) { if (!pathFound) { path[0] = (transform.position + Vector3.up * selectedOffset); path[1] = (touchMovehit.collider.transform.position + Vector3.up * selectedOffset); path[2] = (touchMovehit.collider.transform.position); pathFound = true; } } else if (selected && !pathFound) { selected = false; SpawnScript.hasSelected = false; } } else if (selected && !pathFound) { selected = false; SpawnScript.hasSelected = false; } } } else if (Physics.Raycast(touchRay, out moveHit) && !SpawnScript.hasSelected) { if (moveHit.collider.gameObject == gameObject.transform.GetChild(0).gameObject || moveHit.collider.gameObject == gameObject.transform.GetChild(1).gameObject) { selected = true; if (SFX != null) Instantiate(SFX, transform.position, transform.rotation); CameraScript.camTarget = gameObject; SpawnScript.hasSelected = true; } else { selected = false; SpawnScript.hasSelected = false; } } else if (selected && SpawnScript.hasSelected) { selected = false; SpawnScript.hasSelected = false; } } //Normal input else if (Input.GetMouseButtonDown(0)) { if (Physics.Raycast(moveRay, out moveHit, 100f, moveMask) && selected) { if (moveHit.collider.CompareTag("MoveOption")) { if (moveHit.collider.gameObject.GetComponent<MoveOptions>().isActive) { if (!pathFound) { path[0] = (transform.position + Vector3.up * selectedOffset); path[1] = (moveHit.collider.transform.position + Vector3.up * selectedOffset); path[2] = (moveHit.collider.transform.position); pathFound = true; } } else if (selected && !pathFound) { selected = false; SpawnScript.hasSelected = false; } } else if (selected && !pathFound) { selected = false; SpawnScript.hasSelected = false; } } else if (Physics.Raycast(ray, out hit) && !SpawnScript.hasSelected && !SpawnScript.isMoving) { if (hit.collider.transform.IsChildOf(transform)) // if (hit.collider.gameObject == gameObject.transform.GetChild(0).gameObject || hit.collider.gameObject == gameObject.transform.GetChild(1).gameObject) { selected = true; if (SFX != null) Instantiate(SFX, transform.position, transform.rotation); CameraScript.camTarget = gameObject; SpawnScript.hasSelected = true; } else { selected = false; SpawnScript.hasSelected = false; } } else if (selected && SpawnScript.hasSelected) { selected = false; SpawnScript.hasSelected = false; } } } } private void FixedUpdate() { if (pathFound) { SpawnScript.isMoving = true; if (!reachedPath[0]) { if (!willSmooth) transform.position = Vector3.Lerp(transform.position, path[0], lerpTime); else transform.position = Vector3.SmoothDamp(transform.position, path[0], ref zeroVel, moveVelocity); if (Vector3.Distance(transform.position, path[0]) < marginOfError) { transform.position = path[0]; reachedPath[0] = true; } } else if (!reachedPath[1]) { if (!willSmooth) transform.position = Vector3.Lerp(transform.position, path[1], lerpTime); else transform.position = Vector3.SmoothDamp(transform.position, path[1], ref zeroVel, moveVelocity); if (Vector3.Distance(transform.position, path[1]) < marginOfError) { transform.position = path[1]; reachedPath[1] = true; } } else if (!reachedPath[2]) { if (!willSmooth) transform.position = Vector3.Lerp(transform.position, path[2], lerpTime); else transform.position = Vector3.SmoothDamp(transform.position, path[2], ref zeroVel, moveVelocity); if (Vector3.Distance(transform.position, path[2]) < marginOfError) { transform.position = path[2]; reachedPath[2] = true; selected = false; pathFound = false; reachedPath[0] = false; reachedPath[1] = false; reachedPath[2] = false; if (!executeOnce) { SpawnScript.createObject = true; } SpawnScript.hasSelected = false; SpawnScript.isMoving = false; } } } } /* private void OnMouseOver() { print("MOUSE"); if (Input.GetMouseButtonDown(0)) { print("MOUSECLICK"); selected = true; } }*/ private void OnTriggerEnter(Collider other) { if (ID == 1) { if (other.CompareTag("Evolve") && !executeOnce) { if (other.GetComponent<EvolveTile>().enemy && enemy) StartCoroutine("Evolve", other); else if (!other.GetComponent<EvolveTile>().enemy && !enemy) StartCoroutine("Evolve", other); } } if (other.CompareTag("Piece") && pathFound && !executeOnce) { if (other.GetComponentInParent<PieceScript>().ID == ID) StartCoroutine("Merge", other); } } IEnumerator Evolve(Collider other) { if (selected) SpawnScript.createObject = true; print("Evolve"); executeOnce = true; if (materialScript != null) materialScript.Dissolve(); yield return new WaitForSeconds(mergeTime); SpawnScript.points = SpawnScript.points + (int)Mathf.Pow(2, ID); SpawnScript.hasSelected = false; if (evolveSound != null) Instantiate(evolveSound, transform.position, transform.rotation); Instantiate(particle, transform.position, transform.rotation); Instantiate(evolutionTarget, transform.position, transform.rotation); Destroy(gameObject); } IEnumerator Merge(Collider other) { executeOnce = true; if (materialScript != null) materialScript.Dissolve(); yield return new WaitForSeconds(mergeTime); if (mergeSound != null) Instantiate(mergeSound, transform.position, transform.rotation); SpawnScript.createObject = true; SpawnScript.points = SpawnScript.points + (int)Mathf.Pow(2, ID); Instantiate(particle, transform.position, transform.rotation); Instantiate(evolutionTarget, transform.position, transform.rotation); Destroy(other.transform.parent.parent.gameObject); Destroy(gameObject); } }
39.785185
181
0.518805
[ "MIT" ]
Whalebot/NeoMatchess
Assets/Scripts/PieceScript.cs
10,744
C#
using System; using System.Globalization; using Autofac; using NUnit.Framework; using Orchard.Localization.Services; using Orchard.Services; using Orchard.Tokens.Implementation; using Orchard.Tokens.Providers; using Orchard.Localization.Models; namespace Orchard.Tokens.Tests { [TestFixture] public class DateTokenTests { private IContainer _container; private ITokenizer _tokenizer; private IClock _clock; private IDateTimeFormatProvider _dateTimeFormats; private IDateLocalizationServices _dateLocalizationServices; private IDateFormatter _dateFormatter; [SetUp] public void Init() { var builder = new ContainerBuilder(); builder.RegisterType<StubOrchardServices>().As<IOrchardServices>(); builder.RegisterType<TokenManager>().As<ITokenManager>(); builder.RegisterType<Tokenizer>().As<ITokenizer>(); builder.RegisterType<DateTokens>().As<ITokenProvider>(); builder.RegisterType<StubClock>().As<IClock>(); builder.RegisterType<StubWorkContextAccessor>().As<IWorkContextAccessor>(); builder.RegisterType<SiteCalendarSelector>().As<ICalendarSelector>(); builder.RegisterType<DefaultCalendarManager>().As<ICalendarManager>(); builder.RegisterType<CultureDateTimeFormatProvider>().As<IDateTimeFormatProvider>(); builder.RegisterType<DefaultDateFormatter>().As<IDateFormatter>(); builder.RegisterType<DefaultDateLocalizationServices>().As<IDateLocalizationServices>(); _container = builder.Build(); _tokenizer = _container.Resolve<ITokenizer>(); _clock = _container.Resolve<IClock>(); _dateTimeFormats = _container.Resolve<IDateTimeFormatProvider>(); _dateLocalizationServices = _container.Resolve<IDateLocalizationServices>(); _dateFormatter = _container.Resolve<IDateFormatter>(); } [Test] public void TestDate() { Assert.That(_tokenizer.Replace("{Date}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); Assert.That(_tokenizer.Replace("{Date}", new { Date = new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc) }), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc), new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateSince() { var date = _clock.UtcNow.AddHours(-25); Assert.That(_tokenizer.Replace("{Date.Since}", new { Date = date }), Is.EqualTo("1 day ago")); } [Test] public void TestDateShort() { Assert.That(_tokenizer.Replace("{Date.Short}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortDateTimeFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateShortDate() { Assert.That(_tokenizer.Replace("{Date.ShortDate}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortDateFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateShortTime() { Assert.That(_tokenizer.Replace("{Date.ShortTime}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortTimeFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateLong() { Assert.That(_tokenizer.Replace("{Date.Long}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongDateTimeFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateLongDate() { Assert.That(_tokenizer.Replace("{Date.LongDate}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongDateFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateLongTime() { Assert.That(_tokenizer.Replace("{Date.LongTime}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongTimeFormat, new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateFormat() { Assert.That(_tokenizer.Replace("{Date.Format:yyyyMMdd}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, "yyyyMMdd", new DateLocalizationOptions() { EnableTimeZoneConversion = false }))); } [Test] public void TestDateLocal() { Assert.That(_tokenizer.Replace("{Date.Local}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow))); Assert.That(_tokenizer.Replace("{Date.Local}", new { Date = new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc) }), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(new DateTime(1978, 11, 15, 0, 0, 0, DateTimeKind.Utc)))); } [Test] public void TestDateLocalShort() { Assert.That(_tokenizer.Replace("{Date.Local.Short}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortDateTimeFormat))); } [Test] public void TestDateLocalShortDate() { Assert.That(_tokenizer.Replace("{Date.Local.ShortDate}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortDateFormat))); } [Test] public void TestDateLocalShortTime() { Assert.That(_tokenizer.Replace("{Date.Local.ShortTime}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.ShortTimeFormat))); } [Test] public void TestDateLocalLong() { Assert.That(_tokenizer.Replace("{Date.Local.Long}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongDateTimeFormat))); } [Test] public void TestDateLocalLongDate() { Assert.That(_tokenizer.Replace("{Date.Local.LongDate}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongDateFormat))); } [Test] public void TestDateLocalLongTime() { Assert.That(_tokenizer.Replace("{Date.Local.LongTime}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, _dateTimeFormats.LongTimeFormat))); } [Test] public void TestDateLocalFormat() { Assert.That(_tokenizer.Replace("{Date.Local.Format:yyyyMMdd}", null), Is.EqualTo(_dateLocalizationServices.ConvertToLocalizedString(_clock.UtcNow, "yyyyMMdd"))); } } }
54.593985
311
0.69894
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Modules/Orchard.Tokens/Tests/DateTokenTests.cs
7,263
C#
using System; using System.Collections.Specialized; namespace com.GraphDefined.SMSApi.API.Action { public class EditField : Rest<Response.Field> { public EditField(Credentials Client, SMSAPIClient Proxy, String fieldId) : base(Client, Proxy) { FieldId = fieldId; } protected override string Resource { get { return "contacts/fields/" + FieldId; } } protected override RequestMethods Method { get { return RequestMethods.PUT; } } protected override NameValueCollection Parameters { get { var parameters = base.Parameters; if (Name != null) parameters.Add("name", Name); return parameters; } } public string FieldId { get; } public string Name; public EditField SetName(string name) { Name = name; return this; } } }
25.5
91
0.535294
[ "Apache-2.0" ]
GraphDefined/SMSAPI
smsapi/Actions/Contacts/EditField.cs
1,020
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("Features.WindowsRuntime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Features.WindowsRuntime")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
36.655172
84
0.745061
[ "MIT" ]
LTGKeithYang/CaliburnFrameworkStudy
samples/features/Features.WindowsRuntime/Properties/AssemblyInfo.cs
1,066
C#
using System.Linq; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.MultiTenancy; using AbpTemplate.Authorization; using AbpTemplate.Authorization.Roles; using AbpTemplate.Authorization.Users; namespace AbpTemplate.EntityFrameworkCore.Seed.Tenants { public class TenantRoleAndUserBuilder { private readonly AbpTemplateDbContext _context; private readonly int _tenantId; public TenantRoleAndUserBuilder(AbpTemplateDbContext context, int tenantId) { _context = context; _tenantId = tenantId; } public void Create() { CreateRolesAndUsers(); } private void CreateRolesAndUsers() { // Admin role var adminRole = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin); if (adminRole == null) { adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType<RolePermissionSetting>() .Where(p => p.TenantId == _tenantId && p.RoleId == adminRole.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new AbpTemplateAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = _tenantId, Name = permission.Name, IsGranted = true, RoleId = adminRole.Id }) ); _context.SaveChanges(); } // Admin user var adminUser = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == AbpUserBase.AdminUserName); if (adminUser == null) { adminUser = User.CreateTenantAdminUser(_tenantId, "[email protected]"); adminUser.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(adminUser, "123qwe"); adminUser.IsEmailConfirmed = true; adminUser.IsActive = true; _context.Users.Add(adminUser); _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id)); _context.SaveChanges(); // User account of admin user if (_tenantId == 1) { _context.UserAccounts.Add(new UserAccount { TenantId = _tenantId, UserId = adminUser.Id, UserName = AbpUserBase.AdminUserName, EmailAddress = adminUser.EmailAddress }); _context.SaveChanges(); } } } } }
36.776699
168
0.560982
[ "MIT" ]
aspnetboilerplate/module-zero-core-template-docker
src/AbpTemplate.EntityFrameworkCore/EntityFrameworkCore/Seed/Tenants/TenantRoleAndUserBuilder.cs
3,790
C#
using System; using System.Reflection; namespace Python.Runtime { /// <summary> /// Bundles the information required to support an indexer property. /// </summary> [Serializable] internal class Indexer { public MethodBinder GetterBinder; public MethodBinder SetterBinder; public Indexer() { GetterBinder = new MethodBinder(); SetterBinder = new MethodBinder(); } public bool CanGet { get { return GetterBinder.Count > 0; } } public bool CanSet { get { return SetterBinder.Count > 0; } } public void AddProperty(PropertyInfo pi) { MethodInfo getter = pi.GetGetMethod(true); MethodInfo setter = pi.GetSetMethod(true); if (getter != null) { GetterBinder.AddMethod(getter); } if (setter != null) { SetterBinder.AddMethod(setter); } } internal NewReference GetItem(BorrowedReference inst, BorrowedReference args) { return GetterBinder.Invoke(inst, args, null); } internal void SetItem(BorrowedReference inst, BorrowedReference args) { SetterBinder.Invoke(inst, args, null); } internal bool NeedsDefaultArgs(BorrowedReference args) { var pynargs = Runtime.PyTuple_Size(args); MethodBase[] methods = SetterBinder.GetMethods(); if (methods.Length == 0) { return false; } MethodBase mi = methods[0]; ParameterInfo[] pi = mi.GetParameters(); // need to subtract one for the value int clrnargs = pi.Length - 1; if (pynargs == clrnargs || pynargs > clrnargs) { return false; } for (var v = pynargs; v < clrnargs; v++) { if (pi[v].DefaultValue == DBNull.Value) { return false; } } return true; } /// <summary> /// This will return default arguments a new instance of a tuple. The size /// of the tuple will indicate the number of default arguments. /// </summary> /// <param name="args">This is pointing to the tuple args passed in</param> /// <returns>a new instance of the tuple containing the default args</returns> internal NewReference GetDefaultArgs(BorrowedReference args) { // if we don't need default args return empty tuple if (!NeedsDefaultArgs(args)) { return Runtime.PyTuple_New(0); } var pynargs = Runtime.PyTuple_Size(args); // Get the default arg tuple MethodBase[] methods = SetterBinder.GetMethods(); MethodBase mi = methods[0]; ParameterInfo[] pi = mi.GetParameters(); int clrnargs = pi.Length - 1; var defaultArgs = Runtime.PyTuple_New(clrnargs - pynargs); for (var i = 0; i < clrnargs - pynargs; i++) { if (pi[i + pynargs].DefaultValue == DBNull.Value) { continue; } using var arg = Converter.ToPython(pi[i + pynargs].DefaultValue, pi[i + pynargs].ParameterType); Runtime.PyTuple_SetItem(defaultArgs.Borrow(), i, arg.Steal()); } return defaultArgs; } } }
30.416667
112
0.52
[ "MIT" ]
FilamentGames/pythonnet
src/runtime/indexer.cs
3,650
C#
using fi.retorch.com.Areas.Dashboard.Code.Enums; using fi.retorch.com.Areas.Dashboard.Models; using fi.retorch.com.Areas.Legacy.Code.Base; using fi.retorch.com.Areas.Legacy.Models; using fi.retorch.com.Data; using fi.retorch.com.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace fi.retorch.com.Areas.Legacy.Controllers { public class ImportController : BaseController { // legacy user_id private bool hasUserId { get { return Request.Cookies["user_id"] != null; } } private int UserId { get { return int.Parse(Request.Cookies["user_id"].Value); } set { Response.Cookies["user_id"].Value = value.ToString(); } } // GET: Dashboard/Import public ActionResult Index() { LoginModel model = new LoginModel(); model.Authorized = hasUserId; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model) { bool isValid = false; int id = model.Validate(legacyDb); if (id > 0) { UserId = id; isValid = true; } return Json(isValid, JsonRequestBehavior.DenyGet); } public ActionResult Bookmarks() { Dictionary<int, int> results = new Dictionary<int, int>(); // import accounts and return list if (hasUserId) { LegacyBookmarkList importData = new LegacyBookmarkList(legacyDb, UserId); foreach (LegacyBookmarkModel importBookmark in importData.Items) { // create replacement BookmarkModel newBookmark = importBookmark.ConvertLegacyToModel(); // save it to db newBookmark.Save(newBookmark, db, userKey, true); // map new id to old results.Add(importBookmark.Id, newBookmark.Id); } } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } public ActionResult Categories() { int defaultGroupId = 0; Dictionary<int, int> results = new Dictionary<int, int>(); // import categories and return list if (hasUserId) { CategoryGroupModel defaultCategoryGroup = CategoryGroupModel.FindByName(db, userKey, "Household Expenses"); if (defaultCategoryGroup == null) { defaultCategoryGroup = new CategoryGroupModel(); defaultCategoryGroup.TransferType = (int)TransferTypeEnum.Expense; defaultCategoryGroup.Name = "Categories"; CategoryGroupModel.Save(defaultCategoryGroup, db, userKey, true); } defaultGroupId = defaultCategoryGroup.Id; Session["DefaultGroupId"] = defaultGroupId; LegacyCategoryList importData = new LegacyCategoryList(legacyDb, UserId); foreach (LegacyCategoryModel importCategory in importData.Items) { // create replacement CategoryModel newCategory = importCategory.ConvertLegacyToModel(defaultGroupId); // save it to db CategoryModel.Save(newCategory, db, userKey, true); // map new id to old results.Add(importCategory.Id, newCategory.Id); } Session["CategoryMappings"] = results; } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } public ActionResult Accounts() { Dictionary<int, int> results = new Dictionary<int, int>(); // import accounts and return list if (hasUserId) { LegacyAccountList importData = new LegacyAccountList(legacyDb, UserId); foreach (LegacyAccountModel importAccount in importData.Items) { // create replacement AccountModel newAccount = importAccount.ConvertLegacyToModel(db, userKey); // save it to db AccountModel.Save(newAccount, db, userKey, true, newAccount.DisplayOrder); // map new id to old results.Add(importAccount.Id, newAccount.Id); } Session["AccountMappings"] = results; } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } public ActionResult AccountCategories() { Dictionary<int, int> CategoryMappings = (Dictionary <int, int>)Session["CategoryMappings"]; Dictionary<int, int> AccountMappings = (Dictionary <int, int>)Session["AccountMappings"]; List<Tuple<int, int>> results = new List<Tuple<int, int>>(); var query = from ac in legacyDb.act_account_categories join a in legacyDb.act_accounts on ac.account_id equals a.account_id where a.user_id == UserId select ac; List<act_account_categories> actCategories = query.Distinct().ToList(); foreach (act_account_categories actCategory in actCategories) { AccountCategory data = new AccountCategory(); if (AccountMappings.Keys.Contains(actCategory.account_id) && CategoryMappings.Keys.Contains(actCategory.category_id)) { data.AccountId = AccountMappings[actCategory.account_id]; data.CategoryId = CategoryMappings[actCategory.category_id]; data.IsActive = true; db.AccountCategories.Add(data); int result = db.SaveChanges(); if (result > 0) { results.Add(new Tuple<int, int>(data.AccountId, data.CategoryId)); } } } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } public ActionResult Reminders() { int defaultCategoryId = 0; Dictionary<int, int> results = new Dictionary<int, int>(); // import Reminders and return list if (hasUserId) { Dictionary<int, int> AccountMappings = (Dictionary<int, int>)Session["AccountMappings"]; Dictionary<int, int> CategoryMappings = (Dictionary<int, int>)Session["CategoryMappings"]; CategoryModel defaultCategory = new CategoryModel(); defaultCategory.Accounts = new List<MultipleSelectModel>(); defaultCategory.GroupId = int.Parse(Session["DefaultGroupId"].ToString()); defaultCategory.Name = "Uncategorized"; defaultCategory.IsActive = true; CategoryModel.Save(defaultCategory, db, userKey, true); defaultCategoryId = defaultCategory.Id; Session["DefaultCategoryId"] = defaultCategoryId; LegacyReminderList importData = new LegacyReminderList(legacyDb, UserId); foreach (LegacyReminderModel importReminder in importData.Items) { if (AccountMappings.ContainsKey(importReminder.AccountId)) { // create replacement ReminderModel newReminder = importReminder.ConvertLegacyToModel(defaultCategoryId, AccountMappings, CategoryMappings); // save it to db ReminderModel.Save(newReminder, db, userKey, true, false); // map new id to old results.Add(importReminder.Id, newReminder.Id); } } db.SaveChanges(); } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } public ActionResult Transactions() { int defaultCategoryId = 0; Dictionary<int, int> results = new Dictionary<int, int>(); // import Transactions and return list if (hasUserId) { Dictionary<int, int> AccountMappings = (Dictionary <int, int>)Session["AccountMappings"]; Dictionary<int, int> CategoryMappings = (Dictionary<int, int>)Session["CategoryMappings"]; defaultCategoryId = (int)Session["DefaultCategoryId"]; LegacyTransactionList importData = new LegacyTransactionList(legacyDb, UserId); foreach (LegacyTransactionModel importTransaction in importData.Items) { if (AccountMappings.ContainsKey(importTransaction.AccountId)) { // create replacement TransactionModel newTransaction = importTransaction.ConvertLegacyToModel(defaultCategoryId, AccountMappings, CategoryMappings); // save it to db TransactionModel.Save(newTransaction, db, userKey, true, false); // map new id to old results.Add(importTransaction.Id, newTransaction.Id); } } db.SaveChanges(); } return Json(results.ToArray(), JsonRequestBehavior.AllowGet); } } }
37.693182
151
0.544468
[ "MIT" ]
jcbeck37/fi-retorch
fi.retorch.com/fi.retorch.com/Areas/Legacy/Controllers/ImportController.cs
9,953
C#
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; namespace VisualPosSuite.POSFrontEnd.GUI { [Flags] public enum ResizeDirection : short { None = 0, /// <summary> /// Not implemented /// </summary> West = 1, /// <summary> /// Not implemented /// </summary> North = 2, East = 4, South = 8, All = West | North | East | South } public class ResizableControl : UserControl { #region Fields private ResizeDirection _onResizeDirection; private Point _startLocation; private int _snap; private Size _dragOffset; private Point _oldLocation; private Size _oldSize; private bool _drawSizeGliph; private bool _moved; private bool _resized; private bool _isClick; private int _resizezableInTime; private bool _lockInViewPort; private bool _snapToOthers; private int _edgeSize; private ResizeDirection _direction; private bool _dragable; private readonly Timer tmrClick; #endregion #region Properties /// <summary> /// Gets or sets if the control can be dragged (moved with mouse) /// </summary> [Category("Resize"), Description("Specifies if control can be draged."), DefaultValue(true)] public virtual bool Dragable { get { return _dragable; } set { _dragable = value; } } /// <summary> /// Gets or sets the direction of resize (flags) /// </summary> [Category("Resize"), Description("Specifies direction of resize."), DefaultValue(ResizeDirection.All)] public virtual ResizeDirection Direction { get { return _direction; } set { _direction = value; } } /// <summary> /// Gets or sets the edge size of resizing /// </summary> [Category("Resize"), Description("Specifies edge size for mouse"), DefaultValue(15)] public virtual int EdgeSize { get { return _edgeSize; } set { _edgeSize = value; } } /// <summary> /// Gets or sets if the control grid of snaping (1 = no snaping). /// Value must be grater or equals than 1 /// </summary> [Category("Resize"), Description("Specifies snaping"), DefaultValue(5)] public virtual int Snap { get { return _snap; } set { if (value < 1) throw new ArgumentOutOfRangeException(@"Snap", value, @"Snap must be bigger than 0 (>=1)"); _snap = value; } } /// <summary> /// Not used (not implemented) /// </summary> [Category("Resize"), Description("Specifies snaping to other controls"), DefaultValue(false), Browsable(false)] public virtual bool SnapToOthers { get { return _snapToOthers; } set { _snapToOthers = value; } } /// <summary> /// Gets or sets if size gliph is drawed /// </summary> [Category("Resize"), Description("Specifies if the rezise gliph is drawed"), DefaultValue(true)] public virtual bool DrawSizeGliph { get { return _drawSizeGliph; } set { if (_drawSizeGliph != value) Refresh(); _drawSizeGliph = value; } } /// <summary> /// Gets or sets time after click is fired (0 means instant) /// </summary> [Category("Resize"), Description("Specifies time after click event is fired"), DefaultValue(0)] public virtual int ResizezableInTime { get { return _resizezableInTime; } set { if (value > 0) tmrClick.Interval = value; _resizezableInTime = value; } } /// <summary> /// Gets or sets if user can resize outside the parent control /// </summary> [Category("Resize"), Description("Specifies if user can resize outside the parent control"), DefaultValue(0)] public virtual bool LockInViewPort { get { return _lockInViewPort; } set { _lockInViewPort = value; } } public Size MinimumSizeForResize { get; set; } #endregion #region Overrides of Control protected override bool DoubleBuffered { get { return base.DoubleBuffered; } set { base.DoubleBuffered = value; } } #endregion #region Events /// <summary> /// Event trigered after the control was resized (not fired on Size property changed) /// </summary> [Category("Resize")] public event ControlResizeHandler AfterResize; /// <summary> /// Event trigered after the control was moved (not fired on Location property changed) /// </summary> [Category("Resize")] public event ControlMovedHandler AfterMove; /// <summary> /// Event trigered when resize starts /// </summary> [Category("Resize")] public event EventHandler BeginResize; /// <summary> /// Event trigered when drag starts /// </summary> [Category("Resize")] public event EventHandler BeginMove; #endregion #region Constructors public ResizableControl() { tmrClick = new Timer(); _dragable = true; _direction = ResizeDirection.All; _edgeSize = 15; _snap = 5; _snapToOthers = false; _drawSizeGliph = false; _resizezableInTime = 0; _lockInViewPort = true; _onResizeDirection = ResizeDirection.None; _isClick = false; base.DoubleBuffered = true; } #endregion #region Events private void tmrClick_Tick(object sender, EventArgs e) { _isClick = false; tmrClick.Stop(); } #endregion #region Overrides of UserControl protected override void OnMouseDown(MouseEventArgs e) { _moved = _resized = false; //seteaza flag-ul pentru click daca se foloseste ResizezableInTime _isClick = ResizezableInTime > 0; if (ResizezableInTime > 0) tmrClick.Start(); var mr = GetMouseDirection(e.Location); if (mr == ResizeDirection.All && Dragable) { _startLocation = e.Location; _oldLocation = Location; } if (e.Button == MouseButtons.Left && Direction != ResizeDirection.None) { if (mr == ResizeDirection.All && !Dragable) { mr = ResizeDirection.None; _dragOffset = Size.Empty; } else { _dragOffset = GetOffset(GetMouseDirection(e.Location), e.Location); _oldSize = Size; } _onResizeDirection = mr; } base.OnMouseDown(e); } protected override void OnMouseMove(MouseEventArgs e) { if (_isClick) return; if (_onResizeDirection != ResizeDirection.None) { if (_onResizeDirection == ResizeDirection.All) { if (BeginMove != null) BeginMove(this, EventArgs.Empty); MoveByMouse(e.Location); } else { if (BeginResize != null) BeginResize(this, EventArgs.Empty); ResizeByMouse(_onResizeDirection, e.Location, _dragOffset); } } if (Direction != ResizeDirection.None) { ResizeDirection mdirection = GetMouseDirection(e.Location); Cursor = HaveResizeDirection(mdirection) ? GetCursorForDirection(mdirection) : Cursors.Arrow; } base.OnMouseMove(e); } protected override void OnMouseUp(MouseEventArgs e) { if(!_isClick) if (_onResizeDirection == ResizeDirection.All && _moved) { ApplySnapOnMove(); if (AfterMove != null) AfterMove(this, new ControlMovedArgs(_oldLocation, Location)); } else if (_onResizeDirection != ResizeDirection.None && _resized) { ApplySnapResize(GetDirectionFromResizeDirection(_onResizeDirection)); if (AfterResize != null) AfterResize(this, new ControlResizedArgs(_oldSize, Size)); } _onResizeDirection = ResizeDirection.None; base.OnMouseUp(e); } protected override void OnPaint(PaintEventArgs e) { if (DrawSizeGliph && HaveResizeDirection(ResizeDirection.South | ResizeDirection.East)) { var rc = new Rectangle(Width - 16, Height - 16, 16, 16); ControlPaint.DrawSizeGrip(e.Graphics, BackColor, rc); } base.OnPaint(e); } #endregion #region Overrides of ContainerControl protected override void Dispose(bool disposing) { try { tmrClick?.Dispose(); } finally { base.Dispose(disposing); } } #endregion #region Private methods private Cursor GetCursorForDirection(ResizeDirection direction) { if (direction == ResizeDirection.None || direction == ResizeDirection.All) return Cursors.Arrow; if (HaveResizeDirection(direction, ResizeDirection.West | ResizeDirection.North) || HaveResizeDirection(direction, ResizeDirection.East | ResizeDirection.South)) return Cursors.SizeNWSE; if (HaveResizeDirection(direction, ResizeDirection.West | ResizeDirection.South) || HaveResizeDirection(direction, ResizeDirection.East | ResizeDirection.North)) return Cursors.SizeNESW; if (HaveResizeDirection(direction, ResizeDirection.North) || HaveResizeDirection(direction, ResizeDirection.South)) return Cursors.SizeNS; if (HaveResizeDirection(direction, ResizeDirection.West) || HaveResizeDirection(direction, ResizeDirection.East)) return Cursors.SizeWE; return Cursors.Arrow; } private void MoveByMouse(Point location) { Point mloffset = location - (Size)_startLocation; int mnewx = Location.X + mloffset.X; int mnewy = Location.Y + mloffset.Y; //todo snap as drag if (LockInViewPort) { if(mnewx < 0) mnewx = 0; if (mnewy < 0) mnewy = 0; if(Parent != null && Parent.Width < Width + mnewx) mnewx = Parent.Width - Width; if (Parent != null && Parent.Height < Height + mnewy) mnewy = Parent.Height - Height; } Location = new Point(mnewx, mnewy); _moved = true; } private void ResizeByMouse(ResizeDirection direction, Point location, Size offset) { if (HaveResizeDirection(direction, ResizeDirection.East | ResizeDirection.South)) if ( LockInViewPort && Parent != null && ( Parent.Width < Left + location.X + offset.Width || Parent.Height < Top + location.Y + offset.Height ) ) { Size = new Size(Math.Min(location.X + offset.Width, Parent.Width - Left), Math.Min(location.Y + offset.Height, Parent.Height - Top)); } else if (MinimumSizeForResize.Width > location.X + offset.Width || MinimumSizeForResize.Height > location.Y + offset.Height) Size = new Size(Math.Max(MinimumSizeForResize.Width, location.X + offset.Width), Math.Max(MinimumSizeForResize.Height, location.Y + offset.Height)); else Size = new Size(location.X + offset.Width, location.Y + offset.Height); else if (HaveResizeDirection(direction, ResizeDirection.West | ResizeDirection.North)) { /*var mns = new Size(location.X + offset.Width, location.Y + offset.Height); Location = Location - (Size - mns); Size = mns;//todo*/ } else if (HaveResizeDirection(direction, ResizeDirection.North | ResizeDirection.East)) { /*var mns = new Size(location.X + offset.Width, location.Y + offset.Height); Location = Location - (Size - mns); Size = mns;//todo*/ } else if (HaveResizeDirection(direction, ResizeDirection.West | ResizeDirection.South)) { /*var mns = new Size(location.X + offset.Width, location.Y + offset.Height); Location = Location - (Size - mns); Size = mns;//todo*/ } else if (HaveResizeDirection(direction, ResizeDirection.West)) { /*var mns = new Size(location.X + offset.Width, location.Y + offset.Height); Location = Location - (Size - mns); Size = mns;//todo*/ } else if (HaveResizeDirection(direction, ResizeDirection.North)) { /*var mns = new Size(location.X + offset.Width, location.Y + offset.Height); Location = Location - (Size - mns); Size = mns;//todo*/ } else if (HaveResizeDirection(direction, ResizeDirection.East)) if (LockInViewPort && Parent != null && Parent.Width < Left + location.X + offset.Width) Size = new Size(Parent.Width - Left, Height); else if (MinimumSizeForResize.Width > location.X + offset.Width) Size = new Size(Math.Max(MinimumSizeForResize.Width, location.X + offset.Width), Height); else Size = new Size(location.X + offset.Width, Height); else if (HaveResizeDirection(direction, ResizeDirection.South)) if (LockInViewPort && Parent != null && Parent.Height < Top + location.Y + offset.Height) Size = new Size(Width, Parent.Height - Top); else if (MinimumSizeForResize.Height > location.Y + offset.Height) Size = new Size(Width, Math.Max(MinimumSizeForResize.Height, location.Y + offset.Height)); else Size = new Size(Width, location.Y + offset.Height); else return; Refresh(); _resized = true; } private Size GetOffset(ResizeDirection direction, Point location) { if (HaveResizeDirection(direction, ResizeDirection.East | ResizeDirection.South)) return new Size(Width - location.X, Height - location.Y); return Size.Empty; } private ResizeDirection GetMouseDirection(Point location) { if (location.X <= EdgeSize && location.Y > EdgeSize && location.Y < Height - EdgeSize && Direction.HasFlag(ResizeDirection.West)) return ResizeDirection.West; if (location.X <= EdgeSize && location.Y <= EdgeSize && Direction.HasFlag(ResizeDirection.West | ResizeDirection.North)) return ResizeDirection.West | ResizeDirection.North; if (location.X > EdgeSize && location.Y <= EdgeSize && location.X < Width - EdgeSize && Direction.HasFlag(ResizeDirection.North)) return ResizeDirection.North; if (location.X >= Width - EdgeSize && location.Y <= EdgeSize && Direction.HasFlag(ResizeDirection.North | ResizeDirection.East)) return ResizeDirection.North | ResizeDirection.East; if (location.Y > EdgeSize && location.X >= Width - EdgeSize && location.Y < Height - EdgeSize && Direction.HasFlag(ResizeDirection.East)) return ResizeDirection.East; if (location.X >= Width - EdgeSize && location.Y >= Height - EdgeSize && Direction.HasFlag(ResizeDirection.East | ResizeDirection.South)) return ResizeDirection.East | ResizeDirection.South; if (location.X > EdgeSize && location.Y >= Height - EdgeSize && location.X < Width - EdgeSize && Direction.HasFlag(ResizeDirection.South)) return ResizeDirection.South; if (location.X <= EdgeSize && location.Y >= Height - EdgeSize && Direction.HasFlag(ResizeDirection.South | ResizeDirection.West)) return ResizeDirection.South | ResizeDirection.West; return ResizeDirection.All; } private bool HaveResizeDirection(ResizeDirection direction) { return Direction == ResizeDirection.All || HaveResizeDirection(Direction, direction); } private bool HaveResizeDirection(ResizeDirection direction, ResizeDirection have) { return direction == have || (direction & have) == have; } private bool HaveDirection(FDirection direction, FDirection have) { return direction == have || (direction & have) == have; } private FDirection GetDirectionFromResizeDirection(ResizeDirection direction) { if (direction == ResizeDirection.East || direction == ResizeDirection.West) return FDirection.Horizontal; if (direction == ResizeDirection.North || direction == ResizeDirection.South) return FDirection.Vertical; return FDirection.Both; } private void ApplySnapOnMove(FDirection direction = FDirection.Both) { int msl; if (HaveDirection(direction, FDirection.Horizontal)) { msl = Left % Snap; if (msl != 0) Left += (Snap - msl); } if (HaveDirection(direction, FDirection.Vertical)) { msl = Top % Snap; if (msl != 0) Top += (Snap - msl); } Refresh(); } private void ApplySnapResize(FDirection direction = FDirection.Both) { int msl; if (HaveDirection(direction, FDirection.Horizontal)) { msl = Width % Snap; if (msl != 0) Width += (Snap - msl); } if (HaveDirection(direction, FDirection.Vertical)) { msl = Height % Snap; if (msl != 0) Height += (Snap - msl); } Refresh(); } #endregion #region Enums [Flags] private enum FDirection : short { Vertical = 0, Horizontal = 1, Both = Vertical | Horizontal } #endregion } #region Event Args public delegate void ControlResizeHandler(object sender, ControlResizedArgs args); public delegate void ControlMovedHandler(object sender, ControlMovedArgs args); public class ControlResizedArgs : EventArgs { /// <summary> /// Gets the old size of control /// </summary> public Size OldSize { get; private set; } /// <summary> /// Gets the new size of control /// </summary> public Size NewSize { get; private set; } public ControlResizedArgs() { } public ControlResizedArgs(Size oldSize, Size newSize) { OldSize = oldSize; NewSize = newSize; } } public class ControlMovedArgs : EventArgs { /// <summary> /// Gets the old location of control /// </summary> public Point OldLocation { get; private set; } /// <summary> /// Gets the new location of control /// </summary> public Point NewLocation { get; private set; } public ControlMovedArgs() { } public ControlMovedArgs(Point oldLocation, Point newLocation) { OldLocation = oldLocation; NewLocation = newLocation; } } #endregion }
34.587879
151
0.503548
[ "MIT" ]
AbabeiAndrei/ResizableControl
ResizableControl.cs
22,830
C#
using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; namespace Patternizer { internal class RepeatStep : Step { private int _repeatCount; private Expression<Func<StepPattern, StepPattern>> _pattern; /// <summary> /// Initializes a new instance of the <see cref="RepeatStep"/> class. /// </summary> /// <param name="repeatCount">The repeat count, if > 0 then it must be an exact match. Otherwise 1-* matches is ok</param> /// <param name="pattern">Pattern.</param> public RepeatStep (int repeatCount, Expression<Func<StepPattern, StepPattern>> pattern) { _repeatCount = repeatCount; _pattern = pattern; } public override StepPatternEvaluationResult Evaluate (Point? lastStepEndPoint, List<Line> lines, StepContext context) { if (_repeatCount > 0) { throw new NotImplementedException ("Repeat count is not implemented yet"); } var preEvaluationList = new List<Line> (lines); var func = _pattern.Compile (); var isValid = false; PatternResult lastResult = null; var lastValidCount = preEvaluationList.Count; bool control = true; while (control) { if (preEvaluationList.Count == 0) { control = false; continue; } var pattern = func.Invoke (new StepPattern()); var result = pattern.Evaluate (preEvaluationList, context); if (result.IsValid) { isValid = true; lastValidCount = preEvaluationList.Count; } else { control = false; } lastResult = result; } if (isValid) { lines.RemoveRange(0, lines.Count - lastValidCount); } return new StepPatternEvaluationResult (isValid, lastResult.LastPointInPattern); } } }
27.078125
130
0.678592
[ "MIT" ]
johankson/Patternizer
src/Patternizer/RepeatStep.cs
1,733
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.ContractsLight; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using BuildXL.App.Tracing; using BuildXL.Engine; using BuildXL.Engine.Distribution; using BuildXL.Engine.Recovery; using BuildXL.FrontEnd.Factory; using BuildXL.FrontEnd.Sdk; using BuildXL.FrontEnd.Sdk.FileSystem; using BuildXL.Ide.Generator; using BuildXL.Native.IO; using BuildXL.Native.Processes; using BuildXL.Scheduler; using BuildXL.Storage; using BuildXL.ToolSupport; using BuildXL.Tracing; using BuildXL.Utilities; using BuildXL.Utilities.Configuration; using BuildXL.Utilities.Instrumentation.Common; using BuildXL.Utilities.Tracing; using BuildXL.ViewModel; using Logger = BuildXL.App.Tracing.Logger; using AppLogEventId = BuildXL.App.Tracing.LogEventId; using SchedulerLogEventId = BuildXL.Scheduler.Tracing.LogEventId; using EngineLogEventId = BuildXL.Engine.Tracing.LogEventId; using ProcessesLogEventId = BuildXL.Processes.Tracing.LogEventId; using ProcessNativeMethods = BuildXL.Native.Processes.ProcessUtilities; using TracingLogEventId = BuildXL.Tracing.LogEventId; using PipsLogEventId = BuildXL.Pips.Tracing.LogEventId; using StorageLogEventId = BuildXL.Storage.Tracing.LogEventId; using Strings = bxl.Strings; #pragma warning disable SA1649 // File name must match first type name using BuildXL.Utilities.CrashReporting; using static BuildXL.Utilities.FormattableStringEx; namespace BuildXL { /// <summary> /// Host for the BuildXL bxl.exe application. Enables special start/end behaviors such as logging details about the app host /// </summary> internal interface IAppHost { /// <summary> /// Called when the engine starts a run /// </summary> void StartRun(LoggingContext loggingContext); /// <summary> /// Called when the host ends a run /// </summary> void EndRun(LoggingContext loggingContext); /// <summary> /// Whether telemetry should be shut down after the run /// </summary> bool ShutDownTelemetryAfterRun { get; } } /// <summary> /// A single BuildXLApp will execute, and then this process will exit. /// </summary> internal sealed class SingleInstanceHost : IAppHost { /// <inheritdoc /> public void StartRun(LoggingContext loggingContext) { return; } /// <inheritdoc /> public void EndRun(LoggingContext loggingContext) { return; } /// <inheritdoc/> public bool ShutDownTelemetryAfterRun => true; } internal readonly struct AppResult { public readonly ExitKind ExitKind; public readonly ExitKind CloudBuildExitKind; public readonly EngineState EngineState; public readonly string ErrorBucket; public readonly string BucketMessage; public readonly bool KillServer; private AppResult(ExitKind exitKind, ExitKind cloudBuildExitKind, EngineState engineState, string errorBucket, string bucketMessage, bool killServer) { ExitKind = exitKind; CloudBuildExitKind = cloudBuildExitKind; EngineState = engineState; ErrorBucket = errorBucket; BucketMessage = bucketMessage; KillServer = killServer; } public static AppResult Create(ExitKind exitKind, EngineState engineState, string errorBucket, string bucketMessage = "", bool killServer = false) { return new AppResult(exitKind, exitKind, engineState, errorBucket, bucketMessage, killServer); } public static AppResult Create(ExitKind exitKind, ExitKind cloudBuildExitKind, EngineState engineState, string errorBucket, string bucketMessage = "", bool killServer = false) { return new AppResult(exitKind, cloudBuildExitKind, engineState, errorBucket, bucketMessage, killServer); } } /// <summary> /// Single instance of the BuildXL app. Corresponds to exactly one command line invocation / build. /// </summary> internal sealed class BuildXLApp : IDisposable { // We give the failure completion logic a generous 300 seconds to complete since in some cases taking a crash dump // can take quite a while private const int FailureCompletionTimeoutMs = 300 * 1000; // 24K buffer size means that internally, the StreamWriter will use 48KB for a char[] array, and 73731 bytes for an encoding byte array buffer --- all buffers <85000 bytes, and therefore are not in large object heap private const int LogFileBufferSize = 24 * 1024; private static Encoding s_utf8NoBom; private LoggingContext m_loggingContextForCrashHandler; private readonly IAppHost m_appHost; private readonly IConsole m_console; // This one is only to be used for the initial run of the engine. private readonly ICommandLineConfiguration m_initialConfiguration; // The following are not readonly because when the engine uses a cached graph these two are recomputed. private IConfiguration m_configuration; private PathTable m_pathTable; private readonly DateTime m_startTimeUtc; private readonly IReadOnlyCollection<string> m_commandLineArguments; // If server mode was requested but cannot be started, here is the reason private readonly ServerModeStatusAndPerf? m_serverModeStatusAndPerf; private static readonly BuildInfo s_buildInfo = BuildInfo.FromRunningApplication(); private static readonly MachineInfo s_machineInfo = MachineInfo.CreateForCurrentMachine(); // Cancellation request handling. private readonly CancellationTokenSource m_cancellationSource = new CancellationTokenSource(); private int m_cancellationAlreadyAttempted = 0; private LoggingContext m_appLoggingContext; private BuildViewModel m_buildViewModel; private readonly CrashCollectorMacOS m_crashCollector; // Allow a longer Aria telemetry flush time in CloudBuild since we're more willing to wait at the tail of builds there private TimeSpan TelemetryFlushTimeout => m_configuration.InCloudBuild() ? TimeSpan.FromMinutes(1) : AriaV2StaticState.DefaultShutdownTimeout; /// <nodoc /> [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope")] public BuildXLApp( IAppHost host, IConsole console, ICommandLineConfiguration initialConfig, PathTable pathTable, IReadOnlyCollection<string> commandLineArguments = null, // Pass null here if you want client to override cmd args. DateTime? startTimeUtc = null, ServerModeStatusAndPerf? serverModeStatusAndPerf = null) { Contract.RequiresNotNull(initialConfig, "initialConfig can't be null"); Contract.RequiresNotNull(pathTable, "pathTable can't be null"); Contract.RequiresNotNull(host, "host can't be null"); var mutableConfig = new BuildXL.Utilities.Configuration.Mutable.CommandLineConfiguration(initialConfig); string exeLocation = null; if (commandLineArguments != null) { exeLocation = commandLineArguments.FirstOrDefault(); // The location may come as an absolute or relative path, depending on how bxl was called from command line. // Let's make sure we always pass an absolute path if (exeLocation != null) { if (!Path.IsPathRooted(exeLocation)) { // For the relative path case, we interpret it relative to the current directory of the app exeLocation = Path.Combine(Directory.GetCurrentDirectory(), exeLocation); } } } BuildXLEngine.PopulateLoggingAndLayoutConfiguration(mutableConfig, pathTable, exeLocation); // If /debuggerBreakOnExit assume /debugScript if (mutableConfig.FrontEnd.DebuggerBreakOnExit()) { mutableConfig.FrontEnd.DebugScript = true; } // Disable graph caching if debugging if (mutableConfig.FrontEnd.DebugScript()) { mutableConfig.Cache.CacheGraph = false; mutableConfig.Engine.ReuseEngineState = false; } ConfigureDistributionLogging(pathTable, mutableConfig); ConfigureCloudBuildLogging(pathTable, mutableConfig); if (mutableConfig.Logging.CacheMissAnalysisOption.Mode != CacheMissMode.Disabled) { ConfigureCacheMissLogging(pathTable, mutableConfig); } m_configuration = mutableConfig; m_initialConfiguration = mutableConfig; if (console == null) { console = CreateStandardConsole(m_configuration.Logging, pathTable); } m_appHost = host; m_console = console; // Process start time isn't helpful if in an app server, so we allow an override. m_startTimeUtc = startTimeUtc ?? Process.GetCurrentProcess().StartTime.ToUniversalTime(); // Allow the client to override the command line that gets logged which will be different from the server m_commandLineArguments = commandLineArguments ?? AssemblyHelper.GetCommandLineArgs(); m_pathTable = pathTable; // This app was requested to be launched in server mode, but the server cannot be started // We store this to log it once the appropriate listeners are set up m_serverModeStatusAndPerf = serverModeStatusAndPerf; m_crashCollector = OperatingSystemHelper.IsMacOS ? new CrashCollectorMacOS(new[] { CrashType.BuildXL, CrashType.Kernel }) : null; m_buildViewModel = new BuildViewModel(); } private static void ConfigureCacheMissLogging(PathTable pathTable, BuildXL.Utilities.Configuration.Mutable.CommandLineConfiguration mutableConfig) { mutableConfig.Logging.CustomLog.Add( mutableConfig.Logging.CacheMissLog, (new[] { (int)SharedLogEventId.CacheMissAnalysis, (int)SharedLogEventId.CacheMissAnalysisBatchResults, (int)BuildXL.Scheduler.Tracing.LogEventId.MissingKeyWhenSavingFingerprintStore, (int)BuildXL.Scheduler.Tracing.LogEventId.FingerprintStoreSavingFailed, (int)BuildXL.Scheduler.Tracing.LogEventId.FingerprintStoreToCompareTrace, (int)BuildXL.Scheduler.Tracing.LogEventId.SuccessLoadFingerprintStoreToCompare }, null)); } private static void ConfigureDistributionLogging(PathTable pathTable, BuildXL.Utilities.Configuration.Mutable.CommandLineConfiguration mutableConfig) { if (mutableConfig.Distribution.BuildRole != DistributedBuildRoles.None) { mutableConfig.Logging.CustomLog.Add( mutableConfig.Logging.RpcLog, (DistributionHelpers.DistributionAllMessages.ToArray(), null)); } } private static void ConfigureCloudBuildLogging(PathTable pathTable, BuildXL.Utilities.Configuration.Mutable.CommandLineConfiguration mutableConfig) { if (mutableConfig.InCloudBuild()) { // Unless explicitly specified, async logging is enabled by default in CloudBuild if (!mutableConfig.Logging.EnableAsyncLogging.HasValue) { mutableConfig.Logging.EnableAsyncLogging = true; } var logPath = mutableConfig.Logging.Log; // NOTE: We rely on explicit exclusion of pip output messages in CloudBuild rather than turning them off by default. mutableConfig.Logging.CustomLog.Add( mutableConfig.Logging.PipOutputLog, (new[] { (int)ProcessesLogEventId.PipProcessOutput }, null)); mutableConfig.Logging.CustomLog.Add( mutableConfig.Logging.DevLog, (new List<int>(FrontEndControllerFactory.DevLogEvents) { // Add useful low volume-messages for dev diagnostics here (int)SharedLogEventId.DominoInvocation, (int)AppLogEventId.StartupTimestamp, (int)AppLogEventId.StartupCurrentDirectory, (int)AppLogEventId.DominoCompletion, (int)AppLogEventId.DominoPerformanceSummary, (int)AppLogEventId.DominoCatastrophicFailure, (int)TracingLogEventId.UnexpectedConditionLocal, (int)TracingLogEventId.UnexpectedConditionTelemetry, (int)SchedulerLogEventId.CriticalPathPipRecord, (int)SchedulerLogEventId.CriticalPathChain, (int)EngineLogEventId.HistoricMetadataCacheLoaded, (int)EngineLogEventId.HistoricMetadataCacheSaved, (int)EngineLogEventId.HistoricPerfDataLoaded, (int)EngineLogEventId.HistoricPerfDataSaved, (int)SchedulerLogEventId.CreateSymlinkFromSymlinkMap, (int)SchedulerLogEventId.SymlinkFileTraceMessage, (int)SharedLogEventId.StartEngineRun, (int)EngineLogEventId.StartCheckingForPipGraphReuse, (int)EngineLogEventId.EndCheckingForPipGraphReuse, (int)EngineLogEventId.GraphNotReusedDueToChangedInput, (int)EngineLogEventId.StartLoadingHistoricPerfData, (int)EngineLogEventId.EndLoadingHistoricPerfData, (int)EngineLogEventId.StartSerializingPipGraph, (int)EngineLogEventId.EndSerializingPipGraph, (int)EngineLogEventId.ScrubbingStarted, (int)EngineLogEventId.ScrubbingFinished, (int)SchedulerLogEventId.StartSchedulingPipsWithFilter, (int)SchedulerLogEventId.EndSchedulingPipsWithFilter, (int)StorageLogEventId.StartScanningJournal, (int)StorageLogEventId.EndScanningJournal, (int)EngineLogEventId.StartExecute, (int)EngineLogEventId.EndExecute, (int)SchedulerLogEventId.PipDetailedStats, (int)SchedulerLogEventId.ProcessesCacheHitStats, (int)SchedulerLogEventId.ProcessesCacheMissStats, (int)SchedulerLogEventId.ProcessesSemaphoreQueuedStats, (int)SchedulerLogEventId.CacheTransferStats, (int)SchedulerLogEventId.OutputFileStats, (int)SchedulerLogEventId.SourceFileHashingStats, (int)SchedulerLogEventId.OutputFileHashingStats, (int)SchedulerLogEventId.BuildSetCalculatorStats, (int)PipsLogEventId.EndFilterApplyTraversal, (int)SchedulerLogEventId.EndAssigningPriorities, (int)EngineLogEventId.DeserializedFile, (int)SchedulerLogEventId.PipQueueConcurrency, (int)EngineLogEventId.GrpcSettings, (int)EngineLogEventId.ChosenABTesting, (int)EngineLogEventId.SynchronouslyWaitedForCache, (int)Scheduler.Tracing.LogEventId.PipFingerprintData, (int)EngineLogEventId.DistributionWorkerChangedState, }, // all errors should be included in a dev log EventLevel.Error)); // Distribution related messages are disabled in default text log and routed to special log file mutableConfig.Logging.NoLog.AddRange(DistributionHelpers.DistributionInfoMessages); mutableConfig.Logging.NoLog.AddRange(DistributionHelpers.DistributionWarnings); // Need to route events to ETW from custom log since no log is enabled for text log // Use special distribution log kind in order to have a tag for only searching distribution // log events in Kusto. mutableConfig.Logging.CustomLogEtwKinds[mutableConfig.Logging.PipOutputLog] = "pipoutput"; } } void IDisposable.Dispose() { m_cancellationSource.Dispose(); } /// <nodoc /> public AppResult Run(EngineState engineState = null) { if (Environment.GetEnvironmentVariable("BuildXLDebugOnStart") == "1" || m_initialConfiguration.LaunchDebugger) { if (OperatingSystemHelper.IsUnixOS) { Console.WriteLine("=== Attach to this process from a debugger, then press ENTER to continue ..."); Console.ReadLine(); } else { Debugger.Launch(); } } // Get rid of any prior engine state if this build is not configured to reuse it if (!m_configuration.Engine.ReuseEngineState) { engineState?.Dispose(); engineState = null; } using (var appLoggers = new AppLoggers(m_startTimeUtc, m_console, m_configuration.Logging, m_pathTable, notWorker: m_configuration.Distribution.BuildRole != DistributedBuildRoles.Worker, buildViewModel: m_buildViewModel, // TODO: Remove this once we can add timestamps for all logs by default displayWarningErrorTime: m_configuration.InCloudBuild())) { // Mapping roots. Error is logged here to console because file logging may be set up under // the mapped path. In success case, logging of root mappings is done below to ensure it goes IReadOnlyDictionary<string, AbsolutePath> rootMappings = m_configuration.Engine.RootMap; if (rootMappings != null && rootMappings.Count != 0) { if (!(m_appHost is SingleInstanceHost)) { return RunWithLoggingScope((pm) => AppResult.Create(ExitKind.InvalidCommandLine, null, string.Empty), sendFinalStatistics: appLoggers.SendFinalStatistics); } if (!ApplyRootMappings(rootMappings)) { return RunWithLoggingScope((pm) => AppResult.Create(ExitKind.InternalError, null, "FailedToApplyRootMappings"), sendFinalStatistics: appLoggers.SendFinalStatistics); } } // Remote telemetry is also disable when a debugger is attached. The motivation is that it messes up // the statistics because typically these are error cases and the timings will be off. A second motivation // is that telemetry systems typically don't respect the guideline of not throwing exceptions in regular // execution path, so a lot of first chance exceptions are encountered from telemetry when debugging. var remoteTelemetryEnabled = m_configuration.Logging.RemoteTelemetry != RemoteTelemetry.Disabled && !Debugger.IsAttached; Stopwatch stopWatch = null; if (remoteTelemetryEnabled) { stopWatch = Stopwatch.StartNew(); AriaV2StaticState.Enable( AriaTenantToken.Key, m_configuration.Logging.LogsRootDirectory(m_pathTable).ToString(m_pathTable), TelemetryFlushTimeout); stopWatch.Stop(); } else { AriaV2StaticState.Disable(); } return RunWithLoggingScope( configureLogging: loggingContext => { appLoggers.ConfigureLogging(loggingContext); if (m_configuration.InCloudBuild()) { appLoggers.EnableEtwOutputLogging(loggingContext); } }, sendFinalStatistics: () => appLoggers.SendFinalStatistics(), run: (pm) => { if (!ProcessNativeMethods.SetupProcessDumps(m_configuration.Logging.LogsDirectory.ToString(m_pathTable), out var coreDumpDirectory)) { Logger.Log.DisplayCoreDumpDirectoryNoPermissionsWarning(pm.LoggingContext, coreDumpDirectory); } if (remoteTelemetryEnabled) { if (m_configuration.Logging.RemoteTelemetry == RemoteTelemetry.EnabledAndNotify) { Logger.Log.TelemetryEnabledNotifyUser(pm.LoggingContext, pm.LoggingContext.Session.Id); } else if (m_configuration.Logging.RemoteTelemetry == RemoteTelemetry.EnabledAndHideNotification) { Logger.Log.TelemetryEnabledHideNotification(pm.LoggingContext, pm.LoggingContext.Session.Id); } LoggingHelpers.LogCategorizedStatistic(pm.LoggingContext, Strings.TelemetryInitialization, Strings.DurationMs, (int)stopWatch.ElapsedMilliseconds); } CollectAndUploadCrashReports(pm.LoggingContext, remoteTelemetryEnabled); foreach (var mapping in rootMappings) { Logger.Log.MappedRoot(pm.LoggingContext, mapping.Key, mapping.Value.ToString(m_pathTable)); } // Start a cleanup if requested Thread logCleanupThread = null; if (m_configuration.Logging.LogsToRetain > 0) { logCleanupThread = new Thread(() => { var rootLogsDirectory = m_configuration.Logging.LogsRootDirectory(m_pathTable).ToString(m_pathTable); CleanupLogsDirectory(pm.LoggingContext, rootLogsDirectory, m_configuration.Logging.LogsToRetain); }); logCleanupThread.IsBackground = true; // Kill it if not done by the time we finish the build logCleanupThread.Priority = ThreadPriority.Lowest; logCleanupThread.Start(); } var result = RunInternal(pm, m_cancellationSource.Token, appLoggers, engineState); if (logCleanupThread != null && logCleanupThread.IsAlive) { Logger.Log.WaitingCleanupLogDir(pm.LoggingContext); logCleanupThread.Join(); } ProcessNativeMethods.TeardownProcessDumps(); return result; }); } } /// <nodoc /> private void CollectAndUploadCrashReports(LoggingContext context, bool remoteTelemetryEnabled) { if (m_crashCollector != null) { // Put the state file at the root of the logs directory var stateFileDirectory = m_configuration.Logging.LogsRootDirectory(m_pathTable).ToString(m_pathTable); CrashCollectorMacOS.Upload upload = (IReadOnlyList<CrashReport> reports, string sessionId) => { if (!remoteTelemetryEnabled) { return false; } foreach (var report in reports) { Logger.Log.DominoMacOSCrashReport(context, sessionId, report.Content, report.Type.ToString(), report.FileName); } return true; }; try { m_crashCollector.UploadCrashReportsFromLastSession(context.Session.Id, stateFileDirectory, out var stateFilePath, upload); } catch (Exception ex) { Logger.Log.DisplayCrashReportProcessingFailedWarning(context, stateFileDirectory, ex.GetLogEventMessage()); } } } /// <nodoc /> private AppResult RunInternal(PerformanceMeasurement pm, CancellationToken cancellationToken, AppLoggers appLoggers, EngineState engineState) { EngineState newEngineState = null; UnhandledExceptionEventHandler unhandledExceptionHandler = null; Action<Exception> unexpectedExceptionHandler = null; EventHandler<UnobservedTaskExceptionEventArgs> unobservedTaskHandler = null; EventHandler<FirstChanceExceptionEventArgs> firstChanceExceptionHandler = null; try { // This has a value if BuildXL was started in server mode if (m_serverModeStatusAndPerf.HasValue) { ServerModeStatusAndPerf serverModeStatusAndPerf = m_serverModeStatusAndPerf.Value; // There is always an up to date check related to starting server mode Logger.Log.DeploymentUpToDateCheckPerformed(pm.LoggingContext, serverModeStatusAndPerf.UpToDateCheck, serverModeStatusAndPerf.CacheCreated.HasValue, serverModeStatusAndPerf.CacheCreated.HasValue ? serverModeStatusAndPerf.CacheCreated.Value : default(ServerDeploymentCacheCreated)); // We maybe created a deployment cache if (serverModeStatusAndPerf.CacheCreated.HasValue) { Logger.Log.DeploymentCacheCreated(pm.LoggingContext, serverModeStatusAndPerf.CacheCreated.Value); } // The server mode maybe didn't start properly if (serverModeStatusAndPerf.ServerModeCannotStart.HasValue) { Logger.Log.CannotStartServer(pm.LoggingContext, serverModeStatusAndPerf.ServerModeCannotStart.Value); } } unhandledExceptionHandler = (sender, eventArgs) => { HandleUnhandledFailure( eventArgs.ExceptionObject as Exception, appLoggers, pm); }; unexpectedExceptionHandler = (exception) => { if (EngineEnvironmentSettings.FailFastOnNullReferenceException && exception is NullReferenceException) { // Detach unhandled exception handler. Failing fast. AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler; HandleUnhandledFailure( exception, appLoggers, pm, predefinedRootCause: ExceptionRootCause.FailFast); } }; firstChanceExceptionHandler = OnFirstChanceException; ExceptionUtilities.UnexpectedException += unexpectedExceptionHandler; AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler; AppDomain.CurrentDomain.FirstChanceException += firstChanceExceptionHandler; if (EngineEnvironmentSettings.FailFastOnCacheCriticalError) { Cache.ContentStore.Interfaces.Tracing.CriticalErrorsObserver.OnCriticalError += (sender, args) => HandleUnhandledFailure(args.CriticalException, appLoggers, pm); } unobservedTaskHandler = (sender, eventArgs) => { HandleUnhandledFailure( eventArgs.Exception, appLoggers, pm); }; TaskScheduler.UnobservedTaskException += unobservedTaskHandler; if (!OperatingSystemHelper.IsUnixOS) { // Set the execution state to prevent the machine from going to sleep for the duration of the build NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_SYSTEM_REQUIRED | NativeMethods.EXECUTION_STATE.ES_CONTINUOUS); } using (PerformanceCollector collector = CreateCounterCollectorIfEnabled(pm.LoggingContext)) { m_appHost.StartRun(pm.LoggingContext); // Initialize the resources.csv log file if it is enabled. if (m_configuration.Logging.StatusLog.IsValid) { appLoggers.ConfigureStatusLogFile(m_configuration.Logging.StatusLog); } try { Contract.Assume(m_initialConfiguration == m_configuration, "Expect the initial configuration to still match the updatable configuration object."); newEngineState = RunEngineWithDecorators(pm.LoggingContext, cancellationToken, appLoggers, engineState, collector); Contract.Assert(EngineState.CorrectEngineStateTransition(engineState, newEngineState, out var incorrectMessage), incorrectMessage); if (Events.Log.HasEventWriteFailures) { Logger.Log.EventWriteFailuresOccurred(pm.LoggingContext); } appLoggers.LogEventSummary(pm.LoggingContext); // Log Ado Summary var buildSummary = m_buildViewModel.BuildSummary; if (buildSummary != null) { try { string filePath = buildSummary.RenderMarkdown(); WriteToConsole("##vso[task.uploadsummary]" + filePath); } catch (IOException e) { WriteErrorToConsole(Strings.App_Main_FailedToWriteSummary, e.Message); // No need to change exit code, only behavior is lack of log in the extensions page. } catch (UnauthorizedAccessException e) { WriteErrorToConsole(Strings.App_Main_FailedToWriteSummary, e.Message); // No need to change exit code, only behavior is lack of log in the extensions page. } } if (appLoggers.TrackingEventListener.HasFailures) { WriteErrorToConsoleWithDefaultColor(Strings.App_Main_BuildFailed); LogGeneratedFiles(pm.LoggingContext, appLoggers.TrackingEventListener, translator: appLoggers.PathTranslatorForLogging); var classification = ClassifyFailureFromLoggedEvents(pm.LoggingContext, appLoggers.TrackingEventListener); var cbClassification = GetExitKindForCloudBuild(appLoggers.TrackingEventListener); return AppResult.Create(classification.ExitKind, cbClassification, newEngineState, classification.ErrorBucket, bucketMessage: classification.BucketMessage); } WriteToConsole(Strings.App_Main_BuildSucceeded); LogGeneratedFiles(pm.LoggingContext, appLoggers.TrackingEventListener, translator: appLoggers.PathTranslatorForLogging); if (m_configuration.Ide.IsEnabled) { var translator = appLoggers.PathTranslatorForLogging; var configFile = m_initialConfiguration.Startup.ConfigFile; IdeGenerator.WriteCmd(GetExpandedCmdLine(m_commandLineArguments), m_configuration.Ide, configFile, m_pathTable, translator); var solutionFile = IdeGenerator.GetSolutionPath(m_configuration.Ide, m_pathTable).ToString(m_pathTable); if (translator != null) { solutionFile = translator.Translate(solutionFile); } WriteToConsole(Strings.App_Vs_SolutionFile, solutionFile); var vsVersions = IdeGenerator.GetVersionsNotHavingLatestPlugin(); if (vsVersions != null) { WriteWarningToConsole(Strings.App_Vs_InstallPlugin, vsVersions, IdeGenerator.LatestPluginVersion); } } return AppResult.Create(ExitKind.BuildSucceeded, newEngineState, string.Empty); } finally { // Allow the app host to perform any shutdown actions before the logging is cleaned up. m_appHost.EndRun(pm.LoggingContext); if (!OperatingSystemHelper.IsUnixOS) { // Reset the ExecutionState NativeMethods.SetThreadExecutionState(NativeMethods.EXECUTION_STATE.ES_CONTINUOUS); } } } } finally { // Release the build view model so that we can garbage collect any state it maintained. m_buildViewModel = null; // Due to some nasty patterns, we hold onto a static collection of hashers. Make sure these are no longer // referenced. ContentHashingUtilities.DisposeAndResetHasher(); if (unexpectedExceptionHandler != null) { ExceptionUtilities.UnexpectedException -= unexpectedExceptionHandler; } if (unhandledExceptionHandler != null) { AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler; } if (unobservedTaskHandler != null) { TaskScheduler.UnobservedTaskException -= unobservedTaskHandler; } if (firstChanceExceptionHandler != null) { AppDomain.CurrentDomain.FirstChanceException -= firstChanceExceptionHandler; } } } private void OnFirstChanceException(object sender, FirstChanceExceptionEventArgs e) { // Bug #1209727: Intercept first chance exception for ArgumentNullException for additional logging. if (e.Exception is ArgumentNullException argumentNullException && argumentNullException.ParamName == "destination") { // Log full exception string with stack trace as unexpected condition OnUnexpectedCondition(string.Join(Environment.NewLine, "Bug 1209727", e.Exception.ToString())); } } private EngineState RunEngineWithDecorators( LoggingContext loggingContext, CancellationToken cancellationToken, AppLoggers appLoggers, EngineState engineState, PerformanceCollector performanceCollector) { var fileSystem = new PassThroughFileSystem(m_pathTable); var engineContext = EngineContext.CreateNew(cancellationToken, m_pathTable, fileSystem); var frontEndControllerFactory = FrontEndControllerFactory.Create( m_configuration.FrontEnd.FrontEndMode(), loggingContext, m_initialConfiguration, performanceCollector); return RunEngine( loggingContext, engineContext, m_initialConfiguration, performanceCollector, frontEndControllerFactory, appLoggers.TrackingEventListener, engineState); } internal static (ExitKind ExitKind, string ErrorBucket, string BucketMessage) ClassifyFailureFromLoggedEvents(LoggingContext loggingContext, TrackingEventListener listener) { // The loss of connectivity to other machines during a distributed build is generally the true cause of the // failure even though it may manifest itself as a different failure first (like failure to materialize) if (listener.CountsPerEventId((int)EngineLogEventId.DistributionExecutePipFailedNetworkFailure) >= 1) { return (ExitKind: ExitKind.InfrastructureError, ErrorBucket: EngineLogEventId.DistributionExecutePipFailedNetworkFailure.ToString(), BucketMessage: string.Empty); } else if (listener.CountsPerEventId((int)SchedulerLogEventId.ProblematicWorkerExit) >= 1 && (listener.InternalErrorDetails.Count > 0 || listener.InfrastructureErrorDetails.Count > 0)) { string errorMessage = listener.InternalErrorDetails.Count > 0 ? listener.InternalErrorDetails.FirstErrorMessage : listener.InfrastructureErrorDetails.FirstErrorMessage; string errorName = listener.InternalErrorDetails.Count > 0 ? listener.InternalErrorDetails.FirstErrorName : listener.InfrastructureErrorDetails.FirstErrorName; return (ExitKind: ExitKind.InfrastructureError, ErrorBucket: $"{SchedulerLogEventId.ProblematicWorkerExit.ToString()}.{errorName}", BucketMessage: errorMessage); } else if (listener.InternalErrorDetails.Count > 0) { return (ExitKind: ExitKind.InternalError, ErrorBucket: listener.InternalErrorDetails.FirstErrorName, BucketMessage: listener.InternalErrorDetails.FirstErrorMessage); } else if (listener.InfrastructureErrorDetails.Count > 0) { return (ExitKind: ExitKind.InfrastructureError, ErrorBucket: listener.InfrastructureErrorDetails.FirstErrorName, BucketMessage: listener.InfrastructureErrorDetails.FirstErrorMessage); } else { return (ExitKind: ExitKind.UserError, ErrorBucket: listener.UserErrorDetails.FirstErrorName, BucketMessage: listener.UserErrorDetails.FirstErrorMessage); } } /// <summary> /// Computes the legacy ExitKind used for CloudBuild integration. This needs to exist until GBR understands /// the simpler InternalError/InfrastructureError/UserError categorization. /// </summary> private static ExitKind GetExitKindForCloudBuild(TrackingEventListener listener) { foreach (var item in listener.CountsPerEvent) { if (item.Value > 0) { // Pick the best bucket by the type of events that were logged. First wins. switch (item.Key) { case (int)BuildXL.Scheduler.Tracing.LogEventId.FileMonitoringError: return ExitKind.BuildFailedWithFileMonErrors; case (int)BuildXL.Processes.Tracing.LogEventId.PipProcessExpectedMissingOutputs: return ExitKind.BuildFailedWithMissingOutputErrors; case (int)BuildXL.Pips.Tracing.LogEventId.InvalidOutputDueToSimpleDoubleWrite: return ExitKind.BuildFailedSpecificationError; case (int)BuildXL.Processes.Tracing.LogEventId.PipProcessError: case (int)SharedLogEventId.DistributionWorkerForwardedError: return ExitKind.BuildFailedWithPipErrors; case (int)AppLogEventId.CancellationRequested: return ExitKind.BuildCancelled; case (int)BuildXL.Pips.Tracing.LogEventId.NoPipsMatchedFilter: return ExitKind.NoPipsMatchFilter; } } } return ExitKind.BuildFailedWithGeneralErrors; } private void LogGeneratedFiles(LoggingContext loggingContext, TrackingEventListener trackingListener, PathTranslator translator) { if (m_configuration.Logging.LogsDirectory.IsValid) { // When using the new style logging configuration, just show the path to the logs directory WriteToConsole(Strings.App_LogsDirectory, m_configuration.Logging.LogsDirectory.ToString(m_pathTable)); } else { // Otherwise, show the path(s) of the various logs that could have been created Action<string, AbsolutePath> logFunction = (message, file) => { if (file.IsValid) { string path = file.ToString(m_pathTable); if (translator != null) { path = translator.Translate(path); } bool fileExists = File.Exists(path); if (fileExists) { if (trackingListener.HasFailures) { WriteToConsole(message, path); } else { WriteErrorToConsoleWithDefaultColor(message, path); } } } }; logFunction(Strings.App_Main_Log, m_configuration.Logging.Log); logFunction(Strings.App_Main_Log, m_configuration.Logging.ErrorLog); logFunction(Strings.App_Main_Log, m_configuration.Logging.WarningLog); foreach (var log in m_configuration.Logging.CustomLog) { logFunction(Strings.App_Main_Log, log.Key); } logFunction(Strings.App_Main_Snapshot, m_configuration.Export.SnapshotFile); } } private AppResult RunWithLoggingScope(Func<PerformanceMeasurement, AppResult> run, Action sendFinalStatistics, Action<LoggingContext> configureLogging = null) { AppResult result = AppResult.Create(ExitKind.InternalError, null, "FailedBeforeRunAttempted"); Guid relatedActivityId; if (!string.IsNullOrEmpty(m_configuration.Logging.RelatedActivityId)) { var success = Guid.TryParse(m_configuration.Logging.RelatedActivityId, out relatedActivityId); Contract.Assume(success, "relatedActivityId guid must have been validated already as part of config validation."); } else { relatedActivityId = Guid.NewGuid(); } var sessionId = ComputeSessionId(relatedActivityId); LoggingContext topLevelContext = new LoggingContext( relatedActivityId, Branding.ProductExecutableName, new LoggingContext.SessionInfo(sessionId.ToString(), ComputeEnvironment(m_configuration), relatedActivityId)); using (PerformanceMeasurement pm = PerformanceMeasurement.StartWithoutStatistic( topLevelContext, (loggingContext) => { m_appLoggingContext = loggingContext; // Note the m_appLoggingContext is cleaned up. In the initial implementation this was a static, but after pr comment it is now an instance. m_loggingContextForCrashHandler = loggingContext; Events.StaticContext = loggingContext; FileUtilitiesStaticLoggingContext.LoggingContext = loggingContext; // As the most of filesystem operations are defined as static, we need to reset counters not to add values between server-mode builds. // We should do so after we have set the proper logging context. FileUtilities.CreateCounters(); var utcNow = DateTime.UtcNow; var localNow = utcNow.ToLocalTime(); configureLogging?.Invoke(loggingContext); string translatedLogDirectory = string.Empty; if (m_configuration.Logging.LogsDirectory.IsValid) { // Log directory is not valid if BuildXL is invoked with /setupJournal argument. // Otherwise, it is always valid as we call PopulateLoggingAndLayoutConfiguration in the BuildXLApp constructor. // If the user does not provide /logDirectory, then the method call above (PopulateLogging...) will find a default one. var pathTranslator = GetPathTranslator(m_configuration.Logging, m_pathTable); var logDirectory = m_configuration.Logging.LogsDirectory.ToString(m_pathTable); translatedLogDirectory = pathTranslator != null ? pathTranslator.Translate(logDirectory) : logDirectory; } LogDominoInvocation( loggingContext, GetExpandedCmdLine(m_commandLineArguments), s_buildInfo, s_machineInfo, loggingContext.Session.Id, relatedActivityId.ToString(), m_configuration.Logging.Environment, utcNow.Ticks, translatedLogDirectory, m_configuration.InCloudBuild(), Directory.GetCurrentDirectory(), m_initialConfiguration.Startup.ConfigFile.ToString(m_pathTable)); // "o" means it is round-trippable. It happens to be ISO-8601. Logger.Log.StartupTimestamp( loggingContext, utcNow.ToString("o", CultureInfo.InvariantCulture), localNow.ToString("o", CultureInfo.InvariantCulture)); Logger.Log.StartupCurrentDirectory(loggingContext, Directory.GetCurrentDirectory()); }, (loggingContext) => { var exitKind = result.ExitKind; var utcNow = DateTime.UtcNow; LogDominoCompletion( loggingContext, ExitCode.FromExitKind(exitKind), exitKind, result.CloudBuildExitKind, result.ErrorBucket, result.BucketMessage, Convert.ToInt32(utcNow.Subtract(m_startTimeUtc).TotalMilliseconds), utcNow.Ticks, m_configuration.InCloudBuild()); sendFinalStatistics(); m_appLoggingContext = null; // If required, shut down telemetry now that the last telemetry event has been sent. if (m_appHost.ShutDownTelemetryAfterRun && AriaV2StaticState.IsEnabled) { Stopwatch sw = Stopwatch.StartNew(); Exception telemetryShutdownException; var shutdownResult = AriaV2StaticState.TryShutDown(TelemetryFlushTimeout, out telemetryShutdownException); switch (shutdownResult) { case AriaV2StaticState.ShutDownResult.Failure: Logger.Log.TelemetryShutDownException(loggingContext, telemetryShutdownException?.Message); break; case AriaV2StaticState.ShutDownResult.Timeout: LogTelemetryShutdownInfo(loggingContext, sw.ElapsedMilliseconds); Logger.Log.TelemetryShutdownTimeout(loggingContext, sw.ElapsedMilliseconds); break; case AriaV2StaticState.ShutDownResult.Success: LogTelemetryShutdownInfo(loggingContext, sw.ElapsedMilliseconds); break; } } })) { result = run(pm); } return result; } /// <summary> /// Logging DominoCompletion with an extra CloudBuild event /// </summary> public static void LogDominoCompletion(LoggingContext context, int exitCode, ExitKind exitKind, ExitKind cloudBuildExitKind, string errorBucket, string bucketMessage, int processRunningTime, long utcTicks, bool inCloudBuild) { Logger.Log.DominoCompletion(context, exitCode, exitKind.ToString(), errorBucket, // This isn't a command line but it should still be sanatized for sake of not overflowing in telemetry ScrubCommandLine(bucketMessage, 1000, 1000), processRunningTime); // Sending a different event to CloudBuild ETW listener. if (inCloudBuild) { BuildXL.Tracing.CloudBuildEventSource.Log.DominoCompletedEvent(new BuildXL.Tracing.CloudBuild.DominoCompletedEvent { ExitCode = exitCode, UtcTicks = utcTicks, ExitKind = cloudBuildExitKind, }); } } /// <summary> /// Logging DominoInvocation with an extra CloudBuild event /// </summary> public static void LogDominoInvocation( LoggingContext context, string commandLine, BuildInfo buildInfo, MachineInfo machineInfo, string sessionIdentifier, string relatedSessionIdentifier, ExecutionEnvironment environment, long utcTicks, string logDirectory, bool inCloudBuild, string startupDirectory, string mainConfigurationFile) { Logger.Log.DominoInvocation(context, ScrubCommandLine(commandLine, 100000, 100000), buildInfo, machineInfo, sessionIdentifier, relatedSessionIdentifier, startupDirectory, mainConfigurationFile); Logger.Log.DominoInvocationForLocalLog(context, commandLine, buildInfo, machineInfo, sessionIdentifier, relatedSessionIdentifier, startupDirectory, mainConfigurationFile); if (inCloudBuild) { // Sending a different event to CloudBuild ETW listener. BuildXL.Tracing.CloudBuildEventSource.Log.DominoInvocationEvent(new BuildXL.Tracing.CloudBuild.DominoInvocationEvent { UtcTicks = utcTicks, // Truncate the command line that gets to the CB event to avoid exceeding the max event payload of 64kb CommandLineArgs = commandLine?.Substring(0, Math.Min(commandLine.Length, 4 * 1024)), DominoVersion = buildInfo.CommitId, Environment = environment, LogDirectory = logDirectory, }); } } /// <summary> /// Scrubs the command line to make it amenable (short enough) to be sent to telemetry /// </summary> internal static string ScrubCommandLine(string rawCommandLine, int leadingChars, int trailingChars) { Contract.RequiresNotNull(rawCommandLine); Contract.Requires(leadingChars >= 0); Contract.Requires(trailingChars >= 0); if (rawCommandLine.Length < leadingChars + trailingChars) { return rawCommandLine; } int indexOfBreakWithinPrefix = rawCommandLine.LastIndexOf(' ', leadingChars); string prefix = indexOfBreakWithinPrefix == -1 ? rawCommandLine.Substring(0, leadingChars) : rawCommandLine.Substring(0, indexOfBreakWithinPrefix); string breakMarker = indexOfBreakWithinPrefix == -1 ? "[...]" : " [...]"; int indexOfBreakWithinSuffix = rawCommandLine.IndexOf(' ', rawCommandLine.Length - trailingChars); string suffix = indexOfBreakWithinSuffix == -1 ? rawCommandLine.Substring(rawCommandLine.Length - trailingChars) : rawCommandLine.Substring(indexOfBreakWithinSuffix, rawCommandLine.Length - indexOfBreakWithinSuffix); return prefix + breakMarker + suffix; } /// <summary> /// Computes session identifier which allows easier searching in Kusto for /// builds based traits: Cloudbuild BuildId (i.e. RelatedActivityId), ExecutionEnvironment, Distributed build role /// /// Search for masters: '| where sessionId has "0001-FFFF"' /// Search for workers: '| where sessionId has "0002-FFFF"' /// Search for office metabuild: '| where sessionId has "FFFF-0F"' /// </summary> private Guid ComputeSessionId(Guid relatedActivityId) { var bytes = relatedActivityId.ToByteArray(); var executionEnvironment = m_configuration.Logging.Environment; var distributedBuildRole = m_configuration.Distribution.BuildRole; var inCloudBuild = m_configuration.InCloudBuild(); // SessionId: // 00-03: 00-03 from random guid var randomBytes = Guid.NewGuid().ToByteArray(); for (int i = 0; i <= 3; i++) { bytes[i] = randomBytes[i]; } // 04-05: BuildRole bytes[4] = 0; bytes[5] = (byte)distributedBuildRole; // 06-07: InCloudBuild = FFFF, !InCloudBuild = 0000 var inCloudBuildSpecifier = inCloudBuild ? byte.MaxValue : (byte)0; bytes[6] = inCloudBuildSpecifier; bytes[7] = inCloudBuildSpecifier; // 08-09: executionEnvironment bytes[8] = (byte)(((int)executionEnvironment >> 8) & 0xFF); bytes[9] = (byte)((int)executionEnvironment & 0xFF); // 10-15: 10-15 from relatedActivityId // Do nothing byte array is initially seeded from related activity id return new Guid(bytes); } private static void LogTelemetryShutdownInfo(LoggingContext loggingContext, long elapsedMilliseconds) { Logger.Log.TelemetryShutDown(loggingContext, elapsedMilliseconds); // Note we log how long the telemetry shutdown took. It is necessary to shut down telemetry inside // RunWithLoggingScope in order to be able to log how long it took. BuildXL.Tracing.Logger.Log.StatisticWithoutTelemetry( loggingContext, "TelemetryShutdown.DurationMs", elapsedMilliseconds); } /// <summary> /// Produces a cmd line with expanded response files; starts with mapped BuildXL path. /// </summary> private static string GetExpandedCmdLine(IReadOnlyCollection<string> rawArgs) { Contract.RequiresNotNull(rawArgs, "rawArgs must not be null."); Contract.Ensures(Contract.Result<string>() != null, "Result of the method can't be null."); var cl = new CommandLineUtilities(rawArgs); return string.Join(" ", cl.ExpandedArguments); } /// <summary> /// Applies the root drive remappings /// </summary> private bool ApplyRootMappings(IReadOnlyDictionary<string, AbsolutePath> rootMappings) { if (rootMappings.Count != 0) { foreach (var mapping in rootMappings) { try { var rootPath = mapping.Value.ToString(m_pathTable); if (!Directory.Exists(rootPath)) { Directory.CreateDirectory(rootPath); } } catch (Exception ex) { WriteErrorToConsole( Strings.App_RootMapping_CantCreateDirectory, mapping.Value, mapping.Key, ex.GetLogEventMessage()); return false; } } if ( !ProcessNativeMethods.ApplyDriveMappings( rootMappings.Select(kvp => new PathMapping(kvp.Key[0], kvp.Value.ToString(m_pathTable))).ToArray())) { WriteErrorToConsole(Strings.App_RootMapping_CantApplyRootMappings); return false; } } return true; } private static void CleanupLogsDirectory(LoggingContext loggingContext, string rootLogsDirectory, int logsToRetain) { string[] allLogDirs; try { allLogDirs = Directory.EnumerateDirectories(rootLogsDirectory).ToArray(); if (allLogDirs.Length <= logsToRetain) { return; } Array.Sort(allLogDirs, (x, y) => Directory.GetCreationTime(x).CompareTo(Directory.GetCreationTime(y))); } catch (DirectoryNotFoundException) { return; // Nothing to delete. } catch (Exception ex) { // Possible exceptions here are PathTooLongException, SecurityException and UnauthorizedAccessException. We catch all just to be safe. Logger.Log.FailedToEnumerateLogDirsForCleanup(loggingContext, rootLogsDirectory, ex.GetLogEventMessage()); return; } for (int idx = 0; idx < allLogDirs.Length - logsToRetain; ++idx) { string dir = allLogDirs[idx]; try { FileUtilities.DeleteDirectoryContents(dir, true); } catch (BuildXLException ex) { // No worries. Will do it next time. Logger.Log.FailedToCleanupLogDir(loggingContext, dir, ex.Message); } } } #region EventListenerConfiguration /// <summary> /// All code generated EventSource implementations /// </summary> internal static IEnumerable<EventSource> GeneratedEventSources => new EventSource[] { global::bxl.ETWLogger.Log, global::BuildXL.Engine.Cache.ETWLogger.Log, global::BuildXL.Engine.ETWLogger.Log, global::BuildXL.Scheduler.ETWLogger.Log, global::BuildXL.Tracing.ETWLogger.Log, global::BuildXL.Pips.ETWLogger.Log, global::BuildXL.Native.ETWLogger.Log, global::BuildXL.Storage.ETWLogger.Log, global::BuildXL.Processes.ETWLogger.Log, }.Concat( FrontEndControllerFactory.GeneratedEventSources ); internal static PathTranslator GetPathTranslator(ILoggingConfiguration conf, PathTable pathTable) { return conf.SubstTarget.IsValid && conf.SubstSource.IsValid && !conf.DisableLoggedPathTranslation ? new PathTranslator(conf.SubstTarget.ToString(pathTable), conf.SubstSource.ToString(pathTable)) : null; } /// <summary> /// Enables per-task diagnostics according to arguments. /// </summary> private static void EnableTaskDiagnostics(ILoggingConfiguration configuration, BaseEventListener listener) { for (int i = 1; i <= (int)Tasks.Max; i++) { if ((configuration.Diagnostic & (DiagnosticLevels)(1 << i)) != 0) { listener.EnableTaskDiagnostics((EventTask)i); } } } private sealed class AppLoggers : IDisposable { internal const string DefaultLogKind = "default"; internal const string StatusLogKind = "status"; private readonly IConsole m_console; private readonly ILoggingConfiguration m_configuration; private readonly PathTable m_pathTable; private readonly DateTime m_baseTime; private readonly object m_lock = new object(); private readonly List<BaseEventListener> m_listeners = new List<BaseEventListener>(); private readonly Dictionary<AbsolutePath, TextWriterEventListener> m_listenersByPath = new Dictionary<AbsolutePath, TextWriterEventListener>(); private bool m_disposed; private readonly bool m_displayWarningErrorTime; private TextWriterEventListener m_defaultFileListener; private TextWriterEventListener m_statusFileListener; private readonly WarningManager m_warningManager; private readonly EventMask m_noLogMask; /// <summary> /// Path Translator used for logging. Note this may be disabled (null) even if subst or junctions are in effect. /// It should only be used for the sake of logging. /// </summary> public readonly PathTranslator PathTranslatorForLogging; // Note: this is not disposed directly because it is also within m_listeners and it gets disposed with // that collection private StatisticsEventListener m_statisticsEventListener; /// <summary> /// The path to the log file /// </summary> public readonly string LogPath; /// <summary> /// The path to the log directory /// </summary> public readonly string RootLogDirectory; public AppLoggers( DateTime startTime, IConsole console, ILoggingConfiguration configuration, PathTable pathTable, bool notWorker, BuildViewModel buildViewModel, bool displayWarningErrorTime) { Contract.RequiresNotNull(console); Contract.RequiresNotNull(configuration); m_console = console; m_baseTime = startTime; m_configuration = configuration; m_pathTable = pathTable; m_displayWarningErrorTime = displayWarningErrorTime; LogPath = configuration.Log.ToString(pathTable); RootLogDirectory = Path.GetDirectoryName(LogPath); m_noLogMask = new EventMask(enabledEvents: null, disabledEvents: configuration.NoLog, nonMaskableLevel: EventLevel.Error); m_warningManager = CreateWarningManager(configuration); PathTranslatorForLogging = GetPathTranslator(configuration, pathTable); Events.Log.HasDiagnosticsArgument = configuration.Diagnostic != 0; EnsureEventProvidersInitialized(); // Inialize the console logging early if (m_configuration.ConsoleVerbosity != VerbosityLevel.Off) { ConfigureConsoleLogging(notWorker, buildViewModel); } if (notWorker && (m_configuration.OptimizeConsoleOutputForAzureDevOps || m_configuration.OptimizeVsoAnnotationsForAzureDevOps || m_configuration.OptimizeProgressUpdatingForAzureDevOps)) { ConfigureAzureDevOpsLogging(buildViewModel); } } private static WarningManager CreateWarningManager(IWarningHandling configuration) { var warningManager = new WarningManager(); warningManager.AllWarningsAreErrors = configuration.TreatWarningsAsErrors; foreach (var messageNum in configuration.NoWarnings) { warningManager.SetState(messageNum, WarningState.Suppressed); } foreach (var messageNum in configuration.WarningsAsErrors) { warningManager.SetState(messageNum, WarningState.AsError); } foreach (var messageNum in configuration.WarningsNotAsErrors) { warningManager.SetState(messageNum, WarningState.AsWarning); } return warningManager; } public TrackingEventListener TrackingEventListener { get; private set; } public void ConfigureLogging(LoggingContext loggingContext) { lock (m_lock) { Contract.Assume(!m_disposed); ConfigureTrackingListener(); if (m_configuration.FileVerbosity != VerbosityLevel.Off && m_configuration.LogsDirectory.IsValid) { ConfigureFileLogging(); } if (m_configuration.ErrorLog.IsValid) { ConfigureErrorAndWarningLogging(m_configuration.ErrorLog, true, false, displayTime: m_displayWarningErrorTime); } if (m_configuration.WarningLog.IsValid) { ConfigureErrorAndWarningLogging(m_configuration.WarningLog, false, true, displayTime: m_displayWarningErrorTime); } if (m_configuration.StatsLog.IsValid) { ConfigureStatisticsLogFile(m_configuration.StatsLog, loggingContext); } if (m_configuration.CustomLog != null && m_configuration.CustomLog.Count > 0) { ConfigureAdditionalFileLoggers(m_configuration.CustomLog); } } } /// <summary> /// See <see cref="BaseEventListener.SuppressNonCriticalEventsInPreparationForCrash" /> /// </summary> public void SuppressNonCriticalEventsInPreparationForCrash() { lock (m_lock) { Contract.Assume(!m_disposed); foreach (BaseEventListener listener in m_listeners) { listener.SuppressNonCriticalEventsInPreparationForCrash(); } } } /// <summary> /// Sends the FinalStatistic event to telemetry /// </summary> public void SendFinalStatistics() { m_statisticsEventListener.SendFinalStatistics(); } public void Dispose() { lock (m_lock) { if (m_disposed) { return; } foreach (BaseEventListener listener in m_listeners) { listener.Dispose(); } m_listeners.Clear(); m_listenersByPath.Clear(); m_disposed = true; } } private static void OnListenerDisabledDueToDiskWriteFailure(BaseEventListener listener) { throw new BuildXLException( "Failed to write to an event listener, indicating that a volume is out of available space.", ExceptionRootCause.OutOfDiskSpace); } private void AddListener(BaseEventListener listener) { EnableTaskDiagnostics(m_configuration, listener); m_listeners.Add(listener); } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ConfigureTrackingListener() { var trackingEventListener = new TrackingEventListener(Events.Log, m_baseTime, m_warningManager.GetState); AddListener(trackingEventListener); TrackingEventListener = trackingEventListener; } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ConfigureConsoleLogging(bool notWorker, BuildViewModel buildViewModel) { var listener = new ConsoleEventListener( Events.Log, m_console, m_baseTime, m_configuration.UseCustomPipDescriptionOnConsole, m_configuration.LogsDirectory.IsValid ? m_configuration.LogsDirectory.ToString(m_pathTable) : null, notWorker, m_warningManager.GetState, m_configuration.ConsoleVerbosity.ToEventLevel(), m_noLogMask, onDisabledDueToDiskWriteFailure: OnListenerDisabledDueToDiskWriteFailure, maxStatusPips: m_configuration.FancyConsoleMaxStatusPips, optimizeForAzureDevOps: m_configuration.OptimizeConsoleOutputForAzureDevOps || m_configuration.OptimizeVsoAnnotationsForAzureDevOps); listener.SetBuildViewModel(buildViewModel); AddListener(listener); } private void ConfigureAzureDevOpsLogging(BuildViewModel buildViewModel) { var listener = new AzureDevOpsListener( Events.Log, m_console, m_baseTime, buildViewModel, m_configuration.UseCustomPipDescriptionOnConsole, m_warningManager.GetState ); AddListener(listener); } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It complains that 'logFile' isn't disposed, but it is in fact disposed by virtue of being embedded in a StreamWriter which will get disposed.")] private static TextWriter CreateLogFile(string path) { LazilyCreatedStream s = new LazilyCreatedStream(path); // Occasionally we see things logged that aren't valid unicode characters. // Emitting gibberish for these peculiar characters isn't a big deal s_utf8NoBom = s_utf8NoBom ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false); TextWriter writer = new StreamWriter(s, s_utf8NoBom, LogFileBufferSize); return writer; } private void ConfigureStatisticsLogFile(AbsolutePath logFilePath, LoggingContext loggingContext) { AddFileBasedListener( logFilePath, (writer) => { m_statisticsEventListener = new StatisticsEventListener( Events.Log, writer, loggingContext, onDisabledDueToDiskWriteFailure: OnListenerDisabledDueToDiskWriteFailure); m_statisticsEventListener.EnableTaskDiagnostics(Tasks.CommonInfrastructure); return m_statisticsEventListener; }); } public void ConfigureStatusLogFile(AbsolutePath logFilePath) { m_statusFileListener = AddFileBasedListener( logFilePath, (writer) => { var listener = new StatusEventListener( Events.Log, writer, m_baseTime, onDisabledDueToDiskWriteFailure: OnListenerDisabledDueToDiskWriteFailure); listener.EnableTaskDiagnostics(Tasks.CommonInfrastructure); return listener; }); } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It complains that 'writer' isn't disposed, but it is in fact disposed by virtue of being embedded in a TextWriterEventListener.")] private TextWriterEventListener AddFileBasedListener(AbsolutePath logFilePath, Func<TextWriter, TextWriterEventListener> listenerCreator) { string logDir; try { logDir = logFilePath.GetParent(m_pathTable).ToString(m_pathTable); } catch (Exception ex) { WriteErrorToConsole( Strings.Program_ConfigureFileLogging_Can_t_get_directory_name, logFilePath, ex.GetLogEventMessage()); return null; } try { Directory.CreateDirectory(logDir); } catch (Exception ex) { WriteErrorToConsole( Strings.App_ConfigureFileLogging_CantCreateDirectory, logDir, ex.GetLogEventMessage()); } TextWriter writer; try { writer = CreateLogFile(logFilePath.ToString(m_pathTable)); } catch (Exception ex) { WriteErrorToConsole( Strings.App_ConfigureFileLogging_CantOpenLogFile, logFilePath, ex.GetLogEventMessage()); return null; } var listener = listenerCreator(writer); m_listenersByPath[logFilePath] = listener; AddListener(listener); return listener; } private void ConfigureFileLogging() { m_defaultFileListener = AddFileBasedListener( m_configuration.Log, (writer) => { var eventMask = new EventMask(enabledEvents: null, disabledEvents: m_configuration.NoLog, nonMaskableLevel: EventLevel.Error); return new TextWriterEventListener( Events.Log, writer, m_baseTime, m_warningManager.GetState, m_configuration.FileVerbosity.ToEventLevel(), TimeDisplay.Milliseconds, eventMask, onDisabledDueToDiskWriteFailure: OnListenerDisabledDueToDiskWriteFailure, pathTranslator: PathTranslatorForLogging); }); } private void ConfigureAdditionalFileLoggers(IReadOnlyDictionary<AbsolutePath, (IReadOnlyList<int> eventIds, EventLevel? nonMaskableLevel)> additionalLoggers) { foreach (var additionalLogger in additionalLoggers) { AddFileBasedListener( additionalLogger.Key, (writer) => { var eventMask = new EventMask(enabledEvents: additionalLogger.Value.eventIds, disabledEvents: null, nonMaskableLevel: additionalLogger.Value.nonMaskableLevel); return new TextWriterEventListener( Events.Log, writer, m_baseTime, m_warningManager.GetState, m_configuration.FileVerbosity.ToEventLevel(), TimeDisplay.Milliseconds, eventMask, onDisabledDueToDiskWriteFailure: OnListenerDisabledDueToDiskWriteFailure, pathTranslator: PathTranslatorForLogging); }); } } private void ConfigureErrorAndWarningLogging(AbsolutePath logFilePath, bool logErrors, bool logWarnings, bool displayTime) { AddFileBasedListener( logFilePath, (writer) => { return new ErrorAndWarningEventListener( Events.Log, writer, m_baseTime, logErrors, logWarnings, m_warningManager.GetState, PathTranslatorForLogging, timeDisplay: displayTime ? TimeDisplay.Milliseconds : TimeDisplay.None); }); } /// <summary> /// Registers generated event sources as merged event sources /// /// This is a workaround for static initialization issues. We need to access and use each static event-source instance /// before creating any listeners, or the listeners will not appropriately poke them on construction (there is a static list of initialized event sources, /// and the event sources seem to be incorrectly lazy about initializing some internal state). /// </summary> public static void EnsureEventProvidersInitialized() { using (var dummy = new TrackingEventListener(Events.Log)) { foreach (var eventSource in GeneratedEventSources) { Events.Log.RegisterMergedEventSource(eventSource); } } } /// <summary> /// Logs a count of the number of times each event was encountered. This only goes to telemetry /// </summary> public void LogEventSummary(LoggingContext loggingContext) { Logger.Log.EventCounts(loggingContext, TrackingEventListener.ToEventCountDictionary()); } private void WriteErrorToConsole(string format, params object[] args) { m_console.WriteOutputLine(MessageLevel.Error, string.Format(CultureInfo.InvariantCulture, format, args)); } internal void EnableEtwOutputLogging(LoggingContext loggingContext) { EtwOnlyTextLogger.EnableGlobalEtwLogging(loggingContext); m_defaultFileListener?.EnableEtwOutputLogging(new EtwOnlyTextLogger(loggingContext, DefaultLogKind)); m_statusFileListener?.EnableEtwOutputLogging(new EtwOnlyTextLogger(loggingContext, StatusLogKind)); foreach (var logEntry in m_configuration.CustomLogEtwKinds) { TextWriterEventListener listener; if (!string.IsNullOrEmpty(logEntry.Value) && m_listenersByPath.TryGetValue(logEntry.Key, out listener)) { listener.EnableEtwOutputLogging(new EtwOnlyTextLogger(loggingContext, logEntry.Value)); } } } } #endregion private static string ComputeEnvironment(IConfiguration configuration) { using (var builderPool = Pools.StringBuilderPool.GetInstance()) { StringBuilder sb = builderPool.Instance; sb.Append(configuration.Logging.Environment); sb.Append("Script"); foreach (KeyValuePair<string, string> traceInfo in configuration.Logging.TraceInfo.OrderBy(kvp => kvp.Key, StringComparer.OrdinalIgnoreCase)) { sb.Append(';'); sb.Append(traceInfo.Key); sb.Append('='); sb.Append(traceInfo.Value); } return sb.ToString(); } } /// <summary> /// Creates a counter collector if counter collection is enabled /// </summary> /// <returns> /// FxCop complains the IDisposable may not be disposed when it is created with a ternary operator in the using /// statement. Use this helper to avoid suppressing the rule /// </returns> private PerformanceCollector CreateCounterCollectorIfEnabled(LoggingContext loggingContext) { if (m_configuration.Logging.LogMemory) { Logger.Log.MemoryLoggingEnabled(loggingContext); } if (m_configuration.Logging.LogCounters) { return new PerformanceCollector(TimeSpan.FromSeconds(1), m_configuration.Logging.LogMemory); } return null; } internal void OnUnexpectedCondition(string condition) { if (m_appLoggingContext != null) { BuildXL.Tracing.UnexpectedCondition.Log(m_appLoggingContext, condition); } } /// <summary> /// Handle CTRL+C /// </summary> /// <returns>True if we want the program to die immediately; otherwise false</returns> internal bool OnConsoleCancelEvent(bool isTermination) { LoggingContext loggingContext = m_appLoggingContext; if (loggingContext == null) { // Event happened too early or too late --> ignore (let the program terminate). // That should be ok because: // - if it is too early: it's as if it happened before this handler was set; // - if it is too late: BuildXL is terminating anyway. return true; } // Exit hard & immediately in case of termination if (isTermination) { return true; } else { // Only log on the first cancel if (Interlocked.CompareExchange(ref m_cancellationAlreadyAttempted, 1, 0) == 0) { // Log an event and set a cancellation signal but allow execution to continue. // NOTE: it is important to log an error message before calling Cancel(), // because all the clients expect an error to be logged first. Logger.Log.CancellationRequested(loggingContext); m_cancellationSource.Cancel(); } return false; } } private int m_unhandledFailureInProgress = 0; private void HandleUnhandledFailure( Exception exception, AppLoggers loggers, PerformanceMeasurement pm, ExceptionRootCause? predefinedRootCause = null) { if (!OperatingSystemHelper.IsUnixOS) { // If there's an unhandled exception and debugger is attached then // before doing anything else we want to break so that issue can // be immediately debugged. The sample user scenario is having cdb/ntsd // being attached during BuildXL builds. NativeMethods.LaunchDebuggerIfAttached(); } // Given some conditions like running out of disk space, many threads may start crashing at once. // We will give the first thread a chance to emit some telemetry and inform the user, but with multiple // threads blocked here (with arbitrary stacks below), we are possibly deadlocked. So, all threads but // the first are hijacked as watchdog timers: worst case, the process will exit after a generous delay. // TODO: Note that a single thread crashing could still deadlock if it tries to acquire locks held on its own stack. if (Interlocked.CompareExchange(ref m_unhandledFailureInProgress, 1, comparand: 0) != 0) { Thread.Sleep(FailureCompletionTimeoutMs); ExceptionUtilities.FailFast("Second-chance exception handler has not completed in the allowed time.", new InvalidOperationException()); return; } ExitKind effectiveExitKind = ExitKind.InternalError; try { ExceptionRootCause rootCause = predefinedRootCause ?? (exception == null ? ExceptionRootCause.Unknown : ExceptionUtilities.AnalyzeExceptionRootCause(exception)); string failureMessage = exception?.ToStringDemystified() ?? Strings.App_HandleUnhandledFailure_UnknownException; // We want the crash-related critical events below to be visible (not hidden by incidental events from other threads). loggers.SuppressNonCriticalEventsInPreparationForCrash(); // All remaining work may allocate disk space (flushing logs, creating dumps, etc.) // This means that with ExceptionRootCause.OutOfDiskSpace, it is fairly likely that // one of the following things will fail: think of them all as best-effort, and so // choose order carefully. // Writing to anything derived from BaseEventListener should be fairly safe though, due to special // handling in which disk-space failures disable the listener and separately ensure that that failure // is reported (we should end up here); see onDisabledDueToDiskWriteFailure in BaseEventListener. switch (rootCause) { case ExceptionRootCause.OutOfDiskSpace: // Note that we hide failureMessage from the user-facing logs for OutOfDiskSpace // Full info including stacks / dumps may make it to telemetry still. Logger.Log.CatastrophicFailureCausedByDiskSpaceExhaustion(pm.LoggingContext); effectiveExitKind = ExitKind.InfrastructureError; break; case ExceptionRootCause.DataErrorDriveFailure: // Note that we hide failureMessage from the user-facing logs for DataErrorDriveFailure // Full info including stacks / dumps may make it to telemetry still. Logger.Log.StorageCatastrophicFailureCausedByDriveError(pm.LoggingContext); effectiveExitKind = ExitKind.InfrastructureError; break; case ExceptionRootCause.MissingRuntimeDependency: if (exception is FileLoadException && failureMessage.Contains(global::BuildXL.Utilities.Strings.ExceptionUtilities_AccessDeniedPattern)) { if (FileUtilities.TryFindOpenHandlesToFile((exception as FileLoadException).FileName, out string diagnosticInfo)) { failureMessage += Environment.NewLine + diagnosticInfo; } } Logger.Log.CatastrophicFailureMissingRuntimeDependency(pm.LoggingContext, failureMessage); effectiveExitKind = ExitKind.InfrastructureError; break; case ExceptionRootCause.CorruptedCache: // Failure message should have been logged at the detection sites. Logger.Log.CatastrophicFailureCausedByCorruptedCache(pm.LoggingContext); effectiveExitKind = ExitKind.InfrastructureError; break; case ExceptionRootCause.ConsoleNotConnected: // Not a BuildXL error. Do not log or send a telemetry event. // TODO: Maybe log on in the file? Definitely avoid the console to prevent a stack overflow. effectiveExitKind = ExitKind.Aborted; break; default: Logger.Log.CatastrophicFailure(pm.LoggingContext, failureMessage, s_buildInfo?.CommitId ?? string.Empty, s_buildInfo?.Build ?? string.Empty); WriteToConsole(Strings.App_LogsDirectory, loggers.RootLogDirectory); WriteToConsole("Collecting some information about this crash..."); break; } // Send a catastrophic failure telemetry event. This should be earlier in the handling process to ensure // we have the best shot of getting telemetry out before more complicated tasks like taking a process dump happen. AppServer hostServer = m_appHost as AppServer; Logger.Log.DominoCatastrophicFailure(pm.LoggingContext, failureMessage, s_buildInfo, rootCause, wasServer: hostServer != null, firstUserError: loggers.TrackingEventListener.UserErrorDetails.FirstErrorName, lastUserError: loggers.TrackingEventListener.UserErrorDetails.LastErrorName, firstInsfrastructureError: loggers.TrackingEventListener.InfrastructureErrorDetails.FirstErrorName, lastInfrastructureError: loggers.TrackingEventListener.InfrastructureErrorDetails.LastErrorName, firstInternalError: loggers.TrackingEventListener.InternalErrorDetails.FirstErrorName, lastInternalError: loggers.TrackingEventListener.InternalErrorDetails.LastErrorName); loggers.LogEventSummary(pm.LoggingContext); // Mark failure for future recovery. // TODO - FailureRecovery relies on the configuration object and path table. It really shouldn't since these mutate over // the corse of the build. This currently makes them pretty ineffective since m_PathTable.IsValue will most likely // false here due to graph cache reloading. if (m_pathTable != null && m_pathTable.IsValid) { var recovery = FailureRecoveryFactory.Create(pm.LoggingContext, m_pathTable, m_configuration); Analysis.IgnoreResult(recovery.TryMarkFailure(exception, rootCause)); } loggers.Dispose(); pm.Dispose(); if (rootCause == ExceptionRootCause.Unknown) { // Sometimes the crash dumps don't actually get attached to the WER report. Stick a full heap dump // next to the log file for good measure. try { string logPrefix = Path.GetFileNameWithoutExtension(loggers.LogPath); string dumpDir = Path.Combine(loggers.RootLogDirectory, logPrefix, "dumps"); Directory.CreateDirectory(dumpDir); Exception dumpException; Analysis.IgnoreResult(BuildXL.Processes.ProcessDumper.TryDumpProcess(Process.GetCurrentProcess(), Path.Combine(dumpDir, "UnhandledFailure.zip"), out dumpException, compress: true)); } #pragma warning disable ERP022 // Unobserved exception in generic exception handler catch { } #pragma warning restore ERP022 // Unobserved exception in generic exception handler if (!OperatingSystemHelper.IsUnixOS) { string[] filesToAttach = new[] { loggers.LogPath }; WindowsErrorReporting.CreateDump(exception, s_buildInfo, filesToAttach, m_loggingContextForCrashHandler?.Session?.Id); } } Exception telemetryShutdownException; // Use a relatively long shutdown timeout since it is important to capture data from crashes if (AriaV2StaticState.TryShutDown(TimeSpan.FromMinutes(1), out telemetryShutdownException) == AriaV2StaticState.ShutDownResult.Failure) { effectiveExitKind = ExitKind.InfrastructureError; } // If this is a server mode we should try to write the exit code to the pipe so it makes it back to // the client. If the client doesn't get the exit message, it will exit with a error that it couldn't // communicate with the server. hostServer?.WriteExitCodeToClient(effectiveExitKind); if (rootCause == ExceptionRootCause.FailFast) { Environment.FailFast("Configured to fail fast.", exception); } Environment.Exit(ExitCode.FromExitKind(effectiveExitKind)); } #pragma warning disable ERP022 // Unobserved exception in generic exception handler catch (Exception ex) { // Oh my, this isn't going very well. WriteErrorToConsole("Unhandled exception in exception handler"); WriteErrorToConsole(ex.DemystifyToString()); } #pragma warning restore ERP022 // Unobserved exception in generic exception handler finally { if (predefinedRootCause == ExceptionRootCause.FailFast) { Environment.FailFast("Configured to fail fast.", exception); } Environment.Exit(ExitCode.FromExitKind(ExitKind.InternalError)); } } private EngineState RunEngine( LoggingContext loggingContext, EngineContext engineContext, ICommandLineConfiguration configuration, PerformanceCollector performanceCollector, IFrontEndControllerFactory factory, TrackingEventListener trackingEventListener, EngineState engineState) { var appInitializationDurationMs = (int)(DateTime.UtcNow - m_startTimeUtc).TotalMilliseconds; BuildXL.Tracing.Logger.Log.Statistic( loggingContext, new Statistic() { Name = Statistics.AppHostInitializationDurationMs, Value = appInitializationDurationMs, }); var engine = BuildXLEngine.Create( loggingContext, engineContext, configuration, factory, m_buildViewModel, performanceCollector, m_startTimeUtc, trackingEventListener, rememberAllChangedTrackedInputs: true, commitId: s_buildInfo?.IsDeveloperBuild == false ? s_buildInfo.CommitId : null, buildVersion: s_buildInfo?.IsDeveloperBuild == false ? s_buildInfo.Build : null); if (engine == null) { return engineState; } if (configuration.Export.SnapshotFile.IsValid && configuration.Export.SnapshotMode != SnapshotMode.None) { engine.SetSnapshotCollector( new SnapshotCollector( loggingContext, configuration.Export.SnapshotFile, configuration.Export.SnapshotMode, m_commandLineArguments)); } var loggingQueue = m_configuration.Logging.EnableAsyncLogging.GetValueOrDefault() ? new LoggingQueue() : null; var asyncLoggingContext = new LoggingContext(loggingContext.ActivityId, loggingContext.LoggerComponentInfo, loggingContext.Session, loggingContext, loggingQueue); BuildXLEngineResult result = null; // All async logging needs to complete before code that checks the state of logging contexts or tracking event listeners. // The interactions with app loggers (specifically with the TrackingEventListener) presume all // logged events have been flushed. If async logging were still active the state may not be correct // with respect to the Engine's return value. using (loggingQueue?.EnterAsyncLoggingScope(asyncLoggingContext)) { result = engine.Run(asyncLoggingContext, engineState); } Contract.AssertNotNull(result, "Running the engine should return a valid engine result."); // Graph caching complicates some things. we'll have to reload state which invalidates the pathtable and everything that holds // a pathtable like configuration. m_pathTable = engine.Context.PathTable; m_configuration = engine.Configuration; if (!result.IsSuccess) { // if this returns false, we better have seen some errors being logged Contract.Assert( trackingEventListener.HasFailures && loggingContext.ErrorWasLogged, I($"The build has failed but the logging infrastructure has not encountered an error. TrackingEventListener has errors:[{trackingEventListener.HasFailures}.] LoggingContext has errors:[{string.Join(", ", loggingContext.ErrorsLoggedById.ToArray())}]")); } var engineRunDuration = (int)(DateTime.UtcNow - m_startTimeUtc).TotalMilliseconds; AppPerformanceInfo appPerfInfo = new AppPerformanceInfo { AppInitializationDurationMs = appInitializationDurationMs, EnginePerformanceInfo = result.EnginePerformanceInfo, ServerModeUsed = m_appHost is AppServer, ServerModeEnabled = m_initialConfiguration.Server == ServerMode.Enabled, EngineRunDurationMs = engineRunDuration, }; ReportStatsForBuildSummary(appPerfInfo); if (m_configuration.Engine.LogStatistics) { BuildXL.Tracing.Logger.Log.Statistic( loggingContext, new Statistic() { Name = Statistics.WarningWasLogged, Value = loggingContext.WarningWasLogged ? 1 : 0, }); BuildXL.Tracing.Logger.Log.Statistic( loggingContext, new Statistic() { Name = Statistics.ErrorWasLogged, Value = loggingContext.ErrorWasLogged ? 1 : 0, }); BuildXL.Tracing.Logger.Log.Statistic( loggingContext, new Statistic() { Name = Statistics.TimeToEngineRunCompleteMs, Value = engineRunDuration, }); AnalyzeAndLogPerformanceSummary(loggingContext, configuration, appPerfInfo); } return result.EngineState; } /// <summary> /// Analyzes and logs a performance summary. All of the data logged in this message is available in various places in /// the standard and stats log. This just consolidates it together in a human consumable format /// </summary> public void AnalyzeAndLogPerformanceSummary(LoggingContext context, ICommandLineConfiguration config, AppPerformanceInfo perfInfo) { // Don't bother logging this stuff if we don't actually have the data if (perfInfo == null || perfInfo.EnginePerformanceInfo == null || perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo == null) { return; } // Various heuristics for what caused the build to be slow. using (var sbPool = Pools.GetStringBuilder()) { SchedulerPerformanceInfo schedulerInfo = perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo; Contract.RequiresNotNull(schedulerInfo); long loadOrConstructGraph = perfInfo.EnginePerformanceInfo.GraphCacheCheckDurationMs + perfInfo.EnginePerformanceInfo.GraphReloadDurationMs + perfInfo.EnginePerformanceInfo.GraphConstructionDurationMs; // Log the summary // High level var graphConstruction = ComputeTimePercentage(loadOrConstructGraph, perfInfo.EngineRunDurationMs); var appInitialization = ComputeTimePercentage(perfInfo.AppInitializationDurationMs, perfInfo.EngineRunDurationMs); var scrubbing = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.ScrubbingDurationMs, perfInfo.EngineRunDurationMs); var schedulerInit = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.SchedulerInitDurationMs, perfInfo.EngineRunDurationMs); var executePhase = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.ExecutePhaseDurationMs, perfInfo.EngineRunDurationMs); var highLevelOther = Math.Max(0, 100 - appInitialization.Item1 - graphConstruction.Item1 - scrubbing.Item1 - schedulerInit .Item1 - executePhase.Item1); // Graph construction var checkingForPipGraphReuse = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphCacheCheckDurationMs, loadOrConstructGraph); var reloadingPipGraph = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphReloadDurationMs, loadOrConstructGraph); var createGraph = ComputeTimePercentage(perfInfo.EnginePerformanceInfo.GraphConstructionDurationMs, loadOrConstructGraph); var graphConstructionOtherPercent = Math.Max(0, 100 - checkingForPipGraphReuse.Item1 - reloadingPipGraph.Item1 - createGraph.Item1); // Process Overhead long allStepsDuration = 0; foreach (var enumValue in Enum.GetValues(typeof(PipExecutionStep))) { if (enumValue is PipExecutionStep step) { allStepsDuration += (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(step).TotalMilliseconds; } } // ExecuteProcessDuration comes from the PipExecutionCounters and is a bit tighter around the actual external // process invocation than the corresponding counter in PipExecutionStepCounters; long allStepsMinusPipExecution = allStepsDuration - schedulerInfo.ExecuteProcessDurationMs; var hashingInputs = ComputeTimePercentage( (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.Start).TotalMilliseconds, allStepsMinusPipExecution); var checkingForCacheHit = ComputeTimePercentage( (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.CacheLookup).TotalMilliseconds + (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.CheckIncrementalSkip).TotalMilliseconds, allStepsMinusPipExecution); var processOutputs = ComputeTimePercentage( (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.PostProcess).TotalMilliseconds, allStepsMinusPipExecution); var replayFromCache = ComputeTimePercentage( (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.RunFromCache).TotalMilliseconds + (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.MaterializeOutputs).TotalMilliseconds + (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.MaterializeInputs).TotalMilliseconds, allStepsMinusPipExecution); var prepareSandbox = ComputeTimePercentage( schedulerInfo.SandboxedProcessPrepDurationMs, allStepsMinusPipExecution); var nonProcessPips = ComputeTimePercentage( (long)schedulerInfo.PipExecutionStepCounters.GetElapsedTime(PipExecutionStep.ExecuteNonProcessPip).TotalMilliseconds, allStepsMinusPipExecution); var processOverheadOther = Math.Max(0, 100 - hashingInputs.Item1 - checkingForCacheHit.Item1 - processOutputs.Item1 - replayFromCache.Item1 - prepareSandbox.Item1 - nonProcessPips.Item1); StringBuilder sb = new StringBuilder(); if (schedulerInfo.DiskStatistics != null) { foreach (var item in schedulerInfo.DiskStatistics) { sb.AppendFormat("{0}:{1}% ", item.Drive, item.CalculateActiveTime(lastOnly: false)); } } // The performance summary looks at counters that don't get aggregated and sent back to the master from // all workers. So it only applies to single machine builds. if (config.Distribution.BuildWorkers == null || config.Distribution.BuildWorkers.Count == 0) { Logger.Log.DominoPerformanceSummary( context, processPipsCacheHit: (int)schedulerInfo.ProcessPipCacheHits, cacheHitRate: ComputeTimePercentage(schedulerInfo.ProcessPipCacheHits, schedulerInfo.TotalProcessPips).Item1, incrementalSchedulingPrunedPips: (int)schedulerInfo.ProcessPipIncrementalSchedulingPruned, incrementalSchedulingPruneRate: ComputeTimePercentage(schedulerInfo.ProcessPipIncrementalSchedulingPruned, schedulerInfo.TotalProcessPips).Item1, totalProcessPips: (int)schedulerInfo.TotalProcessPips, serverUsed: perfInfo.ServerModeUsed, graphConstructionPercent: graphConstruction.Item3, appInitializationPercent: appInitialization.Item3, scrubbingPercent: scrubbing.Item3, schedulerInitPercent: schedulerInit.Item3, executePhasePercent: executePhase.Item3, highLevelOtherPercent: highLevelOther, checkingForPipGraphReusePercent: checkingForPipGraphReuse.Item3, reloadingPipGraphPercent: reloadingPipGraph.Item3, createGraphPercent: createGraph.Item3, graphConstructionOtherPercent: graphConstructionOtherPercent, processExecutePercent: ComputeTimePercentage(schedulerInfo.ExecuteProcessDurationMs, allStepsDuration).Item1, telemetryTagsPercent: ComputeTelemetryTagsPerformanceSummary(schedulerInfo), processRunningPercent: ComputeTimePercentage(allStepsMinusPipExecution, allStepsDuration).Item1, hashingInputs: hashingInputs.Item1, checkingForCacheHit: checkingForCacheHit.Item1, processOutputs: processOutputs.Item1, replayFromCache: replayFromCache.Item1, prepareSandbox: prepareSandbox.Item1, processOverheadOther: processOverheadOther, nonProcessPips: nonProcessPips.Item1, averageCpu: schedulerInfo.AverageMachineCPU, minAvailableMemoryMb: (int)schedulerInfo.MachineMinimumAvailablePhysicalMB, diskUsage: sb.ToString(), limitingResourcePercentages: perfInfo.EnginePerformanceInfo.LimitingResourcePercentages ?? new LimitingResourcePercentages()); } if (schedulerInfo.ProcessPipsUncacheable > 0) { LogPerfSmell(context, () => Logger.Log.ProcessPipsUncacheable(context, schedulerInfo.ProcessPipsUncacheable)); } // Make sure there were some misses since a complete noop with incremental scheduling shouldn't cause this to trigger if (schedulerInfo.CriticalPathTableHits == 0 && schedulerInfo.CriticalPathTableMisses != 0) { LogPerfSmell(context, () => Logger.Log.NoCriticalPathTableHits(context)); } // Make sure some source files were hashed since a complete noop build with incremental scheduling shouldn't cause this to trigger if (schedulerInfo.FileContentStats.SourceFilesUnchanged == 0 && schedulerInfo.FileContentStats.SourceFilesHashed != 0) { LogPerfSmell(context, () => Logger.Log.NoSourceFilesUnchanged(context)); } if (!perfInfo.ServerModeEnabled) { LogPerfSmell(context, () => Logger.Log.ServerModeDisabled(context)); } if (!perfInfo.EnginePerformanceInfo.GraphCacheCheckJournalEnabled) { LogPerfSmell(context, () => Logger.Log.GraphCacheCheckJournalDisabled(context)); } if (perfInfo.EnginePerformanceInfo.CacheInitializationDurationMs > 5000) { LogPerfSmell(context, () => Logger.Log.SlowCacheInitialization(context, perfInfo.EnginePerformanceInfo.CacheInitializationDurationMs)); } if (perfInfo.EnginePerformanceInfo.SchedulerPerformanceInfo.HitLowMemorySmell) { LogPerfSmell(context, () => Scheduler.Tracing.Logger.Log.HitLowMemorySmell(context)); } if (config.Sandbox.LogProcesses) { LogPerfSmell(context, () => Logger.Log.LogProcessesEnabled(context)); } if (perfInfo.EnginePerformanceInfo.FrontEndIOWeight > 5) { LogPerfSmell(context, () => Logger.Log.FrontendIOSlow(context, perfInfo.EnginePerformanceInfo.FrontEndIOWeight)); } } } private static string ComputeTelemetryTagsPerformanceSummary(SchedulerPerformanceInfo schedulerInfo) { string telemetryTagPerformanceSummary = string.Empty; if (schedulerInfo != null && schedulerInfo.ProcessPipCountersByTelemetryTag != null && schedulerInfo.ExecuteProcessDurationMs > 0) { var elapsedTimesByTelemetryTag = schedulerInfo.ProcessPipCountersByTelemetryTag.GetElapsedTimes(PipCountersByGroup.ExecuteProcessDuration); // TelemetryTag counters get incremented when a pip is cancelled due to ctrl-c or resource exhaustion. Make sure to include the total // cancelled time in the denomenator when calculating the time percentage var executeAndCancelledExecuteDuration = schedulerInfo.ExecuteProcessDurationMs + schedulerInfo.CanceledProcessExecuteDurationMs; int percentagesTotal = 0; telemetryTagPerformanceSummary = string.Join(Environment.NewLine, elapsedTimesByTelemetryTag.Select( elapedTime => { var computedPercentages = ComputeTimePercentage((long)elapedTime.Value.TotalMilliseconds, executeAndCancelledExecuteDuration); percentagesTotal += computedPercentages.Item1; return string.Format("{0,-12}{1,-39}{2}%", string.Empty, elapedTime.Key, computedPercentages.Item1); })); // Humans are picky about percentages adding up neatly to 100%. Make sure other accounts for any rounding slop telemetryTagPerformanceSummary += string.Format("{0}{1,-12}{2,-39}{3}%{0}", Environment.NewLine, string.Empty, "Other:", 100 - percentagesTotal); } return telemetryTagPerformanceSummary; } private void LogPerfSmell(LoggingContext context, Action action) { if (m_firstSmell) { Logger.Log.BuildHasPerfSmells(context); m_firstSmell = false; } action(); } private bool m_firstSmell = true; private static Tuple<int, string, string> ComputeTimePercentage(long numerator, long denominator) { int percent = 0; if (denominator > 0) { percent = (int)(100.0 * numerator / denominator); } string time = (int)TimeSpan.FromMilliseconds(numerator).TotalSeconds + "sec"; string combined = percent + "% (" + time + ")"; return new Tuple<int, string, string>(percent, time, combined); } private void ReportStatsForBuildSummary(AppPerformanceInfo appInfo) { var summary = m_buildViewModel.BuildSummary; if (summary == null) { return; } // Overall Duration information var tree = new PerfTree("Build Duration", appInfo.EngineRunDurationMs) { new PerfTree("Application Initialization", appInfo.AppInitializationDurationMs) }; var engineInfo = appInfo.EnginePerformanceInfo; if (engineInfo != null) { tree.Add(new PerfTree("Graph Construction", engineInfo.GraphCacheCheckDurationMs + engineInfo.GraphReloadDurationMs + engineInfo.GraphConstructionDurationMs) { new PerfTree("Checking for pip graph reuse", engineInfo.GraphCacheCheckDurationMs), new PerfTree("Reloading pip graph", engineInfo.GraphReloadDurationMs), new PerfTree("Create graph", engineInfo.GraphConstructionDurationMs) }); tree.Add(new PerfTree("Scrubbing", engineInfo.ScrubbingDurationMs)); tree.Add(new PerfTree("Scheduler Initialization", engineInfo.SchedulerInitDurationMs)); tree.Add(new PerfTree("Execution Phase", engineInfo.ExecutePhaseDurationMs)); // Cache stats var schedulerInfo = engineInfo.SchedulerPerformanceInfo; if (schedulerInfo != null) { summary.CacheSummary.ProcessPipCacheHit = schedulerInfo.ProcessPipCacheHits; summary.CacheSummary.TotalProcessPips = schedulerInfo.TotalProcessPips; } } summary.DurationTree = tree; } [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Caller is responsible for disposing these objects.")] internal static IConsole CreateStandardConsole(LightConfig lightConfig) { PathTranslator translator; PathTranslator.CreateIfEnabled(lightConfig.SubstTarget, lightConfig.SubstSource, out translator); return new StandardConsole(lightConfig.Color, lightConfig.AnimateTaskbar, lightConfig.FancyConsole, translator); } [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Caller is responsible for disposing these objects.")] internal static IConsole CreateStandardConsole(ILoggingConfiguration loggingConfiguration, PathTable pathTable) { PathTranslator translator = null; if (!loggingConfiguration.DisableLoggedPathTranslation) { PathTranslator.CreateIfEnabled(loggingConfiguration.SubstTarget, loggingConfiguration.SubstSource, pathTable, out translator); } if (loggingConfiguration.OptimizeConsoleOutputForAzureDevOps || loggingConfiguration.OptimizeProgressUpdatingForAzureDevOps || loggingConfiguration.OptimizeVsoAnnotationsForAzureDevOps) { // Use a very simple logger for azure devops return new StandardConsole(colorize: false, animateTaskbar: false, supportsOverwriting: false, pathTranslator: translator); } return new StandardConsole(loggingConfiguration.Color, loggingConfiguration.AnimateTaskbar, loggingConfiguration.FancyConsole, translator); } private void WriteToConsole(string format, params object[] args) { m_console.WriteOutputLine(MessageLevel.Info, string.Format(CultureInfo.InvariantCulture, format, args)); } private void WriteWarningToConsole(string format, params object[] args) { m_console.WriteOutputLine(MessageLevel.Warning, string.Format(CultureInfo.InvariantCulture, format, args)); } private void WriteErrorToConsole(string format, params object[] args) { m_console.WriteOutputLine(MessageLevel.Error, string.Format(CultureInfo.InvariantCulture, format, args)); } private void WriteErrorToConsoleWithDefaultColor(string format, params object[] args) { m_console.WriteOutputLine(MessageLevel.ErrorNoColor, string.Format(CultureInfo.InvariantCulture, format, args)); } } /// <nodoc /> internal static class VerbosityLevelExtensions { /// <nodoc /> public static EventLevel ToEventLevel(this VerbosityLevel level) { switch (level) { case VerbosityLevel.Error: return EventLevel.Error; case VerbosityLevel.Warning: return EventLevel.Warning; case VerbosityLevel.Informational: return EventLevel.Informational; case VerbosityLevel.Verbose: return EventLevel.Verbose; case VerbosityLevel.Off: Contract.Assert(false, "Should not need conversion if it is disabled."); return EventLevel.Informational; default: Contract.Assert(false, "Unsupported verbosity level"); return EventLevel.Informational; } } } /// <summary> /// Performance related information about the BuildXLApp run /// </summary> public sealed class AppPerformanceInfo { /// <nodoc/> public long AppInitializationDurationMs; /// <nodoc/> public bool ServerModeEnabled; /// <nodoc/> public bool ServerModeUsed; /// <nodoc/> public EnginePerformanceInfo EnginePerformanceInfo; /// <nodoc/> public long EngineRunDurationMs; } }
49.850657
302
0.5743
[ "MIT" ]
erikma/BuildXL
Public/Src/App/Bxl/BuildXLApp.cs
125,175
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace AspNetCoreTest.Models.ManageViewModels { public class ConfigureTwoFactorViewModel { public string SelectedProvider { get; set; } public ICollection<SelectListItem> Providers { get; set; } } }
23.1875
66
0.752022
[ "MIT" ]
JRPSoft/Examples
testes_donet_core/teste_mvc/Models/ManageViewModels/ConfigureTwoFactorViewModel.cs
371
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.Formatting; using Microsoft.DotNet.Interactive.ValueSharing; using Newtonsoft.Json.Linq; namespace Microsoft.DotNet.Interactive.Http { public class VariableRouter : IRouter { private readonly Kernel _kernel; public VariableRouter(Kernel kernel) { _kernel = kernel ?? throw new ArgumentNullException(nameof(kernel)); } public VirtualPathData GetVirtualPath(VirtualPathContext context) { return null; } public async Task RouteAsync(RouteContext context) { if (context.HttpContext.Request.Method == HttpMethods.Get) { SingleVariableRequest(context); } else if (context.HttpContext.Request.Method == HttpMethods.Post) { await BatchVariableRequest(context); } } private async Task BatchVariableRequest(RouteContext context) { var segments = context.HttpContext .Request .Path .Value .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.Length == 1 && segments[0] == "variables") { using var reader = new StreamReader(context.HttpContext.Request.Body); var source = await reader.ReadToEndAsync(); var query = JObject.Parse(source); var response = new JObject(); foreach (var kernelProperty in query.Properties()) { var kernelName = kernelProperty.Name; var propertyBag = new JObject(); response[kernelName] = propertyBag; var targetKernel = GetKernel(kernelName); if (targetKernel is null) { context.Handler = async httpContext => { httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync($"kernel {kernelName} not found"); await httpContext.Response.CompleteAsync(); }; return; } if (targetKernel.SupportsCommand<RequestValue>() || targetKernel is ISupportGetValue) { foreach (var variableName in kernelProperty.Value.Values<string>()) { var value = TryGetValue(targetKernel, variableName); if (value is {} ) { propertyBag[variableName] = JToken.Parse(value.Value); } else { context.Handler = async httpContext => { httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync($"variable {variableName} not found on kernel {kernelName}"); await httpContext.Response.CompleteAsync(); }; return; } } } else { context.Handler = async httpContext => { httpContext.Response.StatusCode = 400; await httpContext.Response.WriteAsync($"kernel {kernelName} doesn't support RequestValue"); await httpContext.Response.CompleteAsync(); }; return; } } context.Handler = async httpContext => { httpContext.Response.ContentType = JsonFormatter.MimeType; await using (var writer = new StreamWriter(httpContext.Response.Body)) { await writer.WriteAsync(response.ToString()); } await httpContext.Response.CompleteAsync(); }; } } private FormattedValue TryGetValue(Kernel targetKernel, string variableName) { if (targetKernel is ISupportGetValue fromInProcessKernel) { if (fromInProcessKernel.TryGetValue(variableName, out object value)) { return new FormattedValue(JsonFormatter.MimeType, value.ToDisplayString(JsonFormatter.MimeType)); } return null; } return null; } private void SingleVariableRequest(RouteContext context) { var segments = context.HttpContext .Request .Path .Value .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (segments.FirstOrDefault() == "variables") { var kernelName = segments[1]; var variableName = segments[2]; var targetKernel = GetKernel(kernelName); if (targetKernel is ISupportGetValue languageKernel) { if (languageKernel.TryGetValue(variableName, out object value)) { context.Handler = async httpContext => { await using (var writer = new StreamWriter(httpContext.Response.Body)) { httpContext.Response.ContentType = JsonFormatter.MimeType; await writer.WriteAsync(value.ToDisplayString(JsonFormatter.MimeType)); } await httpContext.Response.CompleteAsync(); }; } } } } private Kernel GetKernel(string kernelName) { Kernel targetKernel = null; if (_kernel.Name != kernelName) { if (_kernel is CompositeKernel composite) { targetKernel = composite.ChildKernels.FirstOrDefault(k => k.Name == kernelName); } } return targetKernel; } } }
38.22043
135
0.478267
[ "MIT" ]
tommymarto/interactive
src/Microsoft.DotNet.Interactive.Http/VariableRouter.cs
7,111
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON constructor. /// </summary> public partial class JConstructor : JContainer { private string? _name; private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens => _values; internal override int IndexOfItem(JToken? item) { if (item == null) { return -1; } return _values.IndexOfReference(item); } internal override void MergeItem(object content, JsonMergeSettings? settings) { if (!(content is JConstructor c)) { return; } if (c.Name != null) { Name = c.Name; } MergeEnumerableContent(this, c, settings); } /// <summary> /// Gets or sets the name of this constructor. /// </summary> /// <value>The constructor name.</value> public string? Name { get => _name; set => _name = value; } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type => JTokenType.Constructor; /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class. /// </summary> public JConstructor() { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object. /// </summary> /// <param name="other">A <see cref="JConstructor"/> object to copy from.</param> public JConstructor(JConstructor other) : base(other) { _name = other.Name; } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, object content) : this(name) { Add(content); } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name. /// </summary> /// <param name="name">The constructor name.</param> public JConstructor(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException("Constructor name cannot be empty.", nameof(name)); } _name = name; } internal override bool DeepEquals(JToken node) { return (node is JConstructor c && _name == c.Name && ContentsEqual(c)); } internal override JToken CloneToken() { return new JConstructor(this); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartConstructor(_name!); int count = _values.Count; for (int i = 0; i < count; i++) { _values[i].WriteTo(writer, converters); } writer.WriteEndConstructor(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken? this[object key] { get { ValidationUtils.ArgumentNotNull(key, nameof(key)); if (!(key is int i)) { throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } return GetItem(i); } set { ValidationUtils.ArgumentNotNull(key, nameof(key)); if (!(key is int i)) { throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } SetItem(i, value); } } internal override int GetDeepHashCode() { return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode(); } /// <summary> /// Loads a <see cref="JConstructor"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param> /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public new static JConstructor Load(JsonReader reader) { return Load(reader, null); } /// <summary> /// Loads a <see cref="JConstructor"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public new static JConstructor Load(JsonReader reader, JsonLoadSettings? settings) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) { throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); } } reader.MoveToContent(); if (reader.TokenType != JsonToken.StartConstructor) { throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JConstructor c = new JConstructor((string)reader.Value!); c.SetLineInfo(reader as IJsonLineInfo, settings); c.ReadTokenFrom(reader, settings); return c; } } }
36.384
218
0.577177
[ "MIT" ]
1Konto/Newtonsoft.Json
Src/Newtonsoft.Json/Linq/JConstructor.cs
9,098
C#
// Copyright 2020 Energinet DataHub A/S // // Licensed under the Apache License, Version 2.0 (the "License2"); // 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 Energinet.DataHub.MeteringPoints.Application.Validation.ValidationErrors; using FluentValidation; namespace Energinet.DataHub.MeteringPoints.Application.Validation.Rules { public class PostCodeFormatMustBeValidRule : AbstractValidator<Address> { private const string PostCodeDkFormatRegEx = @"^([0-9]{4})$"; private const int MaxPostCodeLength = 10; private readonly string _gsrnNumber; public PostCodeFormatMustBeValidRule(string gsrnNumber) { _gsrnNumber = gsrnNumber; When(address => address.CountryCode.Equals("DK"), PostCodeDenmarkFormat).Otherwise(PostCodeFormatMaxLength); } private void PostCodeDenmarkFormat() { RuleFor(installationLocationAddress => installationLocationAddress.PostCode) .Matches(PostCodeDkFormatRegEx) .WithState(installationLocationAddress => new PostCodeWrongFormatValidationError(_gsrnNumber, installationLocationAddress.PostCode)); } private void PostCodeFormatMaxLength() { RuleFor(installationLocationAddress => installationLocationAddress.PostCode) .MaximumLength(MaxPostCodeLength) .WithState(installationLocationAddress => new PostCodeMaximumLengthValidationError(_gsrnNumber, installationLocationAddress.PostCode, MaxPostCodeLength)); } } }
42.765957
170
0.725871
[ "Apache-2.0" ]
pronovo-ag/geh-metering-point
source/Energinet.DataHub.MeteringPoints.Application/Validation/Rules/PostCodeFormatMustBeValidRule.cs
2,012
C#
// <copyright file="CharacterWalkHandlerPlugIn075.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.GameServer.MessageHandler { using System.Runtime.InteropServices; using MUnique.OpenMU.Network.Packets.ClientToServer; using MUnique.OpenMU.Network.PlugIns; using MUnique.OpenMU.PlugIns; /// <summary> /// Packet handler for walk packets. /// </summary> [PlugIn("Character walk handler", "Packet handler for walk packets.")] [Guid("9FD41038-39D9-4D3D-A1DD-A87DB6388248")] [MinimumClient(0, 75, ClientLanguage.Invariant)] internal class CharacterWalkHandlerPlugIn075 : CharacterWalkBaseHandlerPlugIn { /// <inheritdoc/> public override byte Key => WalkRequest075.Code; } }
37.26087
101
0.723454
[ "MIT" ]
psydox/OpenMU
src/GameServer/MessageHandler/CharacterWalkHandlerPlugIn075.cs
859
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Lighthouse.V20200324.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateFirewallRulesRequest : AbstractModel { /// <summary> /// 实例 ID。 /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// 防火墙规则列表。 /// </summary> [JsonProperty("FirewallRules")] public FirewallRule[] FirewallRules{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamArrayObj(map, prefix + "FirewallRules.", this.FirewallRules); } } }
30.627451
86
0.645967
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Lighthouse/V20200324/Models/CreateFirewallRulesRequest.cs
1,584
C#
using System; using System.Collections.Generic; using GoogleApi.Entities.Interfaces; namespace GoogleApi.Entities.Places { /// <summary> /// Base abstract class for Places requests. /// </summary> public abstract class BasePlacesRequest : BaseRequest, IRequestQueryString { /// <summary> /// Base Url. /// </summary> protected internal override string BaseUrl => "maps.googleapis.com/maps/api/place/"; /// <summary> /// Always true. Setter is not supported. /// </summary> public override bool IsSsl { get => true; set => throw new NotSupportedException("This operation is not supported, Request must use SSL"); } /// <summary> /// See <see cref="BaseRequest.GetQueryStringParameters()"/>. /// </summary> /// <returns>The <see cref="IList{KeyValuePair}"/> collection.</returns> public override IList<KeyValuePair<string, string>> GetQueryStringParameters() { if (string.IsNullOrWhiteSpace(this.Key)) throw new ArgumentException("Key is required"); var parameters = base.GetQueryStringParameters(); return parameters; } } }
31.6
108
0.602057
[ "MIT" ]
McSym28/GoogleApi
GoogleApi/Entities/Places/BasePlacesRequest.cs
1,266
C#
using DotnetKubernetesClient; using k8s; using k8s.Models; using KubeOps.Operator.Controller; using KubeOps.Operator.Controller.Results; using KubeOps.Operator.Entities.Extensions; using KubeOps.Operator.Events; using KubeOps.Operator.Rbac; using Operator.Entities; namespace Operator.Controller; [EntityRbac(typeof(V1Alpha1Pki), Verbs = RbacVerb.Get | RbacVerb.List | RbacVerb.Watch | RbacVerb.Create)] [EntityRbac( typeof(V1Deployment), typeof(V1Service), typeof(V1ServiceAccount), typeof(V1Role), typeof(V1RoleBinding), Verbs = RbacVerb.Get | RbacVerb.Create)] [EntityRbac(typeof(V1Secret), Verbs = RbacVerb.Get | RbacVerb.Create | RbacVerb.Update)] internal class PkiController : IResourceController<V1Alpha1Pki> { private readonly ILogger<PkiController> _logger; private readonly IKubernetesClient _client; private readonly IEventManager _eventManager; public PkiController(ILogger<PkiController> logger, IKubernetesClient client, IEventManager eventManager) { _logger = logger; _client = client; _eventManager = eventManager; } public async Task<ResourceControllerResult?> ReconcileAsync(V1Alpha1Pki pki) { if (pki.Status.Namespace == null) { pki.Status.Namespace = await _client.GetCurrentNamespace(); await _client.UpdateStatus(pki); } var @namespace = pki.Status.Namespace!; await UpsertServiceAccount(pki, @namespace); await UpsertRole(pki, @namespace); await UpsertRoleBinding(pki, @namespace); await UpsertSecret(pki, @namespace); await UpsertDeployment(pki, @namespace); await UpsertService(pki, @namespace); return null; } public Task DeletedAsync(V1Alpha1Pki entity) => Task.CompletedTask; private async Task UpsertServiceAccount(V1Alpha1Pki pki, string @namespace) { var serviceAccount = await _client.Get<V1ServiceAccount>(pki.Name(), @namespace); if (serviceAccount != null) { return; } _logger.LogInformation( "Creating service account for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); serviceAccount = new V1ServiceAccount().Initialize().WithOwnerReference(pki); serviceAccount.Metadata.Name = pki.Name(); serviceAccount.Metadata.NamespaceProperty = @namespace; serviceAccount.Validate(); try { await _client.Create(serviceAccount); await _eventManager.PublishAsync(pki, "SERVICE_ACCOUNT_CREATED", "Created the service account the PKI."); } catch (Exception e) { _logger.LogError(e, "Could not create service account for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "SERVICE_ACCOUNT_FAILED", $"Could not create secret for PKI: {e}", EventType.Warning); throw; } } private async Task UpsertRole(V1Alpha1Pki pki, string @namespace) { var role = await _client.Get<V1Role>(pki.Name(), @namespace); if (role != null) { return; } _logger.LogInformation( "Creating role for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); role = new V1Role().Initialize().WithOwnerReference(pki); role.Metadata.Name = pki.Name(); role.Metadata.NamespaceProperty = @namespace; role.Rules = new List<V1PolicyRule> { new() { ApiGroups = new List<string> { string.Empty }, Resources = new List<string> { "secrets" }, Verbs = new List<string> { "get", "update" }, }, }; role.Validate(); try { await _client.Create(role); await _eventManager.PublishAsync(pki, "ROLE_CREATED", "Created the role the PKI."); } catch (Exception e) { _logger.LogError(e, "Could not create role for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "ROLE_FAILED", $"Could not create role for PKI: {e}", EventType.Warning); throw; } } private async Task UpsertRoleBinding(V1Alpha1Pki pki, string @namespace) { var roleBinding = await _client.Get<V1RoleBinding>(pki.Name(), @namespace); if (roleBinding != null) { return; } _logger.LogInformation( "Creating role binding for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); roleBinding = new V1RoleBinding().Initialize().WithOwnerReference(pki); roleBinding.Metadata.Name = pki.Name(); roleBinding.Metadata.NamespaceProperty = @namespace; roleBinding.RoleRef = new() { Kind = "Role", ApiGroup = "rbac.authorization.k8s.io", Name = pki.Name() }; roleBinding.Subjects = new List<V1Subject> { new() { Kind = "ServiceAccount", Name = pki.Name(), NamespaceProperty = @namespace, }, }; roleBinding.Validate(); try { await _client.Create(roleBinding); await _eventManager.PublishAsync(pki, "ROLE_BINDING_CREATED", "Created the role binding the PKI."); } catch (Exception e) { _logger.LogError(e, "Could not create role binding for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "ROLE_BINDING_FAILED", $"Could not create role binding for PKI: {e}", EventType.Warning); throw; } } private async Task UpsertSecret(V1Alpha1Pki pki, string @namespace) { var secret = await _client.Get<V1Secret>(pki.Spec.SecretName, @namespace); if (secret != null) { return; } _logger.LogInformation( "Creating secret for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); secret = new V1Secret().Initialize().WithOwnerReference(pki); secret.Metadata.Name = pki.Spec.SecretName; secret.Metadata.NamespaceProperty = @namespace; secret.WriteData("serialNumber", "0"); secret.Validate(); try { await _client.Create(secret); await _eventManager.PublishAsync(pki, "SECRET_CREATED", "Created the secret for CA storage."); } catch (Exception e) { _logger.LogError(e, "Could not create secret for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "SECRET_FAILED", $"Could not create secret for PKI: {e}", EventType.Warning); throw; } } private async Task UpsertDeployment(V1Alpha1Pki pki, string @namespace) { var deployment = await _client.Get<V1Deployment>(pki.Name(), @namespace); if (deployment != null) { return; } _logger.LogInformation( "Creating deployment for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); deployment = new V1Deployment().Initialize().WithOwnerReference(pki); deployment.Metadata.Name = pki.Name(); deployment.Metadata.NamespaceProperty = @namespace; deployment.SetLabel("app.kubernetes.io/name", pki.Name()); deployment.SetLabel("app.kubernetes.io/part-of", "wirepact"); deployment.SetLabel("app.kubernetes.io/component", "pki"); deployment.SetLabel("app.kubernetes.io/managed-by", pki.Name()); deployment.SetLabel("app.kubernetes.io/created-by", "wirepact-operator"); var podLabels = new Dictionary<string, string> { { "app.kubernetes.io/name", pki.Name() }, { "app.kubernetes.io/component", "pki" }, { "app.kubernetes.io/part-of", "wirepact" }, }; deployment.Spec = new V1DeploymentSpec { Selector = new V1LabelSelector(matchLabels: podLabels), RevisionHistoryLimit = 0, }; var probe = new V1Probe { InitialDelaySeconds = 3, TcpSocket = new V1TCPSocketAction { Port = pki.Spec.Port }, }; deployment.Spec.Template = new V1PodTemplateSpec { Metadata = new V1ObjectMeta { Labels = podLabels }, Spec = new V1PodSpec { ServiceAccountName = pki.Name(), Containers = new List<V1Container> { new() { Image = pki.Spec.Image, ImagePullPolicy = "Always", Name = pki.Name(), Args = new List<string> { $"--port={pki.Spec.Port}", $"--secret-name={pki.Spec.SecretName}", }, Resources = new V1ResourceRequirements { Requests = new Dictionary<string, ResourceQuantity> { { "cpu", new ResourceQuantity("50m") }, { "memory", new ResourceQuantity("16Mi") }, }, Limits = new Dictionary<string, ResourceQuantity> { { "cpu", new ResourceQuantity("50m") }, { "memory", new ResourceQuantity("32Mi") }, }, }, ReadinessProbe = probe, LivenessProbe = probe, Ports = new List<V1ContainerPort> { new() { Name = "grpc", ContainerPort = pki.Spec.Port, }, }, }, }, }, }; deployment.Validate(); try { await _client.Create(deployment); await _eventManager.PublishAsync(pki, "DEPLOYMENT_CREATED", "Created the deployment for the PKI."); } catch (Exception e) { _logger.LogError(e, "Could not create deployment for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "DEPLOYMENT_FAILED", $"Could not create deployment for PKI: {e}", EventType.Warning); throw; } } private async Task UpsertService(V1Alpha1Pki pki, string @namespace) { var service = await _client.Get<V1Service>(pki.Name(), @namespace); if (service != null) { return; } _logger.LogInformation( "Creating service for PKI '{name}' in namespace '{namespace}'.", pki.Name(), @namespace); service = new V1Service().Initialize().WithOwnerReference(pki); service.Metadata.Name = pki.Name(); service.Metadata.NamespaceProperty = @namespace; service.SetLabel("app.kubernetes.io/name", pki.Name()); service.SetLabel("app.kubernetes.io/part-of", "wirepact"); service.SetLabel("app.kubernetes.io/component", "pki"); service.SetLabel("app.kubernetes.io/managed-by", pki.Name()); service.SetLabel("app.kubernetes.io/created-by", "wirepact-operator"); service.Spec = new V1ServiceSpec { Ports = new List<V1ServicePort> { new() { Name = "grpc", Port = pki.Spec.Port, TargetPort = pki.Spec.Port, }, }, Selector = new Dictionary<string, string> { { "app.kubernetes.io/name", pki.Name() }, { "app.kubernetes.io/component", "pki" }, { "app.kubernetes.io/part-of", "wirepact" }, }, }; service.Validate(); try { await _client.Create(service); await _eventManager.PublishAsync(pki, "SERVICE_CREATED", "Created the service for the PKI."); pki.Status.DnsAddress = $"{pki.Name()}.{@namespace}:{pki.Spec.Port}"; await _client.UpdateStatus(pki); } catch (Exception e) { _logger.LogError(e, "Could not create service for PKI '{name}'.", pki.Name()); await _eventManager.PublishAsync( pki, "SERVICE_FAILED", $"Could not create service for PKI: {e}", EventType.Warning); pki.Status.DnsAddress = string.Empty; await _client.UpdateStatus(pki); throw; } } }
35.53022
119
0.551535
[ "Apache-2.0" ]
WirePact/k8s-operator
Operator/Controller/PkiController.cs
12,935
C#
using System; using System.Runtime.Serialization; namespace PocketGauger.Exceptions { [Serializable] public class PocketGaugerZipFileMissingRequiredContentException : Exception { protected PocketGaugerZipFileMissingRequiredContentException(SerializationInfo info, StreamingContext context) : base(info, context) { } public PocketGaugerZipFileMissingRequiredContentException() { } public PocketGaugerZipFileMissingRequiredContentException(string message) : base(message) { } public PocketGaugerZipFileMissingRequiredContentException(string message, Exception innerException) : base(message, innerException) { } } }
27.214286
118
0.690289
[ "Apache-2.0" ]
AquaticInformatics/pocket-gauger-field-data-plugin
src/PocketGauger/Exceptions/PocketGaugerZipFileMissingRequiredContentException.cs
764
C#
using System; namespace ImageTo3d { class Program { static void Help() { Options defaults = new Options(); string[] help = new string[] { "ImageTo3D: converts an image file to a 3d STL file.", " by default thickness of the model depends on darkness of the image thicker being darker", "", " ImageTo3D [-b] [-t] [-n] [-mx] [-my] [-w <width-in-mm>] [-minthick <thick-in-mm>]", " [-noborder] [-borderthick <value-in-mm>] [-borderwidth <value-in-mm>]", " [-maxthick <thick-in-mm>] <image-file> [<output-stl-file>]", "", " -b set output format to binary (default)", " -t set output format to text", " -n use the negative image", " -mx mirror image in X", " -my mirror image in Y", " -w set desired width (default " + defaults.DesiredWidth + ")", " -noborder do not add border round image", " -borderthick thickness of border in millimeters (default " + defaults.BorderThickness + ")", " -borderwidth width of border in millimeters (default " + defaults.BorderWidth + ")", " -minthick set minimum thickness in millimeters (default " + defaults.MinThickness + ")", " -maxthick set mmaximum thickness in millimeters (default " + defaults.MaxThickness + ")" }; foreach (string s in help) Console.WriteLine(s); } static void Main(string[] args) { Options options = new Options(); string inFile = null; string outFile = null; try { for (int i = 0; i < args.Length; ++i) { string arg = args[i]; if (arg[0] == '-') { if (arg == "-b") options.Binary = true; else if (arg == "-t") options.Binary = false; else if (arg == "-n") options.Negative = true; else if (arg == "-mx") options.MirrorX = true; else if (arg == "-my") options.MirrorY = true; else if (arg == "-noborder") options.AddBorder = false; else if (arg == "-w") { if (i >= args.Length - 1) throw new ArgumentException(String.Format("Expected value after {0}", arg)); options.DesiredWidth = Single.Parse(args[++i]); } else if (arg == "-minthick") { if (i >= args.Length - 1) throw new ArgumentException(String.Format("Expected value after {0}", arg)); options.MinThickness = Single.Parse(args[++i]); } else if (arg == "-maxthick") { if (i >= args.Length - 1) throw new ArgumentException(String.Format("Expected value after {0}", arg)); options.MaxThickness = Single.Parse(args[++i]); } else if (arg == "-borderthick") { if (i >= args.Length - 1) throw new ArgumentException(String.Format("Expected value after {0}", arg)); options.BorderThickness = Single.Parse(args[++i]); } else if (arg == "-borderwidth") { if (i >= args.Length - 1) throw new ArgumentException(String.Format("Expected value after {0}", arg)); options.BorderWidth = Single.Parse(args[++i]); } else if (arg == "-help") { Help(); System.Environment.Exit(0); } else { throw new ArgumentException("Unrecognized switch: " + arg); } } else if (inFile == null) inFile = arg; else if (outFile == null) outFile = arg; } } catch (Exception ex) { Console.WriteLine("Bad command line: {0}, use -help for description", ex.Message); Environment.Exit(1); } if (inFile == null) { Console.WriteLine("No input file given"); System.Environment.Exit(1); } Generator g = new Generator(options); g.ProcessFile(inFile, outFile); } } }
44.213115
130
0.390805
[ "MIT" ]
JonPahl/ImageTo3d
ImageTo3d/Program.cs
5,396
C#
namespace AcadLib.Geometry { using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Geometry; using JetBrains.Annotations; using AcRx = Autodesk.AutoCAD.Runtime; /// <summary> /// Provides extension methods for the Spline type. /// </summary> public static class SplineExtensions { /// <summary> /// Gets the centroid of the closed planar spline. /// </summary> /// <param name="spl">The instance to which the method applies.</param> /// <returns>The centroid of the spline (WCS coordinates).</returns> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"> /// eNonPlanarEntity is thrown if the Spline is not planar.</exception> /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"> /// eNotApplicable is thrown if the Spline is not closed.</exception> public static Point3d Centroid([NotNull] this Spline spl) { if (!spl.IsPlanar) throw new AcRx.Exception(AcRx.ErrorStatus.NonPlanarEntity); if (spl.Closed != true) throw new AcRx.Exception(AcRx.ErrorStatus.NotApplicable); using var curves = new DBObjectCollection {spl}; using var dDoc = Region.CreateFromCurves(curves); return ((Region)dDoc[0]).Centroid(); } } }
41.272727
79
0.629956
[ "MIT" ]
coordinate/AcadLib
AcadLib/Model/Geometry/SplineExtensions.cs
1,364
C#
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo namespace DotNetNuke.UI.Modules { /// ----------------------------------------------------------------------------- /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Modules /// Class : ModuleCachingType /// ----------------------------------------------------------------------------- /// <summary> /// ModuleCachingType is an enum that provides the caching types for Module Content /// </summary> /// ----------------------------------------------------------------------------- public enum ModuleCachingType { Memory, Disk, Database } }
42.270833
116
0.61656
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/Library/UI/Modules/ModuleCachingType.cs
2,030
C#
namespace StoreAssignment.Constants { using System; using System.Collections.Generic; using System.Text; class ErrorMessages { public static string NULL_EXCEPTION => "Error: {0} can`t be NULL!"; public static string OUT_OF_RANGE_EXCEPTION => "Error: {0} is out of the proper range!"; public static string NEGATIVE_NUMBER_EXCEPTION => "Error: {0} can`t be negative!"; public static string NOT_VALID_TYPE_EXCEPTION => "Error: Invalid Product Type!"; public static string NOT_VALID_CLOTHING_SIZE_EXCEPTION => "Error: Invalid Clothing Size!"; } }
30.65
98
0.69168
[ "MIT" ]
Nextttttt/.NET-StoreAssignment
StoreAssignment/Constants/ErrorMessages.cs
615
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace KMeansClustering { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.333333
42
0.709091
[ "MIT" ]
matthejo/KMeansClustering
src/KMeansClustering/App.xaml.cs
332
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("002 Medium, Normal")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("002 Medium, Normal")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("c99c58af-b0f0-451a-87f9-58bedc49c7ab")] // 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")]
39.054054
85
0.724567
[ "MIT" ]
AppleJack111/Learn_CSharp
Learn_CSharp_Solution/002 Medium, Normal/Properties/AssemblyInfo.cs
1,448
C#
using System; namespace WRC.Shared { public enum WindowsEvent { Shutdown = 0, Restart = 1, VolumeUp = 2, VolumeDown = 3, ToggleMute = 4 } }
13.928571
28
0.507692
[ "MIT" ]
alzhir2009/Win-Remote-Control
WRC.Shared/WindowsEvent.cs
197
C#
 namespace MyPlayStation.API.Requests { public class GetTrophyTitlesRequest { public int Limit { get; set; } = 125; public int Offset { get; set; } = 0; } }
18.6
45
0.596774
[ "MIT" ]
chowarth/MyPlayStation.API
src/MyPlayStation.API/Requests/GetTrophyTitlesRequest.cs
188
C#
namespace Caliburn.Micro.BubblingAction { using System.Windows; public partial class App : Application { public App() { InitializeComponent(); } } }
17.75
43
0.535211
[ "MIT" ]
BrunoJuchli/Caliburn.Micro
samples/Caliburn.Micro.BubblingAction/Caliburn.Micro.BubblingAction/App.xaml.cs
215
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using OdeToFood.Data; using OdeToFood.Models; using System; namespace OdeToFood.Migrations { [DbContext(typeof(OdeToFoodDbContext))] partial class OdeToFoodDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.1-rtm-125") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("OdeToFood.Models.Restaurant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("Cuisine"); b.Property<string>("Name") .IsRequired() .HasMaxLength(80); b.HasKey("Id"); b.ToTable("Restaurants"); }); #pragma warning restore 612, 618 } } }
31.325581
117
0.626578
[ "MIT" ]
georgimanov/OdeToFood
OdeToFood/Migrations/OdeToFoodDbContextModelSnapshot.cs
1,349
C#
// MIT License // // Copyright (c) 2017 Dennis Kingsley // // 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.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Rhino.PlugIns; namespace RhinoORK { public class RhinoOrkPlugin : PlugIn { public RhinoOrkPlugin() { Instance = this; } /// <summary> /// Gets the only instance of the plug-in. /// </summary> public static RhinoOrkPlugin Instance { get; private set; } } }
32.196078
81
0.698538
[ "MIT" ]
dkingsley/RhinoORK
RhinoORK/RhinoOrkPlugin.cs
1,644
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Slack.NetStandard.Auth; using Xunit; namespace Slack.NetStandard.Tests { public class OauthTests { [Fact] public void AccessTokenInformation() { var ati = Utility.ExampleFileContent<AccessTokenInformation>("AccessTokenInformation.json"); Assert.True(ati.OK); Assert.Equal("xoxb-17653672481-19874698323-pdFZKVeTuE8sk7oOcBrzbqgy",ati.AccessToken); Assert.NotNull(ati.AuthedUser); Assert.Equal("commands,incoming-webhook", ati.Scope); Assert.Equal("chat:write", ati.AuthedUser.Scope); } [Fact] public async Task BasicAuthCheck() { var client = new HttpClient(new ActionHandler(async req => { Assert.Equal("Basic", req.Headers.Authorization.Scheme); Assert.Equal("QWxhZGRpbjpPcGVuU2VzYW1l", req.Headers.Authorization.Parameter); Assert.Equal("code=code",await req.Content.ReadAsStringAsync()); },Utility.ExampleFileContent("AccessTokenInformation.json"))); var ati = await OAuthV2Builder.Exchange(client,"code", "Aladdin", "OpenSesame"); } } }
35.026316
104
0.647633
[ "MIT" ]
AbsShek/Slack.NetStandard
Slack.NetStandard.Tests/OauthTests.cs
1,333
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Math.NET Numerics Test Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Math.NET Project")] [assembly: AssemblyProduct("Math.NET Numerics")] [assembly: AssemblyCopyright("Copyright (c) Math.NET Project")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a4a6a08e-5265-4608-a43d-e4f2e210ba2d")] [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")]
31.315789
63
0.757983
[ "MIT" ]
ABarnabyC/mathnet-numerics
src/TestData/Properties/AssemblyInfo.cs
597
C#
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System.Collections.Generic; namespace Org.Apache.Etch.Bindings.Csharp.Util { /// <summary> /// A hashmap which is from string to integer /// </summary> public class StrIntHashMap : Dictionary<string, int?> { public StrIntHashMap() { // nothing to do . } /// <summary> /// Constructs a StrIntHashMap initialized from another /// </summary> /// <param name="other"></param> public StrIntHashMap( StrIntHashMap other ) : base( other ) { } } }
31.454545
63
0.66763
[ "ECL-2.0", "Apache-2.0" ]
apache/etch
binding-csharp/runtime/src/main/csharp/Org.Apache.Etch.Bindings.Csharp/Util/StrIntHashMap.cs
1,384
C#
using System; using System.Collections.Generic; using System.Linq; using Core.Hotkeys.Exceptions; using WinApi.User32; namespace Core.Hotkeys { /// <summary> /// A combination of keyboard key and modifiers (e.g. control+alt) /// </summary> public class Hotkey { /// <summary> /// Create a hotkey from a key and modifier bitset. /// </summary> /// <param name="key">The key.</param> /// <param name="modifiers">A bitset of modifiers.</param> /// <seealso cref="KeyModifierFlags" /> /// <seealso cref="VirtualKey" /> public Hotkey(VirtualKey key, KeyModifierFlags modifiers) { Key = key; Modifiers = modifiers; } /// <summary> /// Create a hotkey from key and modifier strings. /// </summary> /// <param name="key">A string matching a key value.</param> /// <param name="modifiers">A '+'-separated list of modifier values (without the 'MOD_' prefix).</param> public Hotkey(string key, string modifiers) { Key = parseKey(key); Modifiers = ParseModifiers(modifiers); } public VirtualKey Key { get; } public KeyModifierFlags Modifiers { get; } protected bool Equals(Hotkey other) { return Key == other.Key && Modifiers == other.Modifiers; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((Hotkey) obj); } public override int GetHashCode() { return HashCode.Combine((int) Key, (int) Modifiers); } private VirtualKey parseKey(string keyString) { VirtualKey key; if (Enum.TryParse(keyString, true, out key)) if (Enum.IsDefined(typeof(VirtualKey), key) | key.ToString().Contains(",")) return key; throw new InvalidKeyException(keyString); } private static KeyModifierFlags ParseModifier(string modifierString) { modifierString = $"MOD_{modifierString}"; KeyModifierFlags modifier; if (Enum.TryParse(modifierString, true, out modifier)) if (Enum.IsDefined(typeof(KeyModifierFlags), modifier)) return modifier; throw new InvalidKeyException(modifierString); } private static KeyModifierFlags ParseModifiers(string modifierString) { KeyModifierFlags value = 0; foreach (var s in modifierString.Split("+")) value |= ParseModifier(s); return value; } public override string ToString() { IList<string> modifierList = new List<string>(); var modifierEntries = Enum.GetNames<KeyModifierFlags>() .Zip(Enum.GetValues<KeyModifierFlags>()); foreach (var (name, value) in modifierEntries) if ((Modifiers & value) > 0) modifierList.Add(name); var modifierString = string.Join("+", modifierList.ToArray()); return $"{Key}[{modifierString}]"; } } }
33.71
112
0.565114
[ "Apache-2.0" ]
lDisciple/Watrix
src/Core/Hotkeys/Hotkey.cs
3,373
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Threading; using System.Threading.Tasks; using Timer = System.Timers.Timer; namespace System.Data.Dabber { /// <summary> /// 连接池 /// </summary> public class DbConnectionPool { /// <summary> /// 获取连接 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connString"></param> /// <returns></returns> public static T GetConnection<T>(string connString) where T : DbConnection { return DbConnectionPool<T>.GetConnection(connString); } /// <summary> /// 获取连接 /// </summary> /// <param name="connString"></param> /// <param name="CreateConn"></param> /// <returns></returns> public static DbConnection GetConnection(string connString, Func<string, DbConnection> CreateConn) { return DbConnPool<DbConnection>.GetConnection(connString, CreateConn); } } /// <summary> /// 自动生成泛型继承类的通用数据库连接池(推荐使用) /// 当数据库连接为sealed class时请使用DbConnPool /// </summary> /// <typeparam name="T"></typeparam> public class DbConnectionPool<T> where T : DbConnection { private static ConcurrentDictionary<string, DbConnectionPool<T>> _poolDic = new(); /// <summary> /// 获取实例 /// </summary> /// <returns></returns> public static T GetConnection(string connString) { return GetPool(connString).GetInstance(); } /// <summary> /// 获取实例 /// </summary> /// <param name="connString"></param> /// <returns></returns> public static DbConnectionPool<T> GetPool(string connString) { DbConnectionPool<T> pool; if (Monitor.TryEnter(_poolDic, TimeSpan.FromSeconds(5))) { pool = _poolDic.GetOrAdd(connString, (k) => new DbConnectionPool<T>(connString)); Monitor.Exit(_poolDic); } else { pool = new DbConnectionPool<T>(connString); } return pool; } #region // 内部实现 /// <summary> /// 连接池队列 /// </summary> private ConcurrentQueue<T> _connPool = new(); private Timer _clearTimer = new Timer { Enabled = true, // 启用执行 Interval = 1800000, // 半小时执行一次 AutoReset = true, // 一直执行 }; /// <summary> /// 连接字符串 /// </summary> public string ConnString { get; } /// <summary> /// 私有构造 /// </summary> /// <param name="connString"></param> private DbConnectionPool(string connString) { ConnString = connString; // 定时清理连接池 _clearTimer.Elapsed += (s, e) => { if (_connPool.TryDequeue(out T curr)) // 池子里还有东西就继续清理 { if (curr is InnerPool ip) { ip.Release(); } } }; _clearTimer.Start(); } /// <summary> /// 获取实例 /// </summary> /// <returns></returns> public T GetInstance() { if (_connPool.IsEmpty || !_connPool.TryDequeue(out T result)) { result = CreateInstance(ConnString); } return result; } /// <summary> /// 入队 /// </summary> /// <param name="instance"></param> public void Recycle(T instance) { if (instance != null) { _connPool.Enqueue(instance); } } #endregion /// <summary> /// 创建实例 /// </summary> public static Func<string, T> CreateInstance { get; } /// <summary> /// 静态构造 /// </summary> static DbConnectionPool() { var baseType = typeof(T); var poolType = typeof(DbConnectionPool<T>); var baseCtor = baseType.GetConstructor(new Type[] { typeof(String) }); if (baseCtor == null) { throw new Exception($"不支持没有连接字符串构造的[{baseType.Name}]"); } var assemblyName = new AssemblyName(Guid.NewGuid().ToString()); var getPoolMethod = poolType.GetMethod("GetPool", new Type[] { typeof(String) }); var recycleMethod = poolType.GetMethod("Recycle", new Type[] { baseType }); var disposeMethod = baseType.GetMethod("Dispose", BindingFlags.Public | BindingFlags.Instance); #if NETFrame var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #else var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); #endif var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); var typeBuilder = moduleBuilder.DefineType($"DbConnectionPool{baseType.Name}", TypeAttributes.Public | TypeAttributes.Class, baseType, new Type[] { typeof(InnerPool) }); // 创建构造 var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(String) }); ILGenerator ilOfCtor = constructorBuilder.GetILGenerator(); ilOfCtor.Emit(OpCodes.Ldarg_0); ilOfCtor.Emit(OpCodes.Ldarg_1); ilOfCtor.Emit(OpCodes.Call, baseCtor); ilOfCtor.Emit(OpCodes.Ret); // 添加方法 var methodRelease = typeBuilder.DefineMethod("Release", MethodAttributes.Virtual | MethodAttributes.Public); var ilOfRelease = methodRelease.GetILGenerator(); ilOfRelease.Emit(OpCodes.Ldarg_0); ilOfRelease.Emit(OpCodes.Ldarg_1); ilOfRelease.Emit(OpCodes.Call, disposeMethod); ilOfRelease.Emit(OpCodes.Ret); var methodDispose = typeBuilder.DefineMethod("Dispose", MethodAttributes.Virtual | MethodAttributes.Family, null, new Type[] { typeof(bool) }); var ilOfDispose = methodDispose.GetILGenerator(); ilOfDispose.Emit(OpCodes.Ldarg_0); ilOfDispose.Emit(OpCodes.Callvirt, baseType.GetMethod("get_ConnectionString")); ilOfDispose.Emit(OpCodes.Call, getPoolMethod); ilOfDispose.Emit(OpCodes.Ldarg_0); ilOfDispose.Emit(OpCodes.Callvirt, recycleMethod); ilOfDispose.Emit(OpCodes.Ret); var newType = typeBuilder.CreateType(); #if NETFrame // assemblyBuilder.Save(assemblyName.Name + ".dll"); #endif CreateInstance = (connString) => (T)Activator.CreateInstance(newType, connString); } /// <summary> /// 内部池 /// </summary> public interface InnerPool { /// <summary> /// 释放 /// </summary> void Release(); } } /// <summary> /// 再次封装的数据库代理连接池(不推荐使用) /// 如果数据库连接为sealed class时推荐使用 /// </summary> /// <typeparam name="T"></typeparam> public class DbConnPool<T> where T : DbConnection { private static ConcurrentDictionary<string, DbConnPool<T>> _poolDic = new(); /// <summary> /// 获取实例 /// </summary> /// <returns></returns> public static DbConnection GetConnection(string connString, Func<String, T> CreateConn) { return GetPool(connString).GetInstance(CreateConn); } /// <summary> /// 获取实例 /// </summary> /// <param name="connString"></param> /// <returns></returns> public static DbConnPool<T> GetPool(string connString) { DbConnPool<T> pool; if (Monitor.TryEnter(_poolDic, TimeSpan.FromSeconds(5))) { pool = _poolDic.GetOrAdd(connString, (k) => new DbConnPool<T>(connString)); Monitor.Exit(_poolDic); } else { pool = new DbConnPool<T>(connString); } return pool; } #region // 内部实现 /// <summary> /// 连接池队列 /// </summary> private ConcurrentQueue<DbConnProxy> _connPool = new(); private Timer _clearTimer = new Timer { Enabled = true, // 启用执行 Interval = 1800000, // 半小时执行一次 AutoReset = true, // 一直执行 }; /// <summary> /// 连接字符串 /// </summary> public string ConnString { get; } /// <summary> /// 私有构造 /// </summary> /// <param name="connString"></param> private DbConnPool(string connString) { ConnString = connString; // 定时清理连接池 _clearTimer.Elapsed += (s, e) => { if (_connPool.TryDequeue(out DbConnProxy curr)) // 池子里还有东西就继续清理 { curr.Release(); } }; _clearTimer.Start(); } /// <summary> /// 获取实例 /// </summary> /// <returns></returns> public DbConnection GetInstance(Func<string, T> CreateConn) { if (_connPool.IsEmpty || !_connPool.TryDequeue(out DbConnProxy result)) { result = new DbConnProxy(CreateConn(ConnString)); } return result; } /// <summary> /// 入队 /// </summary> /// <param name="instance"></param> public void Recycle(DbConnection instance) { if (instance is DbConnProxy conn) { _connPool.Enqueue(conn); } } #endregion #region // 内部类 /// <summary> /// 带有连接池的连接 /// </summary> internal class DbConnProxy : DbConnection { public T RealConnection { get; } /// <summary> /// 构造 /// </summary> public DbConnProxy(T model) { RealConnection = model; } /// <summary> /// 不释放资源 /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { GetPool(ConnectionString).Recycle(this); } else { RealConnection.Dispose(); base.Dispose(true); } } /// <summary> /// 释放资源 /// </summary> public virtual void Release() { Dispose(false); } #region // 抽象方法实现 public override string ConnectionString { get => RealConnection.ConnectionString; set => RealConnection.ConnectionString = value; } public override string Database => RealConnection.Database; public override string DataSource => RealConnection.DataSource; public override string ServerVersion => RealConnection.ServerVersion; public override ConnectionState State => RealConnection.State; protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { return RealConnection.BeginTransaction(isolationLevel); } public override void ChangeDatabase(string databaseName) { RealConnection.ChangeDatabase(databaseName); } public override void Close() { RealConnection.Close(); } protected override DbCommand CreateDbCommand() { return RealConnection.CreateCommand(); } public override void Open() { RealConnection.Open(); } #endregion #region // 重写方法 //protected override bool CanRaiseEvents => RealConnection.CanRaiseEvents; public override int ConnectionTimeout => RealConnection.ConnectionTimeout; //protected override DbProviderFactory DbProviderFactory => RealConnection.DbProviderFactory; #if NETFx public override void EnlistTransaction(System.Transactions.Transaction transaction) { RealConnection.EnlistTransaction(transaction); } #endif public override bool Equals(object obj) { return RealConnection.Equals(obj); } public override int GetHashCode() { return RealConnection.GetHashCode(); } public override DataTable GetSchema() { return RealConnection.GetSchema(); } public override DataTable GetSchema(string collectionName) { return RealConnection.GetSchema(collectionName); } public override DataTable GetSchema(string collectionName, string[] restrictionValues) { return RealConnection.GetSchema(collectionName, restrictionValues); } //protected override object GetService(Type service) //{ // return RealConnection.GetService(service); //} #if NET50 [Obsolete] #endif public override object InitializeLifetimeService() { return RealConnection.InitializeLifetimeService(); } //protected override void OnStateChange(StateChangeEventArgs stateChange) //{ // RealConnection.OnStateChange(stateChange); //} #if NETFx public override Task OpenAsync(CancellationToken cancellationToken) { return RealConnection.OpenAsync(cancellationToken); } #endif public override ISite Site { get => RealConnection.Site; set => RealConnection.Site = value; } public override string ToString() { return RealConnection.ToString(); } #endregion } #endregion } }
34.027972
181
0.535142
[ "MIT" ]
erikzhouxin/NDabber
src/Dabber/DbConnectionPool.cs
15,146
C#
namespace OpenClosedBefore { public class Triangle { public decimal Width { get; set; } public decimal Height { get; set; } public Triangle() { } public Triangle(decimal width, decimal height) { Width = width; Height = height; } } }
20.875
55
0.502994
[ "MIT" ]
StaticSphere/oop-fundamentals
OpenClosedBefore/Triangle.cs
336
C#
using System.Collections.Generic; using System.Threading.Tasks; using BuildingBlocks.CQRS.Events; namespace University.Students.Application.Services { public interface IMessageBroker { Task PublishAsync(IEnumerable<IEvent> events); } }
23.272727
54
0.769531
[ "MIT" ]
meysamhadeli/University-Microservices
src/Services/Students/University.Students.Application/Services/IMessageBroker.cs
256
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.Diagnostics; using System.Globalization; using System.IO; namespace System.Net.NetworkInformation { internal static partial class StringParsingHelpers { private static readonly string[] s_newLineSeparator = new string[] { Environment.NewLine }; // Used for string splitting internal static int ParseNumSocketConnections(string filePath, string protocolName) { if (!File.Exists(filePath)) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } // Parse the number of active connections out of /proc/net/sockstat string sockstatFile = File.ReadAllText(filePath); int indexOfTcp = sockstatFile.IndexOf(protocolName, StringComparison.Ordinal); int endOfTcpLine = sockstatFile.IndexOf(Environment.NewLine, indexOfTcp + 1, StringComparison.Ordinal); string tcpLineData = sockstatFile.Substring(indexOfTcp, endOfTcpLine - indexOfTcp); StringParser sockstatParser = new StringParser(tcpLineData, ' '); sockstatParser.MoveNextOrFail(); // Skip "<name>:" sockstatParser.MoveNextOrFail(); // Skip: "inuse" return sockstatParser.ParseNextInt32(); } internal static TcpConnectionInformation[] ParseActiveTcpConnectionsFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile) { if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile)) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile); string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile); string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); // First line is header in each file. TcpConnectionInformation[] connections = new TcpConnectionInformation[v4connections.Length + v6connections.Length - 2]; int index = 0; int skip = 0; // TCP Connections for (int i = 1; i < v4connections.Length; i++) // Skip first line header. { string line = v4connections[i]; connections[index] = ParseTcpConnectionInformationFromLine(line); if (connections[index].State == TcpState.Listen) { skip++; } else { index++; } } // TCP6 Connections for (int i = 1; i < v6connections.Length; i++) // Skip first line header. { string line = v6connections[i]; connections[index] = ParseTcpConnectionInformationFromLine(line); if (connections[index].State == TcpState.Listen) { skip++; } else { index++; } } if (skip != 0) { Array.Resize(ref connections, connections.Length - skip); } return connections; } internal static IPEndPoint[] ParseActiveTcpListenersFromFiles(string tcp4ConnectionsFile, string tcp6ConnectionsFile) { if (!File.Exists(tcp4ConnectionsFile) || !File.Exists(tcp6ConnectionsFile)) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } string tcp4FileContents = File.ReadAllText(tcp4ConnectionsFile); string[] v4connections = tcp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); string tcp6FileContents = File.ReadAllText(tcp6ConnectionsFile); string[] v6connections = tcp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); // First line is header in each file. IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2]; int index = 0; int skip = 0; // TCP Connections for (int i = 1; i < v4connections.Length; i++) // Skip first line header. { TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v4connections[i]); if (ti.State == TcpState.Listen) { endPoints[index] = ti.LocalEndPoint; index++; } else { skip++; } } // TCP6 Connections for (int i = 1; i < v6connections.Length; i++) // Skip first line header. { TcpConnectionInformation ti = ParseTcpConnectionInformationFromLine(v6connections[i]); if (ti.State == TcpState.Listen) { endPoints[index] = ti.LocalEndPoint; index++; } else { skip++; } } if (skip != 0) { Array.Resize(ref endPoints, endPoints.Length - skip); } return endPoints; } public static IPEndPoint[] ParseActiveUdpListenersFromFiles(string udp4File, string udp6File) { if (!File.Exists(udp4File) || !File.Exists(udp6File)) { throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); } string udp4FileContents = File.ReadAllText(udp4File); string[] v4connections = udp4FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); string udp6FileContents = File.ReadAllText(udp6File); string[] v6connections = udp6FileContents.Split(s_newLineSeparator, StringSplitOptions.RemoveEmptyEntries); // First line is header in each file. IPEndPoint[] endPoints = new IPEndPoint[v4connections.Length + v6connections.Length - 2]; int index = 0; // UDP Connections for (int i = 1; i < v4connections.Length; i++) // Skip first line header. { string line = v4connections[i]; IPEndPoint endPoint = ParseLocalConnectionInformation(line); endPoints[index++] = endPoint; } // UDP6 Connections for (int i = 1; i < v6connections.Length; i++) // Skip first line header. { string line = v6connections[i]; IPEndPoint endPoint = ParseLocalConnectionInformation(line); endPoints[index++] = endPoint; } return endPoints; } // Parsing logic for local and remote addresses and ports, as well as socket state. internal static TcpConnectionInformation ParseTcpConnectionInformationFromLine(string line) { StringParser parser = new StringParser(line, ' ', skipEmpty: true); parser.MoveNextOrFail(); // skip Index string localAddressAndPort = parser.MoveAndExtractNext(); // local_address IPEndPoint localEndPoint = ParseAddressAndPort(localAddressAndPort); string remoteAddressAndPort = parser.MoveAndExtractNext(); // rem_address IPEndPoint remoteEndPoint = ParseAddressAndPort(remoteAddressAndPort); string socketStateHex = parser.MoveAndExtractNext(); int nativeTcpState; if (!int.TryParse(socketStateHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out nativeTcpState)) { throw ExceptionHelper.CreateForParseFailure(); } TcpState tcpState = MapTcpState(nativeTcpState); return new SimpleTcpConnectionInformation(localEndPoint, remoteEndPoint, tcpState); } // Common parsing logic for the local connection information. private static IPEndPoint ParseLocalConnectionInformation(string line) { StringParser parser = new StringParser(line, ' ', skipEmpty: true); parser.MoveNextOrFail(); // skip Index string localAddressAndPort = parser.MoveAndExtractNext(); int indexOfColon = localAddressAndPort.IndexOf(':'); if (indexOfColon == -1) { throw ExceptionHelper.CreateForParseFailure(); } string remoteAddressString = localAddressAndPort.Substring(0, indexOfColon); IPAddress localIPAddress = ParseHexIPAddress(remoteAddressString); string portString = localAddressAndPort.Substring(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1)); int localPort; if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort)) { throw ExceptionHelper.CreateForParseFailure(); } return new IPEndPoint(localIPAddress, localPort); } private static IPEndPoint ParseAddressAndPort(string colonSeparatedAddress) { int indexOfColon = colonSeparatedAddress.IndexOf(':'); if (indexOfColon == -1) { throw ExceptionHelper.CreateForParseFailure(); } string remoteAddressString = colonSeparatedAddress.Substring(0, indexOfColon); IPAddress ipAddress = ParseHexIPAddress(remoteAddressString); string portString = colonSeparatedAddress.Substring(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1)); int port; if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port)) { throw ExceptionHelper.CreateForParseFailure(); } return new IPEndPoint(ipAddress, port); } // Maps from Linux TCP states to .NET TcpStates. private static TcpState MapTcpState(int state) { return Interop.Sys.MapTcpState((int)state); } internal static IPAddress ParseHexIPAddress(string remoteAddressString) { if (remoteAddressString.Length <= 8) // IPv4 Address { return ParseIPv4HexString(remoteAddressString); } else if (remoteAddressString.Length == 32) // IPv6 Address { return ParseIPv6HexString(remoteAddressString); } else { throw ExceptionHelper.CreateForParseFailure(); } } // Simply converts the hex string into a long and uses the IPAddress(long) constructor. // Strings passed to this method must be 8 or less characters in length (32-bit address). private static IPAddress ParseIPv4HexString(string hexAddress) { IPAddress ipAddress; long addressValue; if (!long.TryParse(hexAddress, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out addressValue)) { throw ExceptionHelper.CreateForParseFailure(); } ipAddress = new IPAddress(addressValue); return ipAddress; } // Parses a 128-bit IPv6 Address stored as 4 concatenated 32-bit hex numbers. // If isSequence is true it assumes that hexAddress is in sequence of IPv6 bytes. // First number corresponds to lower address part // E.g. IP-address: fe80::215:5dff:fe00:402 // It's bytes in direct order: FE-80-00-00 00-00-00-00 02-15-5D-FF FE-00-04-02 // It's represenation in /proc/net/tcp6: 00-00-80-FE 00-00-00-00 FF-5D-15-02 02-04-00-FE // (dashes and spaces added above for readability) // Strings passed to this must be 32 characters in length. private static IPAddress ParseIPv6HexString(string hexAddress, bool isNetworkOrder = false) { Debug.Assert(hexAddress.Length == 32); byte[] addressBytes = new byte[16]; if (isNetworkOrder) { for (int i = 0; i < 16; i++) { addressBytes[i] = (byte)(HexToByte(hexAddress[(i * 2)]) * 16 + HexToByte(hexAddress[(i * 2) + 1])); } } else { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int srcIndex = i * 4 + 3 - j; int targetIndex = i * 4 + j; addressBytes[targetIndex] = (byte)(HexToByte(hexAddress[srcIndex * 2]) * 16 + HexToByte(hexAddress[srcIndex * 2 + 1])); } } } IPAddress ipAddress = new IPAddress(addressBytes); return ipAddress; } private static byte HexToByte(char val) { if (val <= '9' && val >= '0') { return (byte)(val - '0'); } else if (val >= 'a' && val <= 'f') { return (byte)((val - 'a') + 10); } else if (val >= 'A' && val <= 'F') { return (byte)((val - 'A') + 10); } else { throw ExceptionHelper.CreateForParseFailure(); } } } }
40.896552
141
0.567805
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.cs
14,232
C#
using System.Net; namespace TestNinja.Mocking { public interface IDownloadClient { void DownloadFile(string address, string fileName); } public class DownloadClient : IDownloadClient { public void DownloadFile(string address, string fileName) { var client = new WebClient(); client.DownloadFile(address, fileName); } } }
19.333333
65
0.628079
[ "MIT" ]
dreis0/csharp-testing
testing-course/TestNinja/Mocking/DownloadClient.cs
408
C#
using FoxTunes.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using TinyJson; namespace FoxTunes { public class Discogs : BaseComponent, IDisposable { public static RateLimiter RateLimiter { get; private set; } static Discogs() { RateLimiter = new RateLimiter(1000 / MAX_REQUESTS); } public const string BASE_URL = "https://api.discogs.com"; public const string KEY = "XdvMyQSHURdKVmPQJrXv"; public const string SECRET = "VphFeVoRgCzPewlHHWstAheIKSBduLBR"; public const int MAX_REQUESTS = 2; public Discogs(string baseUrl = BASE_URL, string key = KEY, string secret = SECRET, int maxRequests = MAX_REQUESTS) { this.BaseUrl = string.IsNullOrEmpty(baseUrl) ? BASE_URL : baseUrl; this.Key = string.IsNullOrEmpty(key) ? KEY : key; this.Secret = string.IsNullOrEmpty(secret) ? SECRET : secret; if (maxRequests < 0 || maxRequests > 10) { RateLimiter.Interval = 1000 / MAX_REQUESTS; } else { RateLimiter.Interval = 1000 / maxRequests; } } public string BaseUrl { get; private set; } public string Key { get; private set; } public string Secret { get; private set; } public async Task<IEnumerable<Release>> GetReleases(ReleaseLookup releaseLookup, bool master) { var url = this.GetUrl(releaseLookup, master); Logger.Write(this, LogLevel.Debug, "Querying the API: {0}", url); var request = this.CreateRequest(url); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { Logger.Write(this, LogLevel.Warn, "Status code does not indicate success."); return Enumerable.Empty<Release>(); } return await this.GetReleases(response.GetResponseStream()).ConfigureAwait(false); } } protected virtual async Task<IEnumerable<Release>> GetReleases(Stream stream) { const string RESULTS = "results"; using (var reader = new StreamReader(stream)) { var json = await reader.ReadToEndAsync().ConfigureAwait(false); var data = json.FromJson<Dictionary<string, object>>(); if (data != null) { var results = default(object); if (data.TryGetValue(RESULTS, out results) && results is IList<object> resultsList) { return Release.FromResults(resultsList); } } } return Enumerable.Empty<Release>(); } public async Task<ReleaseDetails> GetRelease(Release release) { var url = release.ResourceUrl; Logger.Write(this, LogLevel.Debug, "Querying the API: {0}", url); var request = this.CreateRequest(url); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { Logger.Write(this, LogLevel.Warn, "Status code does not indicate success."); return null; } return await this.GetRelease(response.GetResponseStream()).ConfigureAwait(false); } } protected virtual async Task<ReleaseDetails> GetRelease(Stream stream) { using (var reader = new StreamReader(stream)) { var json = await reader.ReadToEndAsync().ConfigureAwait(false); var data = json.FromJson<Dictionary<string, object>>(); if (data != null) { return new ReleaseDetails(data); } } return default(ReleaseDetails); } public Task<byte[]> GetData(string url) { Logger.Write(this, LogLevel.Debug, "Querying the API: {0}", url); var request = this.CreateRequest(url); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { Logger.Write(this, LogLevel.Warn, "Status code does not indicate success."); #if NET40 return TaskEx.FromResult(default(byte[])); #else return Task.FromResult(default(byte[])); #endif } return this.GetData(response.GetResponseStream()); } } protected virtual Task<byte[]> GetData(Stream stream) { using (var reader = new BinaryReader(stream)) { using (var temp = new MemoryStream()) { var buffer = new byte[10240]; var count = default(int); read: count = reader.Read(buffer, 0, buffer.Length); if (count == 0) { #if NET40 return TaskEx.FromResult(temp.ToArray()); #else return Task.FromResult(temp.ToArray()); #endif } temp.Write(buffer, 0, count); goto read; } } } protected virtual string GetUrl(ReleaseLookup releaseLookup, bool master) { var builder = new StringBuilder(); builder.Append(this.BaseUrl); builder.Append("/database/search?"); if (master) { builder.Append("type=master&"); builder.Append(UrlHelper.GetParameters(new Dictionary<string, string>() { { "artist", releaseLookup.Artist }, { "release_title", releaseLookup.Album }, { "track", releaseLookup.Title } })); } else { builder.Append("query="); builder.Append(this.GetQuery(releaseLookup)); } return builder.ToString(); } protected virtual string GetQuery(ReleaseLookup releaseLookup) { var builder = new StringBuilder(); var parts = new[] { releaseLookup.Artist, releaseLookup.Album, releaseLookup.Title }; foreach (var part in parts) { if (string.IsNullOrEmpty(part)) { continue; } if (builder.Length > 0) { builder.Append(UrlHelper.EscapeDataString(" - ")); } builder.Append(UrlHelper.EscapeDataString(part)); } return builder.ToString(); } protected virtual HttpWebRequest CreateRequest(string url) { var request = WebRequestFactory.Create(url); RateLimiter.Exec(() => { request.UserAgent = string.Format("{0}/{1} +{2}", Publication.Product, Publication.Version, Publication.HomePage); if (this.Key != null && this.Secret != null) { request.Headers[HttpRequestHeader.Authorization] = string.Format("Discogs key={0}, secret={1}", this.Key, this.Secret); } }); return request; } public bool IsDisposed { get; private set; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (this.IsDisposed || !disposing) { return; } this.OnDisposing(); this.IsDisposed = true; } protected virtual void OnDisposing() { //Nothing to do. } ~Discogs() { Logger.Write(this.GetType(), LogLevel.Error, "Component was not disposed: {0}", this.GetType().Name); try { this.Dispose(true); } catch { //Nothing can be done, never throw on GC thread. } } private static readonly Regex IMAGE_SIZE = new Regex(@"(\d{3,4})x(\d{3,4})"); public static int ImageSize(string url) { var match = IMAGE_SIZE.Match(url); if (match.Success) { var a = match.Groups[1].Value; var b = match.Groups[2].Value; var c = default(int); var d = default(int); int.TryParse(a, out c); int.TryParse(b, out d); return c * d; } else { return 0; } } private static readonly Regex PARENTHESIZED = new Regex(@"\s*\([^)]*\)\s*", RegexOptions.Compiled); public static string Sanitize(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } return PARENTHESIZED.Replace(value, string.Empty).Trim(); } public class ReleaseLookup { const int ERROR_CAPACITY = 10; private ReleaseLookup() { this.Id = Guid.NewGuid(); this.MetaData = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); this._Errors = new List<string>(ERROR_CAPACITY); } private ReleaseLookup(IFileData[] fileDatas) : this() { this.FileDatas = fileDatas; } public ReleaseLookup(string artist, string title, IFileData[] fileDatas) : this(fileDatas) { this.Artist = Sanitize(artist); this.Title = Sanitize(title); } public ReleaseLookup(string artist, string album, bool isCompilation, IFileData[] fileDatas) : this(fileDatas) { this.Artist = Sanitize(artist); this.Album = Sanitize(album); this.IsCompilation = isCompilation; } public Guid Id { get; private set; } public string Artist { get; private set; } public string Album { get; private set; } public string Title { get; private set; } public bool IsCompilation { get; private set; } public ReleaseLookupType Type { get { if (!string.IsNullOrEmpty(this.Artist) && !string.IsNullOrEmpty(this.Album)) { return ReleaseLookupType.Album; } else if (!string.IsNullOrEmpty(this.Title)) { return ReleaseLookupType.Track; } return ReleaseLookupType.None; } } public IFileData[] FileDatas { get; private set; } public Discogs.Release Release { get; set; } public IDictionary<string, string> MetaData { get; private set; } private IList<string> _Errors { get; set; } public IEnumerable<string> Errors { get { return this._Errors; } } public ReleaseLookupStatus Status { get; set; } public void AddError(string error) { this._Errors.Add(error); if (this._Errors.Count > ERROR_CAPACITY) { this._Errors.RemoveAt(0); } } public override string ToString() { var builder = new StringBuilder(); builder.Append(Enum.GetName(typeof(ReleaseLookupType), this.Type)); builder.Append(": "); switch (this.Type) { case ReleaseLookupType.Album: builder.AppendFormat("{0} - {1}", this.Artist, this.Album); break; case ReleaseLookupType.Track: if (!string.IsNullOrEmpty(this.Artist)) { builder.AppendFormat("{0} - {1}", this.Artist, this.Title); } else { builder.Append(this.Title); } break; } return builder.ToString(); } public static IEnumerable<ReleaseLookup> FromFileDatas(IEnumerable<IFileData> fileDatas) { return fileDatas.GroupBy(fileData => { var metaData = default(IDictionary<string, string>); lock (fileData.MetaDatas) { metaData = fileData.MetaDatas.ToDictionary( metaDataItem => metaDataItem.Name, metaDataItem => metaDataItem.Value, StringComparer.OrdinalIgnoreCase ); } var artist = metaData.GetValueOrDefault(CommonMetaData.Artist); var album = metaData.GetValueOrDefault(CommonMetaData.Album); var title = metaData.GetValueOrDefault(CommonMetaData.Title); if (!string.IsNullOrEmpty(artist) && !string.IsNullOrEmpty(album)) { var isCompilation = string.Equals( metaData.GetValueOrDefault(CustomMetaData.VariousArtists), bool.TrueString, StringComparison.OrdinalIgnoreCase ); if (isCompilation) { artist = Strings.Discogs_CompilationArtist; } return new { Artist = artist, Album = album, Title = default(string), IsCompilation = isCompilation }; } else { return new { Artist = artist, Album = default(string), Title = title, IsCompilation = default(bool) }; } }).Select(group => { if (!string.IsNullOrEmpty(group.Key.Artist) && !string.IsNullOrEmpty(group.Key.Album)) { return new ReleaseLookup(group.Key.Artist, group.Key.Album, group.Key.IsCompilation, group.ToArray()); } else { return new ReleaseLookup(group.Key.Artist, group.Key.Title, group.ToArray()); } }); } } public enum ReleaseLookupType : byte { None, Album, Track } public enum ReleaseLookupStatus : byte { None, Processing, Complete, Cancelled, Failed } public class Release { public static readonly string None = "none (" + Publication.Version + ")"; private Release(IDictionary<string, object> data) { const string ID = "id"; const string URI = "uri"; const string RESOURCE_URL = "resource_url"; const string TITLE = "title"; const string THUMB = "thumb"; const string COVER_IMAGE = "cover_image"; this.Id = Convert.ToString(data.GetValueOrDefault(ID)); this.Url = Convert.ToString(data.GetValueOrDefault(URI)); this.ResourceUrl = Convert.ToString(data.GetValueOrDefault(RESOURCE_URL)); this.Title = Convert.ToString(data.GetValueOrDefault(TITLE)); this.ThumbUrl = Convert.ToString(data.GetValueOrDefault(THUMB)); this.CoverUrl = Convert.ToString(data.GetValueOrDefault(COVER_IMAGE)); } public string Id { get; private set; } public string Url { get; private set; } public string ResourceUrl { get; private set; } public string Title { get; private set; } public string ThumbUrl { get; private set; } public int ThumbSize { get { return ImageSize(this.ThumbUrl); } } public string CoverUrl { get; private set; } public int CoverSize { get { return ImageSize(this.CoverUrl); } } public float Similarity(ReleaseLookup releaseLookup) { var title = default(string); switch (releaseLookup.Type) { case ReleaseLookupType.Album: title = string.Format("{0} - {1}", releaseLookup.Artist, releaseLookup.Album); break; case ReleaseLookupType.Track: if (!string.IsNullOrEmpty(releaseLookup.Artist)) { title = string.Format("{0} - {1}", releaseLookup.Artist, releaseLookup.Title); } else { title = releaseLookup.Title; } break; } var similarity = Sanitize(this.Title).Similarity(title, true); return similarity; } public static IEnumerable<Release> FromResults(IList<object> results) { if (results != null) { foreach (var result in results) { if (result is IDictionary<string, object> data) { yield return new Release(data); } } } } } public class ReleaseDetails { public ReleaseDetails(IDictionary<string, object> data) { const string ID = "id"; const string URI = "uri"; const string RESOURCE_URL = "resource_url"; const string TITLE = "title"; const string YEAR = "year"; const string ARTISTS = "artists"; const string GENRES = "genres"; const string TRACKLIST = "tracklist"; this.Id = Convert.ToString(data.GetValueOrDefault(ID)); this.Url = Convert.ToString(data.GetValueOrDefault(URI)); this.ResourceUrl = Convert.ToString(data.GetValueOrDefault(RESOURCE_URL)); this.Title = Convert.ToString(data.GetValueOrDefault(TITLE)); this.Year = Convert.ToString(data.GetValueOrDefault(YEAR)); this.Artists = ArtistDetails.FromResults(data.GetValueOrDefault(ARTISTS) as IList<object>).ToArray(); this.Genres = data.GetValueOrDefault(GENRES) is IList<object> genres ? genres.OfType<string>().ToArray() : new string[] { }; this.Tracks = TrackDetails.FromResults(data.GetValueOrDefault(TRACKLIST) as IList<object>).ToArray(); } public string Id { get; private set; } public string Url { get; private set; } public string ResourceUrl { get; private set; } public string Title { get; private set; } public string Year { get; private set; } public ArtistDetails[] Artists { get; private set; } public string[] Genres { get; private set; } public TrackDetails[] Tracks { get; private set; } } public class ArtistDetails { private ArtistDetails(IDictionary<string, object> data) { const string ID = "id"; const string RESOURCE_URL = "resource_url"; const string NAME = "name"; this.Id = Convert.ToString(data.GetValueOrDefault(ID)); this.ResourceUrl = Convert.ToString(data.GetValueOrDefault(RESOURCE_URL)); this.Name = Convert.ToString(data.GetValueOrDefault(NAME)); } public string Id { get; private set; } public string ResourceUrl { get; private set; } public string Name { get; private set; } public static IEnumerable<ArtistDetails> FromResults(IList<object> results) { if (results != null) { foreach (var result in results) { if (result is IDictionary<string, object> data) { yield return new ArtistDetails(data); } } } } } public class TrackDetails { private TrackDetails(IDictionary<string, object> data) { const string POSITION = "position"; const string TITLE = "title"; const string EXTRAARTISTS = "extraartists"; const string TYPE = "type_"; this.Position = Convert.ToString(data.GetValueOrDefault(POSITION)); this.Artists = ArtistDetails.FromResults(data.GetValueOrDefault(EXTRAARTISTS) as IList<object>).ToArray(); this.Title = Convert.ToString(data.GetValueOrDefault(TITLE)); this.Type = Convert.ToString(data.GetValueOrDefault(TYPE)); } public string Position { get; private set; } public ArtistDetails[] Artists { get; private set; } public string Title { get; private set; } public string Type { get; private set; } public static IEnumerable<TrackDetails> FromResults(IList<object> results) { if (results != null) { foreach (var result in results) { if (result is IDictionary<string, object> data) { yield return new TrackDetails(data); } } } } } } }
36.534535
141
0.466587
[ "MIT" ]
Raimusoft/FoxTunes
FoxTunes.MetaData.Discogs/Discogs.cs
24,334
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPool : MonoBehaviour { public static ObjectPool SharedInstance; public GameObject poolObject; List<GameObject> pooledObjects; public int initPoolAmount; public GameObject GetPooledObject() { // Exist : return disabled object for(int i = 0; i < pooledObjects.Count; i++) { if(pooledObjects[i].activeInHierarchy == false) { return pooledObjects[i]; } } // Not exist : Create, expand pool and return the object GameObject temp = CreateObject(); return temp; } GameObject CreateObject() { GameObject temp = Instantiate(poolObject, Vector3.zero, Quaternion.identity, transform); temp.SetActive(false); pooledObjects.Add(temp); return temp; } void Awake() { SharedInstance = this; pooledObjects = new List<GameObject>(); } void Start() { for(int i = 0; i < initPoolAmount; i++) { CreateObject(); } } }
22.346154
96
0.583477
[ "MIT" ]
lunetis/OperationZERO
Assets/Scripts/Utils/ObjectPool.cs
1,162
C#
using Store.Core.Domain.Entities.Default; using Store.Core.Domain.Interfaces.Infrastructures.Data.Contexts; using Microsoft.EntityFrameworkCore; using Store.Infrastructures.Data.EntityMappings.Default; namespace Store.Infrastructures.Data.Contexts { public class DefaultDbContext : DbContext, IDefaultDbContext { public DbSet<Sample> Samples { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Image> Images { get; set; } public DbSet<OrderedProduct> OrderedProducts { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<Customer> Customers { get; set; } protected DefaultDbContext() { Database.Migrate(); } public DefaultDbContext(DbContextOptions options) : base(options) { Database.Migrate(); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new SampleMap()); modelBuilder.ApplyConfiguration(new CategoryMap()); modelBuilder.ApplyConfiguration(new CustomerMap()); modelBuilder.ApplyConfiguration(new ImageMap()); modelBuilder.ApplyConfiguration(new OrderedProductMap()); modelBuilder.ApplyConfiguration(new OrderMap()); modelBuilder.ApplyConfiguration(new ProductMap()); } } }
37.641026
74
0.666213
[ "MIT" ]
isilveira/ModelWrapper
samples/Store/Store.Infrastructures.Data/Contexts/DefaultDbContext.cs
1,470
C#
namespace Idoit.API.Client.CMDB.Category { public class MemoryRequest : IRequest { public int? category_id { get; set; } public int quantity { get; set; } public int title { get; set; } public int manufacturer { get; set; } public int type { get; set; } public float total_capacity { get; set; } public float capacity { get; set; } public int unit { get; set; } public string description { get; set; } } }
32.666667
49
0.583673
[ "MIT" ]
Kleinrotti/Idoit.API.Client
Idoit.API.Client/CMDB/Category/Request/MemoryRequest.cs
492
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.PolicyInsights.Latest { /// <summary> /// The remediation definition. /// Latest API Version: 2019-07-01. /// </summary> [Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:policyinsights:RemediationAtSubscription'.")] [AzureNativeResourceType("azure-native:policyinsights/latest:RemediationAtSubscription")] public partial class RemediationAtSubscription : Pulumi.CustomResource { /// <summary> /// The time at which the remediation was created. /// </summary> [Output("createdOn")] public Output<string> CreatedOn { get; private set; } = null!; /// <summary> /// The deployment status summary for all deployments created by the remediation. /// </summary> [Output("deploymentStatus")] public Output<Outputs.RemediationDeploymentSummaryResponse> DeploymentStatus { get; private set; } = null!; /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Output("filters")] public Output<Outputs.RemediationFiltersResponse?> Filters { get; private set; } = null!; /// <summary> /// The time at which the remediation was last updated. /// </summary> [Output("lastUpdatedOn")] public Output<string> LastUpdatedOn { get; private set; } = null!; /// <summary> /// The name of the remediation. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Output("policyAssignmentId")] public Output<string?> PolicyAssignmentId { get; private set; } = null!; /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Output("policyDefinitionReferenceId")] public Output<string?> PolicyDefinitionReferenceId { get; private set; } = null!; /// <summary> /// The status of the remediation. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Output("resourceDiscoveryMode")] public Output<string?> ResourceDiscoveryMode { get; private set; } = null!; /// <summary> /// The type of the remediation. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a RemediationAtSubscription resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public RemediationAtSubscription(string name, RemediationAtSubscriptionArgs? args = null, CustomResourceOptions? options = null) : base("azure-native:policyinsights/latest:RemediationAtSubscription", name, args ?? new RemediationAtSubscriptionArgs(), MakeResourceOptions(options, "")) { } private RemediationAtSubscription(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:policyinsights/latest:RemediationAtSubscription", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:policyinsights/latest:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-native:policyinsights:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-native:policyinsights/v20180701preview:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20180701preview:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-native:policyinsights/v20190701:RemediationAtSubscription"}, new Pulumi.Alias { Type = "azure-nextgen:policyinsights/v20190701:RemediationAtSubscription"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing RemediationAtSubscription resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static RemediationAtSubscription Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new RemediationAtSubscription(name, id, options); } } public sealed class RemediationAtSubscriptionArgs : Pulumi.ResourceArgs { /// <summary> /// The filters that will be applied to determine which resources to remediate. /// </summary> [Input("filters")] public Input<Inputs.RemediationFiltersArgs>? Filters { get; set; } /// <summary> /// The resource ID of the policy assignment that should be remediated. /// </summary> [Input("policyAssignmentId")] public Input<string>? PolicyAssignmentId { get; set; } /// <summary> /// The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. /// </summary> [Input("policyDefinitionReferenceId")] public Input<string>? PolicyDefinitionReferenceId { get; set; } /// <summary> /// The name of the remediation. /// </summary> [Input("remediationName")] public Input<string>? RemediationName { get; set; } /// <summary> /// The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. /// </summary> [Input("resourceDiscoveryMode")] public InputUnion<string, Pulumi.AzureNative.PolicyInsights.Latest.ResourceDiscoveryMode>? ResourceDiscoveryMode { get; set; } public RemediationAtSubscriptionArgs() { } } }
46.029412
188
0.638722
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/PolicyInsights/Latest/RemediationAtSubscription.cs
7,825
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Composition { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class SpringVector3NaturalMotionAnimation : global::Windows.UI.Composition.Vector3NaturalMotionAnimation { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::System.TimeSpan Period { get { throw new global::System.NotImplementedException("The member TimeSpan SpringVector3NaturalMotionAnimation.Period is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.SpringVector3NaturalMotionAnimation", "TimeSpan SpringVector3NaturalMotionAnimation.Period"); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public float DampingRatio { get { throw new global::System.NotImplementedException("The member float SpringVector3NaturalMotionAnimation.DampingRatio is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.SpringVector3NaturalMotionAnimation", "float SpringVector3NaturalMotionAnimation.DampingRatio"); } } #endif // Forced skipping of method Windows.UI.Composition.SpringVector3NaturalMotionAnimation.DampingRatio.get // Forced skipping of method Windows.UI.Composition.SpringVector3NaturalMotionAnimation.DampingRatio.set // Forced skipping of method Windows.UI.Composition.SpringVector3NaturalMotionAnimation.Period.get // Forced skipping of method Windows.UI.Composition.SpringVector3NaturalMotionAnimation.Period.set } }
48.590909
198
0.778765
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UI.Composition/Generated/3.0.0.0/Windows.UI.Composition/SpringVector3NaturalMotionAnimation.cs
2,138
C#
using GoTiled.Core; namespace GoTiled.Astar; public class GTWeightedPathMap { private readonly List<GTWeightedConnection>[,] _nodes; public GTWeightedPathMap(int sizeX, int sizeY) { _nodes = new List<GTWeightedConnection>[sizeX, sizeY]; for (var x = 0; x < sizeX; x++) { for (var y = 0; y < sizeY; y++) { var connections = new List<GTWeightedConnection>(); _nodes[x, y] = connections; } } } public int SizeX => _nodes.GetLength(0); public int SizeY => _nodes.GetLength(1); public IReadOnlyList<GTWeightedConnection> GetConnections(GTTile tile) { return _nodes[tile.X, tile.Y]; } public IReadOnlyList<GTWeightedConnection> GetConnections(int x, int y) { return _nodes[x, y]; } public IReadOnlyList<GTWeightedConnection> this[int x, int y] => _nodes[x, y]; public void AddConnection(GTTile origin, GTTile destination, float weight) { _nodes[origin.X, origin.Y].Add(new GTWeightedConnection(destination, weight)); } public bool RemoveConnection(GTTile origin, GTTile destination) { var connection = _nodes[origin.X, origin.Y].SingleOrDefault(x => x.Tile == destination); return connection != null && _nodes[origin.X, origin.Y].Remove(connection); } }
28.625
96
0.628093
[ "MIT" ]
GoTiled/GoTiled
Src/GoTiled.Astar/GTWeightedPathMap.cs
1,376
C#
namespace Pushenger.Api { public class TopicResource { } }
10.285714
30
0.625
[ "Apache-2.0" ]
RichWarrior/Pushenger
src/Pushenger.Api/Resources/TopicResource.cs
74
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeatherServiceApp.Pages { public partial class Forecast { } }
14.153846
33
0.744565
[ "MIT" ]
CodeFontana/WeatherService
WeatherServiceApp/Pages/Forecast.cs
186
C#
using System; using HarmonyLib; using RimWorld; namespace EventsPlusCore.CameraPlus { //[HarmonyPatch(typeof(ColonistBarDrawLocsFinder))] //[HarmonyPatch(nameof(ColonistBarDrawLocsFinder.GetDrawLoc))] //public static class HColonistBAr //{ // private const float TopMargine = 36f; // public static void Prefix(ref float groupStartY) // { // groupStartY = TopMargine; // } //} }
23.157895
66
0.656818
[ "MIT" ]
kbatbouta/CameraPlus
Source/Optimizations/H_MoveBar.cs
442
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="AttributeValueBoolean.cs" company="RHEA System S.A."> // // Copyright 2017 RHEA System S.A. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> // ------------------------------------------------------------------------------------------------ namespace ReqIFSharp { using System; using System.Linq; using System.Runtime.Serialization; using System.Xml; /// <summary> /// The purpose of the <see cref="AttributeValueBoolean"/> class is to define a <see cref="bool"/> attribute value. /// </summary> public class AttributeValueBoolean : AttributeValueSimple { /// <summary> /// Initializes a new instance of the <see cref="AttributeValueBoolean"/> class. /// </summary> public AttributeValueBoolean() { } /// <summary> /// Instantiated a new instance of the <see cref="AttributeValueBoolean"/> class /// </summary> /// <param name="attributeDefinition">The <see cref="AttributeDefinitionBoolean"/> for which this is the default value</param> /// <remarks> /// This constructor shall be used when setting the default value of an <see cref="AttributeDefinitionBoolean"/> /// </remarks> internal AttributeValueBoolean(AttributeDefinitionBoolean attributeDefinition) : base(attributeDefinition) { this.OwningDefinition = attributeDefinition; } /// <summary> /// Initializes a new instance of the <see cref="AttributeValueBoolean"/> class. /// </summary> /// <param name="specElAt"> /// The owning <see cref="SpecElementWithAttributes"/> /// </param> internal AttributeValueBoolean(SpecElementWithAttributes specElAt) : base(specElAt) { } /// <summary> /// Gets or sets the attribute value. /// </summary> public bool TheValue { get; set; } /// <summary> /// Gets or sets the value of this <see cref="AttributeValue"/> /// </summary> /// <remarks> /// This is a convenience property to get/set TheValue or Values in concrete implementation /// </remarks> public override object ObjectValue { get => this.TheValue; set { if (!(value is bool castValue)) { throw new InvalidOperationException($"Cannot use {value} as value for this AttributeValueBoolean."); } if (this.TheValue != castValue) { this.TheValue = castValue; NotifyPropertyChanged(); } } } /// <summary> /// Gets or sets a reference to the value definition /// </summary> public AttributeDefinitionBoolean Definition { get; set; } /// <summary> /// Gets or sets the owning attribute definition. /// </summary> public AttributeDefinitionBoolean OwningDefinition { get; set; } /// <summary> /// Gets the <see cref="AttributeDefinition "/> /// </summary> /// <returns> /// An instance of <see cref="AttributeDefinitionBoolean"/> /// </returns> protected override AttributeDefinition GetAttributeDefinition() { return this.Definition; } /// <summary> /// Sets the <see cref="AttributeDefinition"/> /// </summary> /// <param name="attributeDefinition"> /// The <see cref="AttributeDefinition"/> to set /// </param> protected override void SetAttributeDefinition(AttributeDefinition attributeDefinition) { if (attributeDefinition.GetType() != typeof(AttributeDefinitionBoolean)) { throw new ArgumentException("attributeDefinition must of type AttributeDefinitionBoolean"); } this.Definition = (AttributeDefinitionBoolean)attributeDefinition; } /// <summary> /// Generates a <see cref="AttributeValueBoolean"/> object from its XML representation. /// </summary> /// <param name="reader"> /// an instance of <see cref="XmlReader"/> /// </param> public override void ReadXml(XmlReader reader) { var value = reader["THE-VALUE"]; this.TheValue = XmlConvert.ToBoolean(value); while (reader.Read()) { if (reader.ReadToDescendant("ATTRIBUTE-DEFINITION-BOOLEAN-REF")) { var reference = reader.ReadElementContentAsString(); this.Definition = this.ReqIFContent.SpecTypes.SelectMany(x => x.SpecAttributes).OfType<AttributeDefinitionBoolean>().SingleOrDefault(x => x.Identifier == reference); if (this.Definition == null) { throw new InvalidOperationException($"The attribute-definition Boolean {reference} could not be found for the value."); } } } } /// <summary> /// Converts a <see cref="AttributeValueBoolean"/> object into its XML representation. /// </summary> /// <param name="writer"> /// an instance of <see cref="XmlWriter"/> /// </param> /// <exception cref="SerializationException"> /// The <see cref="Definition"/> may not be null /// </exception> public override void WriteXml(XmlWriter writer) { if (this.Definition == null) { throw new SerializationException("The Definition property of an AttributeValueBoolean may not be null"); } writer.WriteAttributeString("THE-VALUE", this.TheValue ? "true" : "false"); writer.WriteStartElement("DEFINITION"); writer.WriteElementString("ATTRIBUTE-DEFINITION-BOOLEAN-REF", this.Definition.Identifier); writer.WriteEndElement(); } } }
37.877095
185
0.563127
[ "Apache-2.0" ]
LBRNZ/reqifsharp_plus
ReqIFSharp/AttributeValue/AttributeValueBoolean.cs
6,782
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.AlertsManagement.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Alert modification item. /// </summary> public partial class AlertModificationItem { /// <summary> /// Initializes a new instance of the AlertModificationItem class. /// </summary> public AlertModificationItem() { CustomInit(); } /// <summary> /// Initializes a new instance of the AlertModificationItem class. /// </summary> /// <param name="modificationEvent">Reason for the modification. /// Possible values include: 'AlertCreated', 'StateChange', /// 'MonitorConditionChange', 'SeverityChange', 'ActionRuleTriggered', /// 'ActionRuleSuppressed', 'ActionsTriggered', 'ActionsSuppressed', /// 'ActionsFailed'</param> /// <param name="oldValue">Old value</param> /// <param name="newValue">New value</param> /// <param name="modifiedAt">Modified date and time</param> /// <param name="modifiedBy">Modified user details (Principal client /// name)</param> /// <param name="comments">Modification comments</param> /// <param name="description">Description of the modification</param> public AlertModificationItem(AlertModificationEvent? modificationEvent = default(AlertModificationEvent?), string oldValue = default(string), string newValue = default(string), string modifiedAt = default(string), string modifiedBy = default(string), string comments = default(string), string description = default(string)) { ModificationEvent = modificationEvent; OldValue = oldValue; NewValue = newValue; ModifiedAt = modifiedAt; ModifiedBy = modifiedBy; Comments = comments; Description = description; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets reason for the modification. Possible values include: /// 'AlertCreated', 'StateChange', 'MonitorConditionChange', /// 'SeverityChange', 'ActionRuleTriggered', 'ActionRuleSuppressed', /// 'ActionsTriggered', 'ActionsSuppressed', 'ActionsFailed' /// </summary> [JsonProperty(PropertyName = "modificationEvent")] public AlertModificationEvent? ModificationEvent { get; set; } /// <summary> /// Gets or sets old value /// </summary> [JsonProperty(PropertyName = "oldValue")] public string OldValue { get; set; } /// <summary> /// Gets or sets new value /// </summary> [JsonProperty(PropertyName = "newValue")] public string NewValue { get; set; } /// <summary> /// Gets or sets modified date and time /// </summary> [JsonProperty(PropertyName = "modifiedAt")] public string ModifiedAt { get; set; } /// <summary> /// Gets or sets modified user details (Principal client name) /// </summary> [JsonProperty(PropertyName = "modifiedBy")] public string ModifiedBy { get; set; } /// <summary> /// Gets or sets modification comments /// </summary> [JsonProperty(PropertyName = "comments")] public string Comments { get; set; } /// <summary> /// Gets or sets description of the modification /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } } }
38.092593
331
0.615459
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/alertsmanagement/Microsoft.Azure.Management.AlertsManagement/src/Generated/Models/AlertModificationItem.cs
4,114
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SecurityHub.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations { /// <summary> /// AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetails Marshaller /// </summary> public class AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetailsMarshaller : IRequestMarshaller<AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetails, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetails requestObject, JsonMarshallerContext context) { if(requestObject.IsSetContainerPath()) { context.Writer.WritePropertyName("ContainerPath"); context.Writer.Write(requestObject.ContainerPath); } if(requestObject.IsSetMountOptions()) { context.Writer.WritePropertyName("MountOptions"); context.Writer.WriteArrayStart(); foreach(var requestObjectMountOptionsListValue in requestObject.MountOptions) { context.Writer.Write(requestObjectMountOptionsListValue); } context.Writer.WriteArrayEnd(); } if(requestObject.IsSetSize()) { context.Writer.WritePropertyName("Size"); context.Writer.Write(requestObject.Size); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetailsMarshaller Instance = new AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetailsMarshaller(); } }
38.037975
208
0.690183
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersTmpfsDetailsMarshaller.cs
3,005
C#
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.DataLake.Store.RetryPolicies; using NLog; namespace Microsoft.Azure.DataLake.Store { /// <summary> /// ADLS Input stream that reads data from a file on Data lake. It reads data in bulk from server to a buffer and then provides buffered output to the client as per request. /// Data can be read asynchronously/synchronously. Data can be read serially or from arbitrary points in file. Read is fully synchronous till the transport layer. ReadAsync is fully asynchronous till the transport layer. /// AdlsInputStream is not threadsafe since it uses buffer (maintains state so not stateless). /// </summary> public class AdlsInputStream : Stream { /// <summary> /// Logger to log messages related to input stream /// </summary> private static readonly Logger IpStreamLog = LogManager.GetLogger("adls.dotnet.InputStream"); /// <summary> /// Filename including the full path /// </summary> private string Filename { get; } /// <summary> /// UUID that is used to obtain the file handler (stream) easily at server /// </summary> private string SessionId { get; } /// <summary> /// ADLS client /// </summary> private AdlsClient Client { get; } /// <summary> /// Metadata of the file. Basically needed to know the total length of the file /// </summary> private DirectoryEntry Entry { get;} /// <summary> /// Internal buffer that stores the data read from server /// </summary> private byte[] Buffer { get; set; } /// <summary> /// Current pointer of the stream in the file. Expressed as bytes from the begining /// </summary> private long FilePointer { get; set; } /// <summary> /// Pointer within the internal buffer array /// </summary> private long BufferPointer { get; set; } /// <summary> /// Number of bytes read from the server /// </summary> private long BufferSize { get; set; } /// <summary> /// Maximum size of the internal buffer /// </summary> private int BufferCapacity { get; } /// <summary> /// Default Maximum size of the internal buffer /// </summary> internal const int DefaultBufferCapacity = 4 * 1024 * 1024; /// <summary> /// Flag whether stream is disposed /// </summary> private bool _isDisposed; /// <summary> /// Whether stream can read data /// </summary> public override bool CanRead => true; /// <summary> /// Whether the stream can seek data /// </summary> public override bool CanSeek => true; /// <summary> /// Whether the stream can write data /// </summary> public override bool CanWrite => false; /// <summary> /// total Length of the file /// </summary> public override long Length =>Entry.Length; /// <summary> /// Position of the stream from begining /// </summary> public override long Position { get => FilePointer; set => Seek(value, SeekOrigin.Begin); } /// <summary> /// Not supported /// </summary> public override void Flush() { throw new NotSupportedException(); } /// <summary> /// Only for Mocking purpose. For mocking purpose you can inherit from this class and override your methods /// </summary> protected AdlsInputStream() { } internal AdlsInputStream(string filename, AdlsClient client, DirectoryEntry der,int bufferCapacity=DefaultBufferCapacity) { Filename = filename; Client = client; Entry = der; SessionId = Guid.NewGuid().ToString(); FilePointer = 0; BufferPointer = 0; BufferSize = 0; BufferCapacity = bufferCapacity; Buffer = new byte[BufferCapacity]; if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream, Created for file {Filename}, client {client.ClientId}"); } } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read /// Synchronous operation. /// </summary> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <returns>Number of bytes read</returns> public override int Read(byte[] output, int offset, int count) { if (!BeforeReadService(output, offset, count)) { return 0; } //Read pointer of the internal buffer has reached the end if (BufferPointer == BufferSize) { int bytesRead = ReadService(); if (bytesRead == 0) { return 0; } } return AfterReadService(output, offset, count); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read /// Asynchronous operation. /// </summary> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <param name="cancelToken">Cancellation Token</param> /// <returns>Number of bytes read</returns> public override async Task<int> ReadAsync(byte[] output, int offset, int count, CancellationToken cancelToken) { if (!BeforeReadService(output, offset, count)) { return 0; } //Read pointer of the internal buffer has reached the end if (BufferPointer == BufferSize) { int bytesRead = await ReadServiceAsync(cancelToken).ConfigureAwait(false); if (bytesRead == 0) { return 0; } } return AfterReadService(output, offset, count); } /// <summary> /// Verifies the Read arguments before it tries to read actual data /// </summary> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <returns>False if we have reached end of the file else true</returns> private bool BeforeReadService(byte[] output, int offset, int count) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (_isDisposed) { throw new ObjectDisposedException("Stream is disposed"); } if (FilePointer >= Entry.Length) return false; if (output != null && (offset >= output.Length || offset < 0)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (output != null && count + offset > output.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace("ADLFileInputStream, Stream read at offset {0} for file {1} for client {2}", FilePointer, Filename, Client.ClientId); } return true; } /// <summary> /// Copies data from it's internal buffer to output. /// </summary> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <returns>Number of bytes read</returns> private int AfterReadService(byte[] output, int offset, int count) { long bytesRemaining = BufferSize - BufferPointer;//Bytes that are not yet read from buffer long toCopyBytes = Math.Min(bytesRemaining, count);//Number of bytes to be returned to the user, if no. of bytes left in buffer is less than what user has wanted then return only those that are left System.Buffer.BlockCopy(Buffer, (int)BufferPointer, output, offset, (int)toCopyBytes); BufferPointer += toCopyBytes;//Update the read pointer of the internal buffer FilePointer += toCopyBytes; return (int)toCopyBytes; } /// <summary> /// Makes the call to server to read data in bulk. Resets Buffer pointer and size. Asynchronous operation. /// </summary> /// <param name="cancelToken">Cancellation Token</param> /// <returns>Number of bytes read</returns> private async Task<int> ReadServiceAsync(CancellationToken cancelToken) { if (BufferPointer < BufferSize) return 0; if (FilePointer >= Entry.Length) return 0; if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream.ReadServiceAsync, Read from server at offset {FilePointer} for file {Filename} for client {Client.ClientId}"); } OperationResponse resp = new OperationResponse(); BufferSize = await Core.OpenAsync(Filename, SessionId, FilePointer, Buffer, 0, BufferCapacity, Client, new RequestOptions(new ExponentialRetryPolicy()), resp, cancelToken).ConfigureAwait(false); if (!resp.IsSuccessful) { throw Client.GetExceptionFromResponse(resp, $"Error in reading file {Filename} at offset {FilePointer}."); } BufferPointer = 0;//Resets the read pointer since new data is read into buffer return (int)BufferSize; } /// <summary> /// Makes the call to server to read data in bulk. Resets Buffer pointer and size. Asynchronous operation. /// </summary> /// <returns>Number of bytes read</returns> private int ReadService() { if (BufferPointer < BufferSize) return 0; if (FilePointer >= Entry.Length) return 0; if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream.ReadService, Read from server at offset {FilePointer} for file {Filename} for client {Client.ClientId}"); } OperationResponse resp = new OperationResponse(); BufferSize = Core.Open(Filename, SessionId, FilePointer, Buffer, 0, BufferCapacity, Client, new RequestOptions(new ExponentialRetryPolicy()), resp); if (!resp.IsSuccessful) { throw Client.GetExceptionFromResponse(resp, $"Error in reading file {Filename} at offset {FilePointer}."); } BufferPointer = 0;//Resets the read pointer since new data is read into buffer return (int)BufferSize; } /// <summary> /// Reads a sequence of bytes directly from the server. It does not update anything in the stream. /// </summary> /// <param name="position">Position in the file from where it should start reading data</param> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <returns>Number of bytes read</returns> public int Read(long position, byte[] output, int offset, int count) { return ReadAsync(position, output, offset, count).GetAwaiter().GetResult(); } /// <summary> /// Reads a sequence of bytes directly from the server. It does not update anything in the stream. /// </summary> /// <param name="position">Position in the file from where it should start reading data</param> /// <param name="output">Output byte array</param> /// <param name="offset">offset at which data should be put in the output array</param> /// <param name="count">Count of the bytes read</param> /// <returns>Number of bytes read</returns> public async Task<int> ReadAsync(long position, byte[] output, int offset, int count) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (output != null && (offset >= output.Length || offset < 0)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (output != null && count + offset > output.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } OperationResponse resp = new OperationResponse(); int bytesRead = await Core.OpenAsync(Filename, SessionId, position, output, offset, count, Client, new RequestOptions(new ExponentialRetryPolicy()), resp).ConfigureAwait(false); if (!resp.IsSuccessful) { throw Client.GetExceptionFromResponse(resp, $"Error in reading file {Filename} at offset {position}."); } if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream.Read, Read offset {offset} for file {Filename} for client {Client.ClientId}"); } return bytesRead; } /// <summary> /// Updates the position of the stream based on SeekOrigin /// </summary> /// <param name="offset">Byte offset relative to the origin parameter</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>Current new position of the stream</returns> public override long Seek(long offset, SeekOrigin origin) { if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream, Seek to offset {offset} from {Enum.GetName(typeof(SeekOrigin), origin)} for file {Filename} for client {Client.ClientId}"); } if (_isDisposed) { throw new ObjectDisposedException("Stream is disposed"); } long prevFilePointer = FilePointer;//Store previous Filepointer if (origin == SeekOrigin.Current) { FilePointer += offset; } else if (origin == SeekOrigin.Begin) { FilePointer = offset; } else//SeekOrigin.End { FilePointer = Entry.Length + offset; } if (FilePointer < 0) { FilePointer = prevFilePointer; throw new IOException("Cannot seek before the begining of the file"); } if (FilePointer > Entry.Length) { FilePointer = prevFilePointer; throw new IOException("Cannot seek beyond the end of the file"); } long diffFilePointer = FilePointer - prevFilePointer;//Calculate the offset between current pointer and new pointer BufferPointer += diffFilePointer;//Update the BufferPointer based on how much the FilePointer moved if (BufferPointer < 0 || BufferPointer >= BufferSize) { BufferPointer = BufferSize = 0;//Current Filepointer points to data which does not exist in buffer } return FilePointer; } /// <summary> /// Not supported /// </summary> /// <param name="value"></param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Not supported /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// Releases the unmanaged resources used by the Stream and optionally releases the managed resources /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources</param> protected override void Dispose(bool disposing) { if (disposing) { Buffer = null; _isDisposed = true; } BufferSize = BufferPointer = 0; FilePointer = 0; if (IpStreamLog.IsTraceEnabled) { IpStreamLog.Trace($"ADLFileInputStream, Closed for file {Filename}, client {Client.ClientId}"); } base.Dispose(disposing); } } }
44.917949
225
0.579404
[ "MIT" ]
pasn/azure-data-lake-store-net
AdlsDotNetSDK/AdlsInputStream.cs
17,520
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Sircl.Website.Data; using System; namespace Sircl.Website.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.690647
125
0.471082
[ "MIT" ]
codetuner/Sircl2
src/Sircl.Website/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
10,478
C#
using System.Reflection; 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("AWSSDK.SecurityHub")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS SecurityHub. AWS Security Hub provides you with a comprehensive view of your security state within AWS and your compliance with the security industry standards and best practices. Security Hub collects security data from across AWS accounts, services, and supported third-party partners and helps you analyze your security trends and identify the highest priority security issues.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.111.8")]
54.375
464
0.764943
[ "Apache-2.0" ]
playstudios/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/SecurityHub/Properties/AssemblyInfo.cs
1,740
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace BuildStudio.Models.AccountViewModels { public class ResetPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.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; } } }
29.964286
125
0.661502
[ "MIT" ]
eduardomessias/build-studio
BuildStudio/Models/AccountViewModels/ResetPasswordViewModel.cs
841
C#
using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace DawaReplication.OData.Controllers { /// <summary> /// Table Bbr_grundjordstykke Controller. /// </summary> public partial class Bbr_grundjordstykkeController : ControllerBase { /// <summary>The typical constructor.</summary> public Bbr_grundjordstykkeController(ODataDBContext db) : base(db) { } /// <summary>Returns table Bbr_grundjordstykke data.</summary> [EnableQuery] public IActionResult Get() { return Ok(_db.Bbr_grundjordstykke); } /// <summary> /// Return the table row data for primarykey key. /// Returns http code 204 'No Content' if the key is not in the table. /// </summary> /// <param name="key">Primary key for table as string.</param> [EnableQuery] public IActionResult Get(string key) { var row = _db.Bbr_grundjordstykke.Select(x => x).FirstOrDefault(c => c.DawaPkey == key); return Ok(row); } } }
30.555556
100
0.618182
[ "MIT" ]
JakobLindekilde/DawaReplication.OData
DawaReplication.OData/Controllers/Bbr_grundjordstykke.cs
1,100
C#
using System; namespace UE4Launcher.Launcher { [Serializable] internal class ProfileItem<T> { public T DefaultValue { get; } public bool IsEnabled { get; set; } public T Value { get; set; } public ProfileItem(T defaultValue = default(T)) { this.DefaultValue = defaultValue; } } }
17.238095
55
0.571823
[ "Apache-2.0" ]
hillin/ue4launcher
ProjectLauncher/Launcher/ProfileItem.cs
364
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; namespace XELibrary { public class GameStateManager : GameComponent, IGameStateManager { private Stack<GameState> states = new Stack<GameState>(); public event EventHandler OnStateChange; private int initialDrawOrder = 1000; private int drawOrder; public GameStateManager(Game game) : base(game) { game.Services.AddService(typeof(IGameStateManager), this); drawOrder = initialDrawOrder; } public void PopState() { RemoveState(); drawOrder -= 100; //Let everyone know we just changed states if (OnStateChange != null) OnStateChange(this, null); } private void RemoveState() { GameState oldState = (GameState)states.Peek(); //Unregister the event for this state OnStateChange -= oldState.StateChanged; //remove the state from our game components Game.Components.Remove(oldState.Value); states.Pop(); } public void PushState(GameState newState) { drawOrder += 100; newState.DrawOrder = drawOrder; AddState(newState); //Let everyone know we just changed states if (OnStateChange != null) OnStateChange(this, null); } private void AddState(GameState state) { states.Push(state); Game.Components.Add(state); //Register the event for this state OnStateChange += state.StateChanged; } public void ChangeState(GameState newState) { //We are changing states, so pop everything ... //if we don’t want to really change states but just modify, //we should call PushState and PopState while (states.Count > 0) RemoveState(); //changing state, reset our draw order newState.DrawOrder = drawOrder = initialDrawOrder; AddState(newState); //Let everyone know we just changed states if (OnStateChange != null) OnStateChange(this, null); } public bool ContainsState(GameState state) { return (states.Contains(state)); } public GameState State { get { return (states.Peek()); } } } }
26.793814
71
0.561755
[ "MIT" ]
kewlniss/XNAUnleashed
Chapter17/XELibrary/GameStateManager.cs
2,603
C#
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using AutoMapper; using Google.Type; using Mandarin.Api.Transactions; using Mandarin.Transactions.External; using NodaTime; using static Mandarin.Api.Transactions.Transactions; namespace Mandarin.Client.Services.Transactions { /// <inheritdoc /> internal sealed class MandarinGrpcTransactionSynchronizer : ITransactionSynchronizer { private readonly IMapper mapper; private readonly TransactionsClient transactionsClient; /// <summary> /// Initializes a new instance of the <see cref="MandarinGrpcTransactionSynchronizer"/> class. /// </summary> /// <param name="mapper">The mapper to translate between different object types.</param> /// <param name="transactionsClient">The gRPC client to Mandarin API for Transactions.</param> public MandarinGrpcTransactionSynchronizer(IMapper mapper, TransactionsClient transactionsClient) { this.mapper = mapper; this.transactionsClient = transactionsClient; } /// <inheritdoc /> public Task LoadExternalTransactionsInPastDay() => throw MandarinGrpcTransactionSynchronizer.UnsupportedException(); /// <inheritdoc /> public Task LoadExternalTransactionsInPast2Months() => throw MandarinGrpcTransactionSynchronizer.UnsupportedException(); /// <inheritdoc /> public async Task LoadExternalTransactions(LocalDate start, LocalDate end) { var request = new SynchronizeTransactionsRequest { Start = this.mapper.Map<Date>(start), End = this.mapper.Map<Date>(end), }; await this.transactionsClient.SynchronizeTransactionsAsync(request); } /// <inheritdoc /> public Task SynchronizeTransactionAsync(ExternalTransactionId externalTransactionId) => throw MandarinGrpcTransactionSynchronizer.UnsupportedException(); private static Exception UnsupportedException([CallerMemberName] string callerMethod = null) { return new NotSupportedException($"Mandarin API does not support {callerMethod}."); } } }
39.892857
161
0.698747
[ "BSD-3-Clause" ]
KK578/Mandarin
src/Mandarin.Client.Services/Transactions/MandarinGrpcTransactionSynchronizer.cs
2,236
C#
#region MIT // // Gorgon. // Copyright (C) 2020 Michael Winsor // // 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 // 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. // // Created: March 6, 2020 1:37:30 PM // #endregion using Gorgon.Editor.UI; namespace Gorgon.Editor.ImageEditor { /// <summary> /// The settings view model for the emboss effect. /// </summary> internal interface IFxEmboss : IHostedPanelViewModel { /// <summary> /// Property to set or return the amount to emboss. /// </summary> int Amount { get; set; } } }
32.680851
80
0.688151
[ "MIT" ]
Tape-Worm/Gorgon
PlugIns/Gorgon.Editor.ImageEditor/_Internal/ViewModels/Fx/_Interfaces/IFxEmboss.cs
1,538
C#
using System.Collections; using UnityEngine.EventSystems; using System.Collections.Generic; using UnityEngine; public class SelectOnInput : MonoBehaviour { public EventSystem eventSystem; public GameObject selectedObject; private bool buttonSelected; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetAxisRaw("Vertical")!=0 && buttonSelected==false){ eventSystem.SetSelectedGameObject(selectedObject); buttonSelected = true; } } private void OnDisable(){ buttonSelected = false; } }
20.678571
63
0.746114
[ "MIT" ]
knevin123/FYP_DragonSim
Dragon Simulator/Assets/Scripts/SelectOnInput.cs
581
C#