content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class TheHouse : MonoBehaviour { public Transform goOutPoint; public Transform theShepherdPoint; public int sheep = 1; public Transform initSheepPoint; public const int maxSheep = 100; [SerializeField] Sprite[] _appearances; [SerializeField] SpriteRenderer _display; [SerializeField] TextMesh _100txt; [SerializeField] string _nextScene; [SerializeField] SettingData _settingData; int _currentAppearanceState; Settings _settings; TheHellFire _hellFire; TheLight _theLight; void Awake () { _settings = FindObjectOfType<Settings> (); _hellFire = FindObjectOfType<TheHellFire> (); _theLight = FindObjectOfType<TheLight> (); _currentAppearanceState = sheep == 100 ? _appearances.Length - 1 : 0; } void Update () { _100txt.text = sheep.ToString (); } public void OnConverted () { sheep = sheep >= maxSheep ? maxSheep : sheep + 1; ChangeAppearanceAsIncrease (); CollectEnough (sheep); } public void OnInfected () { sheep = sheep <= 0 ? 0 : sheep - 1; ChangeAppearanceAsDecrease (); // if (sheep <= 0) // { // _settings.GameOver (); // } } public void OnHealed () { sheep = sheep >= maxSheep ? maxSheep : sheep + 1; ChangeAppearanceAsIncrease (); CollectEnough (sheep); } void CollectEnough (int sheep) { if (sheep < 100) return; _hellFire.GoToStartPoint (.5f); _theLight.SelfDestructTheStars (); StartCoroutine (GotoNextScene (_nextScene)); } IEnumerator GotoNextScene (string scene) { if (string.IsNullOrEmpty (scene)) yield break; yield return new WaitForSeconds (.5f); var loadScene = _settingData.killedCount >= 7000 ? "Daystar appear" : scene; if (loadScene == "Daystar appear") { _settingData.unlockTheDaystar = true; } SceneManager.LoadScene (string.Format ("Scenes/{0}", loadScene)); } void ChangeAppearanceAsIncrease () { if (_currentAppearanceState < 0) { _currentAppearanceState = 0; } var normalizedHp = sheep / 100f; var ratio = 1f / _appearances.Length * (_currentAppearanceState + 1); if (normalizedHp > ratio) { _display.sprite = _appearances[_currentAppearanceState]; ++_currentAppearanceState; } } void ChangeAppearanceAsDecrease () { if (_currentAppearanceState < 0) { _currentAppearanceState = 0; } var normalizedHp = sheep / 100f; var ratio = 1f / _appearances.Length * (_currentAppearanceState + 1); if (normalizedHp <= ratio) { _display.sprite = _appearances[_currentAppearanceState]; --_currentAppearanceState; } } void OnTriggerEnter (Collider other) { if (other.tag == "The Sheep") { var theSheep = other.GetComponent<TheSheep> (); if (theSheep.target.tag == "The House") { ++sheep; theSheep.SelfDestruct (); } } } }
27.632813
85
0.565734
[ "Unlicense" ]
khiemnd777/100
Assets/Scripts/Pillars/TheHouses/TheHouse.cs
3,539
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace MetaDslx.CodeAnalysis.PooledObjects { // Dictionary that can be recycled via an object pool // NOTE: these dictionaries always have the default comparer. public sealed partial class PooledDictionary<K, V> : Dictionary<K, V> where K : notnull { private readonly ObjectPool<PooledDictionary<K, V>> _pool; private PooledDictionary(ObjectPool<PooledDictionary<K, V>> pool, IEqualityComparer<K> keyComparer) : base(keyComparer) { _pool = pool; } public ImmutableDictionary<K, V> ToImmutableDictionaryAndFree() { var result = this.ToImmutableDictionary(this.Comparer); this.Free(); return result; } public ImmutableDictionary<K, V> ToImmutableDictionary() => this.ToImmutableDictionary(this.Comparer); public void Free() { this.Clear(); _pool?.Free(this); } // global pool private static readonly ObjectPool<PooledDictionary<K, V>> s_poolInstance = CreatePool(EqualityComparer<K>.Default); // if someone needs to create a pool; public static ObjectPool<PooledDictionary<K, V>> CreatePool(IEqualityComparer<K> keyComparer) { ObjectPool<PooledDictionary<K, V>>? pool = null; pool = new ObjectPool<PooledDictionary<K, V>>(() => new PooledDictionary<K, V>(pool!, keyComparer), 128); return pool; } public static PooledDictionary<K, V> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } }
35.534483
125
0.622028
[ "Apache-2.0" ]
balazssimon/meta-cs-lite
src/Main/MetaDslx.CodeAnalysis.Common/RoslynUtilities/PooledDictionary.cs
2,063
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder.AI.QnA.Dialogs; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Extensions.Configuration; namespace Microsoft.BotBuilderSamples.Dialog { /// <summary> /// This is an example root dialog. Replace this with your applications. /// </summary> public class RootDialog : ComponentDialog { /// <summary> /// QnA Maker initial dialog /// </summary> private const string InitialDialog = "initial-dialog"; /// <summary> /// Initializes a new instance of the <see cref="RootDialog"/> class. /// </summary> /// <param name="services">Bot Services.</param> public RootDialog(IBotServices services, IConfiguration configuration) : base("root") { AddDialog(new QnAMakerBaseDialog(services, configuration)); AddDialog(new WaterfallDialog(InitialDialog) .AddStep(InitialStepAsync)); // The initial child Dialog to run. InitialDialogId = InitialDialog; } private async Task<DialogTurnResult> InitialStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { return await stepContext.BeginDialogAsync(nameof(QnAMakerDialog), null, cancellationToken); } } }
34.477273
133
0.643375
[ "BSD-3-Clause" ]
AdityaGhai/Chat-Bot
Bot Source Code/Dialog/RootDialog.cs
1,517
C#
namespace Antlr4.StringTemplate.Extensions { using System; internal static class Arrays { public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Func<TInput, TOutput> transform) { if (array == null) throw new ArgumentNullException("array"); if (transform == null) throw new ArgumentNullException("transform"); TOutput[] result = new TOutput[array.Length]; for (int i = 0; i < array.Length; i++) { result[i] = transform(array[i]); } return result; } } }
26.75
108
0.531153
[ "BSD-3-Clause" ]
antlr/antlrcs
Antlr4.StringTemplate/Extensions/Arrays.cs
644
C#
#pragma checksum "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "3aaafc7750c5122046473faca1b24c93abedc3c5" // <auto-generated/> #pragma warning disable 1591 namespace BlazorAdmin.Pages.CatalogItemPage { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using System.Net.Http.Json; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.AspNetCore.Components.WebAssembly.Http; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 10 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using Microsoft.Extensions.Logging; #line default #line hidden #nullable disable #nullable restore #line 11 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorAdmin; #line default #line hidden #nullable disable #nullable restore #line 12 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorAdmin.Shared; #line default #line hidden #nullable disable #nullable restore #line 13 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorAdmin.Services; #line default #line hidden #nullable disable #nullable restore #line 14 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorAdmin.JavaScript; #line default #line hidden #nullable disable #nullable restore #line 15 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorShared.Authorization; #line default #line hidden #nullable disable #nullable restore #line 16 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorShared.Interfaces; #line default #line hidden #nullable disable #nullable restore #line 17 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorInputFile; #line default #line hidden #nullable disable #nullable restore #line 18 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\_Imports.razor" using BlazorShared.Models; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" [Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS)] #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.RouteAttribute("/admin")] public partial class List : BlazorAdmin.Helpers.BlazorComponent { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.AddMarkupContent(0, "<h1>Manage Product Catalog</h1>"); #nullable restore #line 8 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" if (catalogItems == null) { #line default #line hidden #nullable disable __builder.OpenComponent<BlazorAdmin.Shared.Spinner>(1); __builder.CloseComponent(); #nullable restore #line 11 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" } else { #line default #line hidden #nullable disable __builder.OpenElement(2, "p"); __builder.AddAttribute(3, "class", "esh-link-wrapper"); __builder.OpenElement(4, "button"); __builder.AddAttribute(5, "class", "btn btn-primary"); __builder.AddAttribute(6, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 16 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" CreateClick #line default #line hidden #nullable disable )); __builder.AddMarkupContent(7, "\r\n Create New\r\n "); __builder.CloseElement(); __builder.CloseElement(); __builder.OpenElement(8, "table"); __builder.AddAttribute(9, "class", "table table-striped table-hover"); __builder.OpenElement(10, "thead"); __builder.OpenElement(11, "tr"); __builder.AddMarkupContent(12, "<th></th>\r\n "); __builder.AddMarkupContent(13, "<th>Item Type</th>\r\n "); __builder.AddMarkupContent(14, "<th>Brand</th>\r\n "); __builder.AddMarkupContent(15, "<th>Id</th>\r\n "); __builder.AddMarkupContent(16, "<th>Name</th>\r\n "); __builder.OpenElement(17, "th"); __builder.AddContent(18, #nullable restore #line 29 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" nameof(CatalogItem.Description) #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(19, "\r\n "); __builder.OpenElement(20, "th"); __builder.AddContent(21, #nullable restore #line 30 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" nameof(CatalogItem.Price) #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(22, "\r\n "); __builder.AddMarkupContent(23, "<th>Actions</th>"); __builder.CloseElement(); __builder.CloseElement(); __builder.AddMarkupContent(24, "\r\n "); __builder.OpenElement(25, "tbody"); __builder.AddAttribute(26, "class", "cursor-pointer"); #nullable restore #line 35 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" foreach (var item in catalogItems) { #line default #line hidden #nullable disable __builder.OpenElement(27, "tr"); __builder.AddAttribute(28, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 37 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" () => DetailsClick(item.Id) #line default #line hidden #nullable disable )); __builder.OpenElement(29, "td"); __builder.OpenElement(30, "img"); __builder.AddAttribute(31, "class", "img-thumbnail"); __builder.AddAttribute(32, "src", #nullable restore #line 39 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" $"{item.PictureUri}" #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.CloseElement(); __builder.AddMarkupContent(33, "\r\n "); __builder.OpenElement(34, "td"); __builder.AddContent(35, #nullable restore #line 41 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.CatalogType #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(36, "\r\n "); __builder.OpenElement(37, "td"); __builder.AddContent(38, #nullable restore #line 42 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.CatalogBrand #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(39, "\r\n "); __builder.OpenElement(40, "td"); __builder.AddContent(41, #nullable restore #line 43 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.Id #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(42, "\r\n "); __builder.OpenElement(43, "td"); __builder.AddContent(44, #nullable restore #line 44 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.Name #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(45, "\r\n "); __builder.OpenElement(46, "td"); __builder.AddContent(47, #nullable restore #line 45 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.Description #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(48, "\r\n "); __builder.OpenElement(49, "td"); __builder.AddContent(50, #nullable restore #line 46 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" item.Price #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.AddMarkupContent(51, "\r\n "); __builder.OpenElement(52, "td"); __builder.OpenElement(53, "button"); __builder.AddAttribute(54, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 48 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" () => EditClick(item.Id) #line default #line hidden #nullable disable )); __builder.AddEventStopPropagationAttribute(55, "onclick", #nullable restore #line 48 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" true #line default #line hidden #nullable disable ); __builder.AddAttribute(56, "class", "btn btn-primary"); __builder.AddMarkupContent(57, "\r\n Edit\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(58, "\r\n\r\n "); __builder.OpenElement(59, "button"); __builder.AddAttribute(60, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 52 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" () => DeleteClick(item.Id) #line default #line hidden #nullable disable )); __builder.AddEventStopPropagationAttribute(61, "onclick", #nullable restore #line 52 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" true #line default #line hidden #nullable disable ); __builder.AddAttribute(62, "class", "btn btn-danger"); __builder.AddMarkupContent(63, "\r\n Delete\r\n "); __builder.CloseElement(); __builder.CloseElement(); __builder.CloseElement(); #nullable restore #line 57 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" } #line default #line hidden #nullable disable __builder.CloseElement(); __builder.CloseElement(); __builder.OpenComponent<BlazorAdmin.Pages.CatalogItemPage.Details>(64); __builder.AddAttribute(65, "Brands", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogBrand>>( #nullable restore #line 61 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogBrands #line default #line hidden #nullable disable )); __builder.AddAttribute(66, "Types", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogType>>( #nullable restore #line 61 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogTypes #line default #line hidden #nullable disable )); __builder.AddAttribute(67, "OnEditClick", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<System.Int32>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<System.Int32>(this, #nullable restore #line 61 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" EditClick #line default #line hidden #nullable disable ))); __builder.AddComponentReferenceCapture(68, (__value) => { #nullable restore #line 61 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" DetailsComponent = (BlazorAdmin.Pages.CatalogItemPage.Details)__value; #line default #line hidden #nullable disable } ); __builder.CloseComponent(); __builder.AddMarkupContent(69, "\r\n "); __builder.OpenComponent<BlazorAdmin.Pages.CatalogItemPage.Edit>(70); __builder.AddAttribute(71, "Brands", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogBrand>>( #nullable restore #line 62 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogBrands #line default #line hidden #nullable disable )); __builder.AddAttribute(72, "Types", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogType>>( #nullable restore #line 62 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogTypes #line default #line hidden #nullable disable )); __builder.AddAttribute(73, "OnSaveClick", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<System.String>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<System.String>(this, #nullable restore #line 62 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" ReloadCatalogItems #line default #line hidden #nullable disable ))); __builder.AddComponentReferenceCapture(74, (__value) => { #nullable restore #line 62 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" EditComponent = (BlazorAdmin.Pages.CatalogItemPage.Edit)__value; #line default #line hidden #nullable disable } ); __builder.CloseComponent(); __builder.AddMarkupContent(75, "\r\n "); __builder.OpenComponent<BlazorAdmin.Pages.CatalogItemPage.Create>(76); __builder.AddAttribute(77, "Brands", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogBrand>>( #nullable restore #line 63 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogBrands #line default #line hidden #nullable disable )); __builder.AddAttribute(78, "Types", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogType>>( #nullable restore #line 63 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogTypes #line default #line hidden #nullable disable )); __builder.AddAttribute(79, "OnSaveClick", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<System.String>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<System.String>(this, #nullable restore #line 63 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" ReloadCatalogItems #line default #line hidden #nullable disable ))); __builder.AddComponentReferenceCapture(80, (__value) => { #nullable restore #line 63 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" CreateComponent = (BlazorAdmin.Pages.CatalogItemPage.Create)__value; #line default #line hidden #nullable disable } ); __builder.CloseComponent(); __builder.AddMarkupContent(81, "\r\n "); __builder.OpenComponent<BlazorAdmin.Pages.CatalogItemPage.Delete>(82); __builder.AddAttribute(83, "Brands", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogBrand>>( #nullable restore #line 64 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogBrands #line default #line hidden #nullable disable )); __builder.AddAttribute(84, "Types", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Collections.Generic.IEnumerable<BlazorShared.Models.CatalogType>>( #nullable restore #line 64 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" catalogTypes #line default #line hidden #nullable disable )); __builder.AddAttribute(85, "OnSaveClick", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<System.String>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<System.String>(this, #nullable restore #line 64 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" ReloadCatalogItems #line default #line hidden #nullable disable ))); __builder.AddComponentReferenceCapture(86, (__value) => { #nullable restore #line 64 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" DeleteComponent = (BlazorAdmin.Pages.CatalogItemPage.Delete)__value; #line default #line hidden #nullable disable } ); __builder.CloseComponent(); #nullable restore #line 65 "C:\Users\mcanenes\Source\Repos\eShopOnWeb1\src\BlazorAdmin\Pages\CatalogItemPage\List.razor" } #line default #line hidden #nullable disable } #pragma warning restore 1998 } } #pragma warning restore 1591
39.289286
272
0.667757
[ "MIT" ]
mcanenes/Secureshop
src/BlazorAdmin/obj/Debug/net5.0/Razor/Pages/CatalogItemPage/List.razor.g.cs
22,002
C#
using System.Collections.Generic; using System.Globalization; using System.Numerics; using System.Threading.Tasks; using MiningCore.Crypto.Hashing.Ethash; using MiningCore.Extensions; using MiningCore.Stratum; using NBitcoin; using NLog; namespace MiningCore.Blockchain.Ethereum { public class EthereumJob { public EthereumJob(string id, EthereumBlockTemplate blockTemplate, ILogger logger) { Id = id; BlockTemplate = blockTemplate; this.logger = logger; var target = blockTemplate.Target; if (target.StartsWith("0x")) target = target.Substring(2); blockTarget = new uint256(target.HexToByteArray().ReverseArray()); } private readonly Dictionary<StratumClient, HashSet<string>> workerNonces = new Dictionary<StratumClient, HashSet<string>>(); public string Id { get; } public EthereumBlockTemplate BlockTemplate { get; } private readonly uint256 blockTarget; private readonly ILogger logger; private void RegisterNonce(StratumClient worker, string nonce) { var nonceLower = nonce.ToLower(); if (!workerNonces.TryGetValue(worker, out var nonces)) { nonces = new HashSet<string>(new[] { nonceLower }); workerNonces[worker] = nonces; } else { if (nonces.Contains(nonceLower)) throw new StratumException(StratumError.MinusOne, "duplicate share"); nonces.Add(nonceLower); } } public async Task<(Share Share, string FullNonceHex, string HeaderHash, string MixHash)> ProcessShareAsync(StratumClient worker, string nonce, EthashFull ethash) { // duplicate nonce? lock(workerNonces) { RegisterNonce(worker, nonce); } // assemble full-nonce var context = worker.GetContextAs<EthereumWorkerContext>(); var fullNonceHex = context.ExtraNonce1 + nonce; if (!ulong.TryParse(fullNonceHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var fullNonce)) throw new StratumException(StratumError.MinusOne, "bad nonce " + fullNonceHex); // get dag for block var dag = await ethash.GetDagAsync(BlockTemplate.Height, logger); // compute if (!dag.Compute(logger, BlockTemplate.Header.HexToByteArray(), fullNonce, out var mixDigest, out var resultBytes)) throw new StratumException(StratumError.MinusOne, "bad hash"); resultBytes.ReverseArray(); // test if share meets at least workers current difficulty var resultValue = new uint256(resultBytes); var resultValueBig = resultBytes.ToBigInteger(); var shareDiff = (double) BigInteger.Divide(EthereumConstants.BigMaxValue, resultValueBig) / EthereumConstants.Pow2x32; var stratumDifficulty = context.Difficulty; var ratio = shareDiff / stratumDifficulty; var isBlockCandidate = resultValue <= blockTarget; if (!isBlockCandidate && ratio < 0.99) { // check if share matched the previous difficulty from before a vardiff retarget if (context.VarDiff?.LastUpdate != null && context.PreviousDifficulty.HasValue) { ratio = shareDiff / context.PreviousDifficulty.Value; if (ratio < 0.99) throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})"); // use previous difficulty stratumDifficulty = context.PreviousDifficulty.Value; } else throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})"); } // create share var share = new Share { BlockHeight = (long) BlockTemplate.Height, IpAddress = worker.RemoteEndpoint?.Address?.ToString(), Miner = context.MinerName, Worker = context.WorkerName, UserAgent = context.UserAgent, IsBlockCandidate = isBlockCandidate, Difficulty = stratumDifficulty * EthereumConstants.Pow2x32, BlockHash = mixDigest.ToHexString(true) // OW: is this correct? }; if (share.IsBlockCandidate) { fullNonceHex = "0x" + fullNonceHex; var headerHash = BlockTemplate.Header; var mixHash = mixDigest.ToHexString(true); share.TransactionConfirmationData = $"{mixDigest.ToHexString(true)}:{fullNonceHex}"; return (share, fullNonceHex, headerHash, mixHash); } return (share, null, null, null); } } }
38.172932
169
0.596021
[ "MIT" ]
DmytroSliusar/pooltest
src/MiningCore/Blockchain/Ethereum/EthereumJob.cs
5,079
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.EntityFrameworkCore; using ToDoWebApp.Data; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ToDoWebApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddControllersWithViews(); services.AddRazorPages(); services.Configure<IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 1; // Lockout settings. //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); //options.Lockout.MaxFailedAccessAttempts = 5; //options.Lockout.AllowedForNewUsers = true; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); services.ConfigureApplicationCookie(options => { // Cookie settings options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(5); options.LoginPath = "/Identity/Account/Login"; options.AccessDeniedPath = "/Identity/Account/AccessDenied"; options.SlidingExpiration = true; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } }
37.07767
143
0.606441
[ "MIT" ]
VahidDalirii/MVC
ToDoWebApp/ToDoWebApp/Startup.cs
3,819
C#
using System; using System.Windows.Input; using System.Windows.Threading; using GalaSoft.MvvmLight.Threading; namespace SIL.Cog.Presentation.Views { public static class BusyCursor { private static bool _isBusyUntilIdle; private static int _count; public static void DisplayUntilIdle() { DispatcherHelper.CheckBeginInvokeOnUI(() => { Mouse.OverrideCursor = Cursors.Wait; if (!_isBusyUntilIdle) { _isBusyUntilIdle = true; DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => { Mouse.OverrideCursor = null; _isBusyUntilIdle = false; }), DispatcherPriority.ApplicationIdle); } }); } public static IDisposable Display() { if (DispatcherHelper.UIDispatcher.CheckAccess()) StartBusy(); else DispatcherHelper.UIDispatcher.Invoke(StartBusy); return new BusyCursorDisposable(); } private static void StartBusy() { _count++; Mouse.OverrideCursor = Cursors.Wait; } private static void EndBusy() { _count--; if (!_isBusyUntilIdle && _count == 0) Mouse.OverrideCursor = null; } private class BusyCursorDisposable : IDisposable { public void Dispose() { if (DispatcherHelper.UIDispatcher.CheckAccess()) EndBusy(); else DispatcherHelper.UIDispatcher.Invoke(EndBusy); } } } }
20.96875
64
0.682563
[ "MIT" ]
sillsdev/cog
Cog.Presentation/Views/BusyCursor.cs
1,344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace MotherOut.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
28.969697
96
0.693515
[ "MIT" ]
Florida2DAM/MotherOut
BackEnd/MotherOut/MotherOut/Results/ChallengeResult.cs
958
C#
using MyCrm.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyCrm.Data { public interface IRepository<T> where T: BaseEntity { void Insert(T entity); void Update(T entity); void Delete(T entity); T Find(Guid id); IEnumerable<T> GetAll(); } }
19.1
55
0.657068
[ "MIT" ]
oguzhanozpinar/Entity-GenericRepository-UnitOfWork
MyCrrmData/IRepository.cs
384
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("BottomSheet.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BottomSheet.iOS")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.744833
[ "MIT" ]
Ro9ueAdmin/BottomSheetModal
BottomSheet.iOS/Properties/AssemblyInfo.cs
1,406
C#
using FlowScriptEngine; using PPDFramework.Shaders; namespace FlowScriptEnginePPD.FlowSourceObjects.Graphics.ColorFilter.GreenGrayScale { [ToolTipText("ColorFilter_GreenGrayScale_Value_Summary")] public partial class ValueFlowSourceObject : ExecutableFlowSourceObject { public override string Name { get { return "PPD.Graphics.ColorFilter.GreenGrayScale.Value"; } } [ToolTipText("ColorFilter_GreenGrayScale_Value_Filter")] public GreenGrayScaleColorFilter Filter { get; private set; } [ToolTipText("ColorFilter_GreenGrayScale_Value_Weight")] public float Weight { private get; set; } public override void In(FlowEventArgs e) { SetValue(nameof(Weight)); Filter = new GreenGrayScaleColorFilter { Weight = Weight }; OnSuccess(); } } }
25.666667
83
0.601399
[ "Apache-2.0" ]
KHCmaster/PPD
Win/FlowScriptEnginePPD/FlowSourceObjects/Graphics/ColorFilter/GreenGrayScale/ValueFlowSourceObject.cs
1,003
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using static NiceMethods; public class MoveEnemy : MonoBehaviour { private Rigidbody2D rig; private Transform transf; private Orbit orbit; private Collider2D col; private Stats stats; private bool jumpCD; public float speedx; public float accelerationx; public float decelerationx; public float passiveDecelerationx; public float jumpForce; public Transform jumpCheck; public LayerMask level; public LayerMask player; // Start is called before the first frame update void Start() { rig = GetComponent<Rigidbody2D>(); transf = GetComponent<Transform>(); orbit = GetComponent<Orbit>(); col = GetComponent<Collider2D>(); stats = GetComponent<Stats>(); if (decelerationx > 0) decelerationx *= -1; if (passiveDecelerationx > 0) passiveDecelerationx *= -1; } /* void Update() { if(Input.GetKeyDown(KeyCode.K) && Physics2D.OverlapCircle(jumpCheck.position, 0.1f, level)) { rig.AddRelativeForce(new Vector2(0, jumpForce * stats.JumpFactor)); } } */ void FixedUpdate() { Collider2D[] orbitings = orbit.InGravityField; if(orbitings.Length == 1) { float speedx = this.speedx * stats.speedFactor; Rigidbody2D target = orbitings[0].GetComponentInParent<Rigidbody2D>(); Vector2 relativeVelocity = rig.velocity - target.velocity - target.angularVelocity.ToLinearVelocity(transf.position, target.position); float relativeVelRotX = UnRotation(relativeVelocity, rig.rotation).x; if (relativeVelRotX <= speedx && speedx > 0) { rig.AddForce(Rotation(new Vector2(1, 0), rig.rotation) * accelerationx); } if (relativeVelRotX >= speedx && speedx < 0) { rig.AddForce(Rotation(new Vector2(-1, 0), rig.rotation) * accelerationx); } if(Mathf.Abs(relativeVelRotX) > Mathf.Abs(speedx)) { rig.AddForce(Rotation(new Vector2(UnRotation(relativeVelocity, rig.rotation).x, 0), rig.rotation) * passiveDecelerationx); } } DamageOnContact(col, player, 10); } }
31.36
146
0.623724
[ "MIT-0" ]
Dhayson/BestGameTheSol
Sol Project/Assets/Scripts/MoveEnemy.cs
2,352
C#
// Copyright 2011 - 2014 Xamarin Inc // // 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.Reflection; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; #if !NO_SYSTEM_DRAWING using System.Drawing; #endif #if NET using System.Runtime.InteropServices.ObjectiveC; #endif using ObjCRuntime; #if !COREBUILD #if MONOTOUCH using UIKit; #if !WATCH using CoreAnimation; #endif #endif using CoreGraphics; #endif namespace Foundation { public class NSObjectFlag { public static readonly NSObjectFlag Empty; NSObjectFlag () {} } #if NET && !COREBUILD [ObjectiveCTrackedType] #endif [StructLayout (LayoutKind.Sequential)] public partial class NSObject #if !COREBUILD : IEquatable<NSObject> #endif { #if !COREBUILD const string selConformsToProtocol = "conformsToProtocol:"; const string selEncodeWithCoder = "encodeWithCoder:"; #if MONOMAC static IntPtr selConformsToProtocolHandle = Selector.GetHandle (selConformsToProtocol); static IntPtr selEncodeWithCoderHandle = Selector.GetHandle (selEncodeWithCoder); #endif // replace older Mono[Touch|Mac]Assembly field (ease code sharing across platforms) public static readonly Assembly PlatformAssembly = typeof (NSObject).Assembly; IntPtr handle; IntPtr super; /* objc_super* */ #if !NET Flags flags; #else // See "Toggle-ref support for CoreCLR" in coreclr-bridge.m for more information. Flags actual_flags; internal unsafe Runtime.TrackedObjectInfo* tracked_object_info; internal GCHandle? tracked_object_handle; unsafe Flags flags { get { // Get back the InFinalizerQueue flag, it's the only flag we'll set in the tracked object info structure. // The InFinalizerQueue will never be cleared once set, so there's no need to unset it here if it's not set in the tracked_object_info structure. if (tracked_object_info != null && ((tracked_object_info->Flags) & Flags.InFinalizerQueue) == Flags.InFinalizerQueue) actual_flags |= Flags.InFinalizerQueue; return actual_flags; } set { actual_flags = value; // Update the flags value that we can access them from the toggle ref callback as well. if (tracked_object_info != null) tracked_object_info->Flags = value; } } #endif // NET // This enum has a native counterpart in runtime.h [Flags] internal enum Flags : byte { Disposed = 1, NativeRef = 2, IsDirectBinding = 4, RegisteredToggleRef = 8, InFinalizerQueue = 16, HasManagedRef = 32, // 64, // Used by SoM IsCustomType = 128, } // Must be kept in sync with the same enum in trampolines.h enum XamarinGCHandleFlags : uint { None = 0, WeakGCHandle = 1, HasManagedRef = 2, InitialSet = 4, } [StructLayout (LayoutKind.Sequential)] struct objc_super { public IntPtr Handle; public IntPtr ClassHandle; } bool disposed { get { return ((flags & Flags.Disposed) == Flags.Disposed); } set { flags = value ? (flags | Flags.Disposed) : (flags & ~Flags.Disposed); } } bool HasManagedRef { get { return (flags & Flags.HasManagedRef) == Flags.HasManagedRef; } set { flags = value ? (flags | Flags.HasManagedRef) : (flags & ~Flags.HasManagedRef); } } internal bool IsRegisteredToggleRef { get { return ((flags & Flags.RegisteredToggleRef) == Flags.RegisteredToggleRef); } set { flags = value ? (flags | Flags.RegisteredToggleRef) : (flags & ~Flags.RegisteredToggleRef); } } protected internal bool IsDirectBinding { get { return ((flags & Flags.IsDirectBinding) == Flags.IsDirectBinding); } set { flags = value ? (flags | Flags.IsDirectBinding) : (flags & ~Flags.IsDirectBinding); } } internal bool InFinalizerQueue { get { return ((flags & Flags.InFinalizerQueue) == Flags.InFinalizerQueue); } } bool IsCustomType { get { var value = (flags & Flags.IsCustomType) == Flags.IsCustomType; if (!value) { value = Class.IsCustomType (GetType ()); if (value) flags |= Flags.IsCustomType; } return value; } } [Export ("init")] public NSObject () { bool alloced = AllocIfNeeded (); InitializeObject (alloced); } // This is just here as a constructor chain that can will // only do Init at the most derived class. public NSObject (NSObjectFlag x) { bool alloced = AllocIfNeeded (); InitializeObject (alloced); } public NSObject (IntPtr handle) : this (handle, false) { } public NSObject (IntPtr handle, bool alloced) { this.handle = handle; InitializeObject (alloced); } ~NSObject () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } internal static IntPtr CreateNSObject (IntPtr type_gchandle, IntPtr handle, Flags flags) { // This function is called from native code before any constructors have executed. var type = (Type) Runtime.GetGCHandleTarget (type_gchandle); var obj = (NSObject) RuntimeHelpers.GetUninitializedObject (type); obj.handle = handle; obj.flags = flags; return Runtime.AllocGCHandle (obj); } IntPtr GetSuper () { if (super == IntPtr.Zero) { IntPtr ptr; unsafe { ptr = Marshal.AllocHGlobal (sizeof (objc_super)); *(objc_super*) ptr = default (objc_super); // zero fill } var previousValue = Interlocked.CompareExchange (ref super, ptr, IntPtr.Zero); if (previousValue != IntPtr.Zero) { // somebody beat us to the assignment. Marshal.FreeHGlobal (ptr); ptr = IntPtr.Zero; } } unsafe { objc_super* sup = (objc_super*) super; if (sup->ClassHandle == IntPtr.Zero) sup->ClassHandle = ClassHandle; sup->Handle = handle; } return super; } internal static IntPtr Initialize () { return class_ptr; } #if NET internal Flags FlagsInternal { get { return flags; } set { flags = value; } } #endif [MethodImplAttribute (MethodImplOptions.InternalCall)] extern static void RegisterToggleRef (NSObject obj, IntPtr handle, bool isCustomType); [DllImport ("__Internal")] static extern void xamarin_release_managed_ref (IntPtr handle, bool user_type); #if NET static void RegisterToggleRefMonoVM (NSObject obj, IntPtr handle, bool isCustomType) { // We need this indirection for CoreCLR, otherwise JITting RegisterToggleReference will throw System.Security.SecurityException: ECall methods must be packaged into a system module. RegisterToggleRef (obj, handle, isCustomType); } #endif static void RegisterToggleReference (NSObject obj, IntPtr handle, bool isCustomType) { #if NET if (Runtime.IsCoreCLR) { Runtime.RegisterToggleReferenceCoreCLR (obj, handle, isCustomType); } else { RegisterToggleRefMonoVM (obj, handle, isCustomType); } #else RegisterToggleRef (obj, handle, isCustomType); #endif } #if !XAMCORE_3_0 public static bool IsNewRefcountEnabled () { return true; } #endif /* Register the current object with the toggleref machinery if the following conditions are met: -The new refcounting is enabled; and -The class is not a custom type - it must wrap a framework class. */ protected void MarkDirty () { MarkDirty (false); } internal void MarkDirty (bool allowCustomTypes) { if (IsRegisteredToggleRef) return; if (!allowCustomTypes && IsCustomType) return; IsRegisteredToggleRef = true; RegisterToggleReference (this, Handle, allowCustomTypes); } private void InitializeObject (bool alloced) { if (alloced && handle == IntPtr.Zero && Class.ThrowOnInitFailure) { if (ClassHandle == IntPtr.Zero) throw new Exception (string.Format ("Could not create an native instance of the type '{0}': the native class hasn't been loaded.\n" + "It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.", GetType ().FullName)); throw new Exception (string.Format ("Failed to create a instance of the native type '{0}'.\n" + "It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.", new Class (ClassHandle).Name)); } // The authorative value for the IsDirectBinding value is the register attribute: // // [Register ("MyClass", true)] // the second parameter specifies the IsDirectBinding value // class MyClass : NSObject {} // // Unfortunately looking up this attribute every time a class is instantiated is // slow (since fetching attributes is slow), so we guess here: if the actual type // of the object is in the platform assembly, then we assume IsDirectBinding=true: // // IsDirectBinding = (this.GetType ().Assembly == PlatformAssembly); // // and any subclasses in the platform assembly which is not a direct binding have // to set the correct value in their constructors. IsDirectBinding = (this.GetType ().Assembly == PlatformAssembly); Runtime.RegisterNSObject (this, handle); bool native_ref = (flags & Flags.NativeRef) == Flags.NativeRef; CreateManagedRef (!alloced || native_ref); } [DllImport ("__Internal")] static extern bool xamarin_set_gchandle_with_flags_safe (IntPtr handle, IntPtr gchandle, XamarinGCHandleFlags flags); void CreateManagedRef (bool retain) { HasManagedRef = true; bool isUserType = Runtime.IsUserType (handle); if (isUserType) { var flags = XamarinGCHandleFlags.HasManagedRef | XamarinGCHandleFlags.InitialSet | XamarinGCHandleFlags.WeakGCHandle; var gchandle = GCHandle.Alloc (this, GCHandleType.WeakTrackResurrection); var h = GCHandle.ToIntPtr (gchandle); if (!xamarin_set_gchandle_with_flags_safe (handle, h, flags)) { // A GCHandle already existed: this shouldn't happen, but let's handle it anyway. Runtime.NSLog ("Tried to create a managed reference from an object that already has a managed reference (type: {0})", GetType ()); gchandle.Free (); } } if (retain) DangerousRetain (); } void ReleaseManagedRef () { var handle = this.Handle; // Get a copy of the handle, because it will be cleared out when calling Runtime.NativeObjectHasDied, and we still need the handle later. var user_type = Runtime.IsUserType (handle); HasManagedRef = false; if (!user_type) { /* If we're a wrapper type, we need to unregister here, since we won't enter the release trampoline */ Runtime.NativeObjectHasDied (handle, this); } xamarin_release_managed_ref (handle, user_type); FreeData (); #if NET if (tracked_object_handle.HasValue) { tracked_object_handle.Value.Free (); tracked_object_handle = null; } #endif } static bool IsProtocol (Type type, IntPtr protocol) { while (type != typeof (NSObject) && type != null) { var attrs = type.GetCustomAttributes (typeof(ProtocolAttribute), false); var protocolAttribute = (ProtocolAttribute) (attrs.Length > 0 ? attrs [0] : null); if (protocolAttribute != null && !protocolAttribute.IsInformal) { string name; if (!string.IsNullOrEmpty (protocolAttribute.Name)) { name = protocolAttribute.Name; } else { attrs = type.GetCustomAttributes (typeof(RegisterAttribute), false); var registerAttribute = (RegisterAttribute) (attrs.Length > 0 ? attrs [0] : null); if (registerAttribute != null && !string.IsNullOrEmpty (registerAttribute.Name)) { name = registerAttribute.Name; } else { name = type.Name; } } var proto = Runtime.GetProtocol (name); if (proto != IntPtr.Zero && proto == protocol) return true; } type = type.BaseType; } return false; } [Preserve] bool InvokeConformsToProtocol (IntPtr protocol) { return ConformsToProtocol (protocol); } [Export ("conformsToProtocol:")] [Preserve ()] [BindingImpl (BindingImplOptions.Optimizable)] public virtual bool ConformsToProtocol (IntPtr protocol) { bool does; bool is_wrapper = IsDirectBinding; bool is_third_party; if (is_wrapper) { is_third_party = this.GetType ().Assembly != NSObject.PlatformAssembly; if (is_third_party) { // Third-party bindings might lie about IsDirectBinding (see bug #14772), // so don't trust any 'true' values unless we're in monotouch.dll. var attribs = this.GetType ().GetCustomAttributes (typeof(RegisterAttribute), false); if (attribs != null && attribs.Length == 1) is_wrapper = ((RegisterAttribute) attribs [0]).IsWrapper; } } #if MONOMAC if (is_wrapper) { does = Messaging.bool_objc_msgSend_IntPtr (this.Handle, selConformsToProtocolHandle, protocol); } else { does = Messaging.bool_objc_msgSendSuper_IntPtr (this.SuperHandle, selConformsToProtocolHandle, protocol); } #else if (is_wrapper) { does = Messaging.bool_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selConformsToProtocol), protocol); } else { does = Messaging.bool_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle (selConformsToProtocol), protocol); } #endif if (does) return true; if (!Runtime.DynamicRegistrationSupported) return false; object [] adoptedProtocols = GetType ().GetCustomAttributes (typeof (AdoptsAttribute), true); foreach (AdoptsAttribute adopts in adoptedProtocols){ if (adopts.ProtocolHandle == protocol) return true; } // Check if this class or any of the interfaces // it implements are protocols. if (IsProtocol (GetType (), protocol)) return true; var ifaces = GetType ().GetInterfaces (); foreach (var iface in ifaces) { if (IsProtocol (iface, protocol)) return true; } return false; } [EditorBrowsable (EditorBrowsableState.Advanced)] public void DangerousRelease () { DangerousRelease (handle); } internal static void DangerousRelease (IntPtr handle) { if (handle == IntPtr.Zero) return; #if MONOMAC Messaging.void_objc_msgSend (handle, Selector.ReleaseHandle); #else Messaging.void_objc_msgSend (handle, Selector.GetHandle (Selector.Release)); #endif } internal static void DangerousRetain (IntPtr handle) { if (handle == IntPtr.Zero) return; #if MONOMAC Messaging.void_objc_msgSend (handle, Selector.RetainHandle); #else Messaging.void_objc_msgSend (handle, Selector.GetHandle (Selector.Retain)); #endif } internal static void DangerousAutorelease (IntPtr handle) { #if MONOMAC Messaging.void_objc_msgSend (handle, Selector.AutoreleaseHandle); #else Messaging.void_objc_msgSend (handle, Selector.GetHandle (Selector.Autorelease)); #endif } [EditorBrowsable (EditorBrowsableState.Advanced)] public NSObject DangerousRetain () { #if MONOMAC Messaging.void_objc_msgSend (handle, Selector.RetainHandle); #else Messaging.void_objc_msgSend (handle, Selector.GetHandle (Selector.Retain)); #endif return this; } [EditorBrowsable (EditorBrowsableState.Advanced)] public NSObject DangerousAutorelease () { #if MONOMAC Messaging.void_objc_msgSend (handle, Selector.AutoreleaseHandle); #else Messaging.void_objc_msgSend (handle, Selector.GetHandle (Selector.Autorelease)); #endif return this; } public IntPtr SuperHandle { get { if (handle == IntPtr.Zero) throw new ObjectDisposedException (GetType ().Name); return GetSuper (); } } public IntPtr Handle { get { return handle; } set { if (handle == value) return; if (handle != IntPtr.Zero) Runtime.UnregisterNSObject (handle); handle = value; #if NET unsafe { if (tracked_object_info != null) tracked_object_info->Handle = value; } #endif if (handle != IntPtr.Zero) Runtime.RegisterNSObject (this, handle); } } [EditorBrowsable (EditorBrowsableState.Never)] protected void InitializeHandle (IntPtr handle) { InitializeHandle (handle, "init*"); } [EditorBrowsable (EditorBrowsableState.Never)] protected void InitializeHandle (IntPtr handle, string initSelector) { if (this.handle == IntPtr.Zero && Class.ThrowOnInitFailure) { if (ClassHandle == IntPtr.Zero) throw new Exception (string.Format ("Could not create an native instance of the type '{0}': the native class hasn't been loaded.\n" + "It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.", GetType ().FullName)); throw new Exception (string.Format ("Failed to create a instance of the native type '{0}'.\n" + "It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.", new Class (ClassHandle).Name)); } if (handle == IntPtr.Zero && Class.ThrowOnInitFailure) { Handle = IntPtr.Zero; // We'll crash if we don't do this. throw new Exception (string.Format ("Could not initialize an instance of the type '{0}': the native '{1}' method returned nil.\n" + "It is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false.", GetType ().FullName, initSelector)); } this.Handle = handle; } private bool AllocIfNeeded () { if (handle == IntPtr.Zero) { #if MONOMAC handle = Messaging.IntPtr_objc_msgSend (Class.GetHandle (this.GetType ()), Selector.AllocHandle); #else handle = Messaging.IntPtr_objc_msgSend (Class.GetHandle (this.GetType ()), Selector.GetHandle (Selector.Alloc)); #endif return true; } return false; } #if !XAMCORE_3_0 private IntPtr GetObjCIvar (string name) { IntPtr native; object_getInstanceVariable (handle, name, out native); return native; } [Obsolete ("Do not use; this API does not properly retain/release existing/new values, so leaks and/or crashes may occur.")] public NSObject GetNativeField (string name) { IntPtr field = GetObjCIvar (name); if (field == IntPtr.Zero) return null; return Runtime.GetNSObject (field); } private void SetObjCIvar (string name, IntPtr value) { object_setInstanceVariable (handle, name, value); } [Obsolete ("Do not use; this API does not properly retain/release existing/new values, so leaks and/or crashes may occur.")] public void SetNativeField (string name, NSObject value) { if (value == null) SetObjCIvar (name, IntPtr.Zero); else SetObjCIvar (name, value.Handle); } [DllImport ("/usr/lib/libobjc.dylib")] extern static void object_getInstanceVariable (IntPtr obj, string name, out IntPtr val); [DllImport ("/usr/lib/libobjc.dylib")] extern static void object_setInstanceVariable (IntPtr obj, string name, IntPtr val); #endif // !XAMCORE_3_0 private void InvokeOnMainThread (Selector sel, NSObject obj, bool wait) { #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (this.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, sel.Handle, obj == null ? IntPtr.Zero : obj.Handle, wait); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (this.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), sel.Handle, obj == null ? IntPtr.Zero : obj.Handle, wait); #endif } public void BeginInvokeOnMainThread (Selector sel, NSObject obj) { InvokeOnMainThread (sel, obj, false); } public void InvokeOnMainThread (Selector sel, NSObject obj) { InvokeOnMainThread (sel, obj, true); } public void BeginInvokeOnMainThread (Action action) { var d = new NSAsyncActionDispatcher (action); #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, NSDispatcher.Selector.Handle, d.Handle, false); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, false); #endif } internal void BeginInvokeOnMainThread (System.Threading.SendOrPostCallback cb, object state) { var d = new NSAsyncSynchronizationContextDispatcher (cb, state); #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, NSDispatcher.Selector.Handle, d.Handle, false); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, false); #endif } public void InvokeOnMainThread (Action action) { using (var d = new NSActionDispatcher (action)) { #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, NSDispatcher.Selector.Handle, d.Handle, true); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, true); #endif } } internal void InvokeOnMainThread (System.Threading.SendOrPostCallback cb, object state) { using (var d = new NSSynchronizationContextDispatcher (cb, state)) { #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, NSDispatcher.Selector.Handle, d.Handle, true); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (d.Handle, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle (NSDispatcher.SelectorName), d.Handle, true); #endif } } public static NSObject FromObject (object obj) { if (obj == null) return NSNull.Null; var t = obj.GetType (); if (t == typeof (NSObject) || t.IsSubclassOf (typeof (NSObject))) return (NSObject) obj; switch (Type.GetTypeCode (t)){ case TypeCode.Boolean: return new NSNumber ((bool) obj); case TypeCode.Char: return new NSNumber ((ushort) (char) obj); case TypeCode.SByte: return new NSNumber ((sbyte) obj); case TypeCode.Byte: return new NSNumber ((byte) obj); case TypeCode.Int16: return new NSNumber ((short) obj); case TypeCode.UInt16: return new NSNumber ((ushort) obj); case TypeCode.Int32: return new NSNumber ((int) obj); case TypeCode.UInt32: return new NSNumber ((uint) obj); case TypeCode.Int64: return new NSNumber ((long) obj); case TypeCode.UInt64: return new NSNumber ((ulong) obj); case TypeCode.Single: return new NSNumber ((float) obj); case TypeCode.Double: return new NSNumber ((double) obj); case TypeCode.String: return new NSString ((string) obj); default: if (t == typeof (IntPtr)) return NSValue.ValueFromPointer ((IntPtr) obj); #if !NO_SYSTEM_DRAWING if (t == typeof (SizeF)) return NSValue.FromSizeF ((SizeF) obj); else if (t == typeof (RectangleF)) return NSValue.FromRectangleF ((RectangleF) obj); else if (t == typeof (PointF)) return NSValue.FromPointF ((PointF) obj); #endif if (t == typeof (nint)) return NSNumber.FromNInt ((nint) obj); else if (t == typeof (nuint)) return NSNumber.FromNUInt ((nuint) obj); else if (t == typeof (nfloat)) return NSNumber.FromNFloat ((nfloat) obj); else if (t == typeof (CGSize)) return NSValue.FromCGSize ((CGSize) obj); else if (t == typeof (CGRect)) return NSValue.FromCGRect ((CGRect) obj); else if (t == typeof (CGPoint)) return NSValue.FromCGPoint ((CGPoint) obj); #if !MONOMAC if (t == typeof (CGAffineTransform)) return NSValue.FromCGAffineTransform ((CGAffineTransform) obj); else if (t == typeof (UIEdgeInsets)) return NSValue.FromUIEdgeInsets ((UIEdgeInsets) obj); #if !WATCH else if (t == typeof (CATransform3D)) return NSValue.FromCATransform3D ((CATransform3D) obj); #endif #endif // last chance for types like CGPath, CGColor... that are not NSObject but are CFObject // see https://bugzilla.xamarin.com/show_bug.cgi?id=8458 INativeObject native = (obj as INativeObject); if (native != null) return Runtime.GetNSObject (native.Handle); return null; } } public void SetValueForKeyPath (IntPtr handle, NSString keyPath) { if (keyPath == null) throw new ArgumentNullException ("keyPath"); #if MONOMAC if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, selSetValue_ForKeyPath_Handle, handle, keyPath.Handle); } else { ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, selSetValue_ForKeyPath_Handle, handle, keyPath.Handle); } #else if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr (this.Handle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); } else { ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr (this.SuperHandle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); } #endif } // if IsDirectBinding is false then we _likely_ have managed state and it's up to the subclass to provide // a correct implementation of GetHashCode / Equals. We default to Object.GetHashCode (like classic) public override int GetHashCode () { if (!IsDirectBinding) return base.GetHashCode (); // Hash is nuint so 64 bits, and Int32.GetHashCode == same Int32 return GetNativeHash ().GetHashCode (); } public override bool Equals (object obj) { var o = obj as NSObject; if (o == null) return false; bool isDirectBinding = IsDirectBinding; // is only one is a direct binding then both cannot be equals if (isDirectBinding != o.IsDirectBinding) return false; // we can only ask `isEqual:` to test equality if both objects are direct bindings return isDirectBinding ? IsEqual (o) : ReferenceEquals (this, o); } // IEquatable<T> public bool Equals (NSObject obj) => Equals ((object) obj); public override string ToString () { if (disposed) return base.ToString (); return Description ?? base.ToString (); } public virtual void Invoke (Action action, double delay) { var d = new NSAsyncActionDispatcher (action); d.PerformSelector (NSDispatcher.Selector, null, delay); } public virtual void Invoke (Action action, TimeSpan delay) { var d = new NSAsyncActionDispatcher (action); d.PerformSelector (NSDispatcher.Selector, null, delay.TotalSeconds); } internal void ClearHandle () { handle = IntPtr.Zero; } protected virtual void Dispose (bool disposing) { if (disposed) return; disposed = true; if (handle != IntPtr.Zero) { if (disposing) { ReleaseManagedRef (); } else { NSObject_Disposer.Add (this); } } else { FreeData (); } } unsafe void FreeData () { if (super != IntPtr.Zero) { Marshal.FreeHGlobal (super); super = IntPtr.Zero; } } [Register ("__NSObject_Disposer")] [Preserve (AllMembers=true)] internal class NSObject_Disposer : NSObject { static readonly List <NSObject> drainList1 = new List<NSObject> (); static readonly List <NSObject> drainList2 = new List<NSObject> (); static List <NSObject> handles = drainList1; static readonly IntPtr class_ptr = Class.GetHandle ("__NSObject_Disposer"); #if MONOMAC static readonly IntPtr drainHandle = Selector.GetHandle ("drain:"); #endif static readonly object lock_obj = new object (); private NSObject_Disposer () { // Disable default ctor, there should be no instances of this class. } static internal void Add (NSObject handle) { bool call_drain; lock (lock_obj) { handles.Add (handle); call_drain = handles.Count == 1; } if (!call_drain) return; #if MONOMAC Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (class_ptr, Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDoneHandle, drainHandle, IntPtr.Zero, false); #else Messaging.void_objc_msgSend_IntPtr_IntPtr_bool (class_ptr, Selector.GetHandle (Selector.PerformSelectorOnMainThreadWithObjectWaitUntilDone), Selector.GetHandle ("drain:"), IntPtr.Zero, false); #endif } [Export ("drain:")] static void Drain (NSObject ctx) { List<NSObject> drainList; lock (lock_obj) { drainList = handles; if (handles == drainList1) handles = drainList2; else handles = drainList1; } foreach (NSObject x in drainList) x.ReleaseManagedRef (); drainList.Clear(); } } [Register ("__XamarinObjectObserver")] class Observer : NSObject { WeakReference obj; Action<NSObservedChange> cback; NSString key; public Observer (NSObject obj, NSString key, Action<NSObservedChange> observer) { if (observer == null) throw new ArgumentNullException (nameof(observer)); this.obj = new WeakReference (obj); this.key = key; this.cback = observer; IsDirectBinding = false; } [Preserve (Conditional = true)] public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { if (keyPath == key && context == Handle) cback (new NSObservedChange (change)); else base.ObserveValue (keyPath, ofObject, change, context); } protected override void Dispose (bool disposing) { if (disposing) { NSObject target; if (obj != null) { target = (NSObject) obj.Target; if (target != null) target.RemoveObserver (this, key, Handle); } obj = null; cback = null; } else { Runtime.NSLog ("Warning: observer object was not disposed manually with Dispose()"); } base.Dispose (disposing); } } public IDisposable AddObserver (string key, NSKeyValueObservingOptions options, Action<NSObservedChange> observer) { return AddObserver (new NSString (key), options, observer); } public IDisposable AddObserver (NSString key, NSKeyValueObservingOptions options, Action<NSObservedChange> observer) { var o = new Observer (this, key, observer); AddObserver (o, key, options, o.Handle); return o; } #endif // !COREBUILD } #if !COREBUILD public class NSObservedChange { NSDictionary dict; public NSObservedChange (NSDictionary source) { dict = source; } public NSKeyValueChange Change { get { var n = (NSNumber) dict [NSObject.ChangeKindKey]; return (NSKeyValueChange) n.Int32Value; } } public NSObject NewValue { get { return dict [NSObject.ChangeNewKey]; } } public NSObject OldValue { get { return dict [NSObject.ChangeOldKey]; } } public NSIndexSet Indexes { get { return (NSIndexSet) dict [NSObject.ChangeIndexesKey]; } } public bool IsPrior { get { var n = dict [NSObject.ChangeNotificationIsPriorKey] as NSNumber; if (n == null) return false; return n.BoolValue; } } } #endif }
31.298364
204
0.697008
[ "BSD-3-Clause" ]
agocke/xamarin-macios
src/Foundation/NSObject2.cs
32,519
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// In C#, tuples can be represented using tuple syntax and be given /// names. However, the underlying representation for tuples unifies /// to a single underlying tuple type, System.ValueTuple. Since the /// names aren't part of the underlying tuple type they have to be /// recorded somewhere else. /// /// Roslyn records tuple names in an attribute: the /// TupleElementNamesAttribute. The attribute contains a single string /// array which records the names of the tuple elements in a pre-order /// depth-first traversal. If the type contains nested parameters, /// they are also recorded in a pre-order depth-first traversal. /// <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> /// can be used to extract tuple names and types from metadata and create /// a <see cref="NamedTypeSymbol"/> with attached names. /// /// <example> /// For instance, a method returning a tuple /// /// <code> /// (int x, int y) M() { ... } /// </code> /// /// will be encoded using an attribute on the return type as follows /// /// <code> /// [return: TupleElementNamesAttribute(new[] { "x", "y" })] /// System.ValueTuple&lt;int, int&gt; M() { ... } /// </code> /// </example> /// /// <example> /// For nested type parameters, we expand the tuple names in a pre-order /// traversal: /// /// <code> /// class C : BaseType&lt;((int e1, int e2) e3, int e4)&lt; { ... } /// </code> /// /// becomes /// /// <code> /// [TupleElementNamesAttribute(new[] { "e3", "e4", "e1", "e2" }); /// class C : BaseType&lt;System.ValueTuple&lt; /// System.ValueTuple&lt;int,int&gt;, int&gt; /// { ... } /// </code> /// </example> /// </summary> internal struct TupleTypeDecoder { private readonly ImmutableArray<string?> _elementNames; // Keep track of how many names we've "used" during decoding. Starts at // the back of the array and moves forward. private int _namesIndex; private bool _foundUsableErrorType; private bool _decodingFailed; private TupleTypeDecoder(ImmutableArray<string?> elementNames) { _elementNames = elementNames; _namesIndex = elementNames.IsDefault ? 0 : elementNames.Length; _decodingFailed = false; _foundUsableErrorType = false; } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return new UnsupportedMetadataTypeSymbol(); } return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute); } public static TypeWithAnnotations DecodeTupleTypesIfApplicable( TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); } TypeSymbol type = metadataType.Type; TypeSymbol decoded = DecodeTupleTypesInternal(type, elementNames, hasTupleElementNamesAttribute); return (object)decoded == (object)type ? metadataType : TypeWithAnnotations.Create(decoded, metadataType.NullableAnnotation, metadataType.CustomModifiers); } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, ImmutableArray<string?> elementNames) { return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute: !elementNames.IsDefaultOrEmpty); } private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray<string?> elementNames, bool hasTupleElementNamesAttribute) { RoslynDebug.AssertNotNull(metadataType); var decoder = new TupleTypeDecoder(elementNames); var decoded = decoder.DecodeType(metadataType); if (!decoder._decodingFailed) { if (!hasTupleElementNamesAttribute || decoder._namesIndex == 0) { return decoded; } } // If not all of the names have been used, the metadata is bad if (decoder._foundUsableErrorType) { return metadataType; } // Bad metadata return new UnsupportedMetadataTypeSymbol(); } private TypeSymbol DecodeType(TypeSymbol type) { switch (type.Kind) { case SymbolKind.ErrorType: _foundUsableErrorType = true; return type; case SymbolKind.DynamicType: case SymbolKind.TypeParameter: return type; case SymbolKind.FunctionPointer: return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); case SymbolKind.PointerType: return DecodePointerType((PointerTypeSymbol)type); case SymbolKind.NamedType: // We may have a tuple type from a substituted type symbol, // but it will be missing names from metadata, so we'll // need to re-create the type. // // Consider the declaration // // class C : BaseType<(int x, int y)> // // The process for decoding tuples in C looks at the BaseType, calls // DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. // However, DecodeOrThrow uses the AbstractTypeMap to construct a // SubstitutedTypeSymbol, which eagerly converts tuple-compatible // types to TupleTypeSymbols. Thus, by the time we get to the Decoder // all metadata instances of System.ValueTuple will have been // replaced with TupleTypeSymbols without names. // // Rather than fixing up after-the-fact it's possible that we could // flow up a SubstituteWith/Without tuple unification to the top level // of the type map and change DecodeOrThrow to call into the substitution // without unification instead. return DecodeNamedType((NamedTypeSymbol)type); case SymbolKind.ArrayType: return DecodeArrayType((ArrayTypeSymbol)type); default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) { return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) { var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); for (int i = type.Signature.ParameterCount - 1; i >= 0; i--) { var param = type.Signature.Parameters[i]; var decodedParam = DecodeTypeInternal(param.TypeWithAnnotations); paramsModified = paramsModified || !decodedParam.IsSameAs(param.TypeWithAnnotations); paramsBuilder.Add(decodedParam); } if (paramsModified) { paramsBuilder.ReverseContents(); parameterTypes = paramsBuilder.ToImmutableAndFree(); } else { parameterTypes = type.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } var decodedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); if (paramsModified || !decodedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(decodedReturnType, parameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) { // First decode the type arguments var typeArgs = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var decodedArgs = DecodeTypeArguments(typeArgs); NamedTypeSymbol decodedType = type; // Now check the container NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol? decodedContainingType; if (containingType is object && containingType.IsGenericType) { decodedContainingType = DecodeNamedType(containingType); Debug.Assert(decodedContainingType.IsGenericType); } else { decodedContainingType = containingType; } // Replace the type if necessary var containerChanged = !ReferenceEquals(decodedContainingType, containingType); var typeArgsChanged = typeArgs != decodedArgs; if (typeArgsChanged || containerChanged) { if (containerChanged) { decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType); // If the type is nested, e.g. Outer<T>.Inner<V>, then Inner is definitely // not a tuple, since we know all tuple-compatible types (System.ValueTuple) // are not nested types. Thus, it is safe to return without checking if // Inner is a tuple. return decodedType.ConstructIfGeneric(decodedArgs); } decodedType = type.ConstructedFrom.Construct(decodedArgs, unbound: false); } // Now decode into a tuple, if it is one if (decodedType.IsTupleType) { int tupleCardinality = decodedType.TupleElementTypesWithAnnotations.Length; if (tupleCardinality > 0) { var elementNames = EatElementNamesIfAvailable(tupleCardinality); Debug.Assert(elementNames.IsDefault || elementNames.Length == tupleCardinality); decodedType = NamedTypeSymbol.CreateTuple(decodedType, elementNames); } } return decodedType; } private ImmutableArray<TypeWithAnnotations> DecodeTypeArguments(ImmutableArray<TypeWithAnnotations> typeArgs) { if (typeArgs.IsEmpty) { return typeArgs; } var decodedArgs = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArgs.Length); var anyDecoded = false; // Visit the type arguments in reverse for (int i = typeArgs.Length - 1; i >= 0; i--) { TypeWithAnnotations typeArg = typeArgs[i]; TypeWithAnnotations decoded = DecodeTypeInternal(typeArg); anyDecoded |= !decoded.IsSameAs(typeArg); decodedArgs.Add(decoded); } if (!anyDecoded) { decodedArgs.Free(); return typeArgs; } decodedArgs.ReverseContents(); return decodedArgs.ToImmutableAndFree(); } private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) { TypeWithAnnotations decodedElementType = DecodeTypeInternal(type.ElementTypeWithAnnotations); return type.WithElementType(decodedElementType); } private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) { TypeSymbol type = typeWithAnnotations.Type; TypeSymbol decoded = DecodeType(type); return ReferenceEquals(decoded, type) ? typeWithAnnotations : TypeWithAnnotations.Create(decoded, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); } private ImmutableArray<string?> EatElementNamesIfAvailable(int numberOfElements) { Debug.Assert(numberOfElements > 0); // If we don't have any element names there's nothing to eat if (_elementNames.IsDefault) { return _elementNames; } // We've gone past the end of the names -- bad metadata if (numberOfElements > _namesIndex) { // We'll want to continue decoding without consuming more names to see if there are any error types _namesIndex = 0; _decodingFailed = true; return default; } // Check to see if all the elements are null var start = _namesIndex - numberOfElements; _namesIndex = start; bool allNull = true; for (int i = 0; i < numberOfElements; i++) { if (_elementNames[start + i] != null) { allNull = false; break; } } if (allNull) { return default; } return ImmutableArray.Create(_elementNames, start, numberOfElements); } } }
39.6743
157
0.586134
[ "MIT" ]
Kuinox/roslyn
src/Compilers/CSharp/Portable/Symbols/Metadata/PE/TupleTypeDecoder.cs
15,594
C#
using Sparkler.Rotorz.Games; using Sparkler.Utility.Editor; using System; using UnityEditor; using UnityEngine; namespace Sparkler.Editor.CodeGeneration { public enum ComponentType : byte { ComponentData, SharedComponentData, BufferElementData, SystemStateComponent, SystemStateSharedComponent, SystemStateBufferElementData, } public enum ComponentFieldAccessType : byte { Public, Internal, Private, } [Serializable] public class ComponentDefinition { public string ComponentName = ""; public string Namespace = ""; public string Directory = ""; public ComponentType ComponentType = ComponentType.ComponentData; public ComponentField[] Fields = new ComponentField[0]; } public class ComponentFieldBlacklistedNamespacesAttribute : BlacklistedNamespacesAttribute { public ComponentFieldBlacklistedNamespacesAttribute() : base( true, @"Mono\..+", @"System\..+", @"JetBrains", @"Bee.", @"NUnit", @"Microsoft\..+", @"Novell\..+", @"ExCSS", @"NiceIO", @"ICSharpCode", @"Unity.Build", @"Newtonsoft\..+", @"Rider", @"TMPro", @"UnityEditor", @"Editor", @"SyntaxTree\..+", @"Unity.Profiling", @"Rotorz" ) { } } [Serializable] public class ComponentField { public string name; [ClassTypeReferenceAttributes( typeof( OnlyBlittableAttribute ), typeof(ComponentFieldBlacklistedNamespacesAttribute))] public ClassTypeReference type; public ComponentFieldAccessType accessType = ComponentFieldAccessType.Public; } [CustomPropertyDrawer( typeof( ComponentField ) )] public class ComponentFieldDrawer : PropertyDrawer { public override void OnGUI( Rect position, SerializedProperty property, GUIContent label ) { PropertyRect propertyRect = new PropertyRect(position); EditorGUI.BeginProperty( position, label, property ); GUIDrawers.DrawFieldWithLabelPercentage( ref propertyRect, property.FindPropertyRelative( nameof( ComponentField.accessType ) ), labelWidth: 100, labelWidthPercentage: 0.3f ); propertyRect.AllocateWidthPrecent( 0.05f ); GUIDrawers.DrawFieldWithLabelPercentage( ref propertyRect, property.FindPropertyRelative( nameof( ComponentField.type ) ), false, labelWidth: 50, labelWidthPercentage: 0.65f ); GUIDrawers.DrawFieldWithLabel( ref propertyRect, property.FindPropertyRelative( nameof( ComponentField.name ) ), labelWidth: 100 ); EditorGUI.EndProperty(); } public override float GetPropertyHeight( SerializedProperty property, GUIContent label ) => EditorGUIUtility.singleLineHeight * 2; } }
31.822785
179
0.759348
[ "MIT" ]
KamilVDono/ECS_FSM
Assets/Sparkler/Scripts/SparklerCore/Editor/CodeGeneration/ComponentDefinition.cs
2,516
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.PowerShell.Cmdlets.PostgreSql.Models.Api20 { using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell; /// <summary>Metadata pertaining to creation and last modification of the resource.</summary> [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] public partial class SystemData { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.SystemData" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemData" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new SystemData(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.SystemData" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemData" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new SystemData(content); } /// <summary> /// Creates a new instance of <see cref="SystemData" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.SystemData" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal SystemData(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("CreatedBy")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); } if (content.Contains("CreatedByType")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedByType = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType?) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedByType, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType.CreateFrom); } if (content.Contains("CreatedAt")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); } if (content.Contains("LastModifiedBy")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); } if (content.Contains("LastModifiedByType")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedByType = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType?) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedByType, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType.CreateFrom); } if (content.Contains("LastModifiedAt")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.SystemData" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal SystemData(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("CreatedBy")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); } if (content.Contains("CreatedByType")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedByType = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType?) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedByType, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType.CreateFrom); } if (content.Contains("CreatedAt")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); } if (content.Contains("LastModifiedBy")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); } if (content.Contains("LastModifiedByType")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedByType = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType?) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedByType, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Support.CreatedByType.CreateFrom); } if (content.Contains("LastModifiedAt")) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Metadata pertaining to creation and last modification of the resource. [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] public partial interface ISystemData { } }
73.225275
461
0.69573
[ "MIT" ]
Agazoth/azure-powershell
src/PostgreSql/generated/api/Models/Api20/SystemData.PowerShell.cs
13,146
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.ComponentModel.Design; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; namespace System.ComponentModel { /// <summary> /// ReflectPropertyDescriptor defines a property. Properties are the main way that a user can /// set up the state of a component. /// The ReflectPropertyDescriptor class takes a component class that the property lives on, /// a property name, the type of the property, and various attributes for the /// property. /// For a property named XXX of type YYY, the associated component class is /// required to implement two methods of the following /// form: /// /// <code> /// public YYY GetXXX(); /// public void SetXXX(YYY value); /// </code> /// The component class can optionally implement two additional methods of /// the following form: /// <code> /// public boolean ShouldSerializeXXX(); /// public void ResetXXX(); /// </code> /// These methods deal with a property's default value. The ShouldSerializeXXX() /// method returns true if the current value of the XXX property is different /// than it's default value, so that it should be persisted out. The ResetXXX() /// method resets the XXX property to its default value. If the ReflectPropertyDescriptor /// includes the default value of the property (using the DefaultValueAttribute), /// the ShouldSerializeXXX() and ResetXXX() methods are ignored. /// If the ReflectPropertyDescriptor includes a reference to an editor /// then that value editor will be used to /// edit the property. Otherwise, a system-provided editor will be used. /// Various attributes can be passed to the ReflectPropertyDescriptor, as are described in /// Attribute. /// ReflectPropertyDescriptors can be obtained by a user programmatically through the /// ComponentManager. /// </summary> internal sealed class ReflectPropertyDescriptor : PropertyDescriptor { private static readonly object s_noValue = new object(); private static readonly int s_bitDefaultValueQueried = InterlockedBitVector32.CreateMask(); private static readonly int s_bitGetQueried = InterlockedBitVector32.CreateMask(s_bitDefaultValueQueried); private static readonly int s_bitSetQueried = InterlockedBitVector32.CreateMask(s_bitGetQueried); private static readonly int s_bitShouldSerializeQueried = InterlockedBitVector32.CreateMask(s_bitSetQueried); private static readonly int s_bitResetQueried = InterlockedBitVector32.CreateMask(s_bitShouldSerializeQueried); private static readonly int s_bitChangedQueried = InterlockedBitVector32.CreateMask(s_bitResetQueried); private static readonly int s_bitIPropChangedQueried = InterlockedBitVector32.CreateMask(s_bitChangedQueried); private static readonly int s_bitReadOnlyChecked = InterlockedBitVector32.CreateMask(s_bitIPropChangedQueried); private static readonly int s_bitAmbientValueQueried = InterlockedBitVector32.CreateMask(s_bitReadOnlyChecked); private static readonly int s_bitSetOnDemand = InterlockedBitVector32.CreateMask(s_bitAmbientValueQueried); private InterlockedBitVector32 _state; // Contains the state bits for this proeprty descriptor. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private readonly Type _componentClass; // used to determine if we should all on us or on the designer private readonly Type _type; // the data type of the property private object _defaultValue; // the default value of the property (or noValue) private object _ambientValue; // the ambient value of the property (or noValue) private PropertyInfo _propInfo; // the property info private MethodInfo _getMethod; // the property get method private MethodInfo _setMethod; // the property set method private MethodInfo _shouldSerializeMethod; // the should serialize method private MethodInfo _resetMethod; // the reset property method private EventDescriptor _realChangedEvent; // <propertyname>Changed event handler on object private EventDescriptor _realIPropChangedEvent; // INotifyPropertyChanged.PropertyChanged event handler on object private readonly Type _receiverType; // Only set if we are an extender /// <summary> /// The main constructor for ReflectPropertyDescriptors. /// </summary> public ReflectPropertyDescriptor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentClass, string name, Type type, Attribute[] attributes) : base(name, attributes) { Debug.WriteLine($"Creating ReflectPropertyDescriptor for {componentClass?.FullName}.{name}"); try { if (type == null) { Debug.WriteLine($"type == null, name == {name}"); throw new ArgumentException(SR.Format(SR.ErrorInvalidPropertyType, name)); } if (componentClass == null) { Debug.WriteLine($"componentClass == null, name == {name}"); throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass))); } _type = type; _componentClass = componentClass; } catch (Exception t) { Debug.Fail($"Property '{name}' on component {componentClass.FullName} failed to init."); Debug.Fail(t.ToString()); throw; } } /// <summary> /// A constructor for ReflectPropertyDescriptors that have no attributes. /// </summary> public ReflectPropertyDescriptor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { _propInfo = propInfo; _getMethod = getMethod; _setMethod = setMethod; if (getMethod != null && propInfo != null && setMethod == null) _state.DangerousSet(s_bitGetQueried | s_bitSetOnDemand, true); else _state.DangerousSet(s_bitGetQueried | s_bitSetQueried, true); } /// <summary> /// A constructor for ReflectPropertyDescriptors that creates an extender property. /// </summary> public ReflectPropertyDescriptor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { _receiverType = receiverType; _getMethod = getMethod; _setMethod = setMethod; _state.DangerousSet(s_bitGetQueried | s_bitSetQueried, true); } /// <summary> /// This constructor takes an existing ReflectPropertyDescriptor and modifies it by merging in the /// passed-in attributes. /// </summary> public ReflectPropertyDescriptor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes) : base(oldReflectPropertyDescriptor, attributes) { _componentClass = componentClass; _type = oldReflectPropertyDescriptor.PropertyType; if (componentClass == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass))); } // If the classes are the same, we can potentially optimize the method fetch because // the old property descriptor may already have it. if (oldReflectPropertyDescriptor is ReflectPropertyDescriptor oldProp) { if (oldProp.ComponentType == componentClass) { _propInfo = oldProp._propInfo; _getMethod = oldProp._getMethod; _setMethod = oldProp._setMethod; _shouldSerializeMethod = oldProp._shouldSerializeMethod; _resetMethod = oldProp._resetMethod; _defaultValue = oldProp._defaultValue; _ambientValue = oldProp._ambientValue; _state = oldProp._state; } // Now we must figure out what to do with our default value. First, check to see // if the caller has provided an new default value attribute. If so, use it. Otherwise, // just let it be and it will be picked up on demand. // if (attributes != null) { foreach (Attribute a in attributes) { if (a is DefaultValueAttribute dva) { _defaultValue = dva.Value; // Default values for enums are often stored as their underlying integer type: if (_defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == _defaultValue.GetType()) { _defaultValue = Enum.ToObject(PropertyType, _defaultValue); } _state.DangerousSet(s_bitDefaultValueQueried, true); } else if (a is AmbientValueAttribute ava) { _ambientValue = ava.Value; _state.DangerousSet(s_bitAmbientValueQueried, true); } } } } } /// <summary> /// Retrieves the ambient value for this property. /// </summary> private object AmbientValue { get { if (!_state[s_bitAmbientValueQueried]) { Attribute a = Attributes[typeof(AmbientValueAttribute)]; if (a != null) { _ambientValue = ((AmbientValueAttribute)a).Value; } else { _ambientValue = s_noValue; } _state[s_bitAmbientValueQueried] = true; } return _ambientValue; } } /// <summary> /// The EventDescriptor for the "{propertyname}Changed" event on the component, or null if there isn't one for this property. /// </summary> private EventDescriptor ChangedEventValue { get { if (!_state[s_bitChangedQueried]) { _realChangedEvent = TypeDescriptor.GetEvents(_componentClass)[Name + "Changed"]; _state[s_bitChangedQueried] = true; } return _realChangedEvent; } } /// <summary> /// The EventDescriptor for the INotifyPropertyChanged.PropertyChanged event on the component, or null if there isn't one for this property. /// </summary> private EventDescriptor IPropChangedEventValue { get { if (!_state[s_bitIPropChangedQueried]) { if (typeof(INotifyPropertyChanged).IsAssignableFrom(ComponentType)) { _realIPropChangedEvent = TypeDescriptor.GetEvents(typeof(INotifyPropertyChanged))["PropertyChanged"]; } _state[s_bitIPropChangedQueried] = true; } return _realIPropChangedEvent; } } /// <summary> /// Retrieves the type of the component this PropertyDescriptor is bound to. /// </summary> public override Type ComponentType => _componentClass; /// <summary> /// Retrieves the default value for this property. /// </summary> private object DefaultValue { get { if (!_state[s_bitDefaultValueQueried]) { Attribute a = Attributes[typeof(DefaultValueAttribute)]; if (a != null) { // Default values for enums are often stored as their underlying integer type: object defaultValue = ((DefaultValueAttribute)a).Value; bool storedAsUnderlyingType = defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType(); _defaultValue = storedAsUnderlyingType ? Enum.ToObject(PropertyType, _defaultValue) : defaultValue; } else { _defaultValue = s_noValue; } _state[s_bitDefaultValueQueried] = true; } return _defaultValue; } } /// <summary> /// The GetMethod for this property /// </summary> private MethodInfo GetMethodValue { get { if (!_state[s_bitGetQueried]) { if (_receiverType == null) { if (_propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; _propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Type.EmptyTypes, Array.Empty<ParameterModifier>()); } if (_propInfo != null) { _getMethod = _propInfo.GetGetMethod(nonPublic: true); } if (_getMethod == null) { throw new InvalidOperationException(SR.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name)); } } else { _getMethod = FindMethod(_componentClass, "Get" + Name, new Type[] { _receiverType }, _type); if (_getMethod == null) { throw new ArgumentException(SR.Format(SR.ErrorMissingPropertyAccessors, Name)); } } _state[s_bitGetQueried] = true; } return _getMethod; } } /// <summary> /// Determines if this property is an extender property. /// </summary> private bool IsExtender => (_receiverType != null); /// <summary> /// Indicates whether this property is read only. /// </summary> public override bool IsReadOnly => SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; /// <summary> /// Retrieves the type of the property. /// </summary> public override Type PropertyType => _type; /// <summary> /// Access to the reset method, if one exists for this property. /// </summary> private MethodInfo ResetMethodValue { get { if (!_state[s_bitResetQueried]) { Type[] args; if (_receiverType == null) { args = Type.EmptyTypes; } else { args = new Type[] { _receiverType }; } _resetMethod = FindMethod(_componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false); _state[s_bitResetQueried] = true; } return _resetMethod; } } /// <summary> /// Accessor for the set method /// </summary> private MethodInfo SetMethodValue { get { if (!_state[s_bitSetQueried] && _state[s_bitSetOnDemand]) { string name = _propInfo.Name; if (_setMethod == null) { for (Type t = ComponentType.BaseType; t != null && t != typeof(object); t = t.BaseType) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; PropertyInfo p = t.GetProperty(name, bindingFlags, binder: null, PropertyType, Type.EmptyTypes, null); if (p != null) { _setMethod = p.GetSetMethod(nonPublic: false); if (_setMethod != null) { break; } } } } _state[s_bitSetQueried] = true; } if (!_state[s_bitSetQueried]) { if (_receiverType == null) { if (_propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; _propInfo = _componentClass.GetProperty(Name, bindingFlags, binder: null, PropertyType, Type.EmptyTypes, Array.Empty<ParameterModifier>()); } if (_propInfo != null) { _setMethod = _propInfo.GetSetMethod(nonPublic: true); } } else { _setMethod = FindMethod(_componentClass, "Set" + Name, new Type[] { _receiverType, _type }, typeof(void)); } _state[s_bitSetQueried] = true; } return _setMethod; } } /// <summary> /// Accessor for the ShouldSerialize method. /// </summary> private MethodInfo ShouldSerializeMethodValue { get { if (!_state[s_bitShouldSerializeQueried]) { Type[] args; if (_receiverType == null) { args = Type.EmptyTypes; } else { args = new Type[] { _receiverType }; } _shouldSerializeMethod = FindMethod(_componentClass, "ShouldSerialize" + Name, args, typeof(bool), publicOnly: false); _state[s_bitShouldSerializeQueried] = true; } return _shouldSerializeMethod; } } /// <summary> /// Allows interested objects to be notified when this property changes. /// </summary> public override void AddValueChanged(object component, EventHandler handler) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } // If there's an event called <propertyname>Changed, hook the caller's handler directly up to that on the component EventDescriptor changedEvent = ChangedEventValue; if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.AddEventHandler(component, handler); } // Otherwise let the base class add the handler to its ValueChanged event for this component else { // Special case: If this will be the FIRST handler added for this component, and the component implements // INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event if (GetValueChangedHandler(component) == null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; iPropChangedEvent?.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); } base.AddValueChanged(component, handler); } } internal bool ExtenderCanResetValue(IExtenderProvider provider, object component) { if (DefaultValue != s_noValue) { return !Equals(ExtenderGetValue(provider, component), _defaultValue); } MethodInfo reset = ResetMethodValue; if (reset != null) { MethodInfo shouldSerialize = ShouldSerializeMethodValue; if (shouldSerialize != null) { try { provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); return (bool)shouldSerialize.Invoke(provider, new object[] { component }); } catch { } } return true; } return false; } internal Type ExtenderGetReceiverType() => _receiverType; internal Type ExtenderGetType(IExtenderProvider provider) => PropertyType; internal object ExtenderGetValue(IExtenderProvider provider, object component) { if (provider != null) { provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); return GetMethodValue.Invoke(provider, new object[] { component }); } return null; } internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc) { if (DefaultValue != s_noValue) { ExtenderSetValue(provider, component, DefaultValue, notifyDesc); } else if (AmbientValue != s_noValue) { ExtenderSetValue(provider, component, AmbientValue, notifyDesc); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); if (ResetMethodValue != null) { ResetMethodValue.Invoke(provider, new object[] { component }); // Now notify the change service that the change was successful. if (changeService != null) { newValue = ExtenderGetValue(provider, component); changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue); } } } } internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc) { if (provider != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); if (SetMethodValue != null) { SetMethodValue.Invoke(provider, new object[] { component, value }); // Now notify the change service that the change was successful. changeService?.OnComponentChanged(component, notifyDesc, oldValue, value); } } } internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component) { provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component }); } catch { } } return AttributesContainsDesignerVisibilityContent(); } else if (DefaultValue == s_noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component }); } catch { } } return true; } return !Equals(DefaultValue, ExtenderGetValue(provider, component)); } [DynamicDependency(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields, typeof(DesignerSerializationVisibilityAttribute))] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The DynamicDependency ensures the correct members are preserved.")] private bool AttributesContainsDesignerVisibilityContent() => Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); /// <summary> /// Indicates whether reset will change the value of the component. If there /// is a DefaultValueAttribute, then this will return true if getValue returns /// something different than the default value. If there is a reset method and /// a ShouldSerialize method, this will return what ShouldSerialize returns. /// If there is just a reset method, this always returns true. If none of these /// cases apply, this returns false. /// </summary> public override bool CanResetValue(object component) { if (IsExtender || IsReadOnly) { return false; } if (DefaultValue != s_noValue) { return !Equals(GetValue(component), DefaultValue); } if (ResetMethodValue != null) { if (ShouldSerializeMethodValue != null) { component = GetInvocationTarget(_componentClass, component); try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch { } } return true; } if (AmbientValue != s_noValue) { return ShouldSerializeValue(component); } return false; } protected override void FillAttributes(IList attributes) { Debug.Assert(_componentClass != null, "Must have a component class for FillAttributes"); // // The order that we fill in attributes is critical. The list of attributes will be // filtered so that matching attributes at the end of the list replace earlier matches // (last one in wins). Therefore, the four categories of attributes we add must be // added as follows: // // 1. Attributes of the property type. These are the lowest level and should be // overwritten by any newer attributes. // // 2. Attributes obtained from any SpecificTypeAttribute. These supercede attributes // for the property type. // // 3. Attributes of the property itself, from base class to most derived. This way // derived class attributes replace base class attributes. // // 4. Attributes from our base MemberDescriptor. While this seems opposite of what // we want, MemberDescriptor only has attributes if someone passed in a new // set in the constructor. Therefore, these attributes always // supercede existing values. // // We need to include attributes from the type of the property. foreach (Attribute typeAttr in TypeDescriptor.GetAttributes(PropertyType)) { attributes.Add(typeAttr); } // NOTE : Must look at method OR property, to handle the case of Extender properties... // // Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-acquire // : the property info, rather than use the one we have cached. The one we have cached // : may ave come from a base class, meaning we will request custom metadata for this // : class twice. Type currentReflectType = _componentClass; int depth = 0; // First, calculate the depth of the object hierarchy. We do this so we can do a single // object create for an array of attributes. while (currentReflectType != null && currentReflectType != typeof(object)) { depth++; currentReflectType = currentReflectType.BaseType; } // Now build up an array in reverse order if (depth > 0) { currentReflectType = _componentClass; Attribute[][] attributeStack = new Attribute[depth][]; while (currentReflectType != null && currentReflectType != typeof(object)) { MemberInfo memberInfo = null; BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly; // Fill in our member info so we can get at the custom attributes. if (IsExtender) { //receiverType is used to avoid ambitiousness when there are overloads for the get method. memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags, binder: null, new Type[] { _receiverType }, modifiers: null); } else { memberInfo = currentReflectType.GetProperty(Name, bindingFlags, binder: null, PropertyType, Type.EmptyTypes, Array.Empty<ParameterModifier>()); } // Get custom attributes for the member info. if (memberInfo != null) { attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo); } // Ready for the next loop iteration. currentReflectType = currentReflectType.BaseType; } // Look in the attribute stack for AttributeProviders foreach (Attribute[] attributeArray in attributeStack) { if (attributeArray != null) { foreach (Attribute attr in attributeArray) { if (attr is AttributeProviderAttribute sta) { Type specificType = Type.GetType(sta.TypeName); if (specificType != null) { Attribute[] stAttrs = null; if (!string.IsNullOrEmpty(sta.PropertyName)) { MemberInfo[] milist = specificType.GetMember(sta.PropertyName); if (milist.Length > 0 && milist[0] != null) { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]); } } else { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType); } if (stAttrs != null) { foreach (Attribute stAttr in stAttrs) { attributes.Add(stAttr); } } } } } } } // Now trawl the attribute stack so that we add attributes // from base class to most derived. foreach (Attribute[] attributeArray in attributeStack) { if (attributeArray != null) { foreach (Attribute attr in attributeArray) { attributes.Add(attr); } } } } // Include the base attributes. These override all attributes on the actual // property, so we want to add them last. base.FillAttributes(attributes); // Finally, override any form of ReadOnlyAttribute. if (SetMethodValue == null) { attributes.Add(ReadOnlyAttribute.Yes); } } /// <summary> /// Retrieves the current value of the property on component, /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// </summary> public override object GetValue(object component) { Debug.WriteLine($"[{Name}]: GetValue({component?.GetType().Name ?? "(null)"})"); if (IsExtender) { Debug.WriteLine($"[{Name}]: ---> returning: null"); return null; } Debug.Assert(component != null, "GetValue must be given a component"); if (component != null) { component = GetInvocationTarget(_componentClass, component); try { return GetMethodValue.Invoke(component, null); } catch (Exception t) { string name = null; IComponent comp = component as IComponent; ISite site = comp?.Site; if (site?.Name != null) { name = site.Name; } if (name == null) { name = component.GetType().FullName; } if (t is TargetInvocationException) { t = t.InnerException; } string message = t.Message ?? t.GetType().Name; throw new TargetInvocationException(SR.Format(SR.ErrorPropertyAccessorException, Name, name, message), t); } } Debug.WriteLine("[" + Name + "]: ---> returning: null"); return null; } /// <summary> /// Handles INotifyPropertyChanged.PropertyChange events from components. /// If event pertains to this property, issue a ValueChanged event. /// </summary> internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e) { if (string.IsNullOrEmpty(e.PropertyName) || string.Compare(e.PropertyName, Name, true, CultureInfo.InvariantCulture) == 0) { OnValueChanged(component, e); } } /// <summary> /// This should be called by your property descriptor implementation /// when the property value has changed. /// </summary> protected override void OnValueChanged(object component, EventArgs e) { if (_state[s_bitChangedQueried] && _realChangedEvent == null) { base.OnValueChanged(component, e); } } /// <summary> /// Allows interested objects to be notified when this property changes. /// </summary> public override void RemoveValueChanged(object component, EventHandler handler) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (handler == null) { throw new ArgumentNullException(nameof(handler)); } // If there's an event called <propertyname>Changed, we hooked the caller's // handler directly up to that on the component, so remove it now. EventDescriptor changedEvent = ChangedEventValue; if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.RemoveEventHandler(component, handler); } // Otherwise the base class added the handler to its ValueChanged // event for this component, so let the base class remove it now. else { base.RemoveValueChanged(component, handler); // Special case: If that was the LAST handler removed for this component, and the component implements // INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event if (GetValueChangedHandler(component) == null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; iPropChangedEvent?.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); } } } /// <summary> /// Will reset the default value for this property on the component. If /// there was a default value passed in as a DefaultValueAttribute, that /// value will be set as the value of the property on the component. If /// there was no default value passed in, a ResetXXX method will be looked /// for. If one is found, it will be invoked. If one is not found, this /// is a nop. /// </summary> public override void ResetValue(object component) { object invokee = GetInvocationTarget(_componentClass, component); if (DefaultValue != s_noValue) { SetValue(component, DefaultValue); } else if (AmbientValue != s_noValue) { SetValue(component, AmbientValue); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events if (changeService != null) { // invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method oldValue = GetMethodValue.Invoke(invokee, null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } if (ResetMethodValue != null) { ResetMethodValue.Invoke(invokee, null); // Now notify the change service that the change was successful. if (changeService != null) { newValue = GetMethodValue.Invoke(invokee, null); changeService.OnComponentChanged(component, this, oldValue, newValue); } } } } /// <summary> /// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// </summary> public override void SetValue(object component, object value) { Debug.WriteLine($"[{Name}]: SetValue({component?.GetType().Name ?? "(null)"}, {value?.GetType().Name ?? "(null)"})"); if (component != null) { ISite site = GetSite(component); object oldValue = null; object invokee = GetInvocationTarget(_componentClass, component); if (!IsReadOnly) { IComponentChangeService changeService = null; // Announce that we are about to change this component if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); } // Make sure that it is ok to send the onchange events if (changeService != null) { oldValue = GetMethodValue.Invoke(invokee, null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw; } } try { try { SetMethodValue.Invoke(invokee, new object[] { value }); OnValueChanged(invokee, EventArgs.Empty); } catch (Exception t) { // Give ourselves a chance to unwind properly before rethrowing the exception. // value = oldValue; // If there was a problem setting the controls property then we get: // ArgumentException (from properties set method) // ==> Becomes inner exception of TargetInvocationException // ==> caught here if (t is TargetInvocationException && t.InnerException != null) { // Propagate the original exception up throw t.InnerException; } else { throw; } } } finally { // Now notify the change service that the change was successful. changeService?.OnComponentChanged(component, this, oldValue, value); } } } } /// <summary> /// Indicates whether the value of this property needs to be persisted. In /// other words, it indicates whether the state of the property is distinct /// from when the component is first instantiated. If there is a default /// value specified in this ReflectPropertyDescriptor, it will be compared against the /// property's current value to determine this. If there isn't, the /// ShouldSerializeXXX method is looked for and invoked if found. If both /// these routes fail, true will be returned. /// /// If this returns false, a tool should not persist this property's value. /// </summary> public override bool ShouldSerializeValue(object component) { component = GetInvocationTarget(_componentClass, component); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch { } } return AttributesContainsDesignerVisibilityContent(); } else if (DefaultValue == s_noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch { } } return true; } return !Equals(DefaultValue, GetValue(component)); } /// <summary> /// Indicates whether value change notifications for this property may originate from outside the property /// descriptor, such as from the component itself (value=true), or whether notifications will only originate /// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may /// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property. /// </summary> public override bool SupportsChangeEvents => IPropChangedEventValue != null || ChangedEventValue != null; } }
42.355054
186
0.513403
[ "MIT" ]
Corillian/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs
50,699
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { /// <summary> /// Data describing an external URL set up by a script. /// </summary> public class UrlData { /// <summary> /// Scene object part hosting the script /// </summary> public UUID hostID; /// <summary> /// The item ID of the script that requested the URL. /// </summary> public UUID itemID; /// <summary> /// The script engine that runs the script. /// </summary> public IScriptModule engine; /// <summary> /// The generated URL. /// </summary> public string url; /// <summary> /// The random UUID component of the generated URL. /// </summary> public UUID urlcode; /// <summary> /// The external requests currently being processed or awaiting retrieval for this URL. /// </summary> public ThreadedClasses.RwLockedDictionary<UUID, RequestData> requests; } public class RequestData { public UUID requestID; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; public string responseType = "text/plain"; //public ManualResetEvent ev; public bool requestDone; public int startTime; public string uri; } /// <summary> /// This module provides external URLs for in-world scripts. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UrlModule")] public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the request ID /// randomly generated when a request is received for this URL. /// </summary> /// <remarks> /// Manipulation or retrieval from this dictionary must be locked on m_UrlMap to preserve consistency with /// m_UrlMap /// </remarks> private ThreadedClasses.RwLockedDictionary<UUID, UrlData> m_RequestMap = new ThreadedClasses.RwLockedDictionary<UUID, UrlData>(); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the full URL /// </summary> private ThreadedClasses.RwLockedDictionary<string, UrlData> m_UrlMap = new ThreadedClasses.RwLockedDictionary<string, UrlData>(); private uint m_HttpsPort = 0; private IHttpServer m_HttpServer = null; private IHttpServer m_HttpsServer = null; public string ExternalHostNameForLSL { get; private set; } /// <summary> /// The default maximum number of urls /// </summary> public const int DefaultTotalUrls = 100; /// <summary> /// Maximum number of external urls that can be set up by this module. /// </summary> public int TotalUrls { get; set; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { IConfig networkConfig = config.Configs["Network"]; if (networkConfig != null) { ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null); bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false); if (ssl_enabled) m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort); } if (ExternalHostNameForLSL == null) ExternalHostNameForLSL = System.Environment.MachineName; IConfig llFunctionsConfig = config.Configs["LL-Functions"]; if (llFunctionsConfig != null) TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls); else TotalUrls = DefaultTotalUrls; } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one // m_HttpServer = MainServer.Instance; // // We can use the https if it is enabled if (m_HttpsPort > 0) { m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort); } } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule scriptModule in scriptModules) { scriptModule.OnScriptRemoved += ScriptRemoved; scriptModule.OnObjectRemoved += ObjectRemoved; } } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); lock(m_UrlMap) /* this lock here is for preventing concurrency when checking for Url amount */ { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new ThreadedClasses.RwLockedDictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttp/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); if (m_HttpsServer == null) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } lock (m_UrlMap) /* this lock here is for preventing concurrency when checking for Url amount */ { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new ThreadedClasses.RwLockedDictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttps/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpsServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public void ReleaseURL(string url) { UrlData data; if (!m_UrlMap.Remove(url, out data)) { return; } foreach (UUID req in data.requests.Keys) m_RequestMap.Remove(req); m_log.DebugFormat( "[URL MODULE]: Releasing url {0} for {1} in {2}", url, data.itemID, data.hostID); RemoveUrl(data); m_UrlMap.Remove(url); } public void HttpContentType(UUID request, string type) { UrlData urlData; if (m_RequestMap.TryGetValue(request, out urlData)) { urlData.requests[request].responseType = type; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } public void HttpResponse(UUID request, int status, string body) { UrlData urlData; if (m_RequestMap.TryGetValue(request, out urlData)) { string responseBody = body; if (urlData.requests[request].responseType.Equals("text/plain")) { string value; if (urlData.requests[request].headers.TryGetValue("user-agent", out value)) { if (value != null && value.IndexOf("MSIE") >= 0) { // wrap the html escaped response if the target client is IE // It ignores "text/plain" if the body is html responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>"; } } } urlData.requests[request].responseCode = status; urlData.requests[request].responseBody = responseBody; //urlData.requests[request].ev.Set(); urlData.requests[request].requestDone =true; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } public string GetHttpHeader(UUID requestId, string header) { UrlData urlData; if (m_RequestMap.TryGetValue(requestId, out urlData)) { string value; if (urlData.requests[requestId].headers.TryGetValue(header, out value)) return value; } else { m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId); } return String.Empty; } public int GetFreeUrls() { return TotalUrls - m_UrlMap.Count; } public void ScriptRemoved(UUID itemID) { // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID); List<string> removeURLs = new List<string>(); m_UrlMap.ForEach(delegate(KeyValuePair<string, UrlData> url) { if (url.Value.itemID == itemID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } }); foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } public void ObjectRemoved(UUID objectID) { List<string> removeURLs = new List<string>(); m_UrlMap.ForEach(delegate(KeyValuePair<string, UrlData> url) { if (url.Value.hostID == objectID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } }); foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } private void RemoveUrl(UrlData data) { m_HttpServer.RemoveHTTPHandler("", "/lslhttp/" + data.urlcode.ToString() + "/"); } private Hashtable NoEvents(UUID requestID, UUID sessionID) { Hashtable response = new Hashtable(); UrlData urlData; // We need to return a 404 here in case the request URL was removed at exactly the same time that a // request was made. In this case, the request thread can outrace llRemoveURL() and still be polling // for the request ID. if(!m_RequestMap.TryGetValue(requestID, out urlData)) { response["int_response_code"] = 404; response["str_response_string"] = ""; response["keepalive"] = false; response["reusecontext"] = false; return response; } if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map urlData.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } return response; } private bool HasEvents(UUID requestID, UUID sessionID) { UrlData urlData; RequestData requestData; // We return true here because an external URL request that happened at the same time as an llRemoveURL() // can still make it through to HttpRequestHandler(). That will return without setting up a request // when it detects that the URL has been removed. The poller, however, will continue to ask for // events for that request, so here we will signal that there are events and in GetEvents we will // return a 404. if (!m_RequestMap.TryGetValue(requestID, out urlData)) { return true; } if (!urlData.requests.TryGetValue(requestID, out requestData)) { return true; } // Trigger return of timeout response. if (System.Environment.TickCount - requestData.startTime > 25000) { return true; } return requestData.requestDone; } private Hashtable GetEvents(UUID requestID, UUID sessionID) { Hashtable response; UrlData url = null; RequestData requestData = null; if (!m_RequestMap.TryGetValue(requestID, out url)) { return NoEvents(requestID, sessionID); } if(!url.requests.TryGetValue(requestID, out requestData)) { return NoEvents(requestID, sessionID); } if (!requestData.requestDone) { return NoEvents(requestID, sessionID); } response = new Hashtable(); if (System.Environment.TickCount - requestData.startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; } //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.responseType; response["keepalive"] = false; response["reusecontext"] = false; //remove from map url.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } public void HttpRequestHandler(UUID requestID, Hashtable request) { string uri = request["uri"].ToString(); bool is_ssl = uri.Contains("lslhttps"); try { Hashtable headers = (Hashtable)request["headers"]; // string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/"; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); //HTTP server code doesn't provide us with QueryStrings string pathInfo; string queryString; queryString = ""; pathInfo = uri.Substring(pos3); UrlData urlData = null; string url; if (is_ssl) url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp; else url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp; // Avoid a race - the request URL may have been released via llRequestUrl() whilst this // request was being processed. if (!m_UrlMap.TryGetValue(url, out urlData)) return; //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData(); requestData.requestID = requestID; requestData.requestDone = false; requestData.startTime = System.Environment.TickCount; requestData.uri = uri; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key, value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { System.String[] keys = (System.String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"]; requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = urlData.url; urlData.requests.Add(requestID, requestData); m_RequestMap.Add(requestID, urlData); urlData.engine.PostScriptEvent( urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); } catch (Exception we) { //Hashtable response = new Hashtable(); m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); } } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } } }
37.609302
162
0.546418
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs
24,258
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network; namespace Azure.ResourceManager.Network.Models { /// <summary> Updates network profile tags. </summary> public partial class NetworkProfileUpdateTagsOperation : Operation<NetworkProfile> { private readonly OperationOrResponseInternals<NetworkProfile> _operation; /// <summary> Initializes a new instance of NetworkProfileUpdateTagsOperation for mocking. </summary> protected NetworkProfileUpdateTagsOperation() { } internal NetworkProfileUpdateTagsOperation(ArmResource operationsBase, Response<NetworkProfileData> response) { _operation = new OperationOrResponseInternals<NetworkProfile>(Response.FromValue(new NetworkProfile(operationsBase, response.Value), response.GetRawResponse())); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override NetworkProfile Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<NetworkProfile>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<NetworkProfile>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); } }
39.344262
229
0.730417
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/LongRunningOperation/NetworkProfileUpdateTagsOperation.cs
2,400
C#
using System; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Sandbox.Common; using Sandbox.Common.Components; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using Sandbox.Engine; using Sandbox.Game; using Sandbox.ModAPI; using Sandbox.ModAPI.Ingame; using Sandbox.ModAPI.Interfaces; using SpaceEngineers.Game.ModAPI; using Sandbox.Game.Entities; using VRage.Game.ModAPI; using VRage.Game; using VRage.Game.Definitions; using VRage.Game.Components; using VRage.ModAPI; using VRage.Utils; using VRageMath; namespace ConquestGame { public enum MySafeZoneAction { Damage = 1, Shooting = 2, Drilling = 4, Welding = 8, Grinding = 16, VoxelHand = 32, Building = 64, LandingGearLock = 128, ConvertToStation = 256, All = 511, AdminIgnore = 382 } public struct ColorBlockCoords { public Vector3I Min; public Vector3I Max; public ColorBlockCoords(Vector3I min, Vector3I max) { Min = min; Max = max; } } public class ConquestGameHelper { public static T CastProhibit<T>(T ptr, object val) => (T)val; public static double deg2rad(int degree) { return degree * (double)Math.PI / 180; } public static int rad2deg(float rad) { return (int) (rad * 180 / Math.PI); } /* uses same function as color picker */ public static VRageMath.Color ConvertHexToColor(string hex) { if (hex.Length > 6) { hex = hex.Substring(1); } 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 Color((int)r, (int)g, (int)b); } public static void ReplaceColorOnConnectedGrids(MyCubeGrid parentGrid, Vector3 findColor, Vector3 replaceColor, bool convertToFriendly=true) { var grids = GetConnectedGrids(parentGrid); foreach(IMyCubeGrid grid in grids) { var matchingBlocks = FindColor(grid as MyCubeGrid, findColor, convertToFriendly); foreach(var block in matchingBlocks) { grid.ColorBlocks(block.Position, block.Position, replaceColor); } } } public static List<IMyCubeGrid> GetConnectedGrids(MyCubeGrid parentGrid) { Debug.d("parentGrid: "+parentGrid.DisplayName); var list = MyAPIGateway.GridGroups.GetGroup(parentGrid, GridLinkTypeEnum.Logical | GridLinkTypeEnum.Physical | GridLinkTypeEnum.NoContactDamage | GridLinkTypeEnum.Mechanical ); Debug.d(list.Count.ToString()); return list; } public static List<IMySlimBlock> FindColor(MyCubeGrid grid, VRageMath.Color targetColor, bool convertToFriendly=true) { var list = new List<IMySlimBlock>(); var targetColorHSV = ToHsvColor(targetColor); var targetColorCompare = targetColorHSV; if (convertToFriendly) { targetColorCompare = ColorMaskToFriendlyHSV(ColorMaskToRGB(targetColorHSV)); } else { targetColorCompare = ColorMaskToRGB(targetColor); } foreach(IMySlimBlock slim in grid.GetBlocks()) { var blockColor = slim.ColorMaskHSV; var blockColorCompare = blockColor; if (convertToFriendly) { blockColorCompare = ColorMaskToFriendlyHSV(ColorMaskToRGB(blockColor)); } else { blockColorCompare = ColorMaskToRGB(slim.ColorMaskHSV); } if (blockColorCompare == targetColorCompare) { list.Add(slim); } } return list; } public static Vector3 ColorMaskToFriendlyHSV(Vector3 colorMask) { var hsv = MyColorPickerConstants.HSVOffsetToHSV(colorMask); return new Vector3(Math.Round(hsv.X * 360, 1), Math.Round(hsv.Y * 100, 1), Math.Round(hsv.Z * 100, 1)); } public static Color ColorMaskToRGB(Vector3 colorMask) { return MyColorPickerConstants.HSVOffsetToHSV(colorMask).HSVtoColor(); } public static Vector3 ToHsvColor(VRageMath.Color color) { return VRageMath.ColorExtensions.ColorToHSV(color); } public static VRageMath.Color ToColor(Vector3 hsv) { return VRageMath.ColorExtensions.HSVtoColor(hsv); } public static void RemoveAllSafeZones() { HashSet<IMyEntity> entity_list = new HashSet<IMyEntity>(); MyAPIGateway.Entities.GetEntities(entity_list); int entityDelete = 0; foreach (var entity in entity_list) { if (entity == null || MyAPIGateway.Entities.Exist(entity) == false) { continue; } if (entity as MySafeZone != null) { entity.Close(); } } } public static string DetermineFactionFromEntityBlocks(MyCubeGrid grid) { var factionCount = new Dictionary<string, int>(); foreach(IMySlimBlock slim in grid.GetBlocks()) { if (slim.FatBlock == null) { continue; } var block = (IMyCubeBlock) slim.FatBlock; if (block == null) { continue; } var factionTag = block.GetOwnerFactionTag(); if (factionTag == "") { continue; } if (!factionCount.ContainsKey(factionTag)) { factionCount.Add(factionTag, 0); } factionCount[factionTag]++; } var highestValue = factionCount.FirstOrDefault(); var lowestValue = factionCount.FirstOrDefault(); foreach(var count in factionCount) { if (count.Value > highestValue.Value) { highestValue = count; } if (count.Value < lowestValue.Value ) { lowestValue = count; } } if (highestValue.Key != lowestValue.Key && highestValue.Value == lowestValue.Value) { return ""; } return highestValue.Key; } public static MySafeZone CreateSafezone(string name, MyPositionAndOrientation pos) { var ob = new MyObjectBuilder_SafeZone(); ob.PositionAndOrientation = pos; ob.PersistentFlags = MyPersistentEntityFlags2.InScene; ob.Factions = new long[] { }; ob.AccessTypeFactions = MySafeZoneAccess.Blacklist; ob.AccessTypePlayers = MySafeZoneAccess.Blacklist; ob.AccessTypeGrids = MySafeZoneAccess.Blacklist; ob.AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist; ob.Shape = MySafeZoneShape.Sphere; ob.Radius = (float) 30; ob.Enabled = true; ob.DisplayName = name; ob.ModelColor = VRageMath.Color.Transparent.ToVector3(); ob.AllowedActions = CastProhibit(MySessionComponentSafeZones.AllowedActions, MySafeZoneAction.Damage | MySafeZoneAction.Shooting | MySafeZoneAction.Welding | MySafeZoneAction.Grinding | MySafeZoneAction.LandingGearLock ); return MyEntities.CreateFromObjectBuilderAndAdd(ob, true) as MySafeZone; } } }
34.082645
148
0.571169
[ "MIT" ]
twosnake/remote_capture_mod
Data/Scripts/testnet/ConquestGameHelper.cs
8,248
C#
namespace Havit.Data.EntityFrameworkCore.CodeGenerator.Services { public interface ITemplate { string TransformText(); // pro zjednodušení použijeme metodu genetovanou T4kou. } }
26.285714
81
0.798913
[ "MIT" ]
havit/HavitFramework
Havit.Data.EntityFrameworkCore.CodeGenerator/Services/ITemplate.cs
189
C#
using Microsoft.EntityFrameworkCore; using Paillave.Etl.Core; using System; using System.Collections.Generic; using Paillave.Etl.Reactive.Operators; using System.Linq; using System.Linq.Expressions; using Paillave.EntityFrameworkCoreExtension.EfSave; using Paillave.EntityFrameworkCoreExtension.BulkSave; namespace Paillave.Etl.EntityFrameworkCore { public class EfCoreSaveArgsBuilder<TInEf, TIn, TOut> { internal EfCoreSaveArgs<TInEf, TIn, TOut> Args { get; set; } public EfCoreSaveArgsBuilder(IStream<TIn> sourceStream, Func<TIn, TInEf> getEntity, Func<TIn, TInEf, TOut> getOutput) { this.Args = new EfCoreSaveArgs<TInEf, TIn, TOut> { SourceStream = sourceStream, GetEntity = getEntity, GetOutput = getOutput }; } private EfCoreSaveArgsBuilder(EfCoreSaveArgs<TInEf, TIn, TOut> args) { this.Args = args; } private TArgs UpdateArgs<TArgs>(TArgs args) where TArgs : IThroughEntityFrameworkCoreArgs<TIn> { args.BatchSize = this.Args.BatchSize; args.BulkLoadMode = this.Args.BulkLoadMode; args.DoNotUpdateIfExists = this.Args.DoNotUpdateIfExists; args.InsertOnly = this.Args.InsertOnly; args.SourceStream = this.Args.SourceStream; args.KeyedConnection = this.Args.KeyedConnection; return args; } public EfCoreSaveArgsBuilder<TNewInEf, TIn, TNewInEf> Entity<TNewInEf>(Func<TIn, TNewInEf> getEntity) where TNewInEf : class => new EfCoreSaveArgsBuilder<TNewInEf, TIn, TNewInEf>(UpdateArgs(new EfCoreSaveArgs<TNewInEf, TIn, TNewInEf> { GetEntity = getEntity, GetOutput = (i, j) => j })); public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> SeekOn(Expression<Func<TInEf, object>> pivot) { this.Args.PivotKeys = new List<Expression<Func<TInEf, object>>> { pivot }; return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> AlternativelySeekOn(Expression<Func<TInEf, object>> pivot) { this.Args.PivotKeys.Add(pivot); return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TNewOut> Output<TNewOut>(Func<TIn, TInEf, TNewOut> getOutput) => new EfCoreSaveArgsBuilder<TInEf, TIn, TNewOut>(UpdateArgs(new EfCoreSaveArgs<TInEf, TIn, TNewOut> { GetEntity = this.Args.GetEntity, GetOutput = getOutput, PivotKeys = this.Args.PivotKeys })); public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> WithBatchSize(int batchSize) { this.Args.BatchSize = batchSize; return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> WithKeyedConnection(string keyedConnection) { this.Args.KeyedConnection = keyedConnection; return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> WithMode(SaveMode bulkLoadMode) { this.Args.BulkLoadMode = bulkLoadMode; return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> DoNotUpdateIfExists(bool doNotUpdateIfExists = true) { this.Args.DoNotUpdateIfExists = doNotUpdateIfExists; return this; } public EfCoreSaveArgsBuilder<TInEf, TIn, TOut> InsertOnly(bool insertOnly = true) { this.Args.InsertOnly = insertOnly; return this; } } public class EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> { internal EfCoreSaveArgs<TInEf, Correlated<TIn>, Correlated<TOut>> Args { get; set; } public EfCoreSaveCorrelatedArgsBuilder(IStream<Correlated<TIn>> sourceStream, Func<TIn, TInEf> getEntity, Func<TIn, TInEf, TOut> getOutput) { this.Args = new EfCoreSaveArgs<TInEf, Correlated<TIn>, Correlated<TOut>> { SourceStream = sourceStream, GetEntity = i => getEntity(i.Row), GetOutput = (i, e) => new Correlated<TOut> { Row = getOutput(i.Row, e), CorrelationKeys = i.CorrelationKeys } }; } private EfCoreSaveCorrelatedArgsBuilder(EfCoreSaveArgs<TInEf, Correlated<TIn>, Correlated<TOut>> args) { this.Args = args; } private TArgs UpdateArgs<TArgs>(TArgs args) where TArgs : IThroughEntityFrameworkCoreArgs<Correlated<TIn>> { args.BatchSize = this.Args.BatchSize; args.BulkLoadMode = this.Args.BulkLoadMode; args.DoNotUpdateIfExists = this.Args.DoNotUpdateIfExists; args.InsertOnly = this.Args.InsertOnly; args.SourceStream = this.Args.SourceStream; args.KeyedConnection = this.Args.KeyedConnection; return args; } public EfCoreSaveCorrelatedArgsBuilder<TNewInEf, TIn, TNewInEf> Entity<TNewInEf>(Func<TIn, TNewInEf> getEntity) where TNewInEf : class => new EfCoreSaveCorrelatedArgsBuilder<TNewInEf, TIn, TNewInEf>(UpdateArgs(new EfCoreSaveArgs<TNewInEf, Correlated<TIn>, Correlated<TNewInEf>> { GetEntity = i => getEntity(i.Row), GetOutput = (i, j) => new Correlated<TNewInEf> { Row = j, CorrelationKeys = i.CorrelationKeys } })); public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> SeekOn(Expression<Func<TInEf, object>> pivot) { this.Args.PivotKeys = new List<Expression<Func<TInEf, object>>> { pivot }; return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> AlternativelySeekOn(Expression<Func<TInEf, object>> pivot) { this.Args.PivotKeys.Add(pivot); return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TNewOut> Output<TNewOut>(Func<TIn, TInEf, TNewOut> getOutput) => new EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TNewOut>(UpdateArgs(new EfCoreSaveArgs<TInEf, Correlated<TIn>, Correlated<TNewOut>> { GetEntity = this.Args.GetEntity, GetOutput = (i, e) => new Correlated<TNewOut> { Row = getOutput(i.Row, e), CorrelationKeys = i.CorrelationKeys }, PivotKeys = this.Args.PivotKeys })); public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> WithBatchSize(int batchSize) { this.Args.BatchSize = batchSize; return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> WithKeyedConnection(string keyedConnection) { this.Args.KeyedConnection = keyedConnection; return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> WithMode(SaveMode bulkLoadMode) { this.Args.BulkLoadMode = bulkLoadMode; return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> DoNotUpdateIfExists(bool doNotUpdateIfExists = true) { this.Args.DoNotUpdateIfExists = doNotUpdateIfExists; return this; } public EfCoreSaveCorrelatedArgsBuilder<TInEf, TIn, TOut> InsertOnly(bool insertOnly = true) { this.Args.InsertOnly = insertOnly; return this; } } internal interface IThroughEntityFrameworkCoreArgs<TIn> { IStream<TIn> SourceStream { get; set; } int BatchSize { get; set; } SaveMode BulkLoadMode { get; set; } bool DoNotUpdateIfExists { get; set; } bool InsertOnly { get; set; } string KeyedConnection { get; set; } } public class EfCoreSaveArgs<TInEf, TIn, TOut> : IThroughEntityFrameworkCoreArgs<TIn> { internal EfCoreSaveArgs() { } public IStream<TIn> SourceStream { get; set; } public int BatchSize { get; set; } = 10000; public SaveMode BulkLoadMode { get; set; } = SaveMode.SqlServerBulk; public Func<TIn, TInEf> GetEntity { get; set; } public Func<TIn, TInEf, TOut> GetOutput { get; set; } public List<Expression<Func<TInEf, object>>> PivotKeys { get; set; } public bool DoNotUpdateIfExists { get; set; } = false; public bool InsertOnly { get; set; } = false; public string KeyedConnection { get; set; } = null; } public enum SaveMode { EntityFrameworkCore, SqlServerBulk, } public class EfCoreSaveStreamNode<TInEf, TIn, TOut> : StreamNodeBase<TOut, IStream<TOut>, EfCoreSaveArgs<TInEf, TIn, TOut>> where TInEf : class { public override ProcessImpact PerformanceImpact => ProcessImpact.Heavy; public override ProcessImpact MemoryFootPrint => ProcessImpact.Light; public EfCoreSaveStreamNode(string name, EfCoreSaveArgs<TInEf, TIn, TOut> args) : base(name, args) { } protected override IStream<TOut> CreateOutputStream(EfCoreSaveArgs<TInEf, TIn, TOut> args) { var ret = args.SourceStream.Observable .Chunk(args.BatchSize) .Map(i => i.Select(j => (Input: j, Entity: args.GetEntity(j))).ToList()) .Do(i => { var dbContext = args.KeyedConnection == null ? this.ExecutionContext.DependencyResolver.Resolve<DbContext>() : this.ExecutionContext.DependencyResolver.Resolve<DbContext>(args.KeyedConnection); this.ExecutionContext.InvokeInDedicatedThreadAsync(dbContext, () => ProcessBatch(i, dbContext, args.BulkLoadMode)).Wait(); }) .FlatMap((i, ct) => PushObservable.FromEnumerable(i, ct)) .Map(i => args.GetOutput(i.Input, i.Entity)); return base.CreateUnsortedStream(ret); } public void ProcessBatch(List<(TIn Input, TInEf Entity)> items, DbContext dbContext, SaveMode bulkLoadMode) { var entities = items.Select(i => i.Item2).ToArray(); var pivotKeys = Args.PivotKeys == null ? (Expression<Func<TInEf, object>>[])null : Args.PivotKeys.ToArray(); switch (bulkLoadMode) { case SaveMode.EntityFrameworkCore: dbContext.EfSaveAsync(entities, pivotKeys, Args.SourceStream.Observable.CancellationToken, Args.DoNotUpdateIfExists, Args.InsertOnly).Wait(); break; case SaveMode.SqlServerBulk: dbContext.BulkSave(entities, pivotKeys, Args.SourceStream.Observable.CancellationToken, Args.DoNotUpdateIfExists, Args.InsertOnly); break; default: break; } DetachAllEntities(dbContext); } public void DetachAllEntities(DbContext dbContext) { var changedEntriesCopy = dbContext.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted) .ToList(); foreach (var entry in changedEntriesCopy) entry.State = EntityState.Detached; } } }
43.969112
161
0.615911
[ "MIT" ]
fundprocess/Etl.Net
src/Paillave.Etl.EntityFrameworkCore/EfCoreSaveStreamNode.cs
11,390
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.AppPlatform.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Persistent disk payload /// </summary> public partial class PersistentDisk { /// <summary> /// Initializes a new instance of the PersistentDisk class. /// </summary> public PersistentDisk() { CustomInit(); } /// <summary> /// Initializes a new instance of the PersistentDisk class. /// </summary> /// <param name="sizeInGB">Size of the persistent disk in GB</param> /// <param name="usedInGB">Size of the used persistent disk in /// GB</param> /// <param name="mountPath">Mount path of the persistent disk</param> public PersistentDisk(int? sizeInGB = default(int?), int? usedInGB = default(int?), string mountPath = default(string)) { SizeInGB = sizeInGB; UsedInGB = usedInGB; MountPath = mountPath; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets size of the persistent disk in GB /// </summary> [JsonProperty(PropertyName = "sizeInGB")] public int? SizeInGB { get; set; } /// <summary> /// Gets size of the used persistent disk in GB /// </summary> [JsonProperty(PropertyName = "usedInGB")] public int? UsedInGB { get; private set; } /// <summary> /// Gets or sets mount path of the persistent disk /// </summary> [JsonProperty(PropertyName = "mountPath")] public string MountPath { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (SizeInGB > 50) { throw new ValidationException(ValidationRules.InclusiveMaximum, "SizeInGB", 50); } if (SizeInGB < 0) { throw new ValidationException(ValidationRules.InclusiveMinimum, "SizeInGB", 0); } if (UsedInGB > 50) { throw new ValidationException(ValidationRules.InclusiveMaximum, "UsedInGB", 50); } if (UsedInGB < 0) { throw new ValidationException(ValidationRules.InclusiveMinimum, "UsedInGB", 0); } } } }
32.505263
127
0.568329
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/appplatform/Microsoft.Azure.Management.AppPlatform/src/Generated/Models/PersistentDisk.cs
3,088
C#
// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team // // 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.Text; namespace ICSharpCode.NRefactory.Xml { /// <summary> /// Derive from this class to create visitor for the XML tree /// </summary> public abstract class AXmlVisitor { /// <summary> Visit AXmlDocument </summary> public virtual void VisitDocument(AXmlDocument document) { foreach (AXmlObject child in document.Children) child.AcceptVisitor(this); } /// <summary> Visit AXmlElement </summary> public virtual void VisitElement(AXmlElement element) { foreach (AXmlObject child in element.Children) child.AcceptVisitor(this); } /// <summary> Visit AXmlTag </summary> public virtual void VisitTag(AXmlTag tag) { foreach (AXmlObject child in tag.Children) child.AcceptVisitor(this); } /// <summary> Visit AXmlAttribute </summary> public virtual void VisitAttribute(AXmlAttribute attribute) { } /// <summary> Visit AXmlText </summary> public virtual void VisitText(AXmlText text) { } } }
34.532258
93
0.737973
[ "MIT" ]
376730969/ILSpy
NRefactory/ICSharpCode.NRefactory.Xml/AXmlVisitor.cs
2,143
C#
using System; using Allergies.Models; namespace Allergies { public class Program { public static void Main() { bool keepRunning; do { Console.WriteLine("Enter your allergy score: "); int scoreInput = int.Parse(Console.ReadLine()); AllergyScore allergyScore = new AllergyScore(scoreInput); allergyScore.PrintAllergies(); Console.WriteLine("Go again? (y/n)"); keepRunning = Console.ReadLine() == "y"; Console.WriteLine(); } while (keepRunning); } } }
24.818182
65
0.615385
[ "MIT" ]
shanencross/Allergies.Solution
Allergies/Program.cs
546
C#
using System; namespace Bitbird.Core.Data.Cache { public class RedisCacheInfo { internal RedisCacheInfo() { } public bool IsConnected { get; set; } public long UsedMemory { get; set; } public long MaximumMemory { get; set; } public double? MemoryPercentage { get { if (MaximumMemory <= 0) { return null; } return Math.Round(100.0 * UsedMemory / MaximumMemory, 2); } } } }
23.08
73
0.466205
[ "MIT" ]
bitbird-dev/Bitbird.Core
Bitbird.Core.Data/Cache/RedisCacheInfo.cs
579
C#
// <copyright file="Fourier.Bluestein.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2015 Math.NET // // 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. // </copyright> using System; using System.Numerics; using MathNet.Numerics.Threading; namespace MathNet.Numerics.IntegralTransforms { /// <summary> /// Complex Fast (FFT) Implementation of the Discrete Fourier Transform (DFT). /// </summary> public static partial class Fourier { /// <summary> /// Sequences with length greater than Math.Sqrt(Int32.MaxValue) + 1 /// will cause k*k in the Bluestein sequence to overflow (GH-286). /// </summary> const int BluesteinSequenceLengthThreshold = 46341; /// <summary> /// Generate the bluestein sequence for the provided problem size. /// </summary> /// <param name="n">Number of samples.</param> /// <returns>Bluestein sequence exp(I*Pi*k^2/N)</returns> static Complex32[] BluesteinSequence32(int n) { double s = Constants.Pi / n; var sequence = new Complex32[n]; // TODO: benchmark whether the second variation is significantly // faster than the former one. If not just use the former one always. if (n > BluesteinSequenceLengthThreshold) { for (int k = 0; k < sequence.Length; k++) { double t = (s * k) * k; sequence[k] = new Complex32((float)Math.Cos(t), (float)Math.Sin(t)); } } else { for (int k = 0; k < sequence.Length; k++) { double t = s * (k * k); sequence[k] = new Complex32((float)Math.Cos(t), (float)Math.Sin(t)); } } return sequence; } /// <summary> /// Generate the bluestein sequence for the provided problem size. /// </summary> /// <param name="n">Number of samples.</param> /// <returns>Bluestein sequence exp(I*Pi*k^2/N)</returns> static Complex[] BluesteinSequence(int n) { double s = Constants.Pi/n; var sequence = new Complex[n]; // TODO: benchmark whether the second variation is significantly // faster than the former one. If not just use the former one always. if (n > BluesteinSequenceLengthThreshold) { for (int k = 0; k < sequence.Length; k++) { double t = (s*k)*k; sequence[k] = new Complex(Math.Cos(t), Math.Sin(t)); } } else { for (int k = 0; k < sequence.Length; k++) { double t = s*(k*k); sequence[k] = new Complex(Math.Cos(t), Math.Sin(t)); } } return sequence; } /// <summary> /// Convolution with the bluestein sequence (Parallel Version). /// </summary> /// <param name="samples">Sample Vector.</param> static void BluesteinConvolutionParallel(Complex32[] samples) { int n = samples.Length; Complex32[] sequence = BluesteinSequence32(n); // Padding to power of two >= 2N–1 so we can apply Radix-2 FFT. int m = ((n << 1) - 1).CeilingToPowerOfTwo(); var b = new Complex32[m]; var a = new Complex32[m]; CommonParallel.Invoke( () => { // Build and transform padded sequence b_k = exp(I*Pi*k^2/N) for (int i = 0; i < n; i++) { b[i] = sequence[i]; } for (int i = m - n + 1; i < b.Length; i++) { b[i] = sequence[m - i]; } Radix2(b, -1); }, () => { // Build and transform padded sequence a_k = x_k * exp(-I*Pi*k^2/N) for (int i = 0; i < samples.Length; i++) { a[i] = sequence[i].Conjugate() * samples[i]; } Radix2(a, -1); }); for (int i = 0; i < a.Length; i++) { a[i] *= b[i]; } Radix2Parallel(a, 1); var nbinv = 1.0f / m; for (int i = 0; i < samples.Length; i++) { samples[i] = nbinv * sequence[i].Conjugate() * a[i]; } } /// <summary> /// Convolution with the bluestein sequence (Parallel Version). /// </summary> /// <param name="samples">Sample Vector.</param> static void BluesteinConvolutionParallel(Complex[] samples) { int n = samples.Length; Complex[] sequence = BluesteinSequence(n); // Padding to power of two >= 2N–1 so we can apply Radix-2 FFT. int m = ((n << 1) - 1).CeilingToPowerOfTwo(); var b = new Complex[m]; var a = new Complex[m]; CommonParallel.Invoke( () => { // Build and transform padded sequence b_k = exp(I*Pi*k^2/N) for (int i = 0; i < n; i++) { b[i] = sequence[i]; } for (int i = m - n + 1; i < b.Length; i++) { b[i] = sequence[m - i]; } Radix2(b, -1); }, () => { // Build and transform padded sequence a_k = x_k * exp(-I*Pi*k^2/N) for (int i = 0; i < samples.Length; i++) { a[i] = sequence[i].Conjugate()*samples[i]; } Radix2(a, -1); }); for (int i = 0; i < a.Length; i++) { a[i] *= b[i]; } Radix2Parallel(a, 1); var nbinv = 1.0/m; for (int i = 0; i < samples.Length; i++) { samples[i] = nbinv*sequence[i].Conjugate()*a[i]; } } /// <summary> /// Swap the real and imaginary parts of each sample. /// </summary> /// <param name="samples">Sample Vector.</param> static void SwapRealImaginary(Complex32[] samples) { for (int i = 0; i < samples.Length; i++) { samples[i] = new Complex32(samples[i].Imaginary, samples[i].Real); } } /// <summary> /// Swap the real and imaginary parts of each sample. /// </summary> /// <param name="samples">Sample Vector.</param> static void SwapRealImaginary(Complex[] samples) { for (int i = 0; i < samples.Length; i++) { samples[i] = new Complex(samples[i].Imaginary, samples[i].Real); } } /// <summary> /// Bluestein generic FFT for arbitrary sized sample vectors. /// </summary> /// <param name="samples">Time-space sample vector.</param> /// <param name="exponentSign">Fourier series exponent sign.</param> internal static void Bluestein(Complex32[] samples, int exponentSign) { int n = samples.Length; if (n.IsPowerOfTwo()) { Radix2Parallel(samples, exponentSign); return; } if (exponentSign == 1) { SwapRealImaginary(samples); } BluesteinConvolutionParallel(samples); if (exponentSign == 1) { SwapRealImaginary(samples); } } /// <summary> /// Bluestein generic FFT for arbitrary sized sample vectors. /// </summary> /// <param name="samples">Time-space sample vector.</param> /// <param name="exponentSign">Fourier series exponent sign.</param> internal static void Bluestein(Complex[] samples, int exponentSign) { int n = samples.Length; if (n.IsPowerOfTwo()) { Radix2Parallel(samples, exponentSign); return; } if (exponentSign == 1) { SwapRealImaginary(samples); } BluesteinConvolutionParallel(samples); if (exponentSign == 1) { SwapRealImaginary(samples); } } } }
33.666667
88
0.483267
[ "MIT" ]
coderIML/math.net
src/Numerics/IntegralTransforms/Fourier.Bluestein.cs
10,106
C#
#region using System.Collections.Generic; using EvilDICOM.Core; using EvilDICOM.Network.Enums; using S = System; using DF = EvilDICOM.Core.DICOMForge; using System.Linq; #endregion namespace EvilDICOM.Network.DIMSE.IOD { public class CFindSeriesIOD : CFindRequestIOD { public CFindSeriesIOD() { QueryLevel = QueryLevel.SERIES; SeriesInstanceUID = string.Empty; SeriesNumber = null; SeriesDescription = string.Empty; Modality = string.Empty; } public CFindSeriesIOD(DICOMObject dcm) : base(dcm) { } public int? SeriesNumber { get { if (_sel.SeriesNumber != null && _sel.SeriesNumber.Data_.Any()) return _sel.SeriesNumber.Data_[0]; return null; } set { _sel.Forge(DF.SeriesNumber()).Data_ = value != null ? new List<int> {(int) value} : new List<int>(); } } public string SeriesDescription { get { return _sel.SeriesDescription != null ? _sel.SeriesDescription.Data : null; } set { _sel.Forge(DF.SeriesDescription(value)); } } public string Modality { get { return _sel.Modality != null ? _sel.Modality.Data : null; } set { _sel.Forge(DF.Modality(value)); } } public string SeriesInstanceUID { get { return _sel.SeriesInstanceUID != null ? _sel.SeriesInstanceUID.Data : null; } set { _sel.Forge(DF.SeriesInstanceUID(value)); } } } }
28.192982
120
0.572495
[ "MIT" ]
damiens/Evil-DICOM
EvilDICOM/EvilDICOM/Network/DIMSE/IOD/CFindSeriesIOD.cs
1,609
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// RewardDetails /// </summary> [DataContract] public partial class RewardDetails : IEquatable<RewardDetails>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="RewardDetails" /> class. /// </summary> /// <param name="RosterId">RosterId.</param> /// <param name="TeamMemberIds">TeamMemberIds.</param> /// <param name="TournamentId">TournamentId.</param> public RewardDetails(long? RosterId = default(long?), List<long?> TeamMemberIds = default(List<long?>), long? TournamentId = default(long?)) { this.RosterId = RosterId; this.TeamMemberIds = TeamMemberIds; this.TournamentId = TournamentId; } /// <summary> /// Gets or Sets RosterId /// </summary> [DataMember(Name="rosterId", EmitDefaultValue=false)] public long? RosterId { get; set; } /// <summary> /// Gets or Sets TeamMemberIds /// </summary> [DataMember(Name="teamMemberIds", EmitDefaultValue=false)] public List<long?> TeamMemberIds { get; set; } /// <summary> /// Gets or Sets TournamentId /// </summary> [DataMember(Name="tournamentId", EmitDefaultValue=false)] public long? TournamentId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RewardDetails {\n"); sb.Append(" RosterId: ").Append(RosterId).Append("\n"); sb.Append(" TeamMemberIds: ").Append(TeamMemberIds).Append("\n"); sb.Append(" TournamentId: ").Append(TournamentId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RewardDetails); } /// <summary> /// Returns true if RewardDetails instances are equal /// </summary> /// <param name="other">Instance of RewardDetails to be compared</param> /// <returns>Boolean</returns> public bool Equals(RewardDetails other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.RosterId == other.RosterId || this.RosterId != null && this.RosterId.Equals(other.RosterId) ) && ( this.TeamMemberIds == other.TeamMemberIds || this.TeamMemberIds != null && this.TeamMemberIds.SequenceEqual(other.TeamMemberIds) ) && ( this.TournamentId == other.TournamentId || this.TournamentId != null && this.TournamentId.Equals(other.TournamentId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.RosterId != null) hash = hash * 59 + this.RosterId.GetHashCode(); if (this.TeamMemberIds != null) hash = hash * 59 + this.TeamMemberIds.GetHashCode(); if (this.TournamentId != null) hash = hash * 59 + this.TournamentId.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
34.282051
148
0.546559
[ "MIT" ]
wildbook/LeagueClientApi
Model/RewardDetails.cs
5,348
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph.CallRecords { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface ICallRecordRequest. /// </summary> public partial interface ICallRecordRequest : Microsoft.Graph.IBaseRequest { /// <summary> /// Creates the specified CallRecord using POST. /// </summary> /// <param name="callRecordToCreate">The CallRecord to create.</param> /// <returns>The created CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> CreateAsync(CallRecord callRecordToCreate); /// <summary> /// Creates the specified CallRecord using POST. /// </summary> /// <param name="callRecordToCreate">The CallRecord to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> CreateAsync(CallRecord callRecordToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified CallRecord. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified CallRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified CallRecord. /// </summary> /// <returns>The CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> GetAsync(); /// <summary> /// Gets the specified CallRecord. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified CallRecord using PATCH. /// </summary> /// <param name="callRecordToUpdate">The CallRecord to update.</param> /// <returns>The updated CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> UpdateAsync(CallRecord callRecordToUpdate); /// <summary> /// Updates the specified CallRecord using PATCH. /// </summary> /// <param name="callRecordToUpdate">The CallRecord to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="Microsoft.Graph.ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated CallRecord.</returns> System.Threading.Tasks.Task<CallRecord> UpdateAsync(CallRecord callRecordToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> ICallRecordRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> ICallRecordRequest Expand(Expression<Func<CallRecord, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> ICallRecordRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> ICallRecordRequest Select(Expression<Func<CallRecord, object>> selectExpression); } }
45.666667
169
0.627737
[ "MIT" ]
andrueastman/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/callrecords/requests/ICallRecordRequest.cs
4,932
C#
using DemoAppInsights.Models; using Serilog; using System; using System.Linq; using System.Web.Mvc; namespace DemoAppInsights.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult SlowPage() { ViewBag.Message = "This is a really slow page."; using (var context = new DemoAppInsightsContext()) { for (var i = 0; i < 20; i++) { var products = context.Products.ToList(); } return View(); } } public ActionResult BuggedCode(int? number) { if (!number.HasValue) return View(); Log.Information("NumberTyped: {Number}", number); if (IsPrime(number.Value)) throw new InvalidOperationException("This is a prime number."); ViewBag.Message = $"The number is {number}"; return View(); } public ActionResult Products() { using (var context = new DemoAppInsightsContext()) { var products = context.Products.ToList(); return View(products); } } private static bool IsPrime(int number) { if (number == 1) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (var i = 3; i < number; i += 2) { if (number % i == 0) return false; } return true; } } }
24.04878
79
0.481237
[ "MIT" ]
abnerdasdores/tdc2016-arqdotnet-appinsights
src/DemoAppInsights/Controllers/HomeController.cs
1,974
C#
using System; using System.Net; using System.Text; namespace SAHB.GraphQLClient.Exceptions { // ReSharper disable once InconsistentNaming /// <summary> /// Throws a new <see cref="GraphQLHttpExecutorServerErrorStatusCodeException"/> which indicates that the GraphQL request returned a non successfull server status code /// </summary> public class GraphQLHttpExecutorServerErrorStatusCodeException : GraphQLException { public HttpStatusCode StatusCode { get; } public string Query { get; } public string Response { get; } public GraphQLHttpExecutorServerErrorStatusCodeException(HttpStatusCode statusCode, string query, string response, string message) : base(GetMessage(statusCode, query, response, message)) { StatusCode = statusCode; Query = query; Response = response; } public GraphQLHttpExecutorServerErrorStatusCodeException(HttpStatusCode statusCode, string query, string response, string message, Exception innerException) : base(GetMessage(statusCode, query, response, message), innerException) { StatusCode = statusCode; Query = query; Response = response; } private static string GetMessage(HttpStatusCode statusCode, string query, string response, string message) { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(message)) builder.AppendLine(message); if (!string.IsNullOrEmpty(query)) builder.AppendLine("Query: " + query); builder.AppendLine("StatusCode: " + statusCode); if (!string.IsNullOrEmpty(response)) builder.AppendLine("Response: " + response); return builder.ToString().TrimEnd(); } } }
41.266667
237
0.662359
[ "MIT" ]
sungam3r/SAHB.GraphQLClient
src/SAHB.GraphQLClient/Exceptions/GraphQLHttpExecutorServerErrorStatusCodeException.cs
1,859
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d3d12umddi.h(640,9) using System; namespace DirectN { [Flags] public enum D3D12DDI_TILE_MAPPING_FLAGS { D3D12DDI_TILE_MAPPING_FLAG_NONE = 0x00000000, D3D12DDI_TILE_MAPPING_FLAG_NO_HAZARD = 0x00000001, } }
24.384615
87
0.687697
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/D3D12DDI_TILE_MAPPING_FLAGS.cs
319
C#
 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SlashSword : MonoBehaviour { public Animator anim; public GameObject powerupCurrent; public GameObject PowerupTurbo; public GameObject slashTrail; public GameObject enemy; public GameObject ForwardBtn; //public GameObject BackwardBtn; public static float PlayerHealth=1f; public float health; public Image playerHealthImg; //public Animation animation1; public bool combat=false; public bool powerupanim = false; public bool slash01anim = false; public bool slash02anim = false; bool movefront=false; bool moveback=false; bool isBlocking=false; public float dis; public static bool canReleaseBeam = false; void Start () { anim=GetComponent<Animator>(); } // Update is called once per frame void Update () { dis = (this.transform.position - enemy.transform.position).magnitude; playerHealthImg.fillAmount = PlayerHealth; health = PlayerHealth; if ( dis<= 12) { ForwardBtn.SetActive (false); } else ForwardBtn.SetActive (true); if (powerupanim == true) { powerupCurrent.SetActive (true); PowerupTurbo.SetActive (true); } if (powerupanim == false) { powerupCurrent.SetActive (false); PowerupTurbo.SetActive (false); } if (slash01anim == true || slash02anim == true) { slashTrail.SetActive (true); } else if (slash01anim == false) { slashTrail.SetActive (false); } else if (slash02anim == false) { slashTrail.SetActive (false); } if(movefront) this.transform.Translate (0, 0, 20*Time.deltaTime); else if(moveback) this.transform.Translate (0, 0, -20*Time.deltaTime); if (isBlocking) anim.SetTrigger ("block"); } public void Fire() { powerupanim = false; slash01anim = false; slash02anim = false; anim.SetTrigger ("fire"); } public void Fire01() { powerupanim = false; slash01anim = false; slash02anim = false; anim.SetTrigger ("fire01"); } public void Slash01() { powerupanim = false; slash02anim = false; canReleaseBeam = false; //anim.SetTrigger ("slash_1"); StartCoroutine(Slash01InProgress()); } public void Slash02() { powerupanim = false; slash01anim = false; canReleaseBeam = false; //anim.SetTrigger ("slash_2"); StartCoroutine(Slash02InProgress()); } public void Jump() { powerupanim = false; slash01anim = false; slash02anim = false; canReleaseBeam = false; anim.SetTrigger ("jump"); } public void PowerUp() { slash01anim = false; slash02anim = false; canReleaseBeam = false; StartCoroutine (TurboOn ()); } public void MoveForward() { anim.SetTrigger ("forward"); StartCoroutine (ForwardRun ()); } public void MoveBackward() { anim.SetTrigger ("backward"); StartCoroutine (BackwardRun ()); } public void Smash() { anim.SetTrigger ("smash"); } public void Block() { isBlocking = true; } public void ReleaseBlock() { isBlocking = false; } IEnumerator ForwardRun() { yield return new WaitForSeconds (0.12f); movefront = true; yield return new WaitForSeconds (0.4f); movefront = false; } IEnumerator BackwardRun() { yield return new WaitForSeconds (0.12f); moveback = true; yield return new WaitForSeconds (0.4f); moveback = false; } IEnumerator TurboOn() { powerupanim = true; anim.SetTrigger ("power"); yield return new WaitForSeconds (2.18f); powerupanim = false; } IEnumerator Slash01InProgress() { slash01anim = true; anim.SetTrigger ("slash_1"); yield return new WaitForSeconds (1.40f); slash01anim = false; } IEnumerator Slash02InProgress() { slash02anim = true; anim.SetTrigger ("slash_2"); yield return new WaitForSeconds (1.7f); slash02anim = false; } }
17.915094
71
0.691417
[ "MIT" ]
koushikbhargav/Sprinkles
Sprinkles/SlashSword.cs
3,800
C#
using Microsoft.EntityFrameworkCore; using SimplCommerce.Core.Domain.IRepositories; using SimplCommerce.Core.Domain.Models; namespace SimplCommerce.Core.Infrastructure.EntityFramework { // TODO This is just a temporary workaround because EF Core 1.0 hasn't support many-many without an entity class to represent the join table public class ProductTemplateProductAttributeRepository : IProductTemplateProductAttributeRepository { private readonly DbContext dbContext; public ProductTemplateProductAttributeRepository(SimplDbContext dbContext) { this.dbContext = dbContext; } public void Remove(ProductTemplateProductAttribute item) { dbContext.Set<ProductTemplateProductAttribute>().Remove(item); } } }
34.956522
144
0.743781
[ "Apache-2.0" ]
dbraunbock/SimplCommerce
src/Core/SimplCommerce.Core/Infrastructure/EntityFramework/ProductTemplateProductAttributeRepository.cs
806
C#
using System.Collections.Generic; namespace Query { public static class Books { public static int CreateBook(int userId, string title, bool favorite, int sort = 0) { return Sql.ExecuteScalar<int>("Book_Create", new {userId, title, favorite, sort } ); } public static void TrashBook(int userId, int bookId) { Sql.ExecuteNonQuery("Book_Trash", new {userId, bookId } ); } public static void DeleteBook(int userId, int bookId) { Sql.ExecuteNonQuery("Book_Delete", new { userId, bookId } ); } public static void UpdateBook(int userId, int bookId, string title) { Sql.ExecuteNonQuery("Book_Update", new { userId, bookId, title } ); } public static void UpdateBookFavorite(int userId, int bookId, bool favorite) { Sql.ExecuteNonQuery("Book_UpdateFavorite", new { userId, bookId, favorite } ); } public static void UpdateBookSort(int userId, int bookId, int sort) { Sql.ExecuteNonQuery("Book_UpdateSort", new { userId, bookId, sort } ); } public static Models.Book GetDetails(int userId, int bookId) { var list = Sql.Populate<Models.Book>( "Book_GetDetails", new { userId, bookId } ); if(list.Count > 0) { return list[0]; } return null; } public static List<Models.Book> GetList(int userId, int sort = 0) { return Sql.Populate<Models.Book>( "Books_GetList", new { userId, sort } ); } } }
27.485294
91
0.505618
[ "MIT" ]
Datasilk/Legendary
Query/Query/Books.cs
1,871
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2019 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:jiangyin@gameframework.cn //------------------------------------------------------------ using System.Collections.Generic; namespace GameFramework.Resource { /// <summary> /// 资源组接口。 /// </summary> public interface IResourceGroup { /// <summary> /// 获取资源组名称。 /// </summary> string Name { get; } /// <summary> /// 获取资源组是否准备完毕。 /// </summary> bool Ready { get; } /// <summary> /// 获取资源组包含资源数量。 /// </summary> int TotalCount { get; } /// <summary> /// 获取资源组中已准备完成资源数量。 /// </summary> int ReadyCount { get; } /// <summary> /// 获取资源组包含资源的总大小。 /// </summary> long TotalLength { get; } /// <summary> /// 获取资源组包含资源压缩后的总大小。 /// </summary> long TotalZipLength { get; } /// <summary> /// 获取资源组中已准备完成资源的总大小。 /// </summary> long ReadyLength { get; } /// <summary> /// 获取资源组的完成进度。 /// </summary> float Progress { get; } /// <summary> /// 获取资源组包含的资源名称列表。 /// </summary> /// <returns>资源组包含的资源名称列表。</returns> string[] GetResourceNames(); /// <summary> /// 获取资源组包含的资源名称列表。 /// </summary> /// <param name="results">资源组包含的资源名称列表。</param> void GetResourceNames(List<string> results); } }
19.776596
63
0.399139
[ "MIT" ]
ElPsyCongree/GameFramework
GameFramework/Resource/IResourceGroup.cs
2,202
C#
// // (C) Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Autodesk.Revit; using System.Collections; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using System.Drawing.Drawing2D; namespace Revit.SDK.Samples.SlabShapeEditing.CS { /// <summary> /// window form contains one picture box to show the /// profile of slab geometry. user can add vertex and crease. /// User can edit slab shape via vertex and crease too. /// </summary> public partial class SlabShapeEditingForm : System.Windows.Forms.Form { enum EditorState { AddVertex, AddCrease, Select, Rotate, Null }; ExternalCommandData m_commandData; //object which contains reference of Revit Application SlabProfile m_slabProfile; //store geometry info of selected slab PointF m_mouseRightDownLocation; //where mouse right button down LineTool m_lineTool; //tool use to draw crease LineTool m_pointTool; //tool use to draw vertex ArrayList m_graphicsPaths; //store all the GraphicsPath objects of crease and vertex. int m_selectIndex; //index of crease and vertex which mouse hovering on. int m_clickedIndex; //index of crease and vertex which mouse clicked. ArrayList m_createdVertices; // new created vertices ArrayList m_createCreases; // new created creases SlabShapeEditor m_slabShapeEditor; //object use to edit slab shape SlabShapeCrease m_selectedCrease; //selected crease, mouse clicked on SlabShapeVertex m_selectedVertex; //selected vertex, mouse clicked on EditorState editorState; //state of user's operation Pen m_toolPen; //pen use to draw new created vertex and crease Pen m_selectPen; // pen use to draw vertex and crease which been selected Pen m_profilePen; // pen use to draw slab's profile const string justNumber = "Please input numbers in textbox!"; //error message const string selectFirst = "Please select a Vertex (or Crease) first!"; //error message /// <summary> /// constructor /// </summary> /// <param name="commandData">selected floor (or slab)</param> /// <param name="commandData">contains reference of Revit Application</param> public SlabShapeEditingForm(Floor floor, ExternalCommandData commandData) { InitializeComponent(); m_commandData = commandData; m_slabProfile = new SlabProfile(floor, commandData); m_slabShapeEditor = floor.SlabShapeEditor; m_lineTool = new LineTool(); m_pointTool = new LineTool(); editorState = EditorState.AddVertex; m_graphicsPaths = new ArrayList(); m_createdVertices = new ArrayList(); m_createCreases = new ArrayList(); m_selectIndex = -1; m_clickedIndex = -1; m_toolPen = new Pen(System.Drawing.Color.Blue, 2); m_selectPen = new Pen(System.Drawing.Color.Red, 2); m_profilePen = new Pen(System.Drawing.Color.Black, (float)(0.5)); } /// <summary> /// represents the geometry info for slab /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void SlabShapePictureBox_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; m_slabProfile.Draw2D(e.Graphics, m_profilePen); if (EditorState.Rotate != editorState) { m_lineTool.Draw2D(e.Graphics, m_toolPen); m_pointTool.DrawRectangle(e.Graphics, m_toolPen); //draw selected beam (line) by red pen DrawSelectedLineRed(e.Graphics, m_selectPen); } } /// <summary> /// Draw selected crease or vertex red /// </summary> /// <param name="graphics">Form graphics object,</param> /// <param name="pen">Pen which used to draw lines</param> private void DrawSelectedLineRed(Graphics graphics, Pen pen) { if (-1 != m_selectIndex) { GraphicsPath selectedPath = (GraphicsPath)m_graphicsPaths[m_selectIndex]; PointF pointF0 = (PointF)selectedPath.PathPoints.GetValue(0); PointF pointF1 = (PointF)selectedPath.PathPoints.GetValue(1); if (m_selectIndex < m_createCreases.Count) { graphics.DrawLine(pen, pointF0, pointF1); } else { graphics.DrawRectangle(pen, pointF0.X - 2, pointF0.Y - 2, 4, 4); } } if (-1 != m_clickedIndex) { GraphicsPath clickedPath = (GraphicsPath)m_graphicsPaths[m_clickedIndex]; PointF pointF0 = (PointF)clickedPath.PathPoints.GetValue(0); PointF pointF1 = (PointF)clickedPath.PathPoints.GetValue(1); if (m_clickedIndex < m_createCreases.Count) { graphics.DrawLine(pen, pointF0, pointF1); } else { graphics.DrawRectangle(pen, pointF0.X - 2, pointF0.Y - 2, 4, 4); } } } /// <summary> /// rotate slab and get selected vertex or crease /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void SlabShapePictureBox_MouseMove(object sender, MouseEventArgs e) { PointF pointF = new PointF(e.X, e.Y); if (EditorState.AddCrease == editorState && 1 == m_lineTool.Points.Count % 2) { m_lineTool.MovePoint = pointF; } else { m_lineTool.MovePoint = PointF.Empty; } if (MouseButtons.Right == e.Button) { double moveX = e.Location.X - m_mouseRightDownLocation.X; double moveY = m_mouseRightDownLocation.Y - e.Location.Y; m_slabProfile.RotateFloor(moveY / 500, moveX / 500); m_mouseRightDownLocation = e.Location; } else if (EditorState.Select == editorState) { for (int i = 0; i < m_graphicsPaths.Count; i++) { GraphicsPath path = (GraphicsPath)m_graphicsPaths[i]; if (path.IsOutlineVisible(pointF, m_toolPen)) { m_selectIndex = i; break; } m_selectIndex = -1; } } this.SlabShapePictureBox.Refresh(); } /// <summary> /// get location where right button click down. /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void SlabShapePictureBox_MouseDown(object sender, MouseEventArgs e) { if (MouseButtons.Right == e.Button) { m_mouseRightDownLocation = e.Location; editorState = EditorState.Rotate; m_clickedIndex = m_selectIndex = -1; } } /// <summary> /// add vertex and crease, select new created vertex and crease /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void SlabShapePictureBox_MouseClick(object sender, MouseEventArgs e) { if (EditorState.AddCrease == editorState) { if (!m_slabProfile.CanCreateVertex(new PointF(e.X, e.Y))) { return; } m_lineTool.Points.Add(new PointF(e.X, e.Y)); int lineSize = m_lineTool.Points.Count; if (0 == m_lineTool.Points.Count % 2) { m_createCreases.Add( m_slabProfile.AddCrease((PointF)m_lineTool.Points[lineSize - 2], (PointF)m_lineTool.Points[lineSize - 1])); } CreateGraphicsPath(); //create graphic path for all the vertex and crease } else if (EditorState.AddVertex == editorState) { SlabShapeVertex vertex = m_slabProfile.AddVertex(new PointF(e.X, e.Y)); if (null == vertex) { return; } m_pointTool.Points.Add(new PointF(e.X, e.Y)); //draw point as a short line, so add two points here m_pointTool.Points.Add(new PointF((float)(e.X + 2), (float)(e.Y + 2))); m_createdVertices.Add(vertex); CreateGraphicsPath(); //create graphic path for all the vertex and crease } else if (EditorState.Select == editorState) { if (m_selectIndex >= 0) { m_clickedIndex = m_selectIndex; if (m_selectIndex <= m_createCreases.Count - 1) { m_selectedCrease = (SlabShapeCrease)(m_createCreases[m_selectIndex]); m_selectedVertex = null; } else { //put all path (crease and vertex) in one arrayList, so reduce creases.count int index = m_selectIndex - m_createCreases.Count; m_selectedVertex = (SlabShapeVertex)(m_createdVertices[index]); m_selectedCrease = null; } } else { m_selectedVertex = null; m_selectedCrease = null; m_clickedIndex = -1; } } this.SlabShapePictureBox.Refresh(); } /// <summary> /// get ready to add vertex /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void PointButton_Click(object sender, EventArgs e) { editorState = EditorState.AddVertex; m_slabProfile.ClearRotateMatrix(); this.SlabShapePictureBox.Cursor = Cursors.Cross; } /// <summary> /// get ready to add crease /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void LineButton_Click(object sender, EventArgs e) { editorState = EditorState.AddCrease; m_slabProfile.ClearRotateMatrix(); this.SlabShapePictureBox.Cursor = Cursors.Cross; } /// <summary> /// get ready to move vertex and crease /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void MoveButton_Click(object sender, EventArgs e) { editorState = EditorState.Select; m_slabProfile.ClearRotateMatrix(); this.SlabShapePictureBox.Cursor = Cursors.Arrow; } /// <summary> /// Move vertex and crease, then update profile of slab /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void UpdateButton_Click(object sender, EventArgs e) { if (-1 == m_clickedIndex) { TaskDialog.Show("Revit", selectFirst); return; } double moveDistance = 0; try { moveDistance = Convert.ToDouble(this.DistanceTextBox.Text); } catch (Exception) { TaskDialog.Show("Revit", justNumber); return; } Transaction transaction = new Transaction( m_commandData.Application.ActiveUIDocument.Document, "Update"); transaction.Start(); if (null != m_selectedCrease) { m_slabShapeEditor.ModifySubElement(m_selectedCrease, moveDistance); } else if (null != m_selectedVertex) { m_slabShapeEditor.ModifySubElement(m_selectedVertex, moveDistance); } transaction.Commit(); //re-calculate geometry info m_slabProfile.GetSlabProfileInfo(); this.SlabShapePictureBox.Refresh(); } /// <summary> /// Reset slab shape /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void ResetButton_Click(object sender, EventArgs e) { m_slabProfile.ResetSlabShape(); m_lineTool.Points.Clear(); m_pointTool.Points.Clear(); } /// <summary> /// Create Graphics Path for each vertex and crease /// </summary> public void CreateGraphicsPath() { m_graphicsPaths.Clear(); //create path for all the lines draw by user for (int i = 0; i < m_lineTool.Points.Count - 1; i += 2) { GraphicsPath path = new GraphicsPath(); path.AddLine((PointF)m_lineTool.Points[i], (PointF)m_lineTool.Points[i + 1]); m_graphicsPaths.Add(path); } for (int i = 0; i < m_pointTool.Points.Count - 1; i += 2) { GraphicsPath path = new GraphicsPath(); path.AddLine((PointF)m_pointTool.Points[i], (PointF)m_pointTool.Points[i + 1]); m_graphicsPaths.Add(path); } } /// <summary> /// set tool tip for MoveButton /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void MoveButton_MouseHover(object sender, EventArgs e) { this.toolTip.SetToolTip(this.MoveButton, "Select Vertex or Crease"); } /// <summary> /// set tool tip for PointButton /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void PointButton_MouseHover(object sender, EventArgs e) { this.toolTip.SetToolTip(this.PointButton, "Add Vertex"); } /// <summary> /// set tool tip for LineButton /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void LineButton_MouseHover(object sender, EventArgs e) { this.toolTip.SetToolTip(this.LineButton, "Add Crease"); } /// <summary> /// change cursor /// </summary> /// <param name="sender">object who sent this event</param> /// <param name="e">event args</param> private void SlabShapePictureBox_MouseHover(object sender, EventArgs e) { switch (editorState) { case EditorState.AddVertex: this.SlabShapePictureBox.Cursor = Cursors.Cross; break; case EditorState.AddCrease: this.SlabShapePictureBox.Cursor = Cursors.Cross; break; case EditorState.Select: this.SlabShapePictureBox.Cursor = Cursors.Arrow; break; default: this.SlabShapePictureBox.Cursor = Cursors.Default; break; } } } }
44.075718
101
0.570582
[ "MIT" ]
xin1627/RevitSdkSamples
SDK/Samples/SlabShapeEditing/CS/SlabShapeEditingForm.cs
16,881
C#
#region auto-generated FILE INFORMATION // ============================================== // This file is distributed under the MIT License // ============================================== // // Filename: ColorDialogEx.cs // Version: 2020-01-13 13:03 // // Copyright (c) 2020, Si13n7 Developments(tm) // All rights reserved. // ______________________________________________ #endregion namespace SilDev.Forms { using System; using System.Drawing; using System.Windows.Forms; /// <summary> /// Expands the functionality for the <see cref="ColorDialog"/> class. /// </summary> public class ColorDialogEx : ColorDialog { private readonly IWin32Window _owner; private readonly string _title; private Point _point; /// <summary> /// Initializes a new instance of the <see cref="ColorDialogEx"/> class. /// </summary> /// <param name="owner"> /// An implementation of <see cref="IWin32Window"/> that will own the modal /// dialog box. /// </param> /// <param name="title"> /// The new title of the window. /// </param> public ColorDialogEx(IWin32Window owner, string title = null) { _owner = owner; _title = title; } /// <summary> /// Initializes a new instance of the <see cref="ColorDialogEx"/> class. /// </summary> /// <param name="point"> /// The new position of the window. /// </param> /// <param name="title"> /// The new title of the window. /// </param> public ColorDialogEx(Point point, string title = null) { _point = point; _title = title; } /// <summary> /// Initializes a new instance of the <see cref="ColorDialogEx"/> class. /// </summary> /// <param name="x"> /// The new position of the left side of the window. /// </param> /// <param name="y"> /// The new position of the top of the window. /// </param> /// <param name="title"> /// The new title of the window. /// </param> public ColorDialogEx(int x, int y, string title = null) { _point = new Point(x, y); _title = title; } protected override IntPtr HookProc(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam) { var hookProc = base.HookProc(hWnd, msg, wparam, lparam); if (msg != (int)WinApi.WindowMenuFlags.WmInitDialog) return hookProc; if (!string.IsNullOrEmpty(_title)) WinApi.NativeMethods.SetWindowText(hWnd, _title); if (_owner != null) { var cRect = new Rectangle(0, 0, 0, 0); if (WinApi.NativeMethods.GetWindowRect(hWnd, ref cRect)) { var width = cRect.Width - cRect.X; var height = cRect.Height - cRect.Y; var pRect = new Rectangle(0, 0, 0, 0); if (WinApi.NativeMethods.GetWindowRect(_owner.Handle, ref pRect)) { var ptCenter = new Point(pRect.X, pRect.Y); ptCenter.X += (pRect.Width - pRect.X) / 2; ptCenter.Y += (pRect.Height - pRect.Y) / 2 - 10; var ptStart = new Point(ptCenter.X, ptCenter.Y); ptStart.X -= width / 2; if (ptStart.X < 0) ptStart.X = 0; ptStart.Y -= height / 2; if (ptStart.Y < 0) ptStart.Y = 0; _point = ptStart; } } } if (_point == null) return hookProc; WinApi.NativeMethods.SetWindowPos(hWnd, IntPtr.Zero, _point.X, _point.Y, 0, 0, WinApi.SetWindowPosFlags.NoSize | WinApi.SetWindowPosFlags.NoZOrder | WinApi.SetWindowPosFlags.ShowWindow); return hookProc; } } }
35.711864
198
0.493118
[ "MIT" ]
None-later/CSharpLib
src/SilDev/Forms/ColorDialogEx.cs
4,216
C#
using System; using System.Collections.Generic; using System.Text; using gov.va.medora.mdo; namespace gov.va.medora.mdws.dto { public class TaggedInpatientStayArray : AbstractTaggedArrayTO { public InpatientStayTO[] stays; public TaggedInpatientStayArray() { } public TaggedInpatientStayArray(string tag) { this.tag = tag; this.count = 0; } public TaggedInpatientStayArray(string tag, InpatientStay[] mdos) { this.tag = tag; if (mdos == null) { this.count = 0; return; } this.stays = new InpatientStayTO[mdos.Length]; for (int i = 0; i < mdos.Length; i++) { this.stays[i] = new InpatientStayTO(mdos[i]); } this.count = stays.Length; } public TaggedInpatientStayArray(string tag, InpatientStay mdo) { this.tag = tag; if (mdo == null) { this.count = 0; return; } this.stays = new InpatientStayTO[1]; this.stays[0] = new InpatientStayTO(mdo); this.count = 1; } public TaggedInpatientStayArray(string tag, Exception e) { this.tag = tag; this.fault = new FaultTO(e); } } }
25.321429
73
0.502116
[ "Apache-2.0" ]
VHAINNOVATIONS/RAPTOR
OtherComponents/MDWSvistalayer/MDWS Source/mdws/mdws/src/dto/TaggedInpatientStayArray.cs
1,418
C#
using System; using Xamarin.Forms; namespace Continuous.Sample.Forms { public class App : Application { public App () { // The root page of your application MainPage = new MainPage (); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
14.125
39
0.650442
[ "MIT" ]
praeclarum/Continuous
Continuous.Sample.Forms/Continuous.Sample.Forms.cs
454
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PublicBookStore.UI.Web.Models { public class OrderDetailModel { public int OrderDetailId { get; set; } public int OrderId { get; set; } public int BookId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public virtual BookModel Book { get; set; } public virtual OrderModel Order { get; set; } } }
25.333333
53
0.648496
[ "MIT" ]
mecitsem/PublicBookStore
PublicBookStore.UI.Web/Models/OrderDetailModel.cs
534
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace NoDoze.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NoDoze.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
33.625
157
0.688145
[ "MIT" ]
NigelThorne/nodoze
NoDoze/Properties/Resources.Designer.cs
2,423
C#
namespace Machete.X12Schema.V5010 { using X12; public interface LoopAMT_2_811 : X12Layout { Segment<AMT> MonetaryAmountInformation { get; } Segment<DTM> DateOrTimeReference { get; } } }
18.153846
55
0.614407
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Layouts/LoopAMT_2_811.cs
236
C#
using SolrExpress.Search; using SolrExpress.Search.Parameter; using System.Collections.Generic; namespace SolrExpress.Solr4.Search.Parameter { public sealed class FacetLimitParameter<TDocument> : BaseFacetLimitParameter<TDocument>, ISearchItemExecution<List<string>> where TDocument : Document { private string _result; public void AddResultInContainer(List<string> container) { container.Add(this._result); } public void Execute() { this._result = $"facet.limit={this.Value}"; } } }
27.045455
127
0.655462
[ "MIT" ]
solr-express/solr-express
src/SolrExpress.Solr4/Search/Parameter/FacetLimitParameter.cs
597
C#
using Microsoft.AspNetCore.Mvc.Filters; namespace AspNetCore.Filters.Permissions { public interface IPermissionHandlerProvider { IPermissionHandler GetHandler(AuthorizationFilterContext context); } }
24.555556
74
0.782805
[ "MIT" ]
linianhui/example-oidc
src/aspnetcore.filters.permissions/IPermissionHandlerProvider.cs
223
C#
using System; namespace paramore.brighter.commandprocessor.viewer.tests.TestDoubles { internal class FakeErrorProducingMessageProducerFactory : IAmAMessageProducerFactory { public IAmAMessageProducer Create() { throw new NotImplementedException(); } } }
25.25
88
0.709571
[ "MIT" ]
uQr/Paramore.Brighter
paramore.brighter.commandprocessor.viewer.tests/TestDoubles/FakeErrorProducingMessageProducerFactory.cs
305
C#
using System; using System.Collections.Generic; using UnityEngine; class GuiTools { static bool IsValidFloat( string val ) { float res; return float.TryParse(val, out res); } public void FloatParam( ref float value, string caption, float maxValue ) { float oldValue = value; string text; if( !guiStringParamAuxData.TryGetValue(caption, out text) ) text = value.ToString(); if( normalTextField == null ) { normalTextField = new GUIStyle("TextField"); alertTextField = new GUIStyle(normalTextField); alertTextField.normal.textColor = Color.red; alertTextField.hover.textColor = Color.red; alertTextField.focused.textColor = Color.red; } GUIStyle textStyle = IsValidFloat(text) ? normalTextField: alertTextField; GUILayout.BeginVertical("box"); GUILayout.Label(caption); GUILayout.BeginHorizontal(); GUILayout.BeginVertical("box"); value = GUILayout.HorizontalSlider(value, 0, maxValue, GUILayout.MinWidth(150) ); GUILayout.EndVertical(); text = GUILayout.TextField( text, textStyle, GUILayout.MinWidth(70) ); GUILayout.EndHorizontal(); GUILayout.EndVertical(); if( value != oldValue ) text = value.ToString(); float res; if( float.TryParse(text, out res) ) value = res; guiStringParamAuxData[caption] = text; } public int Switcher( int curValue, string caption, string[] texts ) { GUILayout.BeginVertical("box"); GUILayout.Label(caption); var newValue = GUILayout.Toolbar( curValue, texts ); GUILayout.EndVertical(); return newValue; } public void Toggle( ref bool value, string caption ) { value = GUILayout.Toggle( value, caption ); } public void ClearCache() { guiStringParamAuxData.Clear(); } public bool MouseOverGUI { get{ return isMouseOverGUI; } } public void ManualUpdate() { isMouseOverGUI = false; } public void CheckMouseOverForLastControl() { //See example: //http://docs.unity3d.com/Documentation/ScriptReference/GUILayoutUtility.GetLastRect.html if( Event.current.type != EventType.Repaint ) return; if( GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition) ) isMouseOverGUI = true; } private Dictionary<string, string> guiStringParamAuxData = new Dictionary<string, string>(); private GUIStyle normalTextField = null; private GUIStyle alertTextField = null; private bool isMouseOverGUI = false; };
26.260417
94
0.686632
[ "MIT" ]
black-square/BirdFlock
Assets/Scripts/GuiTools.cs
2,521
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Linq; using System.Web.Http.Controllers; using System.Web.Http.Properties; namespace System.Web.Http.Tracing.Tracers { /// <summary> /// Tracer for <see cref="IHttpActionSelector"/>. /// </summary> internal class HttpActionSelectorTracer : IHttpActionSelector { private const string SelectActionMethodName = "SelectAction"; private readonly IHttpActionSelector _innerSelector; private readonly ITraceWriter _traceWriter; public HttpActionSelectorTracer(IHttpActionSelector innerSelector, ITraceWriter traceWriter) { _innerSelector = innerSelector; _traceWriter = traceWriter; } public ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor) { return _innerSelector.GetActionMapping(controllerDescriptor); } HttpActionDescriptor IHttpActionSelector.SelectAction(HttpControllerContext controllerContext) { HttpActionDescriptor actionDescriptor = null; _traceWriter.TraceBeginEnd( controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info, _innerSelector.GetType().Name, SelectActionMethodName, beginTrace: null, execute: () => { actionDescriptor = _innerSelector.SelectAction(controllerContext); }, endTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceActionSelectedMessage, FormattingUtilities.ActionDescriptorToString(actionDescriptor)); }, errorTrace: null); // Intercept returned HttpActionDescriptor with a tracing version return actionDescriptor == null ? null : new HttpActionDescriptorTracer(controllerContext, actionDescriptor, _traceWriter); } } }
39.982143
135
0.619473
[ "Apache-2.0" ]
Distrotech/mono
external/aspnetwebstack/src/System.Web.Http/Tracing/Tracers/HttpActionSelectorTracer.cs
2,241
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Core.Commands; /// <summary> /// Classic State pattern requires unique methods totalling Nodes * PossibleCommands /// For this Policy there are 5 nodes, 5 possible commands, for 25 methods /// Using commands we will write more classes, but fewer overall methods /// </summary> public class Policy { static Policy() { // static registration with PolicyTransitionTable wasn't happening without this // TODO: Move to separate partial class RuntimeHelpers.RunClassConstructor(typeof(UnwrittenToOpenTransition).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(UnwrittenToVoidTransition).TypeHandle); } private Policy() { } public Policy(string policyNumber) : this() { Number = policyNumber; } public int Id { get; set; } public string Number { get; set; } public DateTime? DateOpened { get; private set; } public DateTime? DateClosed { get; private set; } public PolicyState State { get; private set; } = PolicyState.Unwritten; private static PolicyTransitionTable _transitionTable = new(); public void UpdateState(PolicyCommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); _transitionTable.ExecuteCommand(command, this); } // TODO: Is this useful? public List<Type> ListAvailableCommands() { return _transitionTable .Where(kvp => kvp.Key == this.State) .Select(kvp => kvp.Value.CommandType) .ToList(); } // TODO: Move to partial class private class UnwrittenToOpenTransition : PolicyTransition { static UnwrittenToOpenTransition() { // register as a valid operation _transitionTable.Add(PolicyState.Unwritten, new UnwrittenToOpenTransition()); } public UnwrittenToOpenTransition() : base(PolicyState.Unwritten, PolicyCommand.OpenCommand) { } public override void Execute(Policy policy, PolicyCommand command) { base.Execute(policy, command); if (command is PolicyCommand.PolicyOpenCommand actualCommand) { policy.State = PolicyState.Open; policy.DateOpened = actualCommand.DateOpened; } } } // TODO: Move to partial class private class UnwrittenToVoidTransition : PolicyTransition { static UnwrittenToVoidTransition() { // register as a valid operation _transitionTable.Add(PolicyState.Unwritten, new UnwrittenToVoidTransition()); } public UnwrittenToVoidTransition() : base(PolicyState.Unwritten, PolicyCommand.VoidCommand) { } public override void Execute(Policy policy, PolicyCommand command) { base.Execute(policy, command); if (command is PolicyCommand.PolicyOpenCommand actualCommand) { policy.State = PolicyState.Void; } } } } public class PolicyTransitionTable : Dictionary<PolicyState, PolicyTransition> { public bool IsValidCommand(PolicyState currentState, PolicyCommand command) { if (this.ContainsKey(currentState)) { if (this[currentState] != null) { return true; } } return false; } public void ExecuteCommand(PolicyCommand command, Policy policy) { if (!IsValidCommand(policy.State, command)) throw new InvalidOperationException(); var transition = this[policy.State]; transition.Execute(policy, command); } } public class PolicyState { public static readonly PolicyState Unwritten = new PolicyState(1, nameof(Unwritten)); public static readonly PolicyState Open = new PolicyState(2, nameof(Open)); public static readonly PolicyState Void = new PolicyState(2, nameof(Void)); public static readonly PolicyState Cancelled = new PolicyState(2, nameof(Cancelled)); public static readonly PolicyState Closed = new PolicyState(2, nameof(Closed)); public int Id { get; private set; } public string Name { get; private set; } public PolicyState(int id, string name) { Id = id; Name = name; } } public class Command<T> where T : Type { public T Value { get; private set; } = default(T); } public class PolicyCommand { // TODO: How to have a list of command but also have specific instance of commands with specific properties like Dates //public static readonly PolicyCommand Open = new PolicyCommand(nameof(Open)); public static readonly PolicyCommand Update = new PolicyCommand(nameof(Update)); //public static readonly PolicyCommand Void = new PolicyCommand(nameof(Void)); public static readonly PolicyCommand Cancel = new PolicyCommand(nameof(Cancel)); public static readonly PolicyCommand Close = new PolicyCommand(nameof(Close)); // TODO: Finish migrating from command instances to command types public static readonly Type OpenCommand = typeof(PolicyOpenCommand); public static readonly Type VoidCommand = typeof(PolicyVoidCommand); public string Name { get; private set; } private PolicyCommand(string name) { Name = name; } public static PolicyCommand Void() => new PolicyVoidCommand(); public class PolicyVoidCommand : PolicyCommand { public PolicyVoidCommand() : base(nameof(Void)) { } } public static PolicyCommand Open(DateTime dateOpened) => new PolicyOpenCommand(dateOpened); public class PolicyOpenCommand : PolicyCommand { public PolicyOpenCommand(DateTime dateOpened) : base(nameof(Open)) { DateOpened = dateOpened; } public DateTime DateOpened { get; } } } public class PolicyTransition { public PolicyState InitialState { get; set; } public Type CommandType { get; set; } protected PolicyTransition(PolicyState initialState, Type commandType) { InitialState = initialState; CommandType = commandType; } // TODO: Rename to Handle? // Transitions are basically command handlers that operate on a policy instance public virtual void Execute(Policy policy, PolicyCommand command) { } }
30.947368
122
0.666512
[ "MIT" ]
ardalis/StatePattern
Core/Commands/Policy.cs
6,470
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface ObservationIncomeValue : Code { } }
36.482759
83
0.710775
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/ObservationIncomeValue.cs
1,058
C#
using System; using System.ComponentModel; namespace SkiaSharp { public class SKSurfaceProperties : SKObject { internal SKSurfaceProperties (IntPtr h, bool owns) : base (h, owns) { } [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete] public SKSurfaceProperties (SKSurfaceProps props) : this (props.Flags, props.PixelGeometry) { } public SKSurfaceProperties (SKPixelGeometry pixelGeometry) : this ((uint)0, pixelGeometry) { } public SKSurfaceProperties (uint flags, SKPixelGeometry pixelGeometry) : this (SkiaApi.sk_surfaceprops_new (flags, pixelGeometry), true) { } public SKSurfaceProperties (SKSurfacePropsFlags flags, SKPixelGeometry pixelGeometry) : this (SkiaApi.sk_surfaceprops_new ((uint)flags, pixelGeometry), true) { } protected override void Dispose (bool disposing) => base.Dispose (disposing); protected override void DisposeNative () => SkiaApi.sk_surfaceprops_delete (Handle); public SKSurfacePropsFlags Flags => (SKSurfacePropsFlags)SkiaApi.sk_surfaceprops_get_flags (Handle); public SKPixelGeometry PixelGeometry => SkiaApi.sk_surfaceprops_get_pixel_geometry (Handle); public bool IsUseDeviceIndependentFonts => Flags.HasFlag (SKSurfacePropsFlags.UseDeviceIndependentFonts); internal static SKSurfaceProperties GetObject (IntPtr handle, bool owns = true) => GetOrAddObject (handle, owns, (h, o) => new SKSurfaceProperties (h, o)); } }
26.888889
87
0.754821
[ "MIT" ]
AlexanderSemenyak/SkiaSharp
binding/Binding/SKSurfaceProperties.cs
1,454
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace LightLib.Data.Models.Assets { [Table("audio_cds")] public class AudioCd { [Key] public int Id { get; set; } [Required] public Guid AssetId { get; set; } [Required] public string Title { get; set; } [Required] public string Artist { get; set; } public int PublicationYear { get; set; } public string Label { get; set; } public string DeweyIndex { get; set; } public string Language { get; set; } public string Genre { get; set; } public string Summary { get; set; } public Asset Asset { get; set; } } }
33.090909
53
0.622253
[ "Apache-2.0" ]
msadeqsirjani/lightlib-lms
LightLib.Data/Models/Assets/AudioCds.cs
730
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Recognizers.Definitions.Spanish; using Microsoft.Recognizers.Text.DateTime.Spanish.Utilities; using Microsoft.Recognizers.Text.DateTime.Utilities; using Microsoft.Recognizers.Text.Number; using Microsoft.Recognizers.Text.Utilities; namespace Microsoft.Recognizers.Text.DateTime.Spanish { public class SpanishTimePeriodExtractorConfiguration : BaseDateTimeOptionsConfiguration, ITimePeriodExtractorConfiguration { public static readonly string ExtractorName = Constants.SYS_DATETIME_TIMEPERIOD; // "TimePeriod"; public static readonly Regex HourNumRegex = new Regex(DateTimeDefinitions.TimeHourNumRegex, RegexFlags); public static readonly Regex PureNumFromTo = new Regex(DateTimeDefinitions.PureNumFromTo, RegexFlags); public static readonly Regex PureNumBetweenAnd = new Regex(DateTimeDefinitions.PureNumBetweenAnd, RegexFlags); public static readonly Regex SpecificTimeFromTo = new Regex(DateTimeDefinitions.SpecificTimeFromTo, RegexFlags); public static readonly Regex SpecificTimeBetweenAnd = new Regex(DateTimeDefinitions.SpecificTimeBetweenAnd, RegexFlags); public static readonly Regex UnitRegex = new Regex(DateTimeDefinitions.TimeUnitRegex, RegexFlags); public static readonly Regex FollowedUnit = new Regex(DateTimeDefinitions.TimeFollowedUnit, RegexFlags); public static readonly Regex NumberCombinedWithUnit = new Regex(DateTimeDefinitions.TimeNumberCombinedWithUnit, RegexFlags); public static readonly Regex TimeOfDayRegex = new Regex(DateTimeDefinitions.TimeOfDayRegex, RegexFlags); public static readonly Regex GeneralEndingRegex = new Regex(DateTimeDefinitions.GeneralEndingRegex, RegexFlags); public static readonly Regex TillRegex = new Regex(DateTimeDefinitions.TillRegex, RegexFlags); private const RegexOptions RegexFlags = RegexOptions.Singleline | RegexOptions.ExplicitCapture; private static readonly Regex FromRegex = new Regex(DateTimeDefinitions.FromRegex, RegexFlags); private static readonly Regex RangeConnectorRegex = new Regex(DateTimeDefinitions.RangeConnectorRegex, RegexFlags); private static readonly Regex BetweenRegex = new Regex(DateTimeDefinitions.BetweenRegex, RegexFlags); public SpanishTimePeriodExtractorConfiguration(IDateTimeOptionsConfiguration config) : base(config) { TokenBeforeDate = DateTimeDefinitions.TokenBeforeDate; SingleTimeExtractor = new BaseTimeExtractor(new SpanishTimeExtractorConfiguration(this)); UtilityConfiguration = new SpanishDatetimeUtilityConfiguration(); var numOptions = NumberOptions.None; if ((config.Options & DateTimeOptions.NoProtoCache) != 0) { numOptions = NumberOptions.NoProtoCache; } var numConfig = new BaseNumberOptionsConfiguration(config.Culture, numOptions); IntegerExtractor = Number.English.IntegerExtractor.GetInstance(numConfig); TimeZoneExtractor = new BaseTimeZoneExtractor(new SpanishTimeZoneExtractorConfiguration(this)); } public string TokenBeforeDate { get; } public IDateTimeUtilityConfiguration UtilityConfiguration { get; } public IDateTimeExtractor SingleTimeExtractor { get; } public IExtractor IntegerExtractor { get; } public IDateTimeExtractor TimeZoneExtractor { get; } public IEnumerable<Regex> SimpleCasesRegex => new Regex[] { PureNumFromTo, PureNumBetweenAnd, SpecificTimeFromTo, SpecificTimeBetweenAnd }; public IEnumerable<Regex> PureNumberRegex => new Regex[] { PureNumFromTo, PureNumBetweenAnd }; bool ITimePeriodExtractorConfiguration.CheckBothBeforeAfter => DateTimeDefinitions.CheckBothBeforeAfter; Regex ITimePeriodExtractorConfiguration.TillRegex => TillRegex; Regex ITimePeriodExtractorConfiguration.TimeOfDayRegex => TimeOfDayRegex; Regex ITimePeriodExtractorConfiguration.GeneralEndingRegex => GeneralEndingRegex; public bool GetFromTokenIndex(string text, out int index) { index = -1; var fromMatch = FromRegex.Match(text); if (fromMatch.Success) { index = fromMatch.Index; } return fromMatch.Success; } public bool GetBetweenTokenIndex(string text, out int index) { index = -1; var match = BetweenRegex.Match(text); if (match.Success) { index = match.Index; } return match.Success; } public bool IsConnectorToken(string text) { return RangeConnectorRegex.IsExactMatch(text, true); } // In Spanish "mañana" can mean both "tomorrow" and "morning". This method filters the isolated occurrences of "mañana" from the // TimePeriodExtractor results as it is more likely to mean "tomorrow" in these cases. public List<ExtractResult> ApplyPotentialPeriodAmbiguityHotfix(string text, List<ExtractResult> timePeriodErs) { { var morningStr = DateTimeDefinitions.MorningTermList[0]; List<ExtractResult> timePeriodErsResult = new List<ExtractResult>(); foreach (var timePeriodEr in timePeriodErs) { if (!timePeriodEr.Text.Equals(morningStr, StringComparison.Ordinal)) { timePeriodErsResult.Add(timePeriodEr); } } return timePeriodErsResult; } } } }
40.328947
148
0.66721
[ "MIT" ]
LFhase/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Spanish/Extractors/SpanishTimePeriodExtractorConfiguration.cs
6,134
C#
using System; #if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; #endif using UnityEngine; #if UNITY_EDITOR using Object = UnityEngine.Object; #endif namespace CippSharp.Core.Reorderable { public class ReorderableAttribute : PropertyAttribute { public bool add; public bool remove; public bool draggable; public bool singleLine; public bool paginate; public bool sortable; public bool labels; public int pageSize; public string elementNameProperty; public string elementNameOverride; public string elementIconPath; public Type surrogateType; public string surrogateProperty; public ReorderableAttribute() : this(null) { } public ReorderableAttribute(string elementNameProperty) : this(true, true, true, elementNameProperty, null, null) { } public ReorderableAttribute(string elementNameProperty, string elementIconPath) : this(true, true, true, elementNameProperty, null, elementIconPath) { } public ReorderableAttribute(string elementNameProperty, string elementNameOverride, string elementIconPath) : this(true, true, true, elementNameProperty, elementNameOverride, elementIconPath) { } public ReorderableAttribute(bool add, bool remove, bool draggable, string elementNameProperty = null, string elementIconPath = null) : this(add, remove, draggable, elementNameProperty, null, elementIconPath) { } public ReorderableAttribute(bool add, bool remove, bool draggable, string elementNameProperty = null, string elementNameOverride = null, string elementIconPath = null) { this.add = add; this.remove = remove; this.draggable = draggable; this.elementNameProperty = elementNameProperty; this.elementNameOverride = elementNameOverride; this.elementIconPath = elementIconPath; sortable = true; labels = true; } } } #if UNITY_EDITOR namespace CippSharp.Core.Reorderable.Editor { [CustomPropertyDrawer(typeof(ReorderableAttribute))] public class ReorderableDrawer : PropertyDrawer { // public const string ARRAY_PROPERTY_NAME = "array"; // public const string LIST_PROPERTY_NAME = "list"; public static readonly string[] ValidArrayNames = new[] {"array", "list", "Array", "List",}; private static Dictionary<int, ReorderableList> lists = new Dictionary<int, ReorderableList>(); public override bool CanCacheInspectorGUI(SerializedProperty property) { return false; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { ReorderableList list = GetList(property, attribute as ReorderableAttribute); return list != null ? list.GetHeight() : EditorGUIUtility.singleLineHeight; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { ReorderableList list = GetList(property, attribute as ReorderableAttribute); if (list != null) { list.DoList(EditorGUI.IndentedRect(position), label); } else { GUI.Label(position, "Array must extend from ReorderableArray", EditorStyles.label); } } public static int GetListId(SerializedProperty property) { if (property != null) { int h1 = property.serializedObject.targetObject.GetHashCode(); int h2 = property.propertyPath.GetHashCode(); return (((h1 << 5) + h1) ^ h2); } return 0; } public static ReorderableList GetList(SerializedProperty property) { return GetList(property, null, GetListId(property)); } public static ReorderableList GetList(SerializedProperty property, ReorderableAttribute attrib) { return GetList(property, attrib, GetListId(property)); } public static ReorderableList GetList(SerializedProperty property, int id) { return GetList(property, null, id); } public static ReorderableList GetList(SerializedProperty property, ReorderableAttribute attrib, int id) { if (property == null) { return null; } ReorderableList list = null; SerializedProperty array = GetArrayProperty(property); if (array != null && array.isArray) { if (!lists.TryGetValue(id, out list)) { if (attrib != null) { Texture icon = !string.IsNullOrEmpty(attrib.elementIconPath) ? AssetDatabase.GetCachedIcon(attrib.elementIconPath) : null; ReorderableList.ElementDisplayType displayType = attrib.singleLine ? ReorderableList.ElementDisplayType.SingleLine : ReorderableList.ElementDisplayType.Auto; list = new ReorderableList(array, attrib.add, attrib.remove, attrib.draggable, displayType, attrib.elementNameProperty, attrib.elementNameOverride, icon); list.paginate = attrib.paginate; list.pageSize = attrib.pageSize; list.sortable = attrib.sortable; list.elementLabels = attrib.labels; //handle surrogate if any if (attrib.surrogateType != null) { SurrogateCallback callback = new SurrogateCallback(attrib.surrogateProperty); list.surrogate = new ReorderableList.Surrogate(attrib.surrogateType, callback.SetReference); } } else { list = new ReorderableList(array, true, true, true); } lists.Add(id, list); } else { list.List = array; } } return list; } public static SerializedProperty GetArrayProperty(SerializedProperty property) { SerializedProperty array = null; int i = 0; while (i < ValidArrayNames.Length) { array = property.FindPropertyRelative(ValidArrayNames[i]); if (array != null) { break; } i++; } return array; } private struct SurrogateCallback { private string property; internal SurrogateCallback(string property) { this.property = property; } internal void SetReference(SerializedProperty element, Object objectReference, ReorderableList list) { SerializedProperty prop = !string.IsNullOrEmpty(property) ? element.FindPropertyRelative(property) : null; if (prop != null && prop.propertyType == SerializedPropertyType.ObjectReference) { prop.objectReferenceValue = objectReference; } } } } } #endif
28.515837
177
0.700571
[ "MIT" ]
Cippman/Unity-Reorderable-List
Runtime/Attributes/ReorderableAttribute.cs
6,302
C#
using System; using LinkedList.Classes; namespace ll_merge { public class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); LList linkedList = new LList(); // 20 -> 15 -> 10; linkedList.Append(20); linkedList.Append(15); linkedList.Append(10); LList linkedListTwo = new LList(); // 200 -> 150 -> 100; linkedListTwo.Append(200); linkedListTwo.Append(150); linkedListTwo.Append(100); Console.WriteLine("Before Merge:"); linkedList.Print(); linkedListTwo.Print(); MergeLists(linkedList, linkedListTwo); Console.WriteLine("After Merge:"); linkedList.Print(); linkedListTwo.Print(); } /// <summary> /// Merges two singly linked lists through mutation. The first linked list exits the function as the merged linked list, and the second linked list becomes empty. The function returns a reference to the head of the first linked list. /// </summary> /// <param name="linkedListOne">The first linked list to be merged. Exits function as the merged linked list.</param> /// <param name="linkedListTwo">The second linked list to be merged. Exits function empty.</param> /// <returns>Returns the head node of the first (merged) linked list.</returns> public static Node MergeLists(LList linkedListOne, LList linkedListTwo) { if(linkedListTwo.Head == null) { return linkedListOne.Head; } linkedListOne.Current = linkedListOne.Head; Node tmp = linkedListOne.Head; while(tmp != null) { tmp = linkedListOne.Current.Next; linkedListOne.Current.Next = linkedListTwo.Head; linkedListTwo.Head = tmp; linkedListOne.Current = linkedListOne.Current.Next; } return linkedListOne.Head; } } }
39.092593
241
0.574135
[ "MIT" ]
Dervival/Data-Structures-and-Algorithms
Challenges/llMerge/llMerge/ll_kth_from_end/Program.cs
2,113
C#
using MTGAHelper.Lib.OutputLogParser.Models.GRE.MatchToClient.IntermissionReq; namespace MTGAHelper.Lib.OutputLogParser.Models.GRE.MatchToClient { public class IntermissionReqResult : MtgaOutputLogPartResultBase<IntermissionReqRaw>, ITagMatchResult { //public override ReaderMtgaOutputLogPartTypeEnum ResultType => ReaderMtgaOutputLogPartTypeEnum.IntermissionReq; } }
35.545455
120
0.823529
[ "MIT" ]
DuncanmaMSFT/MTGAHelper-Windows-Client
MTGAHelper.Lib.OutputLogParser.Models/GRE/MatchToClient/IntermissionReqResult.cs
393
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.Media.Outputs { [OutputType] public sealed class ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeaderResponse { /// <summary> /// The discriminator for derived types. /// Expected value is '#Microsoft.Media.ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader'. /// </summary> public readonly string OdataType; [OutputConstructor] private ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeaderResponse(string odataType) { OdataType = odataType; } } }
30.62069
105
0.710586
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Media/Outputs/ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeaderResponse.cs
888
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.DirectConnect; using Amazon.DirectConnect.Model; using Amazon.DirectConnect.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class DirectConnectMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("directconnect-2012-10-25.normal.json", "directconnect.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void AllocateConnectionOnInterconnectMarshallTest() { var request = InstantiateClassGenerator.Execute<AllocateConnectionOnInterconnectRequest>(); var marshaller = new AllocateConnectionOnInterconnectRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AllocateConnectionOnInterconnectRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AllocateConnectionOnInterconnect").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AllocateConnectionOnInterconnectResponseUnmarshaller.Instance.Unmarshall(context) as AllocateConnectionOnInterconnectResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void AllocatePrivateVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<AllocatePrivateVirtualInterfaceRequest>(); var marshaller = new AllocatePrivateVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AllocatePrivateVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AllocatePrivateVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AllocatePrivateVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as AllocatePrivateVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void AllocatePublicVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<AllocatePublicVirtualInterfaceRequest>(); var marshaller = new AllocatePublicVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AllocatePublicVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AllocatePublicVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AllocatePublicVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as AllocatePublicVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void ConfirmConnectionMarshallTest() { var request = InstantiateClassGenerator.Execute<ConfirmConnectionRequest>(); var marshaller = new ConfirmConnectionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ConfirmConnectionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ConfirmConnection").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ConfirmConnectionResponseUnmarshaller.Instance.Unmarshall(context) as ConfirmConnectionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void ConfirmPrivateVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<ConfirmPrivateVirtualInterfaceRequest>(); var marshaller = new ConfirmPrivateVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ConfirmPrivateVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ConfirmPrivateVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ConfirmPrivateVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as ConfirmPrivateVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void ConfirmPublicVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<ConfirmPublicVirtualInterfaceRequest>(); var marshaller = new ConfirmPublicVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ConfirmPublicVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ConfirmPublicVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ConfirmPublicVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as ConfirmPublicVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void CreateConnectionMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateConnectionRequest>(); var marshaller = new CreateConnectionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateConnectionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateConnection").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateConnectionResponseUnmarshaller.Instance.Unmarshall(context) as CreateConnectionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void CreateInterconnectMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateInterconnectRequest>(); var marshaller = new CreateInterconnectRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateInterconnectRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateInterconnect").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateInterconnectResponseUnmarshaller.Instance.Unmarshall(context) as CreateInterconnectResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void CreatePrivateVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<CreatePrivateVirtualInterfaceRequest>(); var marshaller = new CreatePrivateVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreatePrivateVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreatePrivateVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreatePrivateVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as CreatePrivateVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void CreatePublicVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<CreatePublicVirtualInterfaceRequest>(); var marshaller = new CreatePublicVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreatePublicVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreatePublicVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreatePublicVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as CreatePublicVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DeleteConnectionMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteConnectionRequest>(); var marshaller = new DeleteConnectionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteConnectionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteConnection").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteConnectionResponseUnmarshaller.Instance.Unmarshall(context) as DeleteConnectionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DeleteInterconnectMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteInterconnectRequest>(); var marshaller = new DeleteInterconnectRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteInterconnectRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteInterconnect").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteInterconnectResponseUnmarshaller.Instance.Unmarshall(context) as DeleteInterconnectResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DeleteVirtualInterfaceMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteVirtualInterfaceRequest>(); var marshaller = new DeleteVirtualInterfaceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteVirtualInterfaceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteVirtualInterface").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteVirtualInterfaceResponseUnmarshaller.Instance.Unmarshall(context) as DeleteVirtualInterfaceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeConnectionsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConnectionsRequest>(); var marshaller = new DescribeConnectionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConnectionsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConnections").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConnectionsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConnectionsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeConnectionsOnInterconnectMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeConnectionsOnInterconnectRequest>(); var marshaller = new DescribeConnectionsOnInterconnectRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeConnectionsOnInterconnectRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeConnectionsOnInterconnect").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeConnectionsOnInterconnectResponseUnmarshaller.Instance.Unmarshall(context) as DescribeConnectionsOnInterconnectResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeInterconnectsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeInterconnectsRequest>(); var marshaller = new DescribeInterconnectsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeInterconnectsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeInterconnects").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeInterconnectsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeInterconnectsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeLocationsMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeLocationsRequest>(); var marshaller = new DescribeLocationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeLocations").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeLocationsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLocationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeVirtualGatewaysMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeVirtualGatewaysRequest>(); var marshaller = new DescribeVirtualGatewaysRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeVirtualGateways").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeVirtualGatewaysResponseUnmarshaller.Instance.Unmarshall(context) as DescribeVirtualGatewaysResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("DirectConnect")] public void DescribeVirtualInterfacesMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeVirtualInterfacesRequest>(); var marshaller = new DescribeVirtualInterfacesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeVirtualInterfacesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeVirtualInterfaces").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeVirtualInterfacesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeVirtualInterfacesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
51.270869
164
0.657496
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet.UnitTests/Marshalling/DirectConnectMarshallingTests.cs
30,096
C#
using Skybrud.Essentials.Common; using Skybrud.Essentials.Http; using Skybrud.Essentials.Http.Collections; using Skybrud.Social.GitHub.Http; using Skybrud.Social.GitHub.Models.Repositories; using System; namespace Skybrud.Social.GitHub.Options.Repositories.Labels { /// <summary> /// Options for getting the labels of a GitHub repository. /// </summary> /// <see> /// <cref>https://docs.github.com/en/rest/reference/issues#list-labels-for-a-repository</cref> /// </see> public class GitHubGetLabelsOptions : GitHubHttpRequestOptions { #region Properties /// <summary> /// Gets or sets the alias of the owner. /// </summary> public string Owner { get; set; } /// <summary> /// Gets or sets the alias/slug of the repository. /// </summary> public string Repo { get; set; } /// <summary> /// Gets or sets the maximum amount of labels to returned by each page. Maximum is <c>100</c>. /// </summary> public int PerPage { get; set; } /// <summary> /// Gets or sets the page to be returned. /// </summary> public int Page { get; set; } #endregion #region Constructors /// <summary> /// Initialize a new instance with default options. /// </summary> public GitHubGetLabelsOptions() { } /// <summary> /// Initializes a new instance based on the specified <paramref name="owner"/> and <paramref name="repo"/> slug. /// </summary> /// <param name="owner">The alias of the repository owner.</param> /// <param name="repo">The alias/slug of the repository.</param> public GitHubGetLabelsOptions(string owner, string repo) { Owner = owner; Repo = repo; } /// <summary> /// Initializes a new instance based on the specified <paramref name="owner"/> and <paramref name="repo"/> slug. /// </summary> /// <param name="owner">The alias of the repository owner.</param> /// <param name="repo">The alias/slug of the repository.</param> /// <param name="perPage">The maximum amount of labels to returned by each page. Maximum is <c>100</c>.</param> /// <param name="page">The page to be returned.</param> public GitHubGetLabelsOptions(string owner, string repo, int perPage, int page) { Owner = owner; Repo = repo; PerPage = perPage; Page = page; } /// <summary> /// Initializes a new instance based on the specified <paramref name="repository"/>. /// </summary> /// <param name="repository">The repository.</param> public GitHubGetLabelsOptions(GitHubRepositoryItem repository) { if (repository == null) throw new ArgumentNullException(nameof(repository)); Owner = repository.Owner.Login; Repo = repository.Name; } /// <summary> /// Initializes a new instance based on the specified <paramref name="repository"/>. /// </summary> /// <param name="repository">The repository.</param> /// <param name="perPage">The maximum amount of labels to returned by each page. Maximum is <c>100</c>.</param> /// <param name="page">The page to be returned.</param> public GitHubGetLabelsOptions(GitHubRepositoryItem repository, int perPage, int page) { if (repository == null) throw new ArgumentNullException(nameof(repository)); Owner = repository.Owner.Login; Repo = repository.Name; PerPage = perPage; Page = page; } #endregion #region Member methods /// <inheritdoc /> public override IHttpRequest GetRequest() { // Validate required parameters if (string.IsNullOrWhiteSpace(Owner)) throw new PropertyNotSetException(nameof(Owner)); if (string.IsNullOrWhiteSpace(Repo)) throw new PropertyNotSetException(nameof(Repo)); // Initialize and construct the query string IHttpQueryString query = new HttpQueryString(); if (PerPage > 0) query.Add("per_page", PerPage); if (Page > 0) query.Add("page", Page); // Initialize the request return HttpRequest .Get($"/repos/{Owner}/{Repo}/labels", query) .SetAcceptHeader(MediaTypes); } #endregion } }
37.104839
120
0.585742
[ "MIT" ]
abjerner/Skybrud.Social.GitHub
src/Skybrud.Social.GitHub/Options/Repositories/Labels/GitHubGetLabelsOptions.cs
4,603
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Net; using System.Net.Http; using Xunit; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Web.Http.Controllers { public class VoidResultConverterTest { private readonly VoidResultConverter _converter = new VoidResultConverter(); private readonly HttpControllerContext _context = new HttpControllerContext(); private readonly HttpRequestMessage _request = new HttpRequestMessage(); public VoidResultConverterTest() { _context.Request = _request; _context.Configuration = new HttpConfiguration(); } [Fact] public void Convert_WhenContextIsNull_Throws() { Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: null), "controllerContext"); } [Fact] public void Convert_ReturnsResponseMessageWithRequestAssigned() { var result = _converter.Convert(_context, null); Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Null(result.Content); Assert.Same(_request, result.RequestMessage); } } }
33.153846
130
0.679814
[ "Apache-2.0" ]
Distrotech/mono
external/aspnetwebstack/test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs
1,295
C#
using System; using System.Reactive; using System.Reactive.Linq; using Smith.Services.Utils.TdLib; using TdLib; namespace Smith.Services.Messaging.Chats { public class ChatUpdater : IChatUpdater { private readonly IAgent _agent; public ChatUpdater(IAgent agent) { _agent = agent; } public IObservable<Unit> GetOrderUpdates() { var newUpdates = _agent.Updates.OfType<TdApi.Update.UpdateNewChat>() .Select(_ => Unit.Default); var orderUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatOrder>() .Select(_ => Unit.Default); var messageUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatLastMessage>() .Select(_ => Unit.Default); var pinnedUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatIsPinned>() .Select(_ => Unit.Default); var draftUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatDraftMessage>() .Select(_ => Unit.Default); return newUpdates .Merge(orderUpdates) .Merge(messageUpdates) .Merge(pinnedUpdates) .Merge(draftUpdates); } public IObservable<Chat> GetChatUpdates() { var titleUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatTitle>() .SelectMany(u => GetChat(u.ChatId)); var photoUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatPhoto>() .SelectMany(u => GetChat(u.ChatId)); var inboxUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatReadInbox>() .SelectMany(u => GetChat(u.ChatId)); var messageUpdates = _agent.Updates.OfType<TdApi.Update.UpdateChatLastMessage>() .SelectMany(u => GetChat(u.ChatId)); return titleUpdates .Merge(photoUpdates) .Merge(inboxUpdates) .Merge(messageUpdates); } private IObservable<Chat> GetChat(long chatId) { return _agent.Execute(new TdApi.GetChat { ChatId = chatId }) .SelectMany(chat => { if (chat.Type is TdApi.ChatType.ChatTypePrivate type) { return GetUser(type.UserId) .Select(user => new Chat { ChatData = chat, User = user }); } return Observable.Return(new Chat { ChatData = chat }); }); } private IObservable<TdApi.User> GetUser(int id) { return _agent.Execute(new TdApi.GetUser { UserId = id }); } } }
34.738636
92
0.503108
[ "MIT" ]
ForNeVeR/Smith
src/Smith.Services/Messaging/Chats/ChatUpdater.cs
3,057
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThrowablePickupHandler : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
16.157895
52
0.638436
[ "MIT" ]
HemanthRj96/Repos-Knockback_version_2
Knockback-Revised/Assets/GameAssets/Game objects/Scripts/Scripts Pickup Base/ThrowablePickupHandler.cs
309
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using System; using System.Threading; using System.Threading.Tasks; using Azure.Core.Pipeline; using Azure.Core.Pipeline.Policies; namespace Azure.ApplicationModel.Configuration { /// <summary> /// The client to use for interacting with the Azure Configuration Store. /// </summary> public partial class ConfigurationClient { private readonly Uri _baseUri; private readonly HttpPipeline _pipeline; /// <summary> /// Protected constructor to allow mocking /// </summary> protected ConfigurationClient() { } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationClient"/>. /// </summary> /// <param name="connectionString">Connection string with authentication option and related parameters.</param> public ConfigurationClient(string connectionString) : this(connectionString, new ConfigurationClientOptions()) { } /// <summary> /// Creates a <see cref="ConfigurationClient"/> that sends requests to the configuration store. /// </summary> /// <param name="connectionString">Connection string with authentication option and related parameters.</param> /// <param name="options">Options that allow to configure the management of the request sent to the configuration store.</param> public ConfigurationClient(string connectionString, ConfigurationClientOptions options) { if (connectionString == null) throw new ArgumentNullException(nameof(connectionString)); if (options == null) throw new ArgumentNullException(nameof(options)); ParseConnectionString(connectionString, out _baseUri, out var credential, out var secret); _pipeline = HttpPipeline.Build(options, options.ResponseClassifier, options.RetryPolicy, ClientRequestIdPolicy.Singleton, new AuthenticationPolicy(credential, secret), options.LoggingPolicy, BufferResponsePolicy.Singleton); } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> only if the setting does not already exist in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> AddAsync(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return await AddAsync(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> only if the setting does not already exist in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Add(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return Add(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> only if the setting does not already exist in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> AddAsync(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateAddRequest(setting)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: case 201: return await CreateResponseAsync(response, cancellationToken); default: throw new RequestFailedException(response); } } } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> only if the setting does not already exist in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Add(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateAddRequest(setting)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: case 201: return CreateResponse(response, cancellationToken); default: throw new RequestFailedException(response); } } } private Request CreateAddRequest(ConfigurationSetting setting) { if (setting == null) throw new ArgumentNullException(nameof(setting)); if (string.IsNullOrEmpty(setting.Key)) throw new ArgumentNullException($"{nameof(setting)}.{nameof(setting.Key)}"); var request = _pipeline.CreateRequest(); ReadOnlyMemory<byte> content = Serialize(setting); request.Method = HttpPipelineMethod.Put; BuildUriForKvRoute(request.UriBuilder, setting); request.Headers.Add(IfNoneMatch, "*"); request.Headers.Add(MediaTypeKeyValueApplicationHeader); request.Headers.Add(HttpHeader.Common.JsonContentType); request.Content = HttpPipelineRequestContent.Create(content); return request; } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> if it doesn't exist or overrides an existing setting in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> SetAsync(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return await SetAsync(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> if it doesn't exist or overrides an existing setting in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Set(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return Set(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> if it doesn't exist or overrides an existing setting in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> SetAsync(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateSetRequest(setting)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: return await CreateResponseAsync(response, cancellationToken); case 409: throw new RequestFailedException(response, "The setting is locked"); default: throw new RequestFailedException(response); } } } /// <summary> /// Creates a <see cref="ConfigurationSetting"/> if it doesn't exist or overrides an existing setting in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Set(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateSetRequest(setting)) { var response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: return CreateResponse(response, cancellationToken); case 409: throw new RequestFailedException(response, "The setting is locked"); default: throw new RequestFailedException(response); } } } private Request CreateSetRequest(ConfigurationSetting setting) { if (setting == null) throw new ArgumentNullException(nameof(setting)); if (string.IsNullOrEmpty(setting.Key)) throw new ArgumentNullException($"{nameof(setting)}.{nameof(setting.Key)}"); Request request = _pipeline.CreateRequest(); ReadOnlyMemory<byte> content = Serialize(setting); request.Method = HttpPipelineMethod.Put; BuildUriForKvRoute(request.UriBuilder, setting); request.Headers.Add(MediaTypeKeyValueApplicationHeader); request.Headers.Add(HttpHeader.Common.JsonContentType); if (setting.ETag != default) { request.Headers.Add(IfMatchName, $"\"{setting.ETag.ToString()}\""); } request.Content = HttpPipelineRequestContent.Create(content); return request; } /// <summary> /// Updates an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> UpdateAsync(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return await UpdateAsync(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Updates an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="value">The value of the configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Update(string key, string value, string label = default, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); return Update(new ConfigurationSetting(key, value, label), cancellationToken); } /// <summary> /// Updates an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to update.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> UpdateAsync(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateUpdateRequest(setting)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: return await CreateResponseAsync(response, cancellationToken); default: throw new RequestFailedException(response); } } } /// <summary> /// Updates an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to update.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Update(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using (Request request = CreateUpdateRequest(setting)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: return CreateResponse(response, cancellationToken); default: throw new RequestFailedException(response); } } } private Request CreateUpdateRequest(ConfigurationSetting setting) { if (setting == null) throw new ArgumentNullException(nameof(setting)); if (string.IsNullOrEmpty(setting.Key)) throw new ArgumentNullException($"{nameof(setting)}.{nameof(setting.Key)}"); Request request = _pipeline.CreateRequest(); ReadOnlyMemory<byte> content = Serialize(setting); request.Method = HttpPipelineMethod.Put; BuildUriForKvRoute(request.UriBuilder, setting); request.Headers.Add(MediaTypeKeyValueApplicationHeader); request.Headers.Add(HttpHeader.Common.JsonContentType); if (setting.ETag != default) { request.Headers.Add(IfMatchName, $"\"{setting.ETag}\""); } else { request.Headers.Add(IfMatchName, "*"); } request.Content = HttpPipelineRequestContent.Create(content); return request; } /// <summary> /// Deletes an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="etag">The value of an etag indicates the state of a configuration setting within a configuration store. /// If it is specified, the configuration setting is only deleted if etag value matches etag value in the configuration store. /// If no etag value is passed in, then the setting is always deleted.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response> DeleteAsync(string key, string label = default, ETag etag = default, CancellationToken cancellationToken = default) { using (Request request = CreateDeleteRequest(key, label, etag)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: case 204: return response; default: throw new RequestFailedException(response); } } } /// <summary> /// Deletes an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="etag">The value of an etag indicates the state of a configuration setting within a configuration store. /// If it is specified, the configuration setting is only deleted if etag value matches etag value in the configuration store. /// If no etag value is passed in, then the setting is always deleted.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response Delete(string key, string label = default, ETag etag = default, CancellationToken cancellationToken = default) { using (Request request = CreateDeleteRequest(key, label, etag)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: case 204: return response; default: throw new RequestFailedException(response); } } } private Request CreateDeleteRequest(string key, string label, ETag etag) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key)); Request request = _pipeline.CreateRequest(); request.Method = HttpPipelineMethod.Delete; BuildUriForKvRoute(request.UriBuilder, key, label); if (etag != default) { request.Headers.Add(IfMatchName, $"\"{etag.ToString()}\""); } return request; } /// <summary> /// Retrieve an existing <see cref="ConfigurationSetting"/> from the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="acceptDateTime">The setting will be retrieved exactly as it existed at the provided time.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<ConfigurationSetting>> GetAsync(string key, string label = default, DateTimeOffset acceptDateTime = default, CancellationToken cancellationToken = default) { using (Request request = CreateGetRequest(key, label, acceptDateTime)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: return await CreateResponseAsync(response, cancellationToken); default: throw new RequestFailedException(response); } } } /// <summary> /// Retrieve an existing <see cref="ConfigurationSetting"/> from the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="acceptDateTime">The setting will be retrieved exactly as it existed at the provided time.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<ConfigurationSetting> Get(string key, string label = default, DateTimeOffset acceptDateTime = default, CancellationToken cancellationToken = default) { using (Request request = CreateGetRequest(key, label, acceptDateTime)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: return CreateResponse(response, cancellationToken); default: throw new RequestFailedException(response); } } } private Request CreateGetRequest(string key, string label, DateTimeOffset acceptDateTime) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException($"{nameof(key)}"); Request request = _pipeline.CreateRequest(); request.Method = HttpPipelineMethod.Get; BuildUriForKvRoute(request.UriBuilder, key, label); request.Headers.Add(MediaTypeKeyValueApplicationHeader); if (acceptDateTime != default) { var dateTime = acceptDateTime.UtcDateTime.ToString(AcceptDateTimeFormat); request.Headers.Add(AcceptDatetimeHeader, dateTime); } request.Headers.Add(HttpHeader.Common.JsonContentType); return request; } /// <summary> /// Fetches the <see cref="ConfigurationSetting"/> from the configuration store that match the options selected in the <see cref="SettingSelector"/>. /// </summary> /// <param name="selector">Set of options for selecting settings from the configuration store.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<SettingBatch>> GetBatchAsync(SettingSelector selector, CancellationToken cancellationToken = default) { using (Request request = CreateBatchRequest(selector)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: case 206: return new Response<SettingBatch>(response, await ConfigurationServiceSerializer.ParseBatchAsync(response, selector, cancellationToken)); default: throw new RequestFailedException(response); } } } /// <summary> /// Fetches the <see cref="ConfigurationSetting"/> from the configuration store that match the options selected in the <see cref="SettingSelector"/>. /// </summary> /// <param name="selector">Set of options for selecting settings from the configuration store.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<SettingBatch> GetBatch(SettingSelector selector, CancellationToken cancellationToken = default) { using (Request request = CreateBatchRequest(selector)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: case 206: return new Response<SettingBatch>(response, ConfigurationServiceSerializer.ParseBatch(response, selector, cancellationToken)); default: throw new RequestFailedException(response); } } } private Request CreateBatchRequest(SettingSelector selector) { Request request = _pipeline.CreateRequest(); request.Method = HttpPipelineMethod.Get; BuildUriForGetBatch(request.UriBuilder, selector); request.Headers.Add(MediaTypeKeyValueApplicationHeader); if (selector.AsOf.HasValue) { var dateTime = selector.AsOf.Value.UtcDateTime.ToString(AcceptDateTimeFormat); request.Headers.Add(AcceptDatetimeHeader, dateTime); } return request; } /// <summary> /// Lists chronological/historical representation of <see cref="ConfigurationSetting"/> from the configuration store that match the options selected in the <see cref="SettingSelector"/>. /// </summary> /// <remarks>Revisions are provided in descending order from their respective <see cref="ConfigurationSetting.LastModified"/> date.</remarks> /// <param name="selector">Set of options for selecting settings from the configuration store.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task<Response<SettingBatch>> GetRevisionsAsync(SettingSelector selector, CancellationToken cancellationToken = default) { using (Request request = CreateGetRevisionsRequest(selector)) { Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: case 206: { return new Response<SettingBatch>(response, await ConfigurationServiceSerializer.ParseBatchAsync(response, selector, cancellationToken)); } default: throw new RequestFailedException(response); } } } /// <summary> /// Lists chronological/historical representation of <see cref="ConfigurationSetting"/> from the configuration store that match the options selected in the <see cref="SettingSelector"/>. /// </summary> /// <remarks>Revisions are provided in descending order from their respective <see cref="ConfigurationSetting.LastModified"/> date.</remarks> /// <param name="selector">Set of options for selecting settings from the configuration store.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response<SettingBatch> GetRevisions(SettingSelector selector, CancellationToken cancellationToken = default) { using (Request request = CreateGetRevisionsRequest(selector)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: case 206: { return new Response<SettingBatch>(response, ConfigurationServiceSerializer.ParseBatch(response, selector, cancellationToken)); } default: throw new RequestFailedException(response); } } } private Request CreateGetRevisionsRequest(SettingSelector selector) { var request = _pipeline.CreateRequest(); request.Method = HttpPipelineMethod.Get; BuildUriForRevisions(request.UriBuilder, selector); request.Headers.Add(MediaTypeKeyValueApplicationHeader); if (selector.AsOf.HasValue) { var dateTime = selector.AsOf.Value.UtcDateTime.ToString(AcceptDateTimeFormat); request.Headers.Add(AcceptDatetimeHeader, dateTime); } return request; } } }
49.996711
198
0.617442
[ "MIT" ]
garyke/azure-sdk-for-net
sdk/appconfiguration/Azure.ApplicationModel.Configuration/src/ConfigurationClient.cs
30,400
C#
namespace Kean.Domain.Identity.Events { /// <summary> /// 初始化密码成功时触发的事件 /// </summary> public class InitializePasswordSuccessEvent : IEvent { /// <summary> /// 身份标识 /// </summary> public int Id { get; set; } } }
19.214286
56
0.527881
[ "MIT" ]
snr4978/DotNetService4
Kean.Domain.Identity/Events/InitializePasswordSuccessEvent.cs
305
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AbilityKind.cs" company="nGratis"> // The MIT License (MIT) // // Copyright (c) 2014 - 2021 Cahya Ong // // 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. // </copyright> // <author>Cahya Ong - cahya.ong@gmail.com</author> // <creation_timestamp>Monday, 14 January 2019 11:43:53 AM UTC</creation_timestamp> // -------------------------------------------------------------------------------------------------------------------- namespace nGratis.AI.Kvasir.Contract { public enum AbilityKind { Unknown = 0, NotSupported, Static, Activated, Triggered } }
44.625
120
0.62521
[ "MIT" ]
cahyaong/ai.kvasir
Source/Kvasir.Contract/Engine/AbilityKind.cs
1,787
C#
//GENERATED: CS Code using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine{ public partial class UMovieSceneFloatTrack:UMovieScenePropertyTrack { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern new IntPtr StaticClass(); } }
27.083333
69
0.809231
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/UMovieSceneFloatTrack.cs
325
C#
namespace TAUtil.Gdi.Bitmap { using System.Drawing; using System.IO; using TAUtil.Gdi.Palette; /// <summary> /// Provides methods for converting between <see cref="Bitmap"/> instances /// and serialized binary images using the TA indexed color palette. /// </summary> public static class BitmapConvert { private static readonly BitmapSerializer Serializer; private static readonly BitmapDeserializer Deserializer; static BitmapConvert() { Serializer = new BitmapSerializer(PaletteFactory.TAPalette); Deserializer = new BitmapDeserializer(PaletteFactory.TAPalette); } /// <summary> /// Deserializes a bitmap from the given stream. /// </summary> /// <param name="bytes">The stream to read from.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <returns>The deserialized bitmap.</returns> public static Bitmap ToBitmap(Stream bytes, int width, int height) { return Deserializer.Deserialize(bytes, width, height); } /// <summary> /// Deserializes a bitmap from the given byte array. /// </summary> /// <param name="bytes">The array of bytes to read from.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <returns>The deserialized bitmap.</returns> public static Bitmap ToBitmap(byte[] bytes, int width, int height) { return Deserializer.Deserialize(bytes, width, height); } /// <summary> /// Deserializes a bitmap from the given stream, /// using the specified color index as a transparency mask. /// </summary> /// <param name="bytes">The stream to read from.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <param name="transparencyIndex">The color index used to indicate transparency.</param> /// <returns>The deserialized bitmap.</returns> public static Bitmap ToBitmap(Stream bytes, int width, int height, int transparencyIndex) { var transPalette = new TransparencyMaskedPalette(PaletteFactory.TAPalette, transparencyIndex); var des = new BitmapDeserializer(transPalette); return des.Deserialize(bytes, width, height); } /// <summary> /// Deserializes a bitmap from the given byte array, /// using the specified color index as a transparency mask. /// </summary> /// <param name="bytes">The array of bytes to read from.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <param name="transparencyIndex">The color index used to indicate transparency.</param> /// <returns>The deserialized bitmap.</returns> public static Bitmap ToBitmap(byte[] bytes, int width, int height, int transparencyIndex) { var transPalette = new TransparencyMaskedPalette(PaletteFactory.TAPalette, transparencyIndex); var des = new BitmapDeserializer(transPalette); return des.Deserialize(bytes, width, height); } /// <summary> /// Serializes the given bitmap to an array of bytes. /// The bitmap is expected to use only colors present in the TA color palette. /// </summary> /// <param name="bitmap">The bitmap to serialize.</param> /// <returns>The serialized byte array.</returns> public static byte[] ToBytes(Bitmap bitmap) { return Serializer.ToBytes(bitmap); } /// <summary> /// Serializes the given bitmap to an array of bytes, /// using the specified color index to indicate transparency. /// The bitmap is expected to use only colors present in the TA color palette /// and the transparent color. /// </summary> /// <param name="bitmap">The bitmap to serialize.</param> /// <param name="transparencyIndex">The color index to use as transparency.</param> /// <returns>The serialized byte array.</returns> public static byte[] ToBytes(Bitmap bitmap, int transparencyIndex) { var transPalette = new TransparencyMaskedPalette(PaletteFactory.TAPalette, transparencyIndex); var ser = new BitmapSerializer(transPalette); return ser.ToBytes(bitmap); } /// <summary> /// Serializes the given bitmap to the given stream. /// The bitmap is expected to use only colors present in the TA color palette. /// </summary> /// <param name="s">The stream to write to.</param> /// <param name="bitmap">The bitmap to serialize.</param> public static void ToStream(Stream s, Bitmap bitmap) { Serializer.Serialize(s, bitmap); } /// <summary> /// Serializes the given bitmap to the given stream, /// using the specified color index to indicate transparency. /// The bitmap is expected to use only colors present in the TA color palette /// and the transparent color. /// </summary> /// <param name="s">The stream to write to.</param> /// <param name="bitmap">The bitmap to serialize.</param> /// <param name="transparencyIndex">The color index to use as transparency.</param> public static void ToStream(Stream s, Bitmap bitmap, int transparencyIndex) { var transPalette = new TransparencyMaskedPalette(PaletteFactory.TAPalette, transparencyIndex); var ser = new BitmapSerializer(transPalette); ser.Serialize(s, bitmap); } } }
45.392593
107
0.606723
[ "MIT" ]
ArmouredFish/TAUtil
TAUtil.Gdi/Bitmap/BitmapConvert.cs
6,130
C#
///////////////////////////////////// // SPAWN EDITOR // // This SpawnEditor is a huge mod // // of "ZenArcher's SpawnEditor v2" // // By Nerun // ///////////////////////////////////// using System; using System.IO; using System.Collections; using System.Collections.Generic; using Server; using Server.Items; using Server.Mobiles; using Server.Network; using Server.Regions; using Server.Commands; namespace Server.Gumps { public class SpawnEditorGump : Gump { private int m_page; private ArrayList m_tempList; public Item m_selSpawner; public int page { get{ return m_page; } set{ m_page = value; } } public Item selSpawner { get{ return m_selSpawner; } set{ m_selSpawner = value; } } public ArrayList tempList { get{ return m_tempList; } set{ m_tempList = value; } } public static void Initialize() { CommandSystem.Register( "SpawnEditor", AccessLevel.GameMaster, new CommandEventHandler( SpawnEditor_OnCommand ) ); CommandSystem.Register( "Editor", AccessLevel.GameMaster, new CommandEventHandler( SpawnEditor_OnCommand ) ); } public static void Register( string command, AccessLevel access, CommandEventHandler handler ) { CommandSystem.Register( command, access, handler ); } [Usage( "SpawnEditor" )] [Aliases( "Editor" )] [Description( "Used to find and edit spawns" )] public static void SpawnEditor_OnCommand( CommandEventArgs e ) { Mobile from = e.Mobile; SpawnEditor_OnCommand( from ); } public static void SpawnEditor_OnCommand( Mobile from ) { ArrayList worldList = new ArrayList(); ArrayList facetList = new ArrayList(); Type type = ScriptCompiler.FindTypeByName( "PremiumSpawner", true ); if ( type == typeof( Item ) || type.IsSubclassOf( typeof( Item ) ) ) { bool isAbstract = type.IsAbstract; foreach ( Item item in World.Items.Values ) { if ( isAbstract ? item.GetType().IsSubclassOf( type ) : item.GetType() == type ) worldList.Add( item ); } } foreach( PremiumSpawner worldSpnr in worldList ) { if( worldSpnr.Map == from.Map ) facetList.Add( worldSpnr ); } //TODO: Sort spawner list SpawnEditor_OnCommand( from, 0, facetList ); } public static void SpawnEditor_OnCommand( Mobile from, int page, ArrayList currentList ) { SpawnEditor_OnCommand( from, page, currentList, 0 ); } public static void SpawnEditor_OnCommand( Mobile from, int page, ArrayList currentList, int selected ) { SpawnEditor_OnCommand( from, page, currentList, selected, null ); } public static void SpawnEditor_OnCommand( Mobile from, int page, ArrayList currentList, int selected, Item selSpawner ) { from.SendGump( new SpawnEditorGump( from, page, currentList, selected, selSpawner ) ); } public SpawnEditorGump( Mobile from, int page, ArrayList currentList, int selected, Item spwnr ) : base( 50, 40 ) { tempList = new ArrayList(); Mobile m = from; m_page = page; Region r = from.Region; Map map = from.Map; int buttony = 60; int buttonID = 1; int listnum = 0; tempList = currentList; selSpawner = spwnr; AddPage(0); AddBackground( 0, 0, 600, 450, 5054 ); AddImageTiled( 8, 8, 584, 40, 2624 ); AddAlphaRegion( 8, 8, 584, 40 ); AddImageTiled( 8, 50, 250, 396, 2624 ); AddAlphaRegion( 8, 50, 250, 396 ); AddImageTiled( 260, 50, 332, 396, 2624 ); AddAlphaRegion( 260, 50, 332, 396 ); AddLabel( 220, 20, 52, "PREMIUM SPAWNER EDITOR" ); AddButton( 550, 405, 0x158A, 0x158B, 10002, GumpButtonType.Reply, 1 ); //Quit Button AddButton( 275, 412, 0x845, 0x846, 10008, GumpButtonType.Reply, 0 ); AddLabel( 300, 410, 52, "Refresh" ); if( currentList.Count == 0 ) AddLabel( 50, 210, 52, "No Premium Spawners Found" ); else { if( page == 0 ) { if( currentList.Count < 15 ) listnum = currentList.Count; else listnum = 15; for( int x = 0; x < listnum; x++ ) { Item spawnr = null; if( currentList[x] is Item ) spawnr = currentList[x] as Item; string gumpMsg = ""; Point3D spawnr3D = new Point3D( ( new Point2D( spawnr.X, spawnr.Y ) ), spawnr.Z ); Region spawnrRegion = Region.Find( spawnr3D, map ); if( spawnrRegion.ToString() == "" ) gumpMsg = "PremiumSpawner at " + spawnr.X.ToString() + ", " + spawnr.Y.ToString(); else gumpMsg = spawnrRegion.ToString(); AddButton( 25, buttony, 0x845, 0x846, buttonID, GumpButtonType.Reply, 0 ); AddLabel( 55, buttony, 52, gumpMsg ); buttony += 25; buttonID += 1; } } else if( page > 0 ) { if( currentList.Count < 15 + ( 15 * page ) ) listnum = currentList.Count; else listnum = 15 + ( 15 * page ); for( int x = 15 * page; x < listnum; x++ ) { Item spawnr = null; buttonID = x+1; if( currentList[x] is Item ) spawnr = currentList[x] as Item; string gumpMsg = ""; Point3D spawnr3D = new Point3D( ( new Point2D( spawnr.X, spawnr.Y ) ), spawnr.Z ); Region spawnrRegion = Region.Find( spawnr3D, map ); if( spawnrRegion.ToString() == "" ) gumpMsg = "PremiumSpawner at " + spawnr.X.ToString() + ", " + spawnr.Y.ToString(); else gumpMsg = spawnrRegion.ToString(); AddButton( 25, buttony, 0x845, 0x846, buttonID, GumpButtonType.Reply, 0 ); AddLabel( 55, buttony, 52, gumpMsg ); buttony += 25; } } } if( page == 0 && currentList.Count > 15 ) AddButton( 450, 20, 0x15E1, 0x15E5, 10000, GumpButtonType.Reply, 0 ); else if( page > 0 && currentList.Count > 15 + ( page * 15 ) ) AddButton( 450, 20, 0x15E1, 0x15E5, 10000, GumpButtonType.Reply, 0 ); if( page != 0 ) AddButton( 150, 20, 0x15E3, 0x15E7, 10001, GumpButtonType.Reply, 0 ); int pageNum = (int)currentList.Count / 15; int rem = currentList.Count % 15; int totPages = 0; string stotPages = ""; if( rem > 0 ) { totPages = pageNum + 1; stotPages = totPages.ToString(); } else stotPages = pageNum.ToString(); string pageText = "Page " + ( page + 1 ) + " of " + stotPages; AddLabel( 40, 20, 52, pageText ); if( selected == 0 ) InitializeStartingRightPanel(); else if( selected == 1 ) InitializeSelectedRightPanel(); } public void InitializeStartingRightPanel() { AddLabel( 275, 65, 52, "Filter to current region only" ); AddButton( 500, 65, 0x15E1, 0x15E5, 10003, GumpButtonType.Reply, 0 ); AddTextField( 275, 140, 50, 20, 0 ); AddLabel( 275, 115, 52, "Filter by Distance" ); AddButton( 500, 115, 0x15E1, 0x15E5, 10004, GumpButtonType.Reply, 0 ); AddTextField( 275, 190, 120, 20, 1 ); AddLabel( 275, 165, 52, "Search Spawners by Creature" ); AddButton( 500, 165, 0x15E1, 0x15E5, 10009, GumpButtonType.Reply, 0 ); AddTextField( 275, 240, 50, 20, 2 ); AddLabel( 275, 215, 52, "Search Spawners by SpawnID" ); AddButton( 500, 215, 0x15E1, 0x15E5, 10010, GumpButtonType.Reply, 0 ); } public void InitializeSelectedRightPanel() { string spX = selSpawner.X.ToString(); string spY = selSpawner.Y.ToString(); string spnText = "PremiumSpawner at " + spX + ", " + spY; AddLabel( 350, 65, 52, spnText ); PremiumSpawner initSpn = selSpawner as PremiumSpawner; int strNum = 0; string spns = "Containing: "; string spnsNEW = ""; string spns1 = ""; string spns2 = ""; string spns3 = ""; for( int i = 0; i < initSpn.CreaturesName.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.CreaturesName.Count - 1 ) { if( spns.Length + initSpn.CreaturesName[i].ToString().Length < 50 ) spnsNEW += (string)initSpn.CreaturesName[i] + ", "; else { strNum = 1; spns1 += (string)initSpn.CreaturesName[i] + ", "; } } else spnsNEW += (string)initSpn.CreaturesName[i]; } else if( strNum == 1 ) { if( i < initSpn.CreaturesName.Count - 1 ) { if( spns1.Length + initSpn.CreaturesName[i].ToString().Length < 50 ) spns1 += (string)initSpn.CreaturesName[i] + ", "; else { strNum = 2; spns2 += (string)initSpn.CreaturesName[i] + ", "; } } else { if( spns1.Length + initSpn.CreaturesName[i].ToString().Length < 50 ) spns1 += (string)initSpn.CreaturesName[i]; else { strNum = 3; spns2 += (string)initSpn.CreaturesName[i]; } } } else if( strNum == 2 ) { if( i < initSpn.CreaturesName.Count - 1 ) { if( spns2.Length + initSpn.CreaturesName[i].ToString().Length < 50 ) spns2 += (string)initSpn.CreaturesName[i] + ", "; else { strNum = 3; spns3 += (string)initSpn.CreaturesName[i] + ", "; } } else { if( spns2.Length + initSpn.CreaturesName[i].ToString().Length < 50 ) spns2 += (string)initSpn.CreaturesName[i]; else { strNum = 4; spns3 += (string)initSpn.CreaturesName[i]; } } } else if( strNum == 3 ) { if( i < initSpn.CreaturesName.Count - 1 ) spns3 += (string)initSpn.CreaturesName[i] + ", "; else spns3 += (string)initSpn.CreaturesName[i]; } } string spnsNEWa = ""; string spns1a = ""; string spns2a = ""; string spns3a = ""; for( int i = 0; i < initSpn.SubSpawnerA.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.SubSpawnerA.Count - 1 ) { if( spns.Length + initSpn.SubSpawnerA[i].ToString().Length < 50 ) spnsNEWa += (string)initSpn.SubSpawnerA[i] + ", "; else { strNum = 1; spns1a += (string)initSpn.SubSpawnerA[i] + ", "; } } else spnsNEWa += (string)initSpn.SubSpawnerA[i]; } else if( strNum == 1 ) { if( i < initSpn.SubSpawnerA.Count - 1 ) { if( spns1a.Length + initSpn.SubSpawnerA[i].ToString().Length < 50 ) spns1a += (string)initSpn.SubSpawnerA[i] + ", "; else { strNum = 2; spns2a += (string)initSpn.SubSpawnerA[i] + ", "; } } else { if( spns1a.Length + initSpn.SubSpawnerA[i].ToString().Length < 50 ) spns1a += (string)initSpn.SubSpawnerA[i]; else { strNum = 3; spns2a += (string)initSpn.SubSpawnerA[i]; } } } else if( strNum == 2 ) { if( i < initSpn.SubSpawnerA.Count - 1 ) { if( spns2a.Length + initSpn.SubSpawnerA[i].ToString().Length < 50 ) spns2a += (string)initSpn.SubSpawnerA[i] + ", "; else { strNum = 3; spns3a += (string)initSpn.SubSpawnerA[i] + ", "; } } else { if( spns2a.Length + initSpn.SubSpawnerA[i].ToString().Length < 50 ) spns2a += (string)initSpn.SubSpawnerA[i]; else { strNum = 4; spns3a += (string)initSpn.SubSpawnerA[i]; } } } else if( strNum == 3 ) { if( i < initSpn.SubSpawnerA.Count - 1 ) spns3a += (string)initSpn.SubSpawnerA[i] + ", "; else spns3a += (string)initSpn.SubSpawnerA[i]; } } string spnsNEWb = ""; string spns1b = ""; string spns2b = ""; string spns3b = ""; for( int i = 0; i < initSpn.SubSpawnerB.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.SubSpawnerB.Count - 1 ) { if( spns.Length + initSpn.SubSpawnerB[i].ToString().Length < 50 ) spnsNEWb += (string)initSpn.SubSpawnerB[i] + ", "; else { strNum = 1; spns1b += (string)initSpn.SubSpawnerB[i] + ", "; } } else spnsNEWb += (string)initSpn.SubSpawnerB[i]; } else if( strNum == 1 ) { if( i < initSpn.SubSpawnerB.Count - 1 ) { if( spns1b.Length + initSpn.SubSpawnerB[i].ToString().Length < 50 ) spns1b += (string)initSpn.SubSpawnerB[i] + ", "; else { strNum = 2; spns2b += (string)initSpn.SubSpawnerB[i] + ", "; } } else { if( spns1b.Length + initSpn.SubSpawnerB[i].ToString().Length < 50 ) spns1b += (string)initSpn.SubSpawnerB[i]; else { strNum = 3; spns2b += (string)initSpn.SubSpawnerB[i]; } } } else if( strNum == 2 ) { if( i < initSpn.SubSpawnerB.Count - 1 ) { if( spns2b.Length + initSpn.SubSpawnerB[i].ToString().Length < 50 ) spns2b += (string)initSpn.SubSpawnerB[i] + ", "; else { strNum = 3; spns3b += (string)initSpn.SubSpawnerB[i] + ", "; } } else { if( spns2b.Length + initSpn.SubSpawnerB[i].ToString().Length < 50 ) spns2b += (string)initSpn.SubSpawnerB[i]; else { strNum = 4; spns3b += (string)initSpn.SubSpawnerB[i]; } } } else if( strNum == 3 ) { if( i < initSpn.SubSpawnerB.Count - 1 ) spns3b += (string)initSpn.SubSpawnerB[i] + ", "; else spns3b += (string)initSpn.SubSpawnerB[i]; } } string spnsNEWc = ""; string spns1c = ""; string spns2c = ""; string spns3c = ""; for( int i = 0; i < initSpn.SubSpawnerC.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.SubSpawnerC.Count - 1 ) { if( spns.Length + initSpn.SubSpawnerC[i].ToString().Length < 50 ) spnsNEWc += (string)initSpn.SubSpawnerC[i] + ", "; else { strNum = 1; spns1c += (string)initSpn.SubSpawnerC[i] + ", "; } } else spnsNEWc += (string)initSpn.SubSpawnerC[i]; } else if( strNum == 1 ) { if( i < initSpn.SubSpawnerC.Count - 1 ) { if( spns1c.Length + initSpn.SubSpawnerC[i].ToString().Length < 50 ) spns1c += (string)initSpn.SubSpawnerC[i] + ", "; else { strNum = 2; spns2c += (string)initSpn.SubSpawnerC[i] + ", "; } } else { if( spns1c.Length + initSpn.SubSpawnerC[i].ToString().Length < 50 ) spns1c += (string)initSpn.SubSpawnerC[i]; else { strNum = 3; spns2c += (string)initSpn.SubSpawnerC[i]; } } } else if( strNum == 2 ) { if( i < initSpn.SubSpawnerC.Count - 1 ) { if( spns2c.Length + initSpn.SubSpawnerC[i].ToString().Length < 50 ) spns2c += (string)initSpn.SubSpawnerC[i] + ", "; else { strNum = 3; spns3c += (string)initSpn.SubSpawnerC[i] + ", "; } } else { if( spns2c.Length + initSpn.SubSpawnerC[i].ToString().Length < 50 ) spns2c += (string)initSpn.SubSpawnerC[i]; else { strNum = 4; spns3c += (string)initSpn.SubSpawnerC[i]; } } } else if( strNum == 3 ) { if( i < initSpn.SubSpawnerC.Count - 1 ) spns3c += (string)initSpn.SubSpawnerC[i] + ", "; else spns3c += (string)initSpn.SubSpawnerC[i]; } } string spnsNEWd = ""; string spns1d = ""; string spns2d = ""; string spns3d = ""; for( int i = 0; i < initSpn.SubSpawnerD.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.SubSpawnerD.Count - 1 ) { if( spns.Length + initSpn.SubSpawnerD[i].ToString().Length < 50 ) spnsNEWd += (string)initSpn.SubSpawnerD[i] + ", "; else { strNum = 1; spns1d += (string)initSpn.SubSpawnerD[i] + ", "; } } else spnsNEWd += (string)initSpn.SubSpawnerD[i]; } else if( strNum == 1 ) { if( i < initSpn.SubSpawnerD.Count - 1 ) { if( spns1d.Length + initSpn.SubSpawnerD[i].ToString().Length < 50 ) spns1d += (string)initSpn.SubSpawnerD[i] + ", "; else { strNum = 2; spns2d += (string)initSpn.SubSpawnerD[i] + ", "; } } else { if( spns1d.Length + initSpn.SubSpawnerD[i].ToString().Length < 50 ) spns1d += (string)initSpn.SubSpawnerD[i]; else { strNum = 3; spns2d += (string)initSpn.SubSpawnerD[i]; } } } else if( strNum == 2 ) { if( i < initSpn.SubSpawnerD.Count - 1 ) { if( spns2d.Length + initSpn.SubSpawnerD[i].ToString().Length < 50 ) spns2d += (string)initSpn.SubSpawnerD[i] + ", "; else { strNum = 3; spns3d += (string)initSpn.SubSpawnerD[i] + ", "; } } else { if( spns2d.Length + initSpn.SubSpawnerD[i].ToString().Length < 50 ) spns2d += (string)initSpn.SubSpawnerD[i]; else { strNum = 4; spns3d += (string)initSpn.SubSpawnerD[i]; } } } else if( strNum == 3 ) { if( i < initSpn.SubSpawnerD.Count - 1 ) spns3d += (string)initSpn.SubSpawnerD[i] + ", "; else spns3d += (string)initSpn.SubSpawnerD[i]; } } string spnsNEWe = ""; string spns1e = ""; string spns2e = ""; string spns3e = ""; for( int i = 0; i < initSpn.SubSpawnerE.Count; i++ ) { if( strNum == 0 ) { if( i < initSpn.SubSpawnerE.Count - 1 ) { if( spns.Length + initSpn.SubSpawnerE[i].ToString().Length < 50 ) spnsNEWe += (string)initSpn.SubSpawnerE[i] + ", "; else { strNum = 1; spns1e += (string)initSpn.SubSpawnerE[i] + ", "; } } else spnsNEWe += (string)initSpn.SubSpawnerE[i]; } else if( strNum == 1 ) { if( i < initSpn.SubSpawnerE.Count - 1 ) { if( spns1e.Length + initSpn.SubSpawnerE[i].ToString().Length < 50 ) spns1e += (string)initSpn.SubSpawnerE[i] + ", "; else { strNum = 2; spns2e += (string)initSpn.SubSpawnerE[i] + ", "; } } else { if( spns1e.Length + initSpn.SubSpawnerE[i].ToString().Length < 50 ) spns1e += (string)initSpn.SubSpawnerE[i]; else { strNum = 3; spns2e += (string)initSpn.SubSpawnerE[i]; } } } else if( strNum == 2 ) { if( i < initSpn.SubSpawnerE.Count - 1 ) { if( spns2e.Length + initSpn.SubSpawnerE[i].ToString().Length < 50 ) spns2e += (string)initSpn.SubSpawnerE[i] + ", "; else { strNum = 3; spns3e += (string)initSpn.SubSpawnerE[i] + ", "; } } else { if( spns2e.Length + initSpn.SubSpawnerE[i].ToString().Length < 50 ) spns2e += (string)initSpn.SubSpawnerE[i]; else { strNum = 4; spns3e += (string)initSpn.SubSpawnerE[i]; } } } else if( strNum == 3 ) { if( i < initSpn.SubSpawnerE.Count - 1 ) spns3e += (string)initSpn.SubSpawnerE[i] + ", "; else spns3e += (string)initSpn.SubSpawnerE[i]; } } AddLabel( 275, 85, 52, spns ); AddLabel( 280, 110, 52, "[1]" ); AddLabel( 280, 180, 52, "[2]" ); AddLabel( 280, 250, 52, "[3]" ); AddLabel( 425, 110, 52, "[4]" ); AddLabel( 425, 180, 52, "[5]" ); AddLabel( 425, 250, 52, "[6]" ); AddHtml( 300, 110, 115, 65, spnsNEW, true, true ); AddHtml( 300, 180, 115, 65, spnsNEWa, true, true ); AddHtml( 300, 250, 115, 65, spnsNEWb, true, true ); AddHtml( 445, 110, 115, 65, spnsNEWc, true, true ); AddHtml( 445, 180, 115, 65, spnsNEWd, true, true ); AddHtml( 445, 250, 115, 65, spnsNEWe, true, true ); if( spns1 != "" ) AddLabel( 275, 105, 200, spns1 ); if( spns2 != "" ) AddLabel( 275, 125, 200, spns2 ); if( spns3 != "" ) AddLabel( 275, 145, 200, spns3 ); AddLabel( 320, 320, 52, "Go to Spawner" ); AddButton( 525, 320, 0x15E1, 0x15E5, 10005, GumpButtonType.Reply, 1 ); AddLabel( 320, 345, 52, "Delete Selected Spawner" ); AddButton( 525, 345, 0x15E1, 0x15E5, 10006, GumpButtonType.Reply, 0 ); AddLabel( 320, 370, 52, "Edit Spawns" ); AddButton( 525, 370, 0x15E1, 0x15E5, 10007, GumpButtonType.Reply, 0 ); } public List<string> CreateArray( RelayInfo info, Mobile from ) { List<string> creaturesName = new List<string>(); for ( int i = 0; i < 13; i++ ) { TextRelay te = info.GetTextEntry( i ); if ( te != null ) { string str = te.Text; if ( str.Length > 0 ) { str = str.Trim(); Type type = SpawnerType.GetType( str ); if ( type != null ) creaturesName.Add( str ); else AddLabel( 70, 230, 39, "Invalid Search String" ); } } } return creaturesName; } public override void OnResponse( NetState state, RelayInfo info ) { Mobile from = state.Mobile; int buttonNum = 0; ArrayList currentList = new ArrayList( tempList ); int page = m_page; if( info.ButtonID > 0 && info.ButtonID < 10000 ) buttonNum = 1; else if( info.ButtonID > 20004 ) buttonNum = 30000; else buttonNum = info.ButtonID; switch( buttonNum ) { case 0: { //Close break; } case 1: { selSpawner = currentList[ info.ButtonID - 1 ] as Item; SpawnEditor_OnCommand( from, page, currentList, 1, selSpawner ); break; } case 10000: { if( m_page * 10 < currentList.Count ) { page = m_page += 1; SpawnEditor_OnCommand( from, page, currentList ); } break; } case 10001: { if( m_page != 0 ) { page = m_page -= 1; SpawnEditor_OnCommand( from, page, currentList ); } break; } case 10002: { //Close break; } case 10003: { FilterByRegion( from, tempList, from.Region, from.Map, page ); break; } case 10004: { TextRelay oDis = info.GetTextEntry( 0 ); string sDis = ( oDis == null ? "" : oDis.Text.Trim() ); if( sDis != "" ) { try { int distance = Convert.ToInt32( sDis ); FilterByDistance( tempList, from, distance, page ); } catch { from.SendMessage( "Distance must be a number" ); SpawnEditor_OnCommand( from, page, currentList ); } } else { from.SendMessage( "You must specify a distance" ); SpawnEditor_OnCommand( from, page, currentList ); } break; } case 10005: { from.Location = new Point3D( selSpawner.X, selSpawner.Y, selSpawner.Z ); SpawnEditor_OnCommand( from, page, currentList, 1, selSpawner ); break; } case 10006: { selSpawner.Delete(); SpawnEditor_OnCommand( from ); break; } case 10007: { from.SendGump( new PremiumSpawnerGump( selSpawner as PremiumSpawner ) ); SpawnEditor_OnCommand( from, page, currentList, 1, selSpawner ); break; } case 10008: { SpawnEditor_OnCommand( from ); break; } case 10009: { TextRelay oSearch = info.GetTextEntry( 1 ); string sSearch = ( oSearch == null ? null : oSearch.Text.Trim() ); SearchByName( tempList, from, sSearch, page ); break; } case 10010: { TextRelay oID = info.GetTextEntry( 2 ); string sID = ( oID == null ? "" : oID.Text.Trim() ); if( sID != "" ) { try { int SearchID = Convert.ToInt32( sID ); SearchByID( tempList, from, SearchID, page ); } catch { from.SendMessage( "SpawnID must be a number" ); SpawnEditor_OnCommand( from, page, currentList ); } } else { from.SendMessage( "You must specify a SpawnID" ); SpawnEditor_OnCommand( from, page, currentList ); } break; } case 20000: { PremiumSpawner spawner = selSpawner as PremiumSpawner; spawner.CreaturesName = CreateArray( info, state.Mobile ); break; } case 20001: { PremiumSpawner spawner = selSpawner as PremiumSpawner; SpawnEditor_OnCommand( from, page, currentList, 2, selSpawner ); spawner.BringToHome(); break; } case 20002: { PremiumSpawner spawner = selSpawner as PremiumSpawner; SpawnEditor_OnCommand( from, page, currentList, 2, selSpawner ); spawner.Respawn(); break; } case 20003: { PremiumSpawner spawner = selSpawner as PremiumSpawner; SpawnEditor_OnCommand( from, page, currentList, 2, selSpawner ); state.Mobile.SendGump( new PropertiesGump( state.Mobile, spawner ) ); break; } case 30000: { int buttonID = info.ButtonID - 20004; int index = buttonID / 2; int type = buttonID % 2; PremiumSpawner spawner = selSpawner as PremiumSpawner; TextRelay entry = info.GetTextEntry( index ); if ( entry != null && entry.Text.Length > 0 ) { if ( type == 0 ) // Spawn creature spawner.Spawn( entry.Text ); else // Remove creatures spawner.RemoveCreatures( entry.Text ); //spawner.RemoveCreaturesA( entry.Text ); spawner.CreaturesName = CreateArray( info, state.Mobile ); } break; } } } public static void FilterByRegion( Mobile from, ArrayList facetList, Region regr, Map regmap, int page ) { ArrayList filregList = new ArrayList(); foreach( Item regItem in facetList ) { Point2D p2 = new Point2D( regItem.X, regItem.Y ); Point3D p = new Point3D( p2, regItem.Z ); if( Region.Find( p, regmap ) == regr ) filregList.Add( regItem ); } from.SendGump( new SpawnEditorGump( from, 0, filregList, 0, null ) ); } public static void FilterByDistance( ArrayList currentList, Mobile m, int dis, int page ) { ArrayList fildisList = new ArrayList(); for( int z = 0; z < currentList.Count; z ++ ) { Item disItem = currentList[z] as Item; if( disItem.X >= m.X - dis && disItem.X <= m.X + dis && disItem.Y >= m.Y - dis && disItem.Y <= m.Y + dis ) fildisList.Add( disItem ); } m.SendGump( new SpawnEditorGump( m, 0, fildisList, 0, null ) ); } public static void SearchByName( ArrayList currentList, Mobile from, string search, int page ) { ArrayList searchList = new ArrayList(); foreach( PremiumSpawner spn in currentList ) { foreach( string str in spn.CreaturesName ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } foreach( string str in spn.SubSpawnerA ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } foreach( string str in spn.SubSpawnerB ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } foreach( string str in spn.SubSpawnerC ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } foreach( string str in spn.SubSpawnerD ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } foreach( string str in spn.SubSpawnerE ) { if( str.ToLower().IndexOf( search ) >= 0 ) searchList.Add( spn ); } } from.SendGump( new SpawnEditorGump( from, 0, searchList, 0, null ) ); } public static void SearchByID( ArrayList currentList, Mobile from, int SearchID, int page ) { ArrayList searchList = new ArrayList(); foreach( PremiumSpawner spn in currentList ) { if ( ((PremiumSpawner)spn).SpawnID == SearchID ) { searchList.Add( spn ); } } from.SendGump( new SpawnEditorGump( from, 0, searchList, 0, null ) ); } public void AddTextField( int x, int y, int width, int height, int index ) { AddBackground( x - 2, y - 2, width + 4, height + 4, 0x2486 ); AddTextEntry( x + 2, y + 2, width - 4, height - 4, 0, index, "" ); } } }
25.756782
121
0.56541
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Customs/Nerun's Distro/New/Commands/SpawnEditor.cs
27,534
C#
// <auto-generated> // 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 CRIS.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// VoiceTestDefinition /// </summary> public partial class VoiceTestDefinition { /// <summary> /// Initializes a new instance of the VoiceTestDefinition class. /// </summary> public VoiceTestDefinition() { CustomInit(); } /// <summary> /// Initializes a new instance of the VoiceTestDefinition class. /// </summary> /// <param name="text">Information about the text used in the voice /// test</param> /// <param name="model">Information about the models used in the voice /// test</param> /// <param name="voiceTestKind">The kind of this test (e.g. Text, /// SSML). Possible values include: 'Text', 'SSML'</param> public VoiceTestDefinition(string text, ModelIdentity model, string voiceTestKind) { Text = text; Model = model; VoiceTestKind = voiceTestKind; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets information about the text used in the voice test /// </summary> [JsonProperty(PropertyName = "text")] public string Text { get; set; } /// <summary> /// Gets or sets information about the models used in the voice test /// </summary> [JsonProperty(PropertyName = "model")] public ModelIdentity Model { get; set; } /// <summary> /// Gets or sets the kind of this test (e.g. Text, SSML). Possible /// values include: 'Text', 'SSML' /// </summary> [JsonProperty(PropertyName = "voiceTestKind")] public string VoiceTestKind { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Text == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Text"); } if (Model == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Model"); } if (VoiceTestKind == null) { throw new ValidationException(ValidationRules.CannotBeNull, "VoiceTestKind"); } if (Model != null) { Model.Validate(); } } } }
31.659574
93
0.550403
[ "MIT" ]
msimecek/Azure-Speech-CLI
SpeechCLI/SDK/Models/VoiceTestDefinition.cs
2,976
C#
#if NET20 || NET35 // ReSharper disable once CheckNamespace namespace System.Diagnostics.CodeAnalysis { public sealed class ExcludeFromCodeCoverageAttribute : Attribute { } } #endif
23.125
67
0.794595
[ "MIT" ]
Ifry/ConfuserEx
Confuser.Helpers.Runtime/ExcludeFromCodeCoverageAttribute.cs
187
C#
namespace Org.BouncyCastle.Asn1 { /** * DER TaggedObject - in ASN.1 notation this is any object preceded by * a [n] where n is some number - these are assumed to follow the construction * rules (as with sequences). */ public class DerTaggedObject : Asn1TaggedObject { /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ public DerTaggedObject( int tagNo, Asn1Encodable obj) : base(tagNo, obj) { } /** * @param explicitly true if an explicitly tagged object. * @param tagNo the tag number for this object. * @param obj the tagged object. */ public DerTaggedObject( bool explicitly, int tagNo, Asn1Encodable obj) : base(explicitly, tagNo, obj) { } /** * create an implicitly tagged object that contains a zero * length sequence. */ public DerTaggedObject( int tagNo) : base(false, tagNo, DerSequence.Empty) { } internal override void Encode( DerOutputStream derOut) { if (!IsEmpty()) { byte[] bytes = obj.GetDerEncoded(); if (explicitly) { derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, bytes); } else { // // need to mark constructed types... (preserve Constructed tag) // int flags = (bytes[0] & Asn1Tags.Constructed) | Asn1Tags.Tagged; derOut.WriteTag(flags, tagNo); derOut.Write(bytes, 1, bytes.Length - 1); } } else { derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, new byte[0]); } } } }
21.736111
84
0.635783
[ "MIT" ]
cptnalf/b2_autopush
pemlib/asn/dertaggedobject.cs
1,567
C#
namespace ThreeCs.Textures { using System.Collections.Generic; public class CompressedTexture : Texture { /// <summary> /// Constructor /// </summary> /// <param name="mipmaps"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="format"></param> /// <param name="type"></param> /// <param name="mapping"></param> /// <param name="wrapS"></param> /// <param name="wrapT"></param> /// <param name="magFilter"></param> /// <param name="minFilter"></param> /// <param name="anisotropy"></param> public CompressedTexture(List<MipMap> mipmaps = null, int width = 0, int height = 0, int format = 0, int type = 0, TextureMapping mapping = null, int wrapS = 0, int wrapT = 0, int magFilter = 0, int minFilter = 0, int anisotropy = 1) : base (null, mapping, wrapS, wrapT , magFilter , minFilter , format , type , anisotropy) { // this.Image = { width: width, height: height }; // new Bitmap ???? this.Mipmaps = mipmaps; this.GenerateMipmaps = false; } } }
39.666667
242
0.545378
[ "MIT" ]
GrandStrateguerre/three.cs
ThreeCs/Textures/CompressedTexture.cs
1,192
C#
using BBS.ConsumerServicesAPI.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BBS.ConsumerServicesAPI.Repositories.BaseModels { public class Destination : ISoftDeletable { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public bool IsDeleted { get; set; } public List<Trip> TripsFromHere { get; set; } public List<Trip> TripsToHere { get; set; } } }
24.5
57
0.736735
[ "MIT" ]
berbulalauri/internetbankingapp
BBS.ConsumerServicesAPI/Repositories/BaseModels/Destination.cs
492
C#
using System; using System.Data; using System.Web.Security; using umbraco.BusinessLogic; using umbraco.DataLayer; using umbraco.BasePages; using umbraco.IO; using umbraco.cms.businesslogic.member; namespace umbraco { public class contentItemTasks : interfaces.ITask { private string _alias; private int _parentID; private int _typeID; private int _userID; public int UserId { set { _userID = value; } } public int TypeID { set { _typeID = value; } get { return _typeID; } } public string Alias { set { _alias = value; } get { return _alias; } } public int ParentID { set { _parentID = value; } get { return _parentID; } } public bool Save() { // TODO : fix it!! return true; } public bool Delete() { cms.businesslogic.contentitem.ContentItem d = new cms.businesslogic.contentitem.ContentItem(ParentID); // Version3.0 - moving to recycle bin instead of deletion //d.delete(); d.Move(-20); return true; } public bool Sort() { return false; } public contentItemTasks() { // // TODO: Add constructor logic here // } } }
20.734177
115
0.455433
[ "MIT" ]
AndyButland/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/create/contentItemTasks.cs
1,638
C#
using WhosHere.Mobile.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace WhosHere.Mobile.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ImagePage : ContentPage { private FaceViewModel _vm; public ImagePage() { InitializeComponent(); BindingContext = _vm = new FaceViewModel(); MessagingCenter.Subscribe<FaceViewModel>(this, "", async (e) => { await DisplayAlert("Analyzing image", "Your image is being analyzed", "Ok"); }); } } }
28.809524
92
0.613223
[ "MIT" ]
bjorndaniel/WhosHere
src/WhosHere.Mobile/WhosHere.Mobile/Views/ImagePage.xaml.cs
607
C#
using System; using StrawberryShake.CodeGeneration.CSharp.Builders; namespace StrawberryShake.CodeGeneration.CSharp { internal static class ConstructorBuilderExtensions { public static ConstructorBuilder SetPublic(this ConstructorBuilder builder) { return builder.SetAccessModifier(AccessModifier.Public); } public static ConstructorBuilder SetPrivate(this ConstructorBuilder builder) { return builder.SetAccessModifier(AccessModifier.Private); } public static ConstructorBuilder SetInternal(this ConstructorBuilder builder) { return builder.SetAccessModifier(AccessModifier.Internal); } public static ConstructorBuilder SetProtected(this ConstructorBuilder builder) { return builder.SetAccessModifier(AccessModifier.Protected); } public static ConstructorBuilder AddParameter( this ConstructorBuilder builder, string name, Action<ParameterBuilder> configure) { ParameterBuilder? parameterBuilder = ParameterBuilder.New().SetName(name); configure(parameterBuilder); builder.AddParameter(parameterBuilder); return builder; } public static ParameterBuilder AddParameter( this ConstructorBuilder builder, string? name = null) { ParameterBuilder parameterBuilder = ParameterBuilder.New(); if (name is not null) { parameterBuilder.SetName(name); } builder.AddParameter(parameterBuilder); return parameterBuilder; } public static CodeBlockBuilder AddBody(this ConstructorBuilder method) { var code = CodeBlockBuilder.New(); method.AddCode(code); return code; } } }
31.096774
86
0.637967
[ "MIT" ]
AccountTechnologies/hotchocolate
src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Extensions/ConstructorBuilderExtensions.cs
1,928
C#
using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Configuration; using System.Linq; using System.Reflection; namespace SstRegistrationTestHarness.Core.EntityFramework.Extensions { public static class ModelBuilderExtensions { public static void ApplyConfigurationsFromAssembly(this DbModelBuilder modelBuilder, Assembly assembly) { var configurations = from typeInfo in assembly.DefinedTypes from type in typeInfo.ImplementedInterfaces where type.IsGenericType && type.Name.Equals(typeof(EntityTypeConfiguration<>).Name, StringComparison.InvariantCultureIgnoreCase) && typeInfo.IsClass && !typeInfo.IsAbstract && !typeInfo.IsNested select typeInfo; foreach (var configuration in configurations) { var entityType = configuration.ImplementedInterfaces .Single(x => x.Name.Equals(typeof(EntityTypeConfiguration<>).Name)) .GenericTypeArguments.SingleOrDefault(x => x.IsClass); var applyConfigMethods = modelBuilder.Conventions.GetType().GetMethods().Where(x => x.Name.Equals(nameof(ConventionsConfiguration.Add)) && x.IsGenericMethod); var applyConfigMethod = applyConfigMethods.Single(x => x.GetParameters().Any(y => y.ParameterType.Name.Equals(typeof(EntityTypeConfiguration<>).Name))); var applyConfigGenericMethod = applyConfigMethod.MakeGenericMethod(entityType); applyConfigGenericMethod.Invoke(modelBuilder, new[] { Activator.CreateInstance(configuration) }); } } } }
43.790698
174
0.63675
[ "MIT" ]
ameriles/SSTRegistrationTestHarness
SstRegistrationTestHarness.Core.EntityFramework/Extensions/ModelBuilderExtension.cs
1,885
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Kafkaesque; using Newtonsoft.Json; using Topos.Internals; using Topos.Logging; using Topos.Serialization; using ILogger = Topos.Logging.ILogger; namespace Topos.Kafkaesque { class KafkaesqueFileSystemProducerImplementation : IProducerImplementation { readonly ConcurrentDictionary<string, Lazy<LogWriter>> _writers = new ConcurrentDictionary<string, Lazy<LogWriter>>(); readonly string _directoryPath; readonly ILogger _logger; bool _disposed; public KafkaesqueFileSystemProducerImplementation(string directoryPath, ILoggerFactory loggerFactory) { _directoryPath = directoryPath; _logger = loggerFactory.GetLogger(typeof(KafkaesqueFileSystemProducerImplementation)); _logger.Info("Kafkaesque producer initialized with directory {directoryPath}", directoryPath); } public async Task Send(string topic, string partitionKey, TransportMessage transportMessage) { // partitionKey has no function with Kafkaesque-based broker if (topic == null) throw new ArgumentNullException(nameof(topic)); if (transportMessage == null) throw new ArgumentNullException(nameof(transportMessage)); var eventData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(transportMessage)); var writer = _writers.GetOrAdd(topic, CreateWriter).Value; await writer.WriteAsync(eventData); } public async Task SendMany(string topic, string partitionKey, IEnumerable<TransportMessage> transportMessages) { // partitionKey has no function with Kafkaesque-based broker if (topic == null) throw new ArgumentNullException(nameof(topic)); if (transportMessages == null) throw new ArgumentNullException(nameof(transportMessages)); var writer = _writers.GetOrAdd(topic, CreateWriter).Value; await writer.WriteManyAsync(transportMessages .Select(transportMessage => Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(transportMessage)))); } Lazy<LogWriter> CreateWriter(string topic) { var topicDirectoryPath = Path.Combine(_directoryPath, topic); return new Lazy<LogWriter>(() => { var logDirectory = new LogDirectory(topicDirectoryPath, new Settings(logger: new KafkaesqueToToposLogger(_logger))); _logger.Debug("Initializing new Kafkaesque writer with path {directoryPath}", topicDirectoryPath); return logDirectory.GetWriter(); }); } public void Dispose() { if (_disposed) return; try { var writers = _writers.Values; _logger.Info("Closing {count} Kafkaesque writers", writers.Count); Parallel.ForEach(writers, writer => writer.Value.Dispose()); _logger.Info("Kafkaesque writers successfully closed"); } finally { _disposed = true; } } } }
36.855556
132
0.659029
[ "MIT" ]
mookid8000/Topos
Topos.Kafkaesque/Kafkaesque/KafkaesqueFileSystemProducerImplementation.cs
3,319
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("01.SayHello")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.SayHello")] [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("fe5a3c06-b51c-45e7-aa11-76027be41b16")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.702703
84
0.743369
[ "MIT" ]
kmalinov/Telerik-Academy
Homeworks/Homeworks C# Advanced/Methods/01.SayHello/Properties/AssemblyInfo.cs
1,398
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IMicrosoftTunnelServerGetHealthMetricsRequest. /// </summary> public partial interface IMicrosoftTunnelServerGetHealthMetricsRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> MicrosoftTunnelServerGetHealthMetricsRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<IMicrosoftTunnelServerGetHealthMetricsCollectionPage> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<IMicrosoftTunnelServerGetHealthMetricsCollectionPage> PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest Select(string value); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IMicrosoftTunnelServerGetHealthMetricsRequest OrderBy(string value); } }
39.104651
153
0.610467
[ "MIT" ]
larslynch/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IMicrosoftTunnelServerGetHealthMetricsRequest.cs
3,363
C#
using System; using System.Collections.Generic; using System.Linq; namespace Vesta.Server.Domain { public class Customer : Entity { private IList<Animal> _animals = new List<Animal>(); protected Customer(Guid id) : base(id) { } public Customer(Guid id, long number, FullName name, Email email, Address address) : base(id) { Number = number; Name = name; Email = email; Address = address; } public long Number { get; private set; } public FullName Name { get; private set; } public Email Email { get; private set; } public Address Address { get; set; } public IEnumerable<Animal> Animals => _animals.ToList(); public Animal AddAnimal( Guid id, string name, string gender, int yearOfBirth, string exterior, Address locatedAt, string medicalHistory) { var animal = new Animal(id, name, gender, yearOfBirth, exterior, locatedAt, medicalHistory); _animals.Add(animal); return animal; } } }
28.634146
104
0.564736
[ "MIT" ]
RobGustavsson/Vesta
src/Vesta.Server/Domain/Customer.cs
1,176
C#
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using StLogger = Microsoft.Build.Logging.StructuredLogger; namespace MessagePack.CodeGenerator { // Utility and Extension methods for Roslyn internal static class RoslynExtensions { private static (string fname, string args) GetBuildCommandLine(string csprojPath, string tempPath, bool useDotNet) { string fname = "dotnet"; const string tasks = "Restore;ResolveReferences"; // from Buildalyzer implementation // https://github.com/daveaglick/Buildalyzer/blob/b42d2e3ba1b3673a8133fb41e72b507b01bce1d6/src/Buildalyzer/Environment/BuildEnvironment.cs#L86-L96 Dictionary<string, string> properties = new Dictionary<string, string>() { { "ProviderCommandLineArgs", "true" }, { "GenerateResourceMSBuildArchitecture", "CurrentArchitecture" }, { "DesignTimeBuild", "true" }, { "BuildProjectReferences", "false" }, // {"SkipCompilerExecution","true"}, { "DisableRarCache", "true" }, { "AutoGenerateBindingRedirects", "false" }, { "CopyBuildOutputToOutputDirectory", "false" }, { "CopyOutputSymbolsToOutputDirectory", "false" }, { "SkipCopyBuildProduct", "true" }, { "AddModules", "false" }, { "UseCommonOutputDirectory", "true" }, { "GeneratePackageOnBuild", "false" }, { "RunPostBuildEvent", "false" }, { "SolutionDir", new FileInfo(csprojPath).Directory.FullName + "/" }, }; var propargs = string.Join(" ", properties.Select(kv => $"/p:{kv.Key}=\"{kv.Value}\"")); // how to determine whether command should be executed('dotnet msbuild' or 'msbuild')? if (useDotNet) { fname = "dotnet"; return (fname, $"msbuild \"{csprojPath}\" /t:{tasks} {propargs} /bl:\"{Path.Combine(tempPath, "build.binlog")}\" /v:n"); } else { fname = "msbuild"; return (fname, $"\"{csprojPath}\" /t:{tasks} {propargs} /bl:\"{Path.Combine(tempPath, "build.binlog")}\" /v:n"); } } private static async Task<bool> TryExecute(string csprojPath, string tempPath, bool useDotNet) { // executing build command with output binary log (string fname, string args) = GetBuildCommandLine(csprojPath, tempPath, useDotNet); try { var buildlogpath = Path.Combine(tempPath, "build.binlog"); if (File.Exists(buildlogpath)) { try { File.Delete(buildlogpath); } catch { } } using (var stdout = new MemoryStream()) using (var stderr = new MemoryStream()) { var exitCode = await ProcessUtil.ExecuteProcessAsync(fname, args, stdout, stderr, null).ConfigureAwait(false); if (exitCode != 0) { // write process output to stdout and stderr when error. using (var stdout2 = new MemoryStream(stdout.ToArray())) using (var stderr2 = new MemoryStream(stderr.ToArray())) using (Stream consoleStdout = Console.OpenStandardOutput()) using (Stream consoleStderr = Console.OpenStandardError()) { await stdout2.CopyToAsync(consoleStdout).ConfigureAwait(false); await stderr2.CopyToAsync(consoleStderr).ConfigureAwait(false); } } return File.Exists(buildlogpath); } } catch (Exception e) { Console.WriteLine($"exception occured(fname={fname}, args={args}):{e}"); return false; } } private static IEnumerable<StLogger.Error> FindAllErrors(StLogger.Build build) { var lst = new List<StLogger.Error>(); build.VisitAllChildren<StLogger.Error>(er => lst.Add(er)); return lst; } private static (StLogger.Build, IEnumerable<StLogger.Error>) ProcessBuildLog(string tempPath) { var reader = new StLogger.BinLogReader(); var stlogger = new StLogger.StructuredLogger(); // prevent output temporary file StLogger.StructuredLogger.SaveLogToDisk = false; // never output, but if not set, throw exception when initializing stlogger.Parameters = "tmp.buildlog"; stlogger.Initialize(reader); reader.Replay(Path.Combine(tempPath, "build.binlog")); stlogger.Shutdown(); StLogger.Build buildlog = stlogger.Construction.Build; if (buildlog.Succeeded) { return (buildlog, null); } else { IEnumerable<StLogger.Error> errors = FindAllErrors(buildlog); return (null, errors); } } private static async Task<(StLogger.Build, IEnumerable<StLogger.Error>)> TryGetBuildResultAsync(string csprojPath, string tempPath, bool useDotNet, params string[] preprocessorSymbols) { try { if (!await TryExecute(csprojPath, tempPath, useDotNet).ConfigureAwait(false)) { return (null, Array.Empty<StLogger.Error>()); } else { return ProcessBuildLog(tempPath); } } finally { if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } private static async Task<StLogger.Build> GetBuildResult(string csprojPath, params string[] preprocessorSymbols) { var tempPath = Path.Combine(new FileInfo(csprojPath).Directory.FullName, "__buildtemp"); try { (StLogger.Build build, IEnumerable<StLogger.Error> errors) = await TryGetBuildResultAsync(csprojPath, tempPath, true, preprocessorSymbols).ConfigureAwait(false); if (build == null) { Console.WriteLine("execute `dotnet msbuild` failed, retry with `msbuild`"); var dotnetException = new InvalidOperationException($"failed to build project with dotnet:{string.Join("\n", errors)}"); (build, errors) = await TryGetBuildResultAsync(csprojPath, tempPath, false, preprocessorSymbols).ConfigureAwait(false); if (build == null) { throw new InvalidOperationException($"failed to build project: {string.Join("\n", errors)}"); } } return build; } finally { if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } private static Workspace GetWorkspaceFromBuild(this StLogger.Build build, params string[] preprocessorSymbols) { StLogger.Project csproj = build.Children.OfType<StLogger.Project>().FirstOrDefault(); if (csproj == null) { throw new InvalidOperationException("cannot find cs project build"); } StLogger.Item[] compileItems = Array.Empty<StLogger.Item>(); var properties = new Dictionary<string, StLogger.Property>(); foreach (StLogger.Folder folder in csproj.Children.OfType<StLogger.Folder>()) { if (folder.Name == "Items") { StLogger.Folder compileFolder = folder.Children.OfType<StLogger.Folder>().FirstOrDefault(x => x.Name == "Compile"); if (compileFolder == null) { throw new InvalidOperationException("failed to get compililation documents"); } compileItems = compileFolder.Children.OfType<StLogger.Item>().ToArray(); } else if (folder.Name == "Properties") { properties = folder.Children.OfType<StLogger.Property>().ToDictionary(x => x.Name); } } StLogger.Item[] assemblies = Array.Empty<StLogger.Item>(); foreach (StLogger.Target target in csproj.Children.OfType<StLogger.Target>()) { if (target.Name == "ResolveReferences") { StLogger.Folder folder = target.Children.OfType<StLogger.Folder>().Where(x => x.Name == "TargetOutputs").FirstOrDefault(); if (folder == null) { throw new InvalidOperationException("cannot find result of resolving assembly"); } assemblies = folder.Children.OfType<StLogger.Item>().ToArray(); } } var ws = new AdhocWorkspace(); Project roslynProject = ws.AddProject(Path.GetFileNameWithoutExtension(csproj.ProjectFile), Microsoft.CodeAnalysis.LanguageNames.CSharp); var projectDir = properties["ProjectDir"].Value; Guid pguid = properties.ContainsKey("ProjectGuid") ? Guid.Parse(properties["ProjectGuid"].Value) : Guid.NewGuid(); var projectGuid = ProjectId.CreateFromSerialized(pguid); foreach (StLogger.Item compile in compileItems) { var filePath = compile.Text; var absFilePath = Path.Combine(projectDir, filePath); roslynProject = roslynProject.AddDocument(filePath, File.ReadAllText(absFilePath)).Project; } foreach (StLogger.Item asm in assemblies) { roslynProject = roslynProject.AddMetadataReference(MetadataReference.CreateFromFile(asm.Text)); } var compopt = roslynProject.CompilationOptions as CSharpCompilationOptions; compopt = roslynProject.CompilationOptions as CSharpCompilationOptions; compopt = compopt ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); OutputKind kind; switch (properties["OutputType"].Value) { case "Exe": kind = OutputKind.ConsoleApplication; break; case "Library": kind = OutputKind.DynamicallyLinkedLibrary; break; default: kind = OutputKind.DynamicallyLinkedLibrary; break; } roslynProject = roslynProject.WithCompilationOptions(compopt.WithOutputKind(kind).WithAllowUnsafe(true)); var parseopt = roslynProject.ParseOptions as CSharpParseOptions; roslynProject = roslynProject.WithParseOptions(parseopt.WithPreprocessorSymbols(preprocessorSymbols)); if (!ws.TryApplyChanges(roslynProject.Solution)) { throw new InvalidOperationException("failed to apply solution changes to workspace"); } return ws; } public static async Task<Compilation> GetCompilationFromProject(string csprojPath, params string[] preprocessorSymbols) { StLogger.Build build = await GetBuildResult(csprojPath, preprocessorSymbols).ConfigureAwait(false); using (Workspace workspace = GetWorkspaceFromBuild(build, preprocessorSymbols)) { workspace.WorkspaceFailed += WorkSpaceFailed; Project project = workspace.CurrentSolution.Projects.First(); project = project .WithParseOptions((project.ParseOptions as CSharpParseOptions) .WithLanguageVersion(LanguageVersion.CSharp7_3) // force latest version. .WithPreprocessorSymbols(preprocessorSymbols)) .WithCompilationOptions((project.CompilationOptions as CSharpCompilationOptions).WithAllowUnsafe(true)); Compilation compilation = await project.GetCompilationAsync().ConfigureAwait(false); return compilation; } } private static void WorkSpaceFailed(object sender, WorkspaceDiagnosticEventArgs e) { Console.WriteLine(e); } public static IEnumerable<INamedTypeSymbol> GetNamedTypeSymbols(this Compilation compilation) { foreach (SyntaxTree syntaxTree in compilation.SyntaxTrees) { SemanticModel semModel = compilation.GetSemanticModel(syntaxTree); foreach (ISymbol item in syntaxTree.GetRoot() .DescendantNodes() .Select(x => semModel.GetDeclaredSymbol(x)) .Where(x => x != null)) { var namedType = item as INamedTypeSymbol; if (namedType != null) { yield return namedType; } } } } public static IEnumerable<INamedTypeSymbol> EnumerateBaseType(this ITypeSymbol symbol) { INamedTypeSymbol t = symbol.BaseType; while (t != null) { yield return t; t = t.BaseType; } } public static AttributeData FindAttribute(this IEnumerable<AttributeData> attributeDataList, string typeName) { return attributeDataList .Where(x => x.AttributeClass.ToDisplayString() == typeName) .FirstOrDefault(); } public static AttributeData FindAttributeShortName( this IEnumerable<AttributeData> attributeDataList, string typeName) { return attributeDataList .Where(x => x.AttributeClass.Name == typeName) .FirstOrDefault(); } public static AttributeData FindAttributeIncludeBasePropertyShortName( this IPropertySymbol property, string typeName) { do { AttributeData data = FindAttributeShortName(property.GetAttributes(), typeName); if (data != null) { return data; } property = property.OverriddenProperty; } while (property != null); return null; } public static AttributeSyntax FindAttribute(this BaseTypeDeclarationSyntax typeDeclaration, SemanticModel model, string typeName) { return typeDeclaration.AttributeLists .SelectMany(x => x.Attributes) .Where(x => model.GetTypeInfo(x).Type?.ToDisplayString() == typeName) .FirstOrDefault(); } public static INamedTypeSymbol FindBaseTargetType(this ITypeSymbol symbol, string typeName) { return symbol.EnumerateBaseType() .Where(x => x.OriginalDefinition?.ToDisplayString() == typeName) .FirstOrDefault(); } public static object GetSingleNamedArgumentValue(this AttributeData attribute, string key) { foreach (KeyValuePair<string, TypedConstant> item in attribute.NamedArguments) { if (item.Key == key) { return item.Value.Value; } } return null; } public static bool IsNullable(this INamedTypeSymbol symbol) { if (symbol.IsGenericType) { if (symbol.ConstructUnboundGenericType().ToDisplayString() == "T?") { return true; } } return false; } public static IEnumerable<ISymbol> GetAllMembers(this ITypeSymbol symbol) { ITypeSymbol t = symbol; while (t != null) { foreach (ISymbol item in t.GetMembers()) { yield return item; } t = t.BaseType; } } public static IEnumerable<ISymbol> GetAllInterfaceMembers(this ITypeSymbol symbol) { return symbol.GetMembers() .Concat(symbol.AllInterfaces.SelectMany(x => x.GetMembers())); } } }
41.074419
192
0.549768
[ "BSD-2-Clause" ]
KonH/MessagePack-CSharp
src/MessagePack.UniversalCodeGenerator/Utils/RoslynExtensions.cs
17,664
C#
using System; using System.Collections.Generic; using System.Text; namespace Classes.Dominio { public interface IMensalidade { double CalcularValor(); } }
14.75
33
0.700565
[ "CC0-1.0" ]
Lucas-Krause/Entra21Noturno
Classes/Classes/Dominio/IMensalidade.cs
179
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.Collections.Generic; namespace Microsoft.DotNet.Cli.Utils.Factory.CommandResolution { internal class SingleProjectInfo { public string Name { get; } public string Version { get; } public IEnumerable<ResourceAssemblyInfo> ResourceAssemblies { get; } public SingleProjectInfo(string name, string version, IEnumerable<ResourceAssemblyInfo> resourceAssemblies) { Name = name; Version = version; ResourceAssemblies = resourceAssemblies; } public string GetOutputName() { return $"{Name}.dll"; } } }
29.214286
115
0.661369
[ "MIT" ]
flubu-core/toolset
src/Microsoft.DotNet.Cli.Utils/Factory/CommandResolution/SingleProjectInfo.cs
818
C#
using Flub.TelegramBot.Types; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; namespace Flub.TelegramBot.Methods { /// <summary> /// Use this method to move a sticker in a set created by the bot to a specific position. /// Returns <see langword="true"/> on success. /// </summary> public class SetStickerPositionInSet : Method<bool?> { /// <summary> /// File identifier of the sticker. /// </summary> [Required] [JsonPropertyName("sticker")] public string Sticker { get; set; } /// <summary> /// New sticker position in the set, zero-based. /// </summary> [Required] [JsonPropertyName("position")] public int? Position { get; set; } /// <summary> /// Initializes a new instance of the <see cref="SetStickerPositionInSet"/> class. /// </summary> public SetStickerPositionInSet() : base("setStickerPositionInSet") { } } public static class SetStickerPositionInSetExtension { private static Task<bool?> SetStickerPositionInSet(this TelegramBot bot, SetStickerPositionInSet method, CancellationToken cancellationToken = default) => bot.Send(method, cancellationToken); /// <summary> /// Use this method to move a sticker in a set created by the bot to a specific position. /// Returns <see langword="true"/> on success. /// </summary> /// <param name="bot">The bot to send the request with.</param> /// <param name="sticker">File identifier of the sticker.</param> /// <param name="position">New sticker position in the set, zero-based.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> public static Task<bool?> SetStickerPositionInSet(this TelegramBot bot, string sticker, int? position, CancellationToken cancellationToken = default) => SetStickerPositionInSet(bot, new() { Sticker = sticker, Position = position }, cancellationToken); /// <summary> /// Use this method to move a sticker in a set created by the bot to a specific position. /// Returns <see langword="true"/> on success. /// </summary> /// <param name="bot">The bot to send the request with.</param> /// <param name="sticker">The sticker.</param> /// <param name="position">New sticker position in the set, zero-based.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> public static Task<bool?> SetStickerPositionInSet(this TelegramBot bot, IFile sticker, int? position, CancellationToken cancellationToken = default) => SetStickerPositionInSet(bot, new() { Sticker = sticker?.Id, Position = position }, cancellationToken); /// <summary> /// Use this method to move a sticker in a set created by the bot to a specific position. /// Returns <see langword="true"/> on success. /// </summary> /// <param name="bot">The bot to send the request with.</param> /// <param name="sticker">The sticker.</param> /// <param name="position">New sticker position in the set, zero-based.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <returns>The task object representing the asynchronous operation.</returns> public static Task<bool?> SetStickerPositionInSet(this TelegramBot bot, Sticker sticker, int? position, CancellationToken cancellationToken = default) => SetStickerPositionInSet(bot, new() { Sticker = sticker?.FileId, Position = position }, cancellationToken); } }
43.989691
162
0.615186
[ "MIT" ]
flubl/Flub.TelegramBot
Src/Flub.TelegramBot/Methods/Sticker/SetStickerPositionInSet.cs
4,269
C#
using System; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; namespace OpenRiaServices.Controls { /// <summary> /// Manager that observes and collates the events raised by a <see cref="SortDescriptorCollection"/> /// and all the <see cref="SortDescriptor"/>s it contains. /// </summary> /// <remarks> /// The manager also keeps the collection synchronized with the specified /// <see cref="SortDescriptionCollection"/>. The main challenge in synchronization is /// <see cref="SortDescriptor"/>s can exist in an intermediate state while <see cref="SortDescription"/>s /// cannot. This may occasionally lead to a state where the <see cref="SortDescriptorCollection"/> has /// more items than the <see cref="SortDescriptionCollection"/>. This state will resolve once all of /// the <see cref="SortDescriptor"/>s are fully defined. /// </remarks> internal class SortCollectionManager : CollectionManager { #region Member fields private readonly SortDescriptorCollection _sourceCollection; private readonly SortDescriptionCollection _descriptionCollection; // used during synchronization private bool _ignoreChanges; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SortCollectionManager"/> class. /// </summary> /// <param name="sourceCollection">The collection of <see cref="SortDescriptor"/>s to manage</param> /// <param name="descriptionCollection">The collection of <see cref="SortDescription"/>s to synchronize with the <paramref name="sourceCollection"/></param> /// <param name="expressionCache">The cache with entries for the <see cref="SortDescriptor"/>s</param> /// <param name="validationAction">The callback for validating items that are added or changed</param> public SortCollectionManager(SortDescriptorCollection sourceCollection, SortDescriptionCollection descriptionCollection, ExpressionCache expressionCache, Action<SortDescriptor> validationAction) { if (sourceCollection == null) { throw new ArgumentNullException("sourceCollection"); } if (descriptionCollection == null) { throw new ArgumentNullException("descriptionCollection"); } if (expressionCache == null) { throw new ArgumentNullException("expressionCache"); } if (validationAction == null) { throw new ArgumentNullException("validationAction"); } this._sourceCollection = sourceCollection; this._descriptionCollection = descriptionCollection; this.ExpressionCache = expressionCache; this.ValidationAction = (item) => validationAction((SortDescriptor)item); this.AsINotifyPropertyChangedFunc = (item) => ((SortDescriptor)item).Notifier; ((INotifyCollectionChanged)descriptionCollection).CollectionChanged += this.HandleDescriptionCollectionChanged; this.AddCollection(sourceCollection); } #endregion #region Methods /// <summary> /// Overridden to synchronize collections. /// </summary> /// <param name="sender">The collection that changed</param> /// <param name="e">The collection change event</param> protected override void HandleCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { base.HandleCollectionChanged(sender, e); if (this._ignoreChanges) { return; } this.HandleSortDescriptorCollectionChanged(e); this.AssertCollectionsAreEquivalent(); } /// <summary> /// Synchronizes collections in response to a change in the _descriptionCollection. /// </summary> /// <param name="sender">The collection that changed</param> /// <param name="e">The collection change event</param> private void HandleDescriptionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.OnCollectionChanged(); if (this._ignoreChanges) { return; } this.HandleSortDescriptionCollectionChanged(e); this.AssertCollectionsAreEquivalent(); } /// <summary> /// Overridden to synchronize collections. /// </summary> /// <param name="sender">The item that changed</param> /// <param name="e">The property change event</param> protected override void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { base.HandlePropertyChanged(sender, e); if (this._ignoreChanges) { return; } this.HandleSortDescriptorChanged((SortDescriptor)sender, e); this.AssertCollectionsAreEquivalent(); } /// <summary> /// Overridden to suppress events when synchronizing. /// </summary> protected override void OnCollectionChanged() { if (this._ignoreChanges) { return; } base.OnCollectionChanged(); } /// <summary> /// Overridden to suppress events when synchronizing. /// </summary> protected override void OnPropertyChanged() { if (this._ignoreChanges) { return; } base.OnPropertyChanged(); } /// <summary> /// Resets the <paramref name="sortDescriptors"/> collection to match the <paramref name="sortDescriptions"/> collection. /// </summary> /// <param name="sortDescriptions">The collection to match</param> /// <param name="sortDescriptors">The collection to reset</param> private static void ResetToSortDescriptions(SortDescriptionCollection sortDescriptions, SortDescriptorCollection sortDescriptors) { sortDescriptors.Clear(); foreach (SortDescription description in sortDescriptions) { sortDescriptors.Add(SortCollectionManager.GetDescriptorFromDescription(description)); } } /// <summary> /// Resets the <paramref name="sortDescriptions"/> collection to match the <paramref name="sortDescriptors"/> collection. /// </summary> /// <param name="sortDescriptions">The collection to reset</param> /// <param name="sortDescriptors">The collection to match</param> private static void ResetToSortDescriptors(SortDescriptionCollection sortDescriptions, SortDescriptorCollection sortDescriptors) { sortDescriptions.Clear(); foreach (SortDescriptor descriptor in sortDescriptors) { SortDescription? description = SortCollectionManager.GetDescriptionFromDescriptor(descriptor); if (description.HasValue) { sortDescriptions.Add(description.Value); } } } /// <summary> /// Returns a <see cref="SortDescription"/> equivalent to the specified descriptor. /// </summary> /// <param name="sortDescriptor">The descriptor to get a description from</param> /// <returns>A <see cref="SortDescription"/> equivalent to the specified descriptor</returns> private static SortDescription? GetDescriptionFromDescriptor(SortDescriptor sortDescriptor) { if (string.IsNullOrEmpty(sortDescriptor.PropertyPath)) { return null; } return new SortDescription(sortDescriptor.PropertyPath, sortDescriptor.Direction); } /// <summary> /// Returns a <see cref="SortDescriptor"/> equivalent to the specified description /// </summary> /// <param name="sortDescription">The description to get a descriptor from</param> /// <returns>A <see cref="SortDescriptor"/> equivalent to the specified description</returns> private static SortDescriptor GetDescriptorFromDescription(SortDescription sortDescription) { return new SortDescriptor(sortDescription.PropertyName, sortDescription.Direction); } /// <summary> /// Synchronizes the sort descriptors collection to the sort descriptions collection. /// </summary> /// <param name="e">The collection change event</param> private void HandleSortDescriptionCollectionChanged(NotifyCollectionChangedEventArgs e) { this._ignoreChanges = true; try { // We have to reset in a number of situations // 1) Resetting the SortDescriptions // 2) Collections were not equal before replacing SortDescriptions // 3) Collections were not equal before removing SortDescriptions // 4) Collections were not equal before adding SortDescriptions if ((e.Action == NotifyCollectionChangedAction.Reset) || ((e.Action == NotifyCollectionChangedAction.Replace) && ((this._sourceCollection.Count + e.NewItems.Count) != (this._descriptionCollection.Count + e.OldItems.Count))) || ((e.Action == NotifyCollectionChangedAction.Remove) && (this._sourceCollection.Count != (this._descriptionCollection.Count + e.OldItems.Count))) || ((e.Action == NotifyCollectionChangedAction.Add) && ((this._sourceCollection.Count + e.NewItems.Count) != this._descriptionCollection.Count))) { SortCollectionManager.ResetToSortDescriptions(this._descriptionCollection, this._sourceCollection); } else { if ((e.Action == NotifyCollectionChangedAction.Remove) || (e.Action == NotifyCollectionChangedAction.Replace)) { int index = e.OldStartingIndex; if (e.Action == NotifyCollectionChangedAction.Replace) // TODO: This is a ObservableCollection bug! { index = e.NewStartingIndex; } for (int i = 0; i < e.OldItems.Count; i++) { this._sourceCollection.RemoveAt(index); } } if ((e.Action == NotifyCollectionChangedAction.Add) || (e.Action == NotifyCollectionChangedAction.Replace)) { int index = e.NewStartingIndex; foreach (object item in e.NewItems) { this._sourceCollection.Insert(index++, SortCollectionManager.GetDescriptorFromDescription((SortDescription)item)); } } } } finally { this._ignoreChanges = false; } } /// <summary> /// Synchronizes the sort descriptions collection to the sort descriptors collection. /// </summary> /// <param name="e">The collection change event</param> private void HandleSortDescriptorCollectionChanged(NotifyCollectionChangedEventArgs e) { this._ignoreChanges = true; try { // We have to reset in a number of situations // 1) Resetting the SortDescriptors // 2) Collections were not equal before replacing SortDescriptors // 3) Collections were not equal before removing SortDescriptors // 4) Collections were not equal before adding SortDescriptors if ((e.Action == NotifyCollectionChangedAction.Reset) || ((e.Action == NotifyCollectionChangedAction.Replace) && ((this._sourceCollection.Count + e.OldItems.Count) != (this._descriptionCollection.Count + e.NewItems.Count))) || ((e.Action == NotifyCollectionChangedAction.Remove) && ((this._sourceCollection.Count + e.OldItems.Count) != this._descriptionCollection.Count)) || ((e.Action == NotifyCollectionChangedAction.Add) && (this._sourceCollection.Count != (this._descriptionCollection.Count + e.NewItems.Count)))) { SortCollectionManager.ResetToSortDescriptors(this._descriptionCollection, this._sourceCollection); } else { if ((e.Action == NotifyCollectionChangedAction.Remove) || (e.Action == NotifyCollectionChangedAction.Replace)) { int index = e.OldStartingIndex; if (e.Action == NotifyCollectionChangedAction.Replace) // TODO: This is a DependencyObjectCollection bug! { index = e.NewStartingIndex; } for (int i = 0; i < e.OldItems.Count; i++) { this._descriptionCollection.RemoveAt(index); } } if ((e.Action == NotifyCollectionChangedAction.Add) || (e.Action == NotifyCollectionChangedAction.Replace)) { int index = e.NewStartingIndex; foreach (object item in e.NewItems) { SortDescription? description = SortCollectionManager.GetDescriptionFromDescriptor((SortDescriptor)item); if (description.HasValue) { this._descriptionCollection.Insert(index++, description.Value); } } } } } finally { this._ignoreChanges = false; } } /// <summary> /// Synchronizes the sort descriptions collection to the sort descriptors collection. /// </summary> /// <param name="descriptor">The descriptor that changed</param> /// <param name="e">The property change event</param> private void HandleSortDescriptorChanged(SortDescriptor descriptor, PropertyChangedEventArgs e) { this._ignoreChanges = true; try { // We have to reset when the collections were not equal before the change if (this._sourceCollection.Count != this._descriptionCollection.Count) { SortCollectionManager.ResetToSortDescriptors(this._descriptionCollection, this._sourceCollection); } else { int index = this._sourceCollection.IndexOf(descriptor); SortDescription? description = SortCollectionManager.GetDescriptionFromDescriptor(descriptor); if (!description.HasValue) { this._descriptionCollection.RemoveAt(index); } else { this._descriptionCollection[index] = description.Value; } } } finally { this._ignoreChanges = false; } } /// <summary> /// Asserts that the collections are equivalent. /// </summary> [Conditional("DEBUG")] private void AssertCollectionsAreEquivalent() { if (this._sourceCollection.Count != this._descriptionCollection.Count) { // Collections may not be equivalent if a descriptor isn't fully defined return; } Debug.Assert(SortCollectionManager.AreEquivalent(this._descriptionCollection, this._sourceCollection), "Collections should be equal."); } /// <summary> /// Determines whether the <paramref name="sortDescriptions"/> are equivalent to the <paramref name="sortDescriptors"/>. /// </summary> /// <param name="sortDescriptions">The descriptions to compare</param> /// <param name="sortDescriptors">The descriptors to compare</param> /// <returns><c>true</c> if the collections are equivalent</returns> public static bool AreEquivalent(SortDescriptionCollection sortDescriptions, SortDescriptorCollection sortDescriptors) { Debug.Assert((sortDescriptions != null) && (sortDescriptors != null), "Both should be non-null."); if (sortDescriptions.Count != sortDescriptors.Count) { return false; } for (int i = 0, count = sortDescriptions.Count; i < count; i++) { if (!SortCollectionManager.AreEquivalent(sortDescriptions[i], sortDescriptors[i])) { return false; } } return true; } /// <summary> /// Determines whether the <paramref name="sortDescription"/> and <paramref name="sortDescriptor"/> are equivalent. /// </summary> /// <param name="sortDescription">The description to compare</param> /// <param name="sortDescriptor">The descriptor to compare</param> /// <returns><c>true</c> if the two are equivalent</returns> private static bool AreEquivalent(SortDescription sortDescription, SortDescriptor sortDescriptor) { Debug.Assert((sortDescription != null) && (sortDescriptor != null), "Both should be non-null."); return (sortDescription.Direction == sortDescriptor.Direction) && (sortDescription.PropertyName == sortDescriptor.PropertyPath); } #endregion } }
44.235012
202
0.580397
[ "Apache-2.0" ]
Daniel-Svensson/OpenRiaServices
src/archive/OpenRiaServices.Controls.DomainServices/Framework/OpenRiaServices.Windows.Controls/SortCollectionManager.cs
18,448
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Platform.x64.Instructions { /// <summary> /// CMovNoCarry64 /// </summary> /// <seealso cref="Mosa.Platform.x64.X64Instruction" /> public sealed class CMovNoCarry64 : X64Instruction { public override int ID { get { return 603; } } internal CMovNoCarry64() : base(1, 1) { } public override string AlternativeName { get { return "CMovNC"; } } public override bool IsCarryFlagUsed { get { return true; } } public override BaseInstruction GetOpposite() { return X64.CMovCarry64; } public override void Emit(InstructionNode node, BaseCodeEmitter emitter) { System.Diagnostics.Debug.Assert(node.ResultCount == 1); System.Diagnostics.Debug.Assert(node.OperandCount == 1); emitter.OpcodeEncoder.AppendByte(0x0F); emitter.OpcodeEncoder.SuppressByte(0x40); emitter.OpcodeEncoder.AppendNibble(0b0100); emitter.OpcodeEncoder.AppendBit(0b1); emitter.OpcodeEncoder.AppendBit((node.Result.Register.RegisterCode >> 3) & 0x1); emitter.OpcodeEncoder.AppendBit(0b0); emitter.OpcodeEncoder.AppendBit((node.Operand1.Register.RegisterCode >> 3) & 0x1); emitter.OpcodeEncoder.AppendByte(0x43); emitter.OpcodeEncoder.Append2Bits(0b11); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); } } }
30.22
85
0.743216
[ "BSD-3-Clause" ]
kthompson/MOSA-Project
Source/Mosa.Platform.x64/Instructions/CMovNoCarry64.cs
1,511
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Linus.Saves; public static class DataManager { public enum Language { CN, TW, EN } public static Language language = Language.CN; public static void SetLanguage(Language lan) { language = lan; SaveManager.SetLanguage(language); } }
19.888889
50
0.701117
[ "Unlicense" ]
LinusMC/Dream-Date
Dream Date/Assets/Scripts/Manager/DataManager.cs
360
C#
using System; using System.Collections.Generic; using SystemsRx.Events; using SystemsRx.Executor; using SystemsRx.Executor.Handlers; using SystemsRx.Executor.Handlers.Conventional; using SystemsRx.Threading; using EcsRx.Collections; using EcsRx.Collections.Database; using EcsRx.Collections.Entity; using EcsRx.Components.Database; using EcsRx.Components.Lookups; using EcsRx.Entities; using EcsRx.Extensions; using EcsRx.Groups; using EcsRx.Groups.Observable; using EcsRx.MicroRx.Events; using EcsRx.Plugins.Batching.Builders; using EcsRx.Plugins.ReactiveSystems.Handlers; using EcsRx.Plugins.Views.Components; using EcsRx.Plugins.Views.Systems; using EcsRx.Pools; using EcsRx.Tests.Models; using EcsRx.Tests.Systems; using NSubstitute; using Xunit; using Xunit.Abstractions; namespace EcsRx.Tests.Sanity { public class SanityTests { private ITestOutputHelper _logger; public SanityTests(ITestOutputHelper logger) { _logger = logger; } private (IObservableGroupManager, IEntityDatabase, IComponentDatabase, IComponentTypeLookup) CreateFramework() { var componentLookups = new Dictionary<Type, int> { {typeof(TestComponentOne), 0}, {typeof(TestComponentTwo), 1}, {typeof(TestComponentThree), 2}, {typeof(ViewComponent), 3}, {typeof(TestStructComponentOne), 4}, {typeof(TestStructComponentTwo), 5} }; var componentLookupType = new ComponentTypeLookup(componentLookups); var componentDatabase = new ComponentDatabase(componentLookupType); var entityFactory = new DefaultEntityFactory(new IdPool(), componentDatabase, componentLookupType); var collectionFactory = new DefaultEntityCollectionFactory(entityFactory); var entityDatabase = new EntityDatabase(collectionFactory); var observableGroupFactory = new DefaultObservableObservableGroupFactory(); var observableGroupManager = new ObservableGroupManager(observableGroupFactory, entityDatabase, componentLookupType); return (observableGroupManager, entityDatabase, componentDatabase, componentLookupType); } private SystemExecutor CreateExecutor(IObservableGroupManager observableGroupManager) { var threadHandler = new DefaultThreadHandler(); var reactsToEntityHandler = new ReactToEntitySystemHandler(observableGroupManager); var reactsToGroupHandler = new ReactToGroupSystemHandler(observableGroupManager, threadHandler); var reactsToDataHandler = new ReactToDataSystemHandler(observableGroupManager); var manualSystemHandler = new ManualSystemHandler(); var setupHandler = new SetupSystemHandler(observableGroupManager); var teardownHandler = new TeardownSystemHandler(observableGroupManager); var conventionalSystems = new List<IConventionalSystemHandler> { setupHandler, reactsToEntityHandler, reactsToGroupHandler, reactsToDataHandler, manualSystemHandler, teardownHandler }; return new SystemExecutor(conventionalSystems); } [Fact] public void should_execute_setup_for_matching_entities() { var (observableGroupManager, entityDatabase, _, _) = CreateFramework(); var executor = CreateExecutor(observableGroupManager); executor.AddSystem(new TestSetupSystem()); var collection = entityDatabase.GetCollection(); var entityOne = collection.CreateEntity(); var entityTwo = collection.CreateEntity(); entityOne.AddComponents(new TestComponentOne(), new TestComponentTwo()); entityTwo.AddComponents(new TestComponentTwo()); Assert.Equal("woop", entityOne.GetComponent<TestComponentOne>().Data); Assert.Null(entityTwo.GetComponent<TestComponentTwo>().Data); } [Fact] public void should_not_freak_out_when_removing_components_during_removing_event() { var (observableGroupManager, entityDatabase, _, _) = CreateFramework(); var collection = entityDatabase.GetCollection(); var entityOne = collection.CreateEntity(); var timesCalled = 0; entityOne.ComponentsRemoved.Subscribe(x => { entityOne.RemoveComponent<TestComponentTwo>(); timesCalled++; }); entityOne.AddComponents(new TestComponentOne(), new TestComponentTwo()); entityOne.RemoveComponent<TestComponentOne>(); Assert.Equal(2, timesCalled); } [Fact] public void should_treat_view_handler_as_setup_system_and_teardown_system() { var observableGroupManager = Substitute.For<IObservableGroupManager>(); var setupSystemHandler = new SetupSystemHandler(observableGroupManager); var teardownSystemHandler = new TeardownSystemHandler(observableGroupManager); var viewSystem = Substitute.For<IViewResolverSystem>(); Assert.True(setupSystemHandler.CanHandleSystem(viewSystem)); Assert.True(teardownSystemHandler.CanHandleSystem(viewSystem)); } [Fact] public void should_trigger_both_setup_and_teardown_for_view_resolver() { var (observableGroupManager, entityDatabase, _, _) = CreateFramework(); var executor = CreateExecutor(observableGroupManager); var viewResolverSystem = new TestViewResolverSystem(new EventSystem(new MessageBroker()), new Group(typeof(TestComponentOne), typeof(ViewComponent))); executor.AddSystem(viewResolverSystem); var setupCalled = false; viewResolverSystem.OnSetup = entity => { setupCalled = true; }; var teardownCalled = false; viewResolverSystem.OnTeardown = entity => { teardownCalled = true; }; var collection = entityDatabase.GetCollection(); var entityOne = collection.CreateEntity(); entityOne.AddComponents(new TestComponentOne(), new ViewComponent()); collection.RemoveEntity(entityOne.Id); Assert.True(setupCalled); Assert.True(teardownCalled); } [Fact] public void should_listen_to_multiple_collections_for_updates() { var (observableGroupManager, entityDatabase, _, _) = CreateFramework(); var group = new Group(typeof(TestComponentOne)); var collection1 = entityDatabase.CreateCollection(1); var collection2 = entityDatabase.CreateCollection(2); var addedTimesCalled = 0; var removingTimesCalled = 0; var removedTimesCalled = 0; var observableGroup = observableGroupManager.GetObservableGroup(group, 1, 2); observableGroup.OnEntityAdded.Subscribe(x => addedTimesCalled++); observableGroup.OnEntityRemoving.Subscribe(x => removingTimesCalled++); observableGroup.OnEntityRemoved.Subscribe(x => removedTimesCalled++); var entity1 = collection1.CreateEntity(); entity1.AddComponent<TestComponentOne>(); var entity2 = collection2.CreateEntity(); entity2.AddComponent<TestComponentOne>(); collection1.RemoveEntity(entity1.Id); collection2.RemoveEntity(entity2.Id); Assert.Equal(2, addedTimesCalled); Assert.Equal(2, removingTimesCalled); Assert.Equal(2, removedTimesCalled); } [Fact] public unsafe void should_keep_state_with_batches() { var (_, entityDatabase, componentDatabase, componentLookup) = CreateFramework(); var collection1 = entityDatabase.CreateCollection(1); var entity1 = collection1.CreateEntity(); var startingInt = 2; var finalInt = 10; var startingFloat = 5.0f; var finalFloat = 20.0f; ref var structComponent1 = ref entity1.AddComponent<TestStructComponentOne>(4); var component1Allocation = entity1.ComponentAllocations[4]; structComponent1.Data = startingInt; ref var structComponent2 = ref entity1.AddComponent<TestStructComponentTwo>(5); var component2Allocation = entity1.ComponentAllocations[5]; structComponent2.Data = startingFloat; var entities = new[] {entity1}; var batchBuilder = new BatchBuilder<TestStructComponentOne, TestStructComponentTwo>(componentDatabase, componentLookup); var batch = batchBuilder.Build(entities); ref var initialBatchData = ref batch.Batches[0]; ref var component1 = ref *initialBatchData.Component1; ref var component2 = ref *initialBatchData.Component2; Assert.Equal(startingInt, component1.Data); Assert.Equal(startingFloat, component2.Data); component1.Data = finalInt; component2.Data = finalFloat; Assert.Equal(finalInt, (*batch.Batches[0].Component1).Data); Assert.Equal(finalInt, structComponent1.Data); Assert.Equal(finalInt, componentDatabase.Get<TestStructComponentOne>(4, component1Allocation).Data); Assert.Equal(finalFloat, (*batch.Batches[0].Component2).Data); Assert.Equal(finalFloat, structComponent2.Data); Assert.Equal(finalFloat, componentDatabase.Get<TestStructComponentTwo>(5, component2Allocation).Data); } [Fact] public unsafe void should_retain_pointer_through_new_struct() { var (_, entityDatabase, componentDatabase, componentLookup) = CreateFramework(); var collection1 = entityDatabase.CreateCollection(1); var entity1 = collection1.CreateEntity(); var startingInt = 2; var finalInt = 10; var startingFloat = 5.0f; var finalFloat = 20.0f; ref var structComponent1 = ref entity1.AddComponent<TestStructComponentOne>(4); var component1Allocation = entity1.ComponentAllocations[4]; structComponent1.Data = startingInt; ref var structComponent2 = ref entity1.AddComponent<TestStructComponentTwo>(5); var component2Allocation = entity1.ComponentAllocations[5]; structComponent2.Data = startingFloat; var entities = new[] {entity1}; var batchBuilder = new BatchBuilder<TestStructComponentOne, TestStructComponentTwo>(componentDatabase, componentLookup); var batch = batchBuilder.Build(entities); ref var initialBatchData = ref batch.Batches[0]; ref var component1 = ref *initialBatchData.Component1; ref var component2 = ref *initialBatchData.Component2; Assert.Equal(startingInt, component1.Data); Assert.Equal(startingFloat, component2.Data); component1 = new TestStructComponentOne {Data = finalInt}; component2 = new TestStructComponentTwo {Data = finalFloat}; Assert.Equal(finalInt, (*batch.Batches[0].Component1).Data); Assert.Equal(finalInt, structComponent1.Data); Assert.Equal(finalInt, componentDatabase.Get<TestStructComponentOne>(4, component1Allocation).Data); Assert.Equal(finalFloat, (*batch.Batches[0].Component2).Data); Assert.Equal(finalFloat, structComponent2.Data); Assert.Equal(finalFloat, componentDatabase.Get<TestStructComponentTwo>(5, component2Allocation).Data); } [Fact] public void should_allocate_entities_correctly() { var expectedSize = 5000; var (observableGroupManager, entityDatabase, componentDatabase, componentLookup) = CreateFramework(); var collection = entityDatabase.GetCollection(); var observableGroup = observableGroupManager.GetObservableGroup(new Group(typeof(ViewComponent), typeof(TestComponentOne))); for (var i = 0; i < expectedSize; i++) { var entity = collection.CreateEntity(); entity.AddComponents(new ViewComponent(), new TestComponentOne()); } Assert.Equal(expectedSize, collection.Count); Assert.Equal(expectedSize, observableGroup.Count); var viewComponentPool = componentDatabase.GetPoolFor<ViewComponent>(componentLookup.GetComponentType(typeof(ViewComponent))); Assert.Equal(expectedSize, viewComponentPool.Components.Length); var testComponentPool = componentDatabase.GetPoolFor<TestComponentOne>(componentLookup.GetComponentType(typeof(TestComponentOne))); Assert.Equal(expectedSize, testComponentPool.Components.Length); } } }
45.124161
143
0.651446
[ "MIT" ]
Fijo/ecsrx
src/EcsRx.Tests/Sanity/SanityTests.cs
13,449
C#
// <auto-generated> // 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 FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p2.Pisp.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for /// OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum { [EnumMember(Value = "BillPayment")] BillPayment, [EnumMember(Value = "ContactlessTravel")] ContactlessTravel, [EnumMember(Value = "EcommerceGoods")] EcommerceGoods, [EnumMember(Value = "EcommerceServices")] EcommerceServices, [EnumMember(Value = "Kiosk")] Kiosk, [EnumMember(Value = "Parking")] Parking, [EnumMember(Value = "PartyToParty")] PartyToParty } internal static class OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnumEnumExtension { internal static string ToSerializedValue(this OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum? value) { return value == null ? null : ((OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum)value).ToSerializedValue(); } internal static string ToSerializedValue(this OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum value) { switch( value ) { case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.BillPayment: return "BillPayment"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.ContactlessTravel: return "ContactlessTravel"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.EcommerceGoods: return "EcommerceGoods"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.EcommerceServices: return "EcommerceServices"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.Kiosk: return "Kiosk"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.Parking: return "Parking"; case OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.PartyToParty: return "PartyToParty"; } return null; } internal static OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum? ParseOBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum(this string value) { switch( value ) { case "BillPayment": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.BillPayment; case "ContactlessTravel": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.ContactlessTravel; case "EcommerceGoods": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.EcommerceGoods; case "EcommerceServices": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.EcommerceServices; case "Kiosk": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.Kiosk; case "Parking": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.Parking; case "PartyToParty": return OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.PartyToParty; } return null; } } }
48.693182
198
0.700817
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p2/Pisp/Models/OBWriteFileConsentResponse3DataSCASupportDataRequestedSCAExemptionTypeEnum.cs
4,285
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xunit.Sdk; namespace Spectre.Console.Tests { public sealed class EmbeddedResourceDataAttribute : DataAttribute { private readonly string _args; public EmbeddedResourceDataAttribute(string args) { _args = args ?? throw new ArgumentNullException(nameof(args)); } public override IEnumerable<object[]> GetData(MethodInfo testMethod) { var result = new object[1]; result[0] = ReadManifestData(_args); return new[] { result }; } public static string ReadManifestData(string resourceName) { if (resourceName is null) { throw new ArgumentNullException(nameof(resourceName)); } using (var stream = ResourceReader.LoadResourceStream(resourceName)) { if (stream == null) { throw new InvalidOperationException("Could not load manifest resource stream."); } using (var reader = new StreamReader(stream)) { return reader.ReadToEnd().NormalizeLineEndings(); } } } } }
28.085106
100
0.564394
[ "MIT" ]
PrinceSumberia/spectre.console
src/Spectre.Console.Tests/EmbeddedResourceDataAttribute.cs
1,320
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SaveFileService.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if !XAMARIN && !XAMARIN_FORMS namespace Catel.Services { using Logging; /// <summary> /// Service to save files. /// </summary> public partial class SaveFileService : FileServiceBase, ISaveFileService { private static readonly ILog Log = LogManager.GetCurrentClassLogger(); } } #endif
33.272727
120
0.460383
[ "MIT" ]
14632791/Catel
src/Catel.MVVM/Services/SaveFileService.cs
734
C#
/* Copyright © 2019 Lee Kelleher. * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System.Collections.Generic; using Newtonsoft.Json.Linq; #if NET472 using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Strings; using UmbConstants = Umbraco.Core.Constants; #else using Umbraco.Cms.Core; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Extensions; using UmbConstants = Umbraco.Cms.Core.Constants; #endif namespace Umbraco.Community.Contentment.DataEditors { public sealed class DataListDataEditor : IDataEditor { internal const string DataEditorAlias = Constants.Internals.DataEditorAliasPrefix + "DataList"; internal const string DataEditorName = Constants.Internals.DataEditorNamePrefix + "Data List"; internal const string DataEditorViewPath = Constants.Internals.EmptyEditorViewPath; internal const string DataEditorPreviewViewPath = Constants.Internals.EditorsPathRoot + "data-list.preview.html"; internal const string DataEditorListEditorViewPath = Constants.Internals.EditorsPathRoot + "data-list.editor.html"; internal const string DataEditorDataSourcePreviewViewPath = Constants.Internals.EditorsPathRoot + "data-source.preview.html"; internal const string DataEditorIcon = "icon-fa fa-list-ul"; private readonly ConfigurationEditorUtility _utility; private readonly IShortStringHelper _shortStringHelper; private readonly IIOHelper _ioHelper; #if NET472 public DataListDataEditor( ConfigurationEditorUtility utility, IShortStringHelper shortStringHelper, IIOHelper ioHelper) { _utility = utility; _shortStringHelper = shortStringHelper; _ioHelper = ioHelper; } #else private readonly ILocalizedTextService _localizedTextService; private readonly IJsonSerializer _jsonSerializer; public DataListDataEditor( ILocalizedTextService localizedTextService, IShortStringHelper shortStringHelper, IJsonSerializer jsonSerializer, ConfigurationEditorUtility utility, IIOHelper ioHelper) { _localizedTextService = localizedTextService; _shortStringHelper = shortStringHelper; _jsonSerializer = jsonSerializer; _utility = utility; _ioHelper = ioHelper; } #endif public string Alias => DataEditorAlias; public EditorType Type => EditorType.PropertyValue; public string Name => DataEditorName; public string Icon => DataEditorIcon; public string Group => UmbConstants.PropertyEditors.Groups.Lists; public bool IsDeprecated => false; public IDictionary<string, object> DefaultConfiguration => new Dictionary<string, object>(); public IPropertyIndexValueFactory PropertyIndexValueFactory => new DefaultPropertyIndexValueFactory(); public IConfigurationEditor GetConfigurationEditor() => new DataListConfigurationEditor(_utility, _shortStringHelper, _ioHelper); public IDataValueEditor GetValueEditor() { #if NET472 return new DataValueEditor #else return new DataValueEditor(_localizedTextService, _shortStringHelper, _jsonSerializer) #endif { ValueType = ValueTypes.Json, View = _ioHelper.ResolveRelativeOrVirtualUrl(DataEditorViewPath), }; } public IDataValueEditor GetValueEditor(object configuration) { var view = default(string); if (configuration is Dictionary<string, object> config && config.TryGetValueAs(DataListConfigurationEditor.ListEditor, out JArray array) == true && array.Count > 0 && array[0] is JObject item) { // NOTE: Patches a breaking-change. I'd renamed `type` to become `key`. [LK:2020-04-03] if (item.ContainsKey("key") == false && item.ContainsKey("type") == true) { item.Add("key", item["type"]); item.Remove("type"); } var editor = _utility.GetConfigurationEditor<IDataListEditor>(item.Value<string>("key")); if (editor != null) { view = editor.View; } } #if NET472 return new DataValueEditor #else return new DataValueEditor(_localizedTextService, _shortStringHelper, _jsonSerializer) #endif { Configuration = configuration, ValueType = ValueTypes.Json, View = _ioHelper.ResolveRelativeOrVirtualUrl(view ?? DataEditorViewPath), }; } } }
37.817518
137
0.666667
[ "MPL-2.0" ]
zahertalab/umbraco-contentment
src/Umbraco.Community.Contentment/DataEditors/DataList/DataListDataEditor.cs
5,184
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Types.Models { using System; using ServiceStack.DataAnnotations; using YAF.Types.Interfaces; using YAF.Types.Interfaces.Data; /// <summary> /// The Banned Email Table /// </summary> [Serializable] [UniqueConstraint(nameof(BoardID), nameof(Mask))] public class BannedEmail : IEntity, IHaveID, IHaveBoardID { #region Properties /// <summary> /// Gets or sets the id. /// </summary> [AutoIncrement] [Alias("ID")] public int ID { get; set; } /// <summary> /// Gets BoardId. /// </summary> [References(typeof(Board))] [Required] public int BoardID { get; set; } [Required] [StringLength(255)] public string Mask { get; set; } /// <summary> /// Gets or sets the since. /// </summary> /// <value> /// The since. /// </value> [Required] public DateTime Since { get; set; } /// <summary> /// Gets or sets the reason. /// </summary> /// <value> /// The reason. /// </value> [StringLength(128)] public string Reason { get; set; } #endregion } }
29.2
64
0.589041
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/YAF.Types/Models/BannedEmail.cs
2,260
C#
using System.Windows.Forms; namespace DSIS.UI.Controls { public class ControlWithLayout2 : IControlWithLayout2 { private readonly Control myControl; private readonly string myAncor; private readonly Layout[] myLayout; public ControlWithLayout2(Control control, string ancor, params Layout[] layout) { myControl = control; myAncor = ancor; myLayout = layout; } public Layout[] Float { get { return myLayout; } } public string Ancor { get { return myAncor; } } public Control Control { get { return myControl; } } } }
19.818182
85
0.605505
[ "Apache-2.0" ]
jonnyzzz/phd-project
dsis/src/UIs/UI.Controls/src/ControlWithLayout2.cs
654
C#
using System; using Microsoft.Extensions.DependencyInjection; namespace Prism.Ioc { public interface IServiceCollectionAware { void Populate(IServiceCollection services); IServiceProvider CreateServiceProvider(); } }
20.583333
51
0.744939
[ "MIT" ]
GTX-ABEL/Prism.Maui
src/Prism.Maui/Ioc/IServiceCollectionAware.cs
249
C#
namespace Swarmops.Common.Enums { public enum FinancialValidationType { /// <summary> /// Unknown type. /// </summary> Unknown = 0, /// <summary> /// An approval of an expenditure from a budget. /// </summary> Approval, /// <summary> /// Removal of approved status. /// </summary> UndoApproval, /// <summary> /// Validation of expenditure documents. /// </summary> Validation, /// <summary> /// Removal of validated status. /// </summary> UndoValidation, /// <summary> /// Kill: close this financial doc as not valid. /// </summary> Kill } }
22.114286
60
0.4677
[ "Unlicense" ]
Swarmops/Swarmops
Common/Enums/FinancialValidationType.cs
774
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Permissions { #if NET5_0_OR_GREATER [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif [Flags] public enum TypeDescriptorPermissionFlags { NoFlags = 0, RestrictedRegistrationAccess = 1, } }
30.625
147
0.755102
[ "MIT" ]
333fred/runtime
src/libraries/System.Security.Permissions/src/System/Security/Permissions/TypeDescriptorPermissionFlags.cs
490
C#