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
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. namespace Stride.Core.MicroThreading { public enum ScheduleMode { First, Last, } }
30.363636
118
0.703593
[ "MIT" ]
Aggror/Stride
sources/core/Stride.Core.MicroThreading/ScheduleMode.cs
334
C#
using System.Threading.Tasks; namespace Dime.Scheduler.Sdk { public interface IEndpointBuilder<T> where T : IEndpoint { Task<T> Request(); } }
18.222222
60
0.664634
[ "MIT" ]
dime-scheduler/sdk-dotnet
src/core/Factory/Contracts/IEndpointBuilder.cs
166
C#
using System.Threading.Tasks; using MariCommands.Results; namespace MariCommands { /// <summary> /// A builder callback to executors use to execute a command. /// </summary> /// <param name="module">The module instance.</param> /// <param name="args">The arguments of this command.</param> /// <returns>A <see cref="Task" /> representing an asynchronous operation /// with an <see cref="IResult" />.</returns> public delegate Task<IResult> CommandCallback(object module, object[] args); }
37.214286
80
0.679463
[ "MIT" ]
MariBotOfficial/MariCommands
MariCommands/Models/Commands/CommandCallback.cs
521
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; namespace WCFServiceWebRole { public class WebRole : RoleEntryPoint { public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. return base.OnStart(); } } }
24.52381
83
0.68932
[ "Apache-2.0" ]
khalilme/HopeSystemUniversal
WCFServiceWebRole1/WebRole.cs
515
C#
using System; using Volo.Abp; namespace EasyAbp.PaymentService.Payments { public class AnotherRefundIsInProgressException : BusinessException { public AnotherRefundIsInProgressException(Guid paymentId) : base("AnotherRefundIsInProgress", $"There is another refund with the same payment ({paymentId}) in progress.") { } } }
28.615385
101
0.704301
[ "MIT" ]
EasyAbp/PaymentService
modules/EasyAbp.PaymentService/src/EasyAbp.PaymentService.Domain/EasyAbp/PaymentService/Payments/AnotherRefundIsInProgressException.cs
374
C#
using System; using System.Diagnostics; using System.Reflection; using PostSharp.Reflection; namespace Bluehands.Repository.Diagnostics.Log.Aspects.LogFactory { [Serializable] [DebuggerNonUserCode] internal class LogFactoryFromLog : LogFactoryBase { internal LogFactoryFromLog(MethodBase method, LocationInfo member) : base(method, member) { } protected sealed override Bluehands.Diagnostics.LogExtensions.Log CreateLog(object instance) { var member = Member.GetValue(instance) as Bluehands.Diagnostics.LogExtensions.Log; return member; } } }
24
94
0.78125
[ "MIT" ]
bluehands/Log-Extensions
03 Code/Source/Bluehands.Diagnostics.LogExtensions.Aspects/LogFactory/LogFactoryFromLog.cs
578
C#
namespace ShoppingApp.Web.Areas.Identity.Pages.Account.Manage { using System.Threading.Tasks; using ShoppingApp.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; #pragma warning disable SA1649 // File name should match first type name public class ResetAuthenticatorModel : PageModel #pragma warning restore SA1649 // File name should match first type name { private readonly UserManager<ApplicationUser> userManager; private readonly SignInManager<ApplicationUser> signInManager; private readonly ILogger<ResetAuthenticatorModel> logger; public ResetAuthenticatorModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<ResetAuthenticatorModel> logger) { this.userManager = userManager; this.signInManager = signInManager; this.logger = logger; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGet() { var user = await this.userManager.GetUserAsync(this.User); if (user == null) { return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'."); } return this.Page(); } public async Task<IActionResult> OnPostAsync() { var user = await this.userManager.GetUserAsync(this.User); if (user == null) { return this.NotFound($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'."); } await this.userManager.SetTwoFactorEnabledAsync(user, false); await this.userManager.ResetAuthenticatorKeyAsync(user); this.logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id); await this.signInManager.RefreshSignInAsync(user); this.StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key."; return this.RedirectToPage("./EnableAuthenticator"); } } }
37.15873
147
0.651431
[ "MIT" ]
mariyast1/ShoppingApp
src/Web/ShoppingApp.Web/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml.cs
2,343
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("EntityFrameworkCore.RelationalProviderStarter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EntityFrameworkCore.RelationalProviderStarter")] [assembly: AssemblyCopyright("Copyright \u00A9 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("b0985182-afe8-47a9-990d-43b7021d1e38")] // 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")]
36.717949
84
0.751397
[ "Apache-2.0" ]
Ashrafnet/EntityFramework.Docs
samples/core/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Properties/AssemblyInfo.cs
1,434
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("MinimalisticTelnet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Core bvba")] [assembly: AssemblyProduct("MinimalisticTelnet")] [assembly: AssemblyCopyright("Copyright © Core bvba 2007")] [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("e2093aab-28f4-4145-8296-a79322516fb6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.235294
84
0.755134
[ "Apache-2.0" ]
BogatenkoMaxim/mantis-tests
MinimalisticTelnet/MinimalisticTelnet/MinimalisticTelnet/Properties/AssemblyInfo.cs
1,269
C#
// // System.Drawing.PrintRange.cs // // (C) 2002 Ximian, Inc. http://www.ximian.com // Author: Dennis Hayes (dennish@raytek.com) // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace System.Drawing.Printing { [Serializable] public enum PrintRange { AllPages = 0, Selection = 1, SomePages = 2, CurrentPage = 0x400000 } }
35.731707
73
0.733106
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.Drawing/System.Drawing.Printing/PrintRange.cs
1,465
C#
using Common.Wpf.Extensions; using System.Windows; namespace SystemTemperatureStatusWindow.Options { public partial class GeneralOptionsPanel { public GeneralOptionsPanel() { InitializeComponent(); } public override void LoadPanel(object data) { base.LoadPanel(data); var settings = Properties.Settings.Default; StartWithWindows.IsChecked = settings.AutoStart; } public override bool ValidatePanel() { return true; } public override void SavePanel() { var settings = Properties.Settings.Default; if (StartWithWindows.IsChecked.HasValue && settings.AutoStart != StartWithWindows.IsChecked.Value) settings.AutoStart = StartWithWindows.IsChecked.Value; Application.Current.SetStartWithWindows(settings.AutoStart); } public override string CategoryName => Properties.Resources.OptionCategory_General; } }
25.975
110
0.635226
[ "MIT" ]
ckaczor/SystemTemperatureStatusWindow
Window/Options/GeneralOptionsPanel.xaml.cs
1,041
C#
using UnityEngine; using UnityEngine.UI; using Lean.Common; #if UNITY_EDITOR using UnityEditor; #endif namespace Lean.Gui { /// <summary>This componenent allows you to change a UI element's hitbox to use its graphic Image opacity/alpha.</summary> [ExecuteInEditMode] [RequireComponent(typeof(Image))] [HelpURL(LeanGui.HelpUrlPrefix + "LeanHitbox")] [AddComponentMenu(LeanGui.ComponentMenuPrefix + "Hitbox")] public class LeanHitbox : MonoBehaviour { /// <summary>The alpha threshold specifies the minimum alpha a pixel must have for the event to be considered a "hit" on the Image.</summary> public float Threshold { set { threshold = value; UpdateThreshold(); } get { return threshold; } } [SerializeField] private float threshold = 0.5f; [System.NonSerialized] private Image cachedImage; [System.NonSerialized] private bool cachedImageSet; public Image CachedImage { get { if (cachedImageSet == false) { cachedImage = GetComponent<Image>(); cachedImageSet = true; } return cachedImage; } } public void UpdateThreshold() { CachedImage.alphaHitTestMinimumThreshold = threshold; } protected virtual void Start() { UpdateThreshold(); } } } #if UNITY_EDITOR namespace Lean.Gui { [CanEditMultipleObjects] [CustomEditor(typeof(LeanHitbox))] public class LeanHitbox_Inspector : LeanInspector<LeanHitbox> { protected override void DrawInspector() { if (Draw("threshold", "The alpha threshold specifies the minimum alpha a pixel must have for the event to be considered a 'hit' on the Image.") == true) { Each(t => t.UpdateThreshold(), true); } } } } #endif
24.470588
155
0.716947
[ "MIT" ]
DrScatman/vr-mod
Assets/Lean/GUI/Scripts/LeanHitbox.cs
1,666
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. namespace SharpVk.NVidia { /// <summary> /// /// </summary> [System.Flags] public enum GeometryFlags { /// <summary> /// /// </summary> None = 0, /// <summary> /// /// </summary> Opaque = 1 << 0, /// <summary> /// /// </summary> NoDuplicateAnyHitInvocation = 1 << 1, } }
33.816327
81
0.662643
[ "MIT" ]
FacticiusVir/SharpVk
src/SharpVk/NVidia/GeometryFlags.gen.cs
1,657
C#
namespace SoftUniEF.Data { using System; using System.Collections.Generic; public class Employee { public int EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string MiddleName { get; set; } public string JobTitle { get; set; } public int DepartmentId { get; set; } public int? ManagerId { get; set; } public DateTime HireDate { get; set; } public decimal Salary { get; set; } public int? AddressId { get; set; } public virtual Address Address { get; set; } public virtual Department Department { get; set; } public virtual Employee Manager { get; set; } public virtual ICollection<Department> Departments { get; set; } = new HashSet<Department>(); public virtual ICollection<EmployeeProject> EmployeesProjects { get; set; } = new HashSet<EmployeeProject>(); public virtual ICollection<Employee> Managers { get; set; } = new HashSet<Employee>(); } }
26.170732
117
0.623486
[ "MIT" ]
stanislavstoyanov99/SoftUni-Software-Engineering
DB-with-C#/Labs-And-Homeworks/Entity Framework Core/03. Entity Framework Introduction - Lab/SoftUniEF/SoftUniEF/Data/Employee.cs
1,075
C#
global using BasicGameFrameworkLibrary.BasicGameDataClasses; global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.BasicExtensions; global using CommonBasicLibraries.BasicDataSettingsAndProcesses; global using static CommonBasicLibraries.BasicDataSettingsAndProcesses.BasicDataFunctions; global using CommonBasicLibraries.CollectionClasses; global using fs = CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.JsonSerializers.FileHelpers; global using js = CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.JsonSerializers.SystemTextJsonStrings; //just in case i need those 2. global using BasicGameFrameworkLibrary.CommonInterfaces; global using KismetCP.Data; global using BasicGameFrameworkLibrary.BasicEventModels; global using BasicGameFrameworkLibrary.DIContainers; global using MessengingHelpers; global using CommonBasicLibraries.BasicUIProcesses; global using BasicGameFrameworkLibrary.CommandClasses; global using BasicGameFrameworkLibrary.ViewModels; global using BasicGameFrameworkLibrary.ViewModelInterfaces; global using MVVMFramework.ViewModels; global using KismetCP.Logic; global using BasicGameFrameworkLibrary.MiscProcesses; global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.MapHelpers; global using BasicGameFrameworkLibrary.MultiplayerClasses.BasicPlayerClasses; global using BasicGameFrameworkLibrary.MultiplayerClasses.SavedGameClasses; global using BasicGameFrameworkLibrary.MultiplayerClasses.GameContainers; global using BasicGameFrameworkLibrary.TestUtilities; global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.RandomGenerator; global using BasicGameFrameworkLibrary.MultiplayerClasses.MainViewModels; global using BasicGameFrameworkLibrary.MultiplayerClasses.InterfaceModels; global using GamePackageSerializeGenerator; global using BasicGameFrameworkLibrary.SourceGeneratorHelperClasses; global using BasicGameFrameworkLibrary.MultiplayerClasses.BasicGameClasses; global using BasicGameFrameworkLibrary.MultiplayerClasses.Extensions; global using BasicGameFrameworkLibrary.MultiplayerClasses.InterfaceMessages; global using BasicGameFrameworkLibrary.Dice; global using cs = CommonBasicLibraries.BasicDataSettingsAndProcesses.SColorString; global using BasicGameFrameworkLibrary.SpecializedGameTypes.YahtzeeStyleHelpers.Containers; global using BasicGameFrameworkLibrary.SpecializedGameTypes.YahtzeeStyleHelpers.Data; global using BasicGameFrameworkLibrary.SpecializedGameTypes.YahtzeeStyleHelpers.Logic;
67.72973
145
0.910215
[ "MIT" ]
musictopia2/GamingPackXV3
CP/Games/KismetCP/GlobalUsings.cs
2,506
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PFRCenterGlobal.Helpers; using PFRCenterGlobal.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace PFRCenterGlobal.Views.Register { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Register1Page : ContentPage { public Register1Page() { InitializeComponent(); BindingContext = O2.ToolKit.Core.O2Store.CreateOrGet<RegisterViewModel>(); NavigationCommander.Navigation = this.Navigation; } private void OnLabelTapped(object sender, EventArgs e) { throw new NotImplementedException(); } } }
27.142857
86
0.701316
[ "MIT" ]
AlbusaOxyuranus/pfr-center-global
source/PFRCenterGlobal/Views/Register/Register1Page.xaml.cs
760
C#
// TODO Interaktywne elementy w aplikacji (wizualnie) // TODO Checkbox auto startu w menu // TODO Opcja autostartu // TODO Animacja koloru poprawić wydajność // TODO Dodać przywracanie domyślnych ustawień wszystkim widgetom. // TODO Ujednolicuić przywracanie domyślnych. // TODO Dodać skróty klawiszowe. // TODO Nowe Widgety: kalkulator, mikser głośności, detektor klawiszy // TODO Przechwytywanie aplikacji takich jak: Spotify, Discord // TODO Przechwytywanie stron internetowych takich jak: Youtube, Facebook, Messangare // TODO Dodać samouczek
34.4375
85
0.796733
[ "MIT" ]
BlokerX/GameAssistant
TODOList.cs
565
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.Management.Storage.Models; namespace Azure.Management.Storage { internal partial class QueueServicesRestClient { private string subscriptionId; private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of QueueServicesRestClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> This occurs when one of the required arguments is null. </exception> public QueueServicesRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2019-06-01") { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } endpoint ??= new Uri("https://management.azure.com"); if (apiVersion == null) { throw new ArgumentNullException(nameof(apiVersion)); } this.subscriptionId = subscriptionId; this.endpoint = endpoint; this.apiVersion = apiVersion; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateListRequest(string resourceGroupName, string accountName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/queueServices", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; return message; } /// <summary> List all queue services for the storage account. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async ValueTask<Response<ListQueueServices>> ListAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } using var message = CreateListRequest(resourceGroupName, accountName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ListQueueServices value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = ListQueueServices.DeserializeListQueueServices(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> List all queue services for the storage account. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<ListQueueServices> List(string resourceGroupName, string accountName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } using var message = CreateListRequest(resourceGroupName, accountName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ListQueueServices value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = ListQueueServices.DeserializeListQueueServices(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateSetServicePropertiesRequest(string resourceGroupName, string accountName, QueueServiceProperties parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/queueServices/", false); uri.AppendPath("default", true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Content-Type", "application/json"); using var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; return message; } /// <summary> Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="parameters"> The properties of a storage account’s Queue service, only properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules can be specified. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async ValueTask<Response<QueueServiceProperties>> SetServicePropertiesAsync(string resourceGroupName, string accountName, QueueServiceProperties parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateSetServicePropertiesRequest(resourceGroupName, accountName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { QueueServiceProperties value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = QueueServiceProperties.DeserializeQueueServiceProperties(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="parameters"> The properties of a storage account’s Queue service, only properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules can be specified. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<QueueServiceProperties> SetServiceProperties(string resourceGroupName, string accountName, QueueServiceProperties parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateSetServicePropertiesRequest(resourceGroupName, accountName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { QueueServiceProperties value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = QueueServiceProperties.DeserializeQueueServiceProperties(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetServicePropertiesRequest(string resourceGroupName, string accountName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Storage/storageAccounts/", false); uri.AppendPath(accountName, true); uri.AppendPath("/queueServices/", false); uri.AppendPath("default", true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; return message; } /// <summary> Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async ValueTask<Response<QueueServiceProperties>> GetServicePropertiesAsync(string resourceGroupName, string accountName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } using var message = CreateGetServicePropertiesRequest(resourceGroupName, accountName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { QueueServiceProperties value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = QueueServiceProperties.DeserializeQueueServiceProperties(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. </summary> /// <param name="resourceGroupName"> The name of the resource group within the user&apos;s subscription. The name is case insensitive. </param> /// <param name="accountName"> The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<QueueServiceProperties> GetServiceProperties(string resourceGroupName, string accountName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (accountName == null) { throw new ArgumentNullException(nameof(accountName)); } using var message = CreateGetServicePropertiesRequest(resourceGroupName, accountName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { QueueServiceProperties value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); if (document.RootElement.ValueKind == JsonValueKind.Null) { value = null; } else { value = QueueServiceProperties.DeserializeQueueServiceProperties(document.RootElement); } return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
52.802817
229
0.601014
[ "MIT" ]
asarkar84/azure-sdk-for-net
sdk/storage/Azure.Management.Storage/src/Generated/QueueServicesRestClient.cs
18,757
C#
using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using SailScores.Identity.Entities; namespace SailScores.Web.Areas.Identity.Pages.Account.Manage { public class SetPasswordModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public SetPasswordModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [BindProperty] public InputModel Input { get; set; } [TempData] public string StatusMessage { get; set; } public class InputModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (hasPassword) { return RedirectToPage("./ChangePassword"); } return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword); if (!addPasswordResult.Succeeded) { foreach (var error in addPasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your password has been set."; return RedirectToPage(); } } }
32.21978
129
0.58015
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SailScores/SailScores
SailScores.Web/Areas/Identity/Pages/Account/Manage/SetPassword.cshtml.cs
2,934
C#
using System; using OpenTK.Graphics.OpenGL; public class Rectangle { Vector BottomLeft {get;set;} Vector TopRight {get;set;} Color _color = new Color(1,1,1,1); public Color Color{ get {return _color;} set {_color = value;} } public Rectangle(Vector bottomLeft, Vector topRight) { BottomLeft = bottomLeft; TopRight = topRight; } // TODO: why is this Render(), but the circle has Draw()? Consolidate to one or the other maybe? public void Render() { GL.Color3(_color.Red, _color.Green, _color.Blue); GL.Begin(PrimitiveType.LineLoop); { GL.Vertex2(BottomLeft.X, BottomLeft.Y); GL.Vertex2(BottomLeft.X, TopRight.Y); GL.Vertex2(TopRight.X, TopRight.Y); GL.Vertex2(TopRight.X, BottomLeft.Y); } GL.End(); } public bool Intersects(Point point) { if ( point.X >= BottomLeft.X && point.X <= TopRight.X && point.Y <= TopRight.Y && point.Y >= BottomLeft.Y ) { return true; } else { return false; } } }
27.093023
100
0.549356
[ "MIT" ]
hey-tack/babies-first-game-engine
Rectangle.cs
1,165
C#
using System; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.AsyncWork; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Consensus.Validators; using Stratis.Bitcoin.Features.Miner; using Stratis.Bitcoin.Features.PoA.Voting; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.Utilities; namespace Stratis.Bitcoin.Features.PoA.IntegrationTests.Common { public class TestPoAMiner : PoAMiner { private readonly EditableTimeProvider timeProvider; private CancellationTokenSource cancellation; private readonly ISlotsManager slotsManager; private readonly IConsensusManager consensusManager; private readonly IFederationManager federationManager; public TestPoAMiner( IConsensusManager consensusManager, IDateTimeProvider dateTimeProvider, Network network, INodeLifetime nodeLifetime, ILoggerFactory loggerFactory, IInitialBlockDownloadState ibdState, BlockDefinition blockDefinition, ISlotsManager slotsManager, IConnectionManager connectionManager, PoABlockHeaderValidator poaHeaderValidator, IFederationManager federationManager, IIntegrityValidator integrityValidator, IWalletManager walletManager, INodeStats nodeStats, VotingManager votingManager, PoAMinerSettings poAMinerSettings, IAsyncProvider asyncProvider) : base(consensusManager, dateTimeProvider, network, nodeLifetime, loggerFactory, ibdState, blockDefinition, slotsManager, connectionManager, poaHeaderValidator, federationManager, integrityValidator, walletManager, nodeStats, votingManager, poAMinerSettings, asyncProvider) { this.timeProvider = dateTimeProvider as EditableTimeProvider; this.cancellation = new CancellationTokenSource(); this.slotsManager = slotsManager; this.consensusManager = consensusManager; this.federationManager = federationManager; } public override void InitializeMining() { } public async Task MineBlocksAsync(int count) { for (int i = 0; i < count; i++) { this.timeProvider.AdjustedTimeOffset += TimeSpan.FromSeconds( this.slotsManager.GetRoundLengthSeconds(this.federationManager.GetFederationMembers().Count)); uint timeNow = (uint)this.timeProvider.GetAdjustedTimeAsUnixTimestamp(); uint myTimestamp = this.slotsManager.GetMiningTimestamp(timeNow); this.timeProvider.AdjustedTimeOffset += TimeSpan.FromSeconds(myTimestamp - timeNow); ChainedHeader chainedHeader = await this.MineBlockAtTimestampAsync(myTimestamp).ConfigureAwait(false); if (chainedHeader == null) { i--; this.timeProvider.AdjustedTimeOffset += TimeSpan.FromHours(1); continue; } var builder = new StringBuilder(); builder.AppendLine("<<==============================================================>>"); builder.AppendLine($"Block was mined {chainedHeader}."); builder.AppendLine("<<==============================================================>>"); this.logger.LogInformation(builder.ToString()); } } public override void Dispose() { this.cancellation.Cancel(); base.Dispose(); } } }
38
167
0.639396
[ "MIT" ]
AI-For-Rural/EXOSFullNode
src/Stratis.Bitcoin.Features.PoA.IntegrationTests.Common/TestPoAMiner.cs
3,840
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace DFC.App.JobProfiles.HowToBecome.FunctionalTests.Model.APIResponse { public class HowToBecomeAPIResponse { [JsonProperty("entryRouteSummary")] public List<string> EntryRouteSummary { get; set; } [JsonProperty("entryRoutes")] public EntryRoutes EntryRoutes { get; set; } [JsonProperty("moreInformation")] public MoreInformation MoreInformation { get; set; } } }
27.277778
75
0.698574
[ "MIT" ]
SkillsFundingAgency/dfc-app-howtobecome
DFC.App.JobProfiles.HowToBecome.FunctionalTests/Model/APIResponse/HowToBecomeAPIResponse.cs
493
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using Aliencube.AzureFunctions.Extensions.OpenApi.Attributes; using ApiExampleProject.Authentication.Interfaces; using ApiExampleProject.Common.Constants; using ApiExampleProject.Common.Interfaces; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Microsoft.Graph; using Microsoft.OpenApi.Models; using PolicyManager.DataAccess.Interfaces; using PolicyManager.DataAccess.Models; using PolicyManager.Resources; using PolicyManager.Validators; namespace PolicyManager { public class CheckAccessFunctions { private readonly ITokenValidator tokenValidator; private readonly IJsonHttpContentValidator jsonHttpContentValidator; private readonly IMicrosoftGraphRepository microsoftGraphRepository; private readonly IAuthorizationRepository authorizationRepository; public CheckAccessFunctions(ITokenValidator tokenValidator, IJsonHttpContentValidator jsonHttpContentValidator, IMicrosoftGraphRepository microsoftGraphRepository, IAuthorizationRepository authorizationRepository) { this.tokenValidator = tokenValidator ?? throw new ArgumentNullException(nameof(tokenValidator)); this.jsonHttpContentValidator = jsonHttpContentValidator ?? throw new ArgumentNullException(nameof(jsonHttpContentValidator)); this.microsoftGraphRepository = microsoftGraphRepository ?? throw new ArgumentNullException(nameof(microsoftGraphRepository)); this.authorizationRepository = authorizationRepository ?? throw new ArgumentNullException(nameof(authorizationRepository)); } [FunctionName(nameof(CheckAccess))] [OpenApiOperation(nameof(CheckAccess), "Check Access", Description = "Checks access to a resource.")] [OpenApiParameter("Authorization", In = ParameterLocation.Header, Required = true, Type = typeof(string))] [OpenApiRequestBody(ContentTypes.Application.Json, typeof(IEnumerable<PolicyResult>), Description = "The new environment object.")] [OpenApiResponseBody(HttpStatusCode.Created, ContentTypes.Application.Json, typeof(IEnumerable<PolicyResult>))] [OpenApiResponseBody(HttpStatusCode.BadRequest, ContentTypes.TextType.Plain, typeof(string))] public async Task<HttpResponseMessage> CheckAccess([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "checkAccess")] HttpRequestMessage req, ILogger log) { _ = req ?? throw new ArgumentNullException(nameof(req)); log.LogInformation(PolicyManagerResources.CheckAccessStartLog); var claimsPrincipal = await tokenValidator.ValidateTokenAsync(req.Headers.Authorization); if (claimsPrincipal == null) return new HttpResponseMessage(HttpStatusCode.Unauthorized); var jsonValidationResult = await jsonHttpContentValidator.ValidateJsonAsync<CheckAccessRequest, CheckAccessRequestValidator>(req.Content); if (!jsonValidationResult.IsValid) { return jsonValidationResult.Message; } var groups = await microsoftGraphRepository.FetchMyGroupsAsync(req.Headers.Authorization); var initialState = new InitialState<Group>() { ClaimsPrincipal = claimsPrincipal, Identifier = jsonValidationResult.Item.RequestIdentifier, Groups = groups, }; var policyResults = await authorizationRepository.EvaluateAsync(req.Headers.Authorization, initialState); log.LogInformation(PolicyManagerResources.CheckAccessEndLog); var content = new StringContent(JsonSerializer.Serialize(policyResults), Encoding.UTF8, ContentTypes.Application.Json); return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; } } }
52.881579
221
0.755163
[ "MIT" ]
jwendl/authorization-service-example
src/Authorization/PolicyManager/CheckAccessFunctions.cs
4,021
C#
#region copyright // MIT License // // Copyright (c) 2019 Smint.io GmbH // // 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 (including the next paragraph) 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. // // SPDX-License-Identifier: MIT #endregion using IdentityModel.OidcClient.Browser; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SmintIo.CLAPI.Consumer.Integration.Core.Authenticator.Browser { /// <summary> /// https://github.com/IdentityModel/IdentityModel.OidcClient.Samples/blob/master/NetCoreConsoleClient/src/NetCoreConsoleClient/SystemBrowser.cs /// </summary> public class SystemBrowser : IBrowser { public int Port { get; } private readonly string _path; public SystemBrowser(int? port = null, string path = null) { _path = path; if (!port.HasValue) { Port = GetRandomUnusedPort(); } else { Port = port.Value; } } private int GetRandomUnusedPort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } public async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { using (var listener = new LoopbackHttpListener(Port, _path)) { OpenBrowser(options.StartUrl); try { var result = await listener.WaitForCallbackAsync(); if (string.IsNullOrWhiteSpace(result)) { return new BrowserResult { ResultType = BrowserResultType.UnknownError, Error = "Empty response" }; } return new BrowserResult { Response = result, ResultType = BrowserResultType.Success }; } catch (TaskCanceledException ex) { return new BrowserResult { ResultType = BrowserResultType.Timeout, Error = ex.Message }; } catch (Exception ex) { return new BrowserResult { ResultType = BrowserResultType.UnknownError, Error = ex.Message }; } } } public static void OpenBrowser(string url) { try { Process.Start(url); } catch { // hack because of this: https://github.com/dotnet/corefx/issues/10361 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Process.Start("xdg-open", url); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Process.Start("open", url); } else { throw; } } } } public class LoopbackHttpListener : IDisposable { const int DefaultTimeout = 60 * 5; // 5 mins (in seconds) IWebHost _host; TaskCompletionSource<string> _source = new TaskCompletionSource<string>(); string _url; public string Url => _url; public LoopbackHttpListener(int port, string path = null) { path = path ?? String.Empty; if (path.StartsWith("/")) path = path.Substring(1); _url = $"http://127.0.0.1:{port}/{path}"; _host = new WebHostBuilder() .UseKestrel() .UseUrls(_url) .Configure(Configure) .Build(); _host.Start(); } public void Dispose() { #pragma warning disable VSTHRD110 // Observe result of async calls Task.Run(async () => #pragma warning restore VSTHRD110 // Observe result of async calls { await Task.Delay(500); _host.Dispose(); }); } void Configure(IApplicationBuilder app) { app.Run(async ctx => { if (ctx.Request.Method == "GET") { await SetResultAsync(ctx.Request.QueryString.Value, ctx); } else if (ctx.Request.Method == "POST") { if (!ctx.Request.ContentType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { ctx.Response.StatusCode = 415; } else { using (var sr = new StreamReader(ctx.Request.Body, Encoding.UTF8)) { var body = await sr.ReadToEndAsync(); await SetResultAsync(body, ctx); } } } else { ctx.Response.StatusCode = 405; } }); } private async Task SetResultAsync(string value, HttpContext ctx) { try { ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/html"; await ctx.Response.WriteAsync("<h1>You can now return to the application.</h1>"); await ctx.Response.Body.FlushAsync(); _source.TrySetResult(value); } catch { ctx.Response.StatusCode = 400; ctx.Response.ContentType = "text/html"; await ctx.Response.WriteAsync("<h1>Invalid request.</h1>"); await ctx.Response.Body.FlushAsync(); } } public Task<string> WaitForCallbackAsync(int timeoutInSeconds = DefaultTimeout) { #pragma warning disable VSTHRD110 // Observe result of async calls Task.Run(async () => #pragma warning restore VSTHRD110 // Observe result of async calls { await Task.Delay(timeoutInSeconds * 1000); _source.TrySetCanceled(); }); return _source.Task; } } }
31.862069
148
0.518038
[ "MIT" ]
smintio/CLAPI-C-Integration-Core
NetCore/Authenticator/Browser/SystemBrowser.cs
8,318
C#
namespace Webbrowser { partial class WebForm { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置受控資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改 /// 這個方法的內容。 /// </summary> private void InitializeComponent() { this.Main_Web = new System.Windows.Forms.WebBrowser(); this.Url_Textbox = new System.Windows.Forms.TextBox(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.Web_Menu1 = new System.Windows.Forms.ToolStripMenuItem(); this.返回搜尋頁面 = new System.Windows.Forms.ToolStripMenuItem(); this.返回主頁 = new System.Windows.Forms.ToolStripMenuItem(); this.上一頁 = new System.Windows.Forms.ToolStripMenuItem(); this.下一頁 = new System.Windows.Forms.ToolStripMenuItem(); this.額外功能 = new System.Windows.Forms.ToolStripMenuItem(); this.列印 = new System.Windows.Forms.ToolStripMenuItem(); this.重整網頁 = new System.Windows.Forms.ToolStripMenuItem(); this.停止 = new System.Windows.Forms.ToolStripMenuItem(); this.版面設定 = new System.Windows.Forms.ToolStripMenuItem(); this.列印功能表 = new System.Windows.Forms.ToolStripMenuItem(); this.列印預覽 = new System.Windows.Forms.ToolStripMenuItem(); this.內容 = new System.Windows.Forms.ToolStripMenuItem(); this.另存新檔 = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // Main_Web // this.Main_Web.Location = new System.Drawing.Point(0, 67); this.Main_Web.MinimumSize = new System.Drawing.Size(20, 20); this.Main_Web.Name = "Main_Web"; this.Main_Web.Size = new System.Drawing.Size(798, 421); this.Main_Web.TabIndex = 2; this.Main_Web.Url = new System.Uri("https://google.com", System.UriKind.Absolute); this.Main_Web.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.Main_Web_Navigated); // // Url_Textbox // this.Url_Textbox.Font = new System.Drawing.Font("標楷體", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(136))); this.Url_Textbox.Location = new System.Drawing.Point(0, 30); this.Url_Textbox.Name = "Url_Textbox"; this.Url_Textbox.Size = new System.Drawing.Size(810, 31); this.Url_Textbox.TabIndex = 4; this.Url_Textbox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Url_Textbox_KeyDown); // // menuStrip1 // this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.Web_Menu1, this.上一頁, this.下一頁, this.重整網頁, this.停止, this.額外功能}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(810, 28); this.menuStrip1.TabIndex = 5; this.menuStrip1.Text = "menuStrip1"; // // Web_Menu1 // this.Web_Menu1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.返回搜尋頁面, this.返回主頁}); this.Web_Menu1.Name = "Web_Menu1"; this.Web_Menu1.Size = new System.Drawing.Size(83, 24); this.Web_Menu1.Text = "網頁功能"; // // 返回搜尋頁面 // this.返回搜尋頁面.Name = "返回搜尋頁面"; this.返回搜尋頁面.Size = new System.Drawing.Size(224, 26); this.返回搜尋頁面.Text = "返回搜尋頁面"; this.返回搜尋頁面.Click += new System.EventHandler(this.返回搜尋頁面_Click); // // 返回主頁 // this.返回主頁.Name = "返回主頁"; this.返回主頁.Size = new System.Drawing.Size(224, 26); this.返回主頁.Text = "返回主頁"; this.返回主頁.Click += new System.EventHandler(this.返回主頁_Click); // // 上一頁 // this.上一頁.Name = "上一頁"; this.上一頁.Size = new System.Drawing.Size(68, 24); this.上一頁.Text = "上一頁"; this.上一頁.Click += new System.EventHandler(this.上一頁_Click); // // 下一頁 // this.下一頁.Name = "下一頁"; this.下一頁.Size = new System.Drawing.Size(68, 24); this.下一頁.Text = "下一頁"; this.下一頁.Click += new System.EventHandler(this.下一頁_Click); // // 額外功能 // this.額外功能.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.列印, this.版面設定, this.列印功能表, this.列印預覽, this.內容, this.另存新檔}); this.額外功能.Name = "額外功能"; this.額外功能.Size = new System.Drawing.Size(83, 24); this.額外功能.Text = "額外功能"; // // 列印 // this.列印.Name = "列印"; this.列印.Size = new System.Drawing.Size(224, 26); this.列印.Text = "列印"; this.列印.Click += new System.EventHandler(this.列印_Click); // // 重整網頁 // this.重整網頁.Name = "重整網頁"; this.重整網頁.Size = new System.Drawing.Size(83, 24); this.重整網頁.Text = "重整網頁"; this.重整網頁.Click += new System.EventHandler(this.重整網頁_Click); // // 停止 // this.停止.Name = "停止"; this.停止.Size = new System.Drawing.Size(53, 24); this.停止.Text = "停止"; this.停止.Click += new System.EventHandler(this.停止_Click); // // 版面設定 // this.版面設定.Name = "版面設定"; this.版面設定.Size = new System.Drawing.Size(224, 26); this.版面設定.Text = "版面設定"; this.版面設定.Click += new System.EventHandler(this.版面設定_Click); // // 列印功能表 // this.列印功能表.Name = "列印功能表"; this.列印功能表.Size = new System.Drawing.Size(224, 26); this.列印功能表.Text = "列印功能表"; this.列印功能表.Click += new System.EventHandler(this.列印功能表_Click); // // 列印預覽 // this.列印預覽.Name = "列印預覽"; this.列印預覽.Size = new System.Drawing.Size(224, 26); this.列印預覽.Text = "列印預覽"; this.列印預覽.Click += new System.EventHandler(this.列印預覽_Click); // // 內容 // this.內容.Name = "內容"; this.內容.Size = new System.Drawing.Size(224, 26); this.內容.Text = "內容"; this.內容.Click += new System.EventHandler(this.內容_Click); // // 另存新檔 // this.另存新檔.Name = "另存新檔"; this.另存新檔.Size = new System.Drawing.Size(224, 26); this.另存新檔.Text = "另存新檔"; this.另存新檔.Click += new System.EventHandler(this.另存新檔_Click); // // WebForm // this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(810, 500); this.Controls.Add(this.Url_Textbox); this.Controls.Add(this.Main_Web); this.Controls.Add(this.menuStrip1); this.Font = new System.Drawing.Font("標楷體", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(136))); this.MainMenuStrip = this.menuStrip1; this.Name = "WebForm"; this.Text = "WebForm"; this.MaximumSizeChanged += new System.EventHandler(this.WebForm_Resize); this.MinimumSizeChanged += new System.EventHandler(this.WebForm_Resize); this.Load += new System.EventHandler(this.WebForm_Load); this.Resize += new System.EventHandler(this.WebForm_Resize); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.WebBrowser Main_Web; private System.Windows.Forms.TextBox Url_Textbox; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem Web_Menu1; private System.Windows.Forms.ToolStripMenuItem 返回搜尋頁面; private System.Windows.Forms.ToolStripMenuItem 返回主頁; private System.Windows.Forms.ToolStripMenuItem 上一頁; private System.Windows.Forms.ToolStripMenuItem 下一頁; private System.Windows.Forms.ToolStripMenuItem 額外功能; private System.Windows.Forms.ToolStripMenuItem 列印; private System.Windows.Forms.ToolStripMenuItem 重整網頁; private System.Windows.Forms.ToolStripMenuItem 停止; private System.Windows.Forms.ToolStripMenuItem 版面設定; private System.Windows.Forms.ToolStripMenuItem 列印功能表; private System.Windows.Forms.ToolStripMenuItem 列印預覽; private System.Windows.Forms.ToolStripMenuItem 內容; private System.Windows.Forms.ToolStripMenuItem 另存新檔; } }
42.844538
154
0.542218
[ "MIT" ]
JE-Chen/je_old_repo
CSharp_Webbrowser_and_WebView2_JE/Webbrowser/Webbrowser/Form1.Designer.cs
11,407
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System.Collections.Generic; namespace BESSy.Json.Tests.TestObjects { [JsonObject(MemberSerialization.OptIn)] public class ListTestClass { [JsonProperty] public string id { get; set; } [JsonProperty] public List<ListItem> items { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class ListItem { [JsonProperty] public string id { get; set; } } }
34.717391
68
0.723857
[ "MIT" ]
thehexgod/BESSy.JSON
Src/BESSy.Json.Tests/TestObjects/ListTestClass.cs
1,597
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace TypingDashboard.Migrations { public partial class Upgraded_To_Abp_5_4_0 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits"); migrationBuilder.CreateTable( name: "AbpDynamicParameters", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ParameterName = table.Column<string>(nullable: true), InputType = table.Column<string>(nullable: true), Permission = table.Column<string>(nullable: true), TenantId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpDynamicParameters", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpDynamicParameterValues", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Value = table.Column<string>(nullable: false), TenantId = table.Column<int>(nullable: true), DynamicParameterId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpDynamicParameterValues", x => x.Id); table.ForeignKey( name: "FK_AbpDynamicParameterValues_AbpDynamicParameters_DynamicParameterId", column: x => x.DynamicParameterId, principalTable: "AbpDynamicParameters", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpEntityDynamicParameters", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), EntityFullName = table.Column<string>(nullable: true), DynamicParameterId = table.Column<int>(nullable: false), TenantId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityDynamicParameters", x => x.Id); table.ForeignKey( name: "FK_AbpEntityDynamicParameters_AbpDynamicParameters_DynamicParameterId", column: x => x.DynamicParameterId, principalTable: "AbpDynamicParameters", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpEntityDynamicParameterValues", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Value = table.Column<string>(nullable: false), EntityId = table.Column<string>(nullable: true), EntityDynamicParameterId = table.Column<int>(nullable: false), TenantId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityDynamicParameterValues", x => x.Id); table.ForeignKey( name: "FK_AbpEntityDynamicParameterValues_AbpEntityDynamicParameters_EntityDynamicParameterId", column: x => x.EntityDynamicParameterId, principalTable: "AbpEntityDynamicParameters", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits", columns: new[] { "TenantId", "Code" }, unique: true, filter: "[TenantId] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpDynamicParameters_ParameterName_TenantId", table: "AbpDynamicParameters", columns: new[] { "ParameterName", "TenantId" }, unique: true, filter: "[ParameterName] IS NOT NULL AND [TenantId] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpDynamicParameterValues_DynamicParameterId", table: "AbpDynamicParameterValues", column: "DynamicParameterId"); migrationBuilder.CreateIndex( name: "IX_AbpEntityDynamicParameters_DynamicParameterId", table: "AbpEntityDynamicParameters", column: "DynamicParameterId"); migrationBuilder.CreateIndex( name: "IX_AbpEntityDynamicParameters_EntityFullName_DynamicParameterId_TenantId", table: "AbpEntityDynamicParameters", columns: new[] { "EntityFullName", "DynamicParameterId", "TenantId" }, unique: true, filter: "[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AbpEntityDynamicParameterValues_EntityDynamicParameterId", table: "AbpEntityDynamicParameterValues", column: "EntityDynamicParameterId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AbpDynamicParameterValues"); migrationBuilder.DropTable( name: "AbpEntityDynamicParameterValues"); migrationBuilder.DropTable( name: "AbpEntityDynamicParameters"); migrationBuilder.DropTable( name: "AbpDynamicParameters"); migrationBuilder.DropIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits"); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits", columns: new[] { "TenantId", "Code" }); } } }
44.367742
119
0.537007
[ "MIT" ]
florisrobbemont/TypingDashboard
src/TypingDashboard.EntityFrameworkCore/Migrations/20200320114152_Upgraded_To_Abp_5_4_0.cs
6,879
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Microsoft.Coyote { #pragma warning disable CA1724 // Type names should not match namespaces /// <summary> /// The Coyote project configurations. /// </summary> [DataContract] [Serializable] public class Configuration { /// <summary> /// The user-specified command to perform by the Coyote tool. /// </summary> [DataMember] internal string ToolCommand; /// <summary> /// Something to add to the PATH environment at test time. /// </summary> internal string AdditionalPaths { get; set; } /// <summary> /// The output path. /// </summary> [DataMember] internal string OutputFilePath; /// <summary> /// Timeout in seconds. /// </summary> [DataMember] internal int Timeout; /// <summary> /// The current runtime generation. /// </summary> [DataMember] internal ulong RuntimeGeneration; /// <summary> /// The assembly to be analyzed for bugs. /// </summary> [DataMember] internal string AssemblyToBeAnalyzed; /// <summary> /// Test method to be used. /// </summary> [DataMember] internal string TestMethodName; /// <summary> /// The systematic testing strategy to use. /// </summary> [DataMember] public string SchedulingStrategy { get; internal set; } /// <summary> /// Number of testing iterations. /// </summary> [DataMember] public int TestingIterations { get; internal set; } /// <summary> /// Custom seed to be used by the random value generator. By default, /// this value is null indicating that no seed has been set. /// </summary> [DataMember] public uint? RandomGeneratorSeed { get; internal set; } /// <summary> /// If true, the seed will increment in each /// testing iteration. /// </summary> [DataMember] internal bool IncrementalSchedulingSeed; /// <summary> /// If true, the Coyote tester performs a full exploration, /// and does not stop when it finds a bug. /// </summary> [DataMember] internal bool PerformFullExploration; /// <summary> /// The maximum scheduling steps to explore for unfair schedulers. /// By default this is set to 10,000 steps. /// </summary> [DataMember] public int MaxUnfairSchedulingSteps { get; internal set; } /// <summary> /// The maximum scheduling steps to explore for fair schedulers. /// By default this is set to 100,000 steps. /// </summary> [DataMember] public int MaxFairSchedulingSteps { get; internal set; } /// <summary> /// True if the user has explicitly set the fair scheduling steps. /// </summary> [DataMember] internal bool UserExplicitlySetMaxFairSchedulingSteps; /// <summary> /// If true, then the Coyote tester will consider an execution /// that hits the depth bound as buggy. /// </summary> [DataMember] internal bool ConsiderDepthBoundHitAsBug; /// <summary> /// A strategy-specific bound. /// </summary> [DataMember] public int StrategyBound { get; internal set; } /// <summary> /// Value that controls the probability of triggering a timeout each time a built-in timer /// is scheduled during systematic testing. Decrease the value to increase the frequency of /// timeouts (e.g. a value of 1 corresponds to a 50% probability), or increase the value to /// decrease the frequency (e.g. a value of 10 corresponds to a 10% probability). By default /// this value is 10. /// </summary> [DataMember] public uint TimeoutDelay { get; internal set; } /// <summary> /// Safety prefix bound. By default it is 0. /// </summary> [DataMember] internal int SafetyPrefixBound; /// <summary> /// If this option is enabled, liveness checking is enabled during bug-finding. /// </summary> [DataMember] internal bool IsLivenessCheckingEnabled; /// <summary> /// The liveness temperature threshold. If it is 0 then it is disabled. By default /// this value is assigned to <see cref="MaxFairSchedulingSteps"/> / 2. /// </summary> [DataMember] public int LivenessTemperatureThreshold { get; internal set; } /// <summary> /// True if the user has explicitly set the liveness temperature threshold. /// </summary> [DataMember] internal bool UserExplicitlySetLivenessTemperatureThreshold; /// <summary> /// If this option is enabled, the tester is hashing the program state. /// </summary> [DataMember] internal bool IsProgramStateHashingEnabled; /// <summary> /// If this option is enabled, (safety) monitors are used in the production runtime. /// </summary> [DataMember] internal bool IsMonitoringEnabledInInProduction; /// <summary> /// Attaches the debugger during trace replay. /// </summary> [DataMember] internal bool AttachDebugger; /// <summary> /// The schedule file to be replayed. /// </summary> internal string ScheduleFile; /// <summary> /// The schedule trace to be replayed. /// </summary> internal string ScheduleTrace; /// <summary> /// If true, then messages are logged. /// </summary> [DataMember] public bool IsVerbose { get; internal set; } /// <summary> /// Enables code coverage reporting of a Coyote program. /// </summary> [DataMember] internal bool ReportCodeCoverage; /// <summary> /// Enables activity coverage reporting of a Coyote program. /// </summary> [DataMember] public bool ReportActivityCoverage { get; internal set; } /// <summary> /// Enables activity coverage debugging. /// </summary> internal bool DebugActivityCoverage; /// <summary> /// Is DGML graph showing all test iterations or just one "bug" iteration. /// False means all, and True means only the iteration containing a bug. /// </summary> [DataMember] internal bool IsDgmlBugGraph; /// <summary> /// If specified, requests a DGML graph of the iteration that contains a bug, if a bug is found. /// This is different from a coverage activity graph, as it will also show actor instances. /// </summary> [DataMember] public bool IsDgmlGraphEnabled { get; internal set; } /// <summary> /// Produce an XML formatted runtime log file. /// </summary> [DataMember] public bool IsXmlLogEnabled { get; internal set; } /// <summary> /// If specified, requests a custom runtime log to be used instead of the default. /// This is the AssemblyQualifiedName of the type to load. /// </summary> [DataMember] internal string CustomActorRuntimeLogType; /// <summary> /// Enables debugging. /// </summary> [DataMember] internal bool EnableDebugging; /// <summary> /// Number of parallel bug-finding tasks. /// By default it is 1 task. /// </summary> [DataMember] internal uint ParallelBugFindingTasks; /// <summary> /// Put a debug prompt at the beginning of each child TestProcess. /// </summary> [DataMember] internal bool ParallelDebug; /// <summary> /// Specify ip address if you want to use something other than localhost. /// </summary> [DataMember] internal string TestingSchedulerIpAddress; /// <summary> /// Do not automatically launch the TestingProcesses in parallel mode, instead wait for them /// to be launched independently. /// </summary> [DataMember] internal bool WaitForTestingProcesses; /// <summary> /// Runs this process as a parallel bug-finding task. /// </summary> [DataMember] internal bool RunAsParallelBugFindingTask; /// <summary> /// The testing scheduler unique endpoint. /// </summary> [DataMember] internal string TestingSchedulerEndPoint; /// <summary> /// The unique testing process id. /// </summary> [DataMember] internal uint TestingProcessId; /// <summary> /// Additional assembly specifications to instrument for code coverage, besides those in the /// dependency graph between <see cref="AssemblyToBeAnalyzed"/> and the Microsoft.Coyote DLLs. /// Key is filename, value is whether it is a list file (true) or a single file (false). /// </summary> internal Dictionary<string, bool> AdditionalCodeCoverageAssemblies; /// <summary> /// Enables colored console output. /// </summary> internal bool EnableColoredConsoleOutput; /// <summary> /// If true, then environment exit will be disabled. /// </summary> internal bool DisableEnvironmentExit; /// <summary> /// Enable Coyote sending Telemetry to Azure which is used to help improve the tool (default true). /// </summary> internal bool EnableTelemetry; /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> protected Configuration() { this.OutputFilePath = string.Empty; this.Timeout = 0; this.RuntimeGeneration = 0; this.AssemblyToBeAnalyzed = string.Empty; this.TestMethodName = string.Empty; this.SchedulingStrategy = "random"; this.TestingIterations = 1; this.RandomGeneratorSeed = null; this.IncrementalSchedulingSeed = false; this.PerformFullExploration = false; this.MaxUnfairSchedulingSteps = 10000; this.MaxFairSchedulingSteps = 100000; // 10 times the unfair steps. this.UserExplicitlySetMaxFairSchedulingSteps = false; this.ParallelBugFindingTasks = 0; this.ParallelDebug = false; this.RunAsParallelBugFindingTask = false; this.TestingSchedulerEndPoint = "CoyoteTestScheduler.4723bb92-c413-4ecb-8e8a-22eb2ba22234"; this.TestingSchedulerIpAddress = null; this.TestingProcessId = 0; this.ConsiderDepthBoundHitAsBug = false; this.StrategyBound = 0; this.TimeoutDelay = 10; this.SafetyPrefixBound = 0; this.IsLivenessCheckingEnabled = true; this.LivenessTemperatureThreshold = 50000; this.UserExplicitlySetLivenessTemperatureThreshold = false; this.IsProgramStateHashingEnabled = false; this.IsMonitoringEnabledInInProduction = false; this.AttachDebugger = false; this.ScheduleFile = string.Empty; this.ScheduleTrace = string.Empty; this.ReportCodeCoverage = false; this.ReportActivityCoverage = false; this.DebugActivityCoverage = false; this.IsVerbose = false; this.EnableDebugging = false; this.AdditionalCodeCoverageAssemblies = new Dictionary<string, bool>(); this.EnableColoredConsoleOutput = false; this.DisableEnvironmentExit = true; this.EnableTelemetry = true; string optout = Environment.GetEnvironmentVariable("COYOTE_CLI_TELEMETRY_OPTOUT"); if (optout == "1" || optout == "true") { this.EnableTelemetry = false; } } /// <summary> /// Creates a new configuration with default values. /// </summary> public static Configuration Create() { return new Configuration(); } /// <summary> /// Updates the configuration to use the random scheduling strategy during systematic testing. /// </summary> public Configuration WithRandomStrategy() { this.SchedulingStrategy = "random"; return this; } /// <summary> /// Updates the configuration to use the probabilistic scheduling strategy during systematic testing. /// You can specify a value controlling the probability of each scheduling decision. This value is /// specified as the integer N in the equation 0.5 to the power of N. So for N=1, the probability is /// 0.5, for N=2 the probability is 0.25, N=3 you get 0.125, etc. By default, this value is 3. /// </summary> /// <param name="probabilityLevel">The probability level.</param> public Configuration WithProbabilisticStrategy(uint probabilityLevel = 3) { this.SchedulingStrategy = "fairpct"; this.StrategyBound = (int)probabilityLevel; return this; } /// <summary> /// Updates the configuration to use the PCT scheduling strategy during systematic testing. /// You can specify the number of priority switch points, which by default are 10. /// </summary> /// <param name="isFair">If true, use the fair version of PCT.</param> /// <param name="numPrioritySwitchPoints">The nunmber of priority switch points.</param> public Configuration WithPCTStrategy(bool isFair, uint numPrioritySwitchPoints = 10) { this.SchedulingStrategy = isFair ? "fairpct" : "pct"; this.StrategyBound = (int)numPrioritySwitchPoints; return this; } /// <summary> /// Updates the configuration to use the dfs scheduling strategy during systematic testing. /// </summary> internal Configuration WithDFSStrategy() { this.SchedulingStrategy = "dfs"; return this; } /// <summary> /// Updates the configuration to use the replay scheduling strategy during systematic testing. /// This strategy replays the specified schedule trace to reproduce the same execution. /// </summary> /// <param name="scheduleTrace">The schedule trace to be replayed.</param> public Configuration WithReplayStrategy(string scheduleTrace) { this.SchedulingStrategy = "replay"; this.ScheduleTrace = scheduleTrace; return this; } /// <summary> /// Updates the configuration with the specified number of iterations to run during systematic testing. /// </summary> /// <param name="iterations">The number of iterations to run.</param> public Configuration WithTestingIterations(uint iterations) { this.TestingIterations = (int)iterations; return this; } /// <summary> /// Updates the configuration with the specified number of maximum scheduling steps to explore per /// iteration during systematic testing. The <see cref="MaxUnfairSchedulingSteps"/> is assigned the /// <paramref name="maxSteps"/> value, whereas the <see cref="MaxFairSchedulingSteps"/> is assigned /// a value using the default heuristic, which is 10 * <paramref name="maxSteps"/>. /// </summary> /// <param name="maxSteps">The maximum scheduling steps to explore per iteration.</param> public Configuration WithMaxSchedulingSteps(uint maxSteps) { this.MaxUnfairSchedulingSteps = (int)maxSteps; this.MaxFairSchedulingSteps = 10 * (int)maxSteps; return this; } /// <summary> /// Updates the configuration with the specified number of maximum unfair and fair scheduling /// steps to explore per iteration during systematic testing. It is recommended to use /// <see cref="WithMaxSchedulingSteps(uint)"/> instead of this overloaded method. /// </summary> /// <param name="maxUnfairSteps">The unfair scheduling steps to explore per iteration.</param> /// <param name="maxFairSteps">The fair scheduling steps to explore per iteration.</param> public Configuration WithMaxSchedulingSteps(uint maxUnfairSteps, uint maxFairSteps) { if (maxFairSteps < maxUnfairSteps) { throw new ArgumentException("The max fair steps cannot not be less than the max unfair steps.", nameof(maxFairSteps)); } this.MaxUnfairSchedulingSteps = (int)maxUnfairSteps; this.MaxFairSchedulingSteps = (int)maxFairSteps; this.UserExplicitlySetMaxFairSchedulingSteps = true; return this; } /// <summary> /// Updates the configuration with the specified liveness temperature threshold during /// systematic testing. If this value is 0 it disables liveness checking. It is not /// recommended to explicitly set this value, instead use the default value which is /// assigned to <see cref="MaxFairSchedulingSteps"/> / 2. /// </summary> /// <param name="threshold">The liveness temperature threshold.</param> public Configuration WithLivenessTemperatureThreshold(uint threshold) { this.LivenessTemperatureThreshold = (int)threshold; this.UserExplicitlySetLivenessTemperatureThreshold = true; return this; } /// <summary> /// Updates the <see cref="TimeoutDelay"/> value that controls the probability of triggering /// a timeout each time a built-in timer is scheduled during systematic testing. This value /// is not a unit of time. /// </summary> /// <param name="timeoutDelay">The timeout delay during testing.</param> public Configuration WithTimeoutDelay(uint timeoutDelay) { this.TimeoutDelay = timeoutDelay; return this; } /// <summary> /// Updates the seed used by the random value generator during systematic testing. /// </summary> /// <param name="seed">The seed used by the random value generator.</param> public Configuration WithRandomGeneratorSeed(uint seed) { this.RandomGeneratorSeed = seed; return this; } /// <summary> /// Updates the configuration with verbose output enabled or disabled. /// </summary> /// <param name="isVerbose">If true, then messages are logged.</param> public Configuration WithVerbosityEnabled(bool isVerbose = true) { this.IsVerbose = isVerbose; return this; } /// <summary> /// Updates the configuration with activity coverage enabled or disabled. /// </summary> /// <param name="isEnabled">If true, then enables activity coverage.</param> public Configuration WithActivityCoverageEnabled(bool isEnabled = true) { this.ReportActivityCoverage = isEnabled; return this; } /// <summary> /// Updates the configuration with DGML graph generation enabled or disabled. /// </summary> /// <param name="isEnabled">If true, then enables DGML graph generation.</param> public Configuration WithDgmlGraphEnabled(bool isEnabled = true) { this.IsDgmlGraphEnabled = isEnabled; return this; } /// <summary> /// Updates the configuration with XML log generation enabled or disabled. /// </summary> /// <param name="isEnabled">If true, then enables XML log generation.</param> public Configuration WithXmlLogEnabled(bool isEnabled = true) { this.IsXmlLogEnabled = isEnabled; return this; } } #pragma warning restore CA1724 // Type names should not match namespaces }
37.189624
134
0.602001
[ "MIT" ]
Youssef1313/coyote
Source/Core/Configuration.cs
20,791
C#
namespace ODMIdentity.Admin.Api.Dtos.Clients { public class ClientPropertyApiDto { public int Id { get; set; } public string Key { get; set; } public string Value { get; set; } } }
24.111111
45
0.603687
[ "MIT" ]
omikolaj/IdentityServer4-Admin
ODMIdentity/src/ODMIdentity.Admin.Api/Dtos/Clients/ClientPropertyApiDto.cs
219
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Insma.Mxa.Framework.Audio { public sealed class NoMicrophoneConnectedException : Exception { } }
20.636364
65
0.801762
[ "MIT" ]
baszalmstra/MXA
MXA-Framework/src/Framework/Audio/NoMicrophoneConnectedException.cs
229
C#
using System; namespace Xamarin.Forms.BaiduMaps { public abstract class Annotation : BaseItem { // Coordinate public static readonly BindableProperty CoordinateProperty = BindableProperty.Create( propertyName: nameof(Coordinate), returnType: typeof(Coordinate), declaringType: typeof(Annotation), defaultValue: default(Coordinate) ); public Coordinate Coordinate { get { return (Coordinate)GetValue(CoordinateProperty); } set { SetValue(CoordinateProperty, value); } } // Title public static readonly BindableProperty TitleProperty = BindableProperty.Create( propertyName: nameof(Title), returnType: typeof(string), declaringType: typeof(Annotation), defaultValue: default(string) ); public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /*// Subtitle public static readonly BindableProperty SubtitleProperty = BindableProperty.Create( propertyName: "Subtitle", returnType: typeof(string), declaringType: typeof(Annotation), defaultValue: default(string) ); public string Subtitle { get { return (string)GetValue(SubtitleProperty); } set { SetValue(SubtitleProperty, value); } }*/ /*public event EventHandler<EventArgs> Selected; internal void SendSelected() { Selected?.Invoke(this, EventArgs.Empty); } public event EventHandler<EventArgs> Deselected; internal void SendDeselected() { Deselected?.Invoke(this, EventArgs.Empty); }*/ public event EventHandler<AnnotationDragEventArgs> Drag; internal void SendDrag(AnnotationDragState state) { Drag?.Invoke(this, new AnnotationDragEventArgs(state)); } } }
30.101449
93
0.598941
[ "Apache-2.0" ]
Carl-Wen/Xamarin.Forms.BaiduMaps
Xamarin.Forms.BaiduMaps/Annotation.cs
2,079
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 07.12.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.Int64.SET001.STD.Equals.Complete.Decimal{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int64; using T_DATA2 =System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__01__VV public static class TestSet_504__param__01__VV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=4; var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=4; var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=3; var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_003__greater //----------------------------------------------------------------------- [Test] public static void Test_ZA01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA01NV //----------------------------------------------------------------------- [Test] public static void Test_ZA02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA02VN //----------------------------------------------------------------------- [Test] public static void Test_ZA03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA03NN //----------------------------------------------------------------------- [Test] public static void Test_ZB01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB01NV //----------------------------------------------------------------------- [Test] public static void Test_ZB02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => !((vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB02VN //----------------------------------------------------------------------- [Test] public static void Test_ZB03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB03NN };//class TestSet_504__param__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.Int64.SET001.STD.Equals.Complete.Decimal
23.531178
126
0.526156
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Funcs/Int64/SET001/STD/Equals/Complete/Decimal/TestSet_504__param__01__VV.cs
10,191
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// ORU_R01_ORDER_OBSERVATION (Group) - /// </summary> public interface ORU_R01_ORDER_OBSERVATION : HL7V26Layout { /// <summary> /// ORC /// </summary> Segment<ORC> ORC { get; } /// <summary> /// OBR /// </summary> Segment<OBR> OBR { get; } /// <summary> /// NTE /// </summary> SegmentList<NTE> NTE { get; } /// <summary> /// ROL /// </summary> SegmentList<ROL> ROL { get; } /// <summary> /// TIMING_QTY /// </summary> LayoutList<ORU_R01_TIMING_QTY> TimingQty { get; } /// <summary> /// CTD /// </summary> Segment<CTD> CTD { get; } /// <summary> /// OBSERVATION /// </summary> LayoutList<ORU_R01_OBSERVATION> Observation { get; } /// <summary> /// FT1 /// </summary> SegmentList<FT1> FT1 { get; } /// <summary> /// CTI /// </summary> SegmentList<CTI> CTI { get; } /// <summary> /// SPECIMEN /// </summary> LayoutList<ORU_R01_SPECIMEN> Specimen { get; } } }
23.125
105
0.488514
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.HL7Schema/Generated/V26/Groups/ORU_R01_ORDER_OBSERVATION.cs
1,480
C#
/******************************************************************************* * Copyright 2008 Amazon Technologies, 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://aws.amazon.com/apache2.0 * 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * Marketplace Web Service CSharp Library * API Version: 2009-01-01 * Generated: Fri Feb 13 19:54:50 PST 2009 * */ using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace MountainWarehouse.EasyMWS.WebService.MarketplaceWebService.Model { [XmlType(Namespace = "http://mws.amazonaws.com/doc/2009-01-01/")] [XmlRoot(Namespace = "http://mws.amazonaws.com/doc/2009-01-01/", IsNullable = false)] public class ReportList { private List<Report> reportField; /// <summary> /// Gets and sets the Report property. /// </summary> [XmlElement(ElementName = "Report")] public List<Report> Report { get { if (this.reportField == null) { this.reportField = new List<Report>(); } return this.reportField; } set { this.reportField = value; } } /// <summary> /// Sets the Report property /// </summary> /// <param name="list">Report property</param> /// <returns>this instance</returns> public ReportList WithReport(params Report[] list) { foreach (Report item in list) { Report.Add(item); } return this; } /// <summary> /// Checks if Report property is set /// </summary> /// <returns>true if Report property is set</returns> public Boolean IsSetReport() { return (Report.Count > 0); } /// <summary> /// XML fragment representation of this object /// </summary> /// <returns>XML fragment for this object.</returns> /// <remarks> /// Name for outer tag expected to be set by calling method. /// This fragment returns inner properties representation only /// </remarks> protected internal String ToXMLFragment() { StringBuilder xml = new StringBuilder(); List<Report> reportList = this.Report; foreach (Report report in reportList) { xml.Append("<Report>"); xml.Append(report.ToXMLFragment()); xml.Append("</Report>"); } return xml.ToString(); } /** * * Escape XML special characters */ private String EscapeXML(String str) { StringBuilder sb = new StringBuilder(); foreach (Char c in str) { switch (c) { case '&': sb.Append("&amp;"); break; case '<': sb.Append("&lt;"); break; case '>': sb.Append("&gt;"); break; case '\'': sb.Append("&#039;"); break; case '"': sb.Append("&quot;"); break; default: sb.Append(c); break; } } return sb.ToString(); } } }
28.879433
89
0.47053
[ "Apache-2.0" ]
MountainWarehouse/EasyMWS
src/EasyMWS/EasyMWS/WebService/MarketplaceWebService/Model/ReportList.cs
4,072
C#
using Abp.Application.Services.Dto; using CarPlusGo.CVAS.Insure.Enum; using System; namespace CarPlusGo.CVAS.Insure.Dto { public class PagedInsurancePolicyResultRequestDto : PagedResultRequestDto { public long[] CarBaseIds { get; set; } public string Keyword { get; set; } public long? SupplierId { get; set; } /// <summary> /// 保险合同类型 /// </summary> public InsuranceContractType? InsuranceContractType { get; set; } /// <summary> /// 保单类别 /// </summary> public InsurancePolicyType? InsurancePolicyType { get; set; } /// <summary> /// 保单状态 /// </summary> public InsurancePolicyStatus? InsurancePolicyStatus { get; set; } public DateTime? StartTimeFrom { get; set; } public DateTime? StartTimeTo { get; set; } public DateTime? EndTimeFrom { get; set; } public DateTime? EndTimeTo { get; set; } } }
31.096774
77
0.604772
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
MakingBugs/carplusgo.cvas
src/CarPlusGo.CVAS.Application/Insure/InsurancePolicy/Dto/PagedInsurancePolicyResultRequestDto.cs
994
C#
/****************************************************************************** * Spine Runtimes License Agreement * Last updated May 1, 2019. Replaces all prior versions. * * Copyright (c) 2013-2019, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS * INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 UnityEngine; using UnityEditor; using System.Collections.Generic; using Spine.Unity; using Spine.Unity.Editor; namespace Spine.Unity.Modules { [CustomEditor(typeof(SkeletonRenderSeparator))] public class SkeletonRenderSeparatorInspector : UnityEditor.Editor { SkeletonRenderSeparator component; // Properties SerializedProperty skeletonRenderer_, copyPropertyBlock_, copyMeshRendererFlags_, partsRenderers_; static bool partsRenderersExpanded = false; // For separator field. SerializedObject skeletonRendererSerializedObject; SerializedProperty separatorNamesProp; static bool skeletonRendererExpanded = true; bool slotsReapplyRequired = false; bool partsRendererInitRequired = false; void OnEnable () { if (component == null) component = target as SkeletonRenderSeparator; skeletonRenderer_ = serializedObject.FindProperty("skeletonRenderer"); copyPropertyBlock_ = serializedObject.FindProperty("copyPropertyBlock"); copyMeshRendererFlags_ = serializedObject.FindProperty("copyMeshRendererFlags"); var partsRenderers = component.partsRenderers; partsRenderers_ = serializedObject.FindProperty("partsRenderers"); partsRenderers_.isExpanded = partsRenderersExpanded || // last state partsRenderers.Contains(null) || // null items found partsRenderers.Count < 1 || // no parts renderers (skeletonRenderer_.objectReferenceValue != null && SkeletonRendererSeparatorCount + 1 > partsRenderers.Count); // not enough parts renderers } int SkeletonRendererSeparatorCount { get { if (Application.isPlaying) return component.SkeletonRenderer.separatorSlots.Count; else return separatorNamesProp == null ? 0 : separatorNamesProp.arraySize; } } public override void OnInspectorGUI () { // Restore mesh part for undo logic after undo of "Add Parts Renderer". // Triggers regeneration and assignment of the mesh filter's mesh. if (component.GetComponent<MeshFilter>() && component.GetComponent<MeshFilter>().sharedMesh == null) { component.OnDisable(); component.OnEnable(); } var componentRenderers = component.partsRenderers; int totalParts; using (new SpineInspectorUtility.LabelWidthScope()) { bool componentEnabled = component.enabled; bool checkBox = EditorGUILayout.Toggle("Enable Separator", componentEnabled); if (checkBox != componentEnabled) component.enabled = checkBox; if (component.SkeletonRenderer.disableRenderingOnOverride && !component.enabled) EditorGUILayout.HelpBox("By default, SkeletonRenderer's MeshRenderer is disabled while the SkeletonRenderSeparator takes over rendering. It is re-enabled when SkeletonRenderSeparator is disabled.", MessageType.Info); EditorGUILayout.PropertyField(copyPropertyBlock_); EditorGUILayout.PropertyField(copyMeshRendererFlags_); } // SkeletonRenderer Box using (new SpineInspectorUtility.BoxScope(false)) { // Fancy SkeletonRenderer foldout reference field { EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); var foldoutSkeletonRendererRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight); EditorGUI.PropertyField(foldoutSkeletonRendererRect, skeletonRenderer_); if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties(); if (component.SkeletonRenderer != null) { skeletonRendererExpanded = EditorGUI.Foldout(foldoutSkeletonRendererRect, skeletonRendererExpanded, ""); } EditorGUI.indentLevel--; } int separatorCount = 0; EditorGUI.BeginChangeCheck(); if (component.SkeletonRenderer != null) { // Separators from SkeletonRenderer { bool skeletonRendererMismatch = skeletonRendererSerializedObject != null && skeletonRendererSerializedObject.targetObject != component.SkeletonRenderer; if (separatorNamesProp == null || skeletonRendererMismatch) { if (component.SkeletonRenderer != null) { skeletonRendererSerializedObject = new SerializedObject(component.SkeletonRenderer); separatorNamesProp = skeletonRendererSerializedObject.FindProperty("separatorSlotNames"); separatorNamesProp.isExpanded = true; } } if (separatorNamesProp != null) { if (skeletonRendererExpanded) { EditorGUI.indentLevel++; SkeletonRendererInspector.SeparatorsField(separatorNamesProp); EditorGUI.indentLevel--; } separatorCount = this.SkeletonRendererSeparatorCount; } } if (SkeletonRendererSeparatorCount == 0) { EditorGUILayout.HelpBox("Separators are empty. Change the size to 1 and choose a slot if you want the render to be separated.", MessageType.Info); } } if (EditorGUI.EndChangeCheck()) { skeletonRendererSerializedObject.ApplyModifiedProperties(); if (!Application.isPlaying) slotsReapplyRequired = true; } totalParts = separatorCount + 1; var counterStyle = skeletonRendererExpanded ? EditorStyles.label : EditorStyles.miniLabel; EditorGUILayout.LabelField(string.Format("{0}: separates into {1}.", SpineInspectorUtility.Pluralize(separatorCount, "separator", "separators"), SpineInspectorUtility.Pluralize(totalParts, "part", "parts") ), counterStyle); } // Parts renderers using (new SpineInspectorUtility.BoxScope(false)) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(this.partsRenderers_, true); EditorGUI.indentLevel--; // Null items warning bool nullItemsFound = componentRenderers.Contains(null); if (nullItemsFound) EditorGUILayout.HelpBox("Some items in the parts renderers list are null and may cause problems.\n\nYou can right-click on that element and choose 'Delete Array Element' to remove it.", MessageType.Warning); // (Button) Match Separators count if (separatorNamesProp != null) { int currentRenderers = 0; foreach (var r in componentRenderers) { if (r != null) currentRenderers++; } int extraRenderersNeeded = totalParts - currentRenderers; if (component.enabled && component.SkeletonRenderer != null && extraRenderersNeeded > 0) { EditorGUILayout.HelpBox(string.Format("Insufficient parts renderers. Some parts will not be rendered."), MessageType.Warning); string addMissingLabel = string.Format("Add the missing renderer{1} ({0}) ", extraRenderersNeeded, SpineInspectorUtility.PluralThenS(extraRenderersNeeded)); if (GUILayout.Button(addMissingLabel, GUILayout.Height(40f))) { AddPartsRenderer(extraRenderersNeeded); DetectOrphanedPartsRenderers(component); partsRendererInitRequired = true; } } } if (partsRenderers_.isExpanded != partsRenderersExpanded) partsRenderersExpanded = partsRenderers_.isExpanded; if (partsRenderers_.isExpanded) { using (new EditorGUILayout.HorizontalScope()) { // (Button) Destroy Renderers button if (componentRenderers.Count > 0) { if (GUILayout.Button("Clear Parts Renderers")) { // Do you really want to destroy all? Undo.RegisterCompleteObjectUndo(component, "Clear Parts Renderers"); if (EditorUtility.DisplayDialog("Destroy Renderers", "Do you really want to destroy all the Parts Renderer GameObjects in the list?", "Destroy", "Cancel")) { foreach (var r in componentRenderers) { if (r != null) Undo.DestroyObjectImmediate(r.gameObject); } componentRenderers.Clear(); // Do you also want to destroy orphans? (You monster.) DetectOrphanedPartsRenderers(component); } } } // (Button) Add Part Renderer button if (GUILayout.Button("Add Parts Renderer")) { AddPartsRenderer(1); partsRendererInitRequired = true; } } } } serializedObject.ApplyModifiedProperties(); if (partsRendererInitRequired) { Undo.RegisterCompleteObjectUndo(component.GetComponent<MeshRenderer>(), "Add Parts Renderers"); component.OnEnable(); partsRendererInitRequired = false; } if (slotsReapplyRequired && UnityEngine.Event.current.type == EventType.Repaint) { component.SkeletonRenderer.ReapplySeparatorSlotNames(); component.SkeletonRenderer.LateUpdate(); SceneView.RepaintAll(); slotsReapplyRequired = false; } } public void AddPartsRenderer (int count) { var componentRenderers = component.partsRenderers; bool emptyFound = componentRenderers.Contains(null); if (emptyFound) { bool userClearEntries = EditorUtility.DisplayDialog("Empty entries found", "Null entries found. Do you want to remove null entries before adding the new renderer? ", "Clear Empty Entries", "Don't Clear"); if (userClearEntries) componentRenderers.RemoveAll(x => x == null); } Undo.RegisterCompleteObjectUndo(component, "Add Parts Renderers"); for (int i = 0; i < count; i++) { int index = componentRenderers.Count; var smr = SkeletonPartsRenderer.NewPartsRendererGameObject(component.transform, index.ToString()); Undo.RegisterCreatedObjectUndo(smr.gameObject, "New Parts Renderer GameObject."); componentRenderers.Add(smr); // increment renderer sorting order. if (index == 0) continue; var prev = componentRenderers[index - 1]; if (prev == null) continue; var prevMeshRenderer = prev.GetComponent<MeshRenderer>(); var currentMeshRenderer = smr.GetComponent<MeshRenderer>(); if (prevMeshRenderer == null || currentMeshRenderer == null) continue; int prevSortingLayer = prevMeshRenderer.sortingLayerID; int prevSortingOrder = prevMeshRenderer.sortingOrder; currentMeshRenderer.sortingLayerID = prevSortingLayer; currentMeshRenderer.sortingOrder = prevSortingOrder + SkeletonRenderSeparator.DefaultSortingOrderIncrement; } } /// <summary>Detects orphaned parts renderers and offers to delete them.</summary> public void DetectOrphanedPartsRenderers (SkeletonRenderSeparator component) { var children = component.GetComponentsInChildren<SkeletonPartsRenderer>(); var orphans = new System.Collections.Generic.List<SkeletonPartsRenderer>(); foreach (var r in children) { if (!component.partsRenderers.Contains(r)) orphans.Add(r); } if (orphans.Count > 0) { if (EditorUtility.DisplayDialog("Destroy Submesh Renderers", "Unassigned renderers were found. Do you want to delete them? (These may belong to another Render Separator in the same hierarchy. If you don't have another Render Separator component in the children of this GameObject, it's likely safe to delete. Warning: This operation cannot be undone.)", "Delete", "Cancel")) { foreach (var o in orphans) { Undo.DestroyObjectImmediate(o.gameObject); } } } } #region SkeletonRenderer Context Menu Item [MenuItem ("CONTEXT/SkeletonRenderer/Add Skeleton Render Separator")] static void AddRenderSeparatorComponent (MenuCommand cmd) { var skeletonRenderer = cmd.context as SkeletonRenderer; var newComponent = skeletonRenderer.gameObject.AddComponent<SkeletonRenderSeparator>(); Undo.RegisterCreatedObjectUndo(newComponent, "Add SkeletonRenderSeparator"); } // Validate [MenuItem ("CONTEXT/SkeletonRenderer/Add Skeleton Render Separator", true)] static bool ValidateAddRenderSeparatorComponent (MenuCommand cmd) { var skeletonRenderer = cmd.context as SkeletonRenderer; var separator = skeletonRenderer.GetComponent<SkeletonRenderSeparator>(); bool separatorNotOnObject = separator == null; return separatorNotOnObject; } #endregion } }
43.15534
380
0.732133
[ "MIT" ]
daonq/unity_game
Assets/Spine/Editor/spine-unity/Modules/SkeletonRenderSeparator/Editor/SkeletonRenderSeparatorInspector.cs
13,335
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ using System; using System.Runtime.InteropServices; namespace Noesis { public class PasswordBox : Control { internal new static PasswordBox CreateProxy(IntPtr cPtr, bool cMemoryOwn) { return new PasswordBox(cPtr, cMemoryOwn); } internal PasswordBox(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } internal static HandleRef getCPtr(PasswordBox obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } #region Events #region PasswordChanged public delegate void PasswordChangedHandler(object sender, RoutedEventArgs e); public event PasswordChangedHandler PasswordChanged { add { if (!_PasswordChanged.ContainsKey(swigCPtr.Handle)) { _PasswordChanged.Add(swigCPtr.Handle, null); NoesisGUI_PINVOKE.BindEvent_PasswordBox_PasswordChanged(_raisePasswordChanged, swigCPtr.Handle); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } _PasswordChanged[swigCPtr.Handle] += value; } remove { if (_PasswordChanged.ContainsKey(swigCPtr.Handle)) { _PasswordChanged[swigCPtr.Handle] -= value; if (_PasswordChanged[swigCPtr.Handle] == null) { NoesisGUI_PINVOKE.UnbindEvent_PasswordBox_PasswordChanged(_raisePasswordChanged, swigCPtr.Handle); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif _PasswordChanged.Remove(swigCPtr.Handle); } } } } internal delegate void RaisePasswordChangedCallback(IntPtr cPtr, IntPtr sender, IntPtr e); private static RaisePasswordChangedCallback _raisePasswordChanged = RaisePasswordChanged; [MonoPInvokeCallback(typeof(RaisePasswordChangedCallback))] private static void RaisePasswordChanged(IntPtr cPtr, IntPtr sender, IntPtr e) { try { if (!_PasswordChanged.ContainsKey(cPtr)) { throw new System.InvalidOperationException("Delegate not registered for PasswordChanged event"); } if (sender == System.IntPtr.Zero && e == System.IntPtr.Zero) { _PasswordChanged.Remove(cPtr); return; } if (Noesis.Extend.Initialized) { PasswordChangedHandler handler = _PasswordChanged[cPtr]; if (handler != null) { handler(Noesis.Extend.GetProxy(sender, false), new RoutedEventArgs(e, false)); } } } catch (System.Exception exception) { Noesis.Error.SetNativePendingError(exception); } } static System.Collections.Generic.Dictionary<System.IntPtr, PasswordChangedHandler> _PasswordChanged = new System.Collections.Generic.Dictionary<System.IntPtr, PasswordChangedHandler>(); #endregion #endregion public PasswordBox() { } protected override System.IntPtr CreateCPtr(System.Type type, out bool registerExtend) { if ((object)type.TypeHandle == typeof(PasswordBox).TypeHandle) { registerExtend = false; return NoesisGUI_PINVOKE.new_PasswordBox(); } else { return base.CreateExtendCPtr(type, out registerExtend); } } public static DependencyProperty CaretBrushProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_CaretBrushProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty MaxLengthProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_MaxLengthProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty PasswordCharProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_PasswordCharProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty SelectionBrushProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_SelectionBrushProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty SelectionOpacityProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_SelectionOpacityProperty_get(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public Brush CaretBrush { set { NoesisGUI_PINVOKE.PasswordBox_CaretBrush_set(swigCPtr, Brush.getCPtr(value)); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_CaretBrush_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (Brush)Noesis.Extend.GetProxy(cPtr, false); } } public int MaxLength { set { NoesisGUI_PINVOKE.PasswordBox_MaxLength_set(swigCPtr, value); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { int ret = NoesisGUI_PINVOKE.PasswordBox_MaxLength_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } } public char PasswordChar { set { NoesisGUI_PINVOKE.PasswordBox_PasswordChar_set(swigCPtr, value); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { char ret = NoesisGUI_PINVOKE.PasswordBox_PasswordChar_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } } public string Password { set { NoesisGUI_PINVOKE.PasswordBox_Password_set(swigCPtr, value != null ? value : string.Empty); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { IntPtr strPtr = NoesisGUI_PINVOKE.PasswordBox_Password_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif string str = Noesis.Extend.StringFromNativeUtf8(strPtr); return str; } } public Brush SelectionBrush { set { NoesisGUI_PINVOKE.PasswordBox_SelectionBrush_set(swigCPtr, Brush.getCPtr(value)); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { IntPtr cPtr = NoesisGUI_PINVOKE.PasswordBox_SelectionBrush_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return (Brush)Noesis.Extend.GetProxy(cPtr, false); } } public float SelectionOpacity { set { NoesisGUI_PINVOKE.PasswordBox_SelectionOpacity_set(swigCPtr, value); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif } get { float ret = NoesisGUI_PINVOKE.PasswordBox_SelectionOpacity_get(swigCPtr); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } } new internal static IntPtr GetStaticType() { IntPtr ret = NoesisGUI_PINVOKE.PasswordBox_GetStaticType(); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return ret; } internal new static IntPtr Extend(string typeName) { IntPtr nativeType = NoesisGUI_PINVOKE.Extend_PasswordBox(Marshal.StringToHGlobalAnsi(typeName)); #if UNITY_EDITOR || NOESIS_API if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); #endif return nativeType; } } }
35.948529
118
0.716916
[ "MIT" ]
suggestbot-wearable-text-entry-system/SuggestBot_GazeAssistedTyping
Assets/Plugins/NoesisGUI/Scripts/Proxies/PasswordBox.cs
9,778
C#
using System; using Owin; using Prospa.Extensions.AspNet.WebApi.Owin.Middlewares; namespace Prospa.Extensions.AspNet.WebApi.Owin.Extensions { public static class AppBuilderExtensions { public static void AddRequiredEndpointKey(this IAppBuilder app, Action<RequireEndpointKeyOptions> buildOptions) { var options = new RequireEndpointKeyOptions(); buildOptions(options); app.Use<RequireEndpointKeyMiddleware>(options); } } }
26.263158
119
0.707415
[ "MIT" ]
prospa-group-oss/AspNetCoreExtensions
src/Prospa.Extensions.AspNet.WebApi.Owin/Extensions/AppBuilderExtensions.cs
501
C#
using Cassandra; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; namespace CSharpBencher { public class Writer { private readonly string[] _cassandraContactPoints; private readonly string _localDc; private ISession _session; private Writer(string[] cassandraContactPoints, string localDc) { _cassandraContactPoints = cassandraContactPoints; _localDc = localDc; } public static Writer CreateAndConnect(string[] cassandraContactPoints, string localDc) { var writer = new Writer(cassandraContactPoints, localDc); writer.Connect(); return writer; } private void Connect() { _session = Cluster.Builder() .WithDefaultKeyspace("CsharpDriverBenchmark") .WithQueryTimeout((int)TimeSpan.FromSeconds(5).TotalMilliseconds) .AddContactPoints(_cassandraContactPoints) .WithLoadBalancingPolicy(new DCAwareRoundRobinPolicy(_localDc)) .Build() .Connect(); } public void Write(int serieCount, IPersistorStrategy persistorStrategy) { persistorStrategy.Prepare(_session); const int pointsPerDay = 18000; // Average number of points per day taken from real data var serieIdsToInsert = Enumerable.Range(0, serieCount).Select(i => Guid.NewGuid()).ToList(); StoreSerieIds(serieIdsToInsert); var generatedData = GenerateDataToInsert(serieIdsToInsert, pointsPerDay); var overallStopwatch = Stopwatch.StartNew(); var totalPointCount = serieCount * pointsPerDay; persistorStrategy.Run(_session, generatedData, totalPointCount); Console.WriteLine("----------- Insertion complete, waiting for the last inserts -----------"); while (persistorStrategy.PersistedPointCount < totalPointCount) Thread.Sleep(100); overallStopwatch.Stop(); Console.WriteLine(FormattableString.Invariant($"Insertion complete, {totalPointCount:#,#} data points in {overallStopwatch.Elapsed} ({(int)(totalPointCount / overallStopwatch.Elapsed.TotalSeconds):#,#} point/s)")); persistorStrategy.Cleanup(); } private void StoreSerieIds(List<Guid> serieIdsToInsert) { const string insertIdsStatement = @"INSERT INTO ""SerieId"" (""SerieId"") VALUES (?);"; var preparedInsertStatement = _session.Prepare(insertIdsStatement); foreach (var serieId in serieIdsToInsert) _session.Execute(preparedInsertStatement.Bind(serieId)); } private static IEnumerable<DataToInsert> GenerateDataToInsert(List<Guid> serieIdsToInsert, int pointsPerDay) { var randomValues = GetRandomValues(pointsPerDay); var date = DateTime.UtcNow.Date; // We return a data point per serie for each second, to make sure to balance the write load on different nodes (serieId is part of the partition key) for (var i = 0; i < pointsPerDay; ++i) { var now = date.AddSeconds(i); foreach (var serieId in serieIdsToInsert) yield return new DataToInsert(serieId, now, randomValues[i]); } } private static IList<double> GetRandomValues(int count) { var random = new Random(1); var result = new List<double>(); for (var i = 0; i < count; i++) result.Add(random.NextDouble()); return result; } } }
38.254902
226
0.606612
[ "MIT" ]
Abc-Arbitrage/cassandra-csharp-benchmark
csharp/CSharpBencher/Writer.cs
3,904
C#
using System; using System.Threading; using Datadog.Trace.ClrProfiler.CallTarget; using Datadog.Trace.Configuration; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.XUnit { /// <summary> /// Xunit.Sdk.TestAssemblyRunner`1.RunTestCollectionAsync calltarget instrumentation /// </summary> [InstrumentMethod( AssemblyNames = new[] { "xunit.execution.dotnet", "xunit.execution.desktop" }, TypeName = "Xunit.Sdk.TestAssemblyRunner`1", MethodName = "RunTestCollectionAsync", ReturnTypeName = "System.Threading.Tasks.Task`1<Xunit.Sdk.RunSummary>", ParameterTypeNames = new[] { "Xunit.Sdk.IMessageBus", "_", "_", "_" }, MinimumVersion = "2.2.0", MaximumVersion = "2.*.*", IntegrationName = IntegrationName)] public static class XUnitTestAssemblyRunnerRunTestCollectionAsyncIntegration { private const string IntegrationName = nameof(IntegrationIds.XUnit); private static readonly IntegrationInfo IntegrationId = IntegrationRegistry.GetIntegrationInfo(IntegrationName); /// <summary> /// OnAsyncMethodEnd callback /// </summary> /// <typeparam name="TTarget">Type of the target</typeparam> /// <typeparam name="TReturn">Type of the return type</typeparam> /// <param name="instance">Instance value, aka `this` of the instrumented method.</param> /// <param name="returnValue">Return value</param> /// <param name="exception">Exception instance in case the original code threw an exception.</param> /// <param name="state">Calltarget state value</param> /// <returns>A response value, in an async scenario will be T of Task of T</returns> public static TReturn OnAsyncMethodEnd<TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { if (Common.TestTracer.Settings.IsIntegrationEnabled(IntegrationId)) { // We have to ensure the flush of the buffer after we finish the tests of an assembly. // For some reason, sometimes when all test are finished none of the callbacks to handling the tracer disposal is triggered. // So the last spans in buffer aren't send to the agent. // Other times we reach the 500 items of the buffer in a sec and the tracer start to drop spans. // In a test scenario we must keep all spans. SynchronizationContext currentContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); Common.TestTracer.FlushAsync().GetAwaiter().GetResult(); } finally { SynchronizationContext.SetSynchronizationContext(currentContext); } } return returnValue; } } }
48.918033
147
0.647788
[ "Apache-2.0" ]
alirezavafi/dd-trace-dotnet-splunk
src/Datadog.Trace.ClrProfiler.Managed/AutoInstrumentation/Testing/XUnit/XUnitTestAssemblyRunnerRunTestCollectionAsyncIntegration.cs
2,984
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.1008 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace Vapula.MDE.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [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> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Vapula.MDE.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static System.Drawing.Bitmap broom_s { get { object obj = ResourceManager.GetObject("broom_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap design_s { get { object obj = ResourceManager.GetObject("design_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap disk_s { get { object obj = ResourceManager.GetObject("disk_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap function_add_s { get { object obj = ResourceManager.GetObject("function_add_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap function_l { get { object obj = ResourceManager.GetObject("function_l", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap function_remove_s { get { object obj = ResourceManager.GetObject("function_remove_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap function_s { get { object obj = ResourceManager.GetObject("function_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap library_s { get { object obj = ResourceManager.GetObject("library_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap parameter_s { get { object obj = ResourceManager.GetObject("parameter_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap refresh_s { get { object obj = ResourceManager.GetObject("refresh_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap toggle_minus_s { get { object obj = ResourceManager.GetObject("toggle_minus_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap toggle_plus_s { get { object obj = ResourceManager.GetObject("toggle_plus_s", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
37.067568
176
0.553226
[ "Apache-2.0" ]
sartrey/vapula
Model/vf_mde/Properties/Resources.Designer.cs
5,836
C#
/* dotNetRDF is free and open source software licensed under the MIT License ----------------------------------------------------------------------------- Copyright (c) 2009-2012 dotNetRDF Project (dotnetrdf-developer@lists.sf.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. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using VDS.RDF.Parsing; namespace VDS.RDF.Utilities.Editor.Syntax { /// <summary> /// Static Helper class with useful syntax extensions /// </summary> public static class SyntaxExtensions { /// <summary> /// Convert friendly display names for syntax into recognized internal syntax name /// </summary> /// <param name="name">Friendly Name</param> /// <returns>Internal Syntax Name</returns> public static String GetSyntaxName(this String name) { switch (name) { case "RDF/JSON": return "RdfJson"; case "RDF/XML": return "RdfXml"; case "HTML": return "XHtmlRdfA"; case "Notation 3": return "Notation3"; case "SPARQL Results XML": return "SparqlResultsXml"; case "SPARQL Results JSON": return "SparqlResultsJson"; case "SPARQL Query": return "SparqlQuery11"; case "SPARQL Update": return "SparqlUpdate11"; case "NTriples": case "NQuads": case "Turtle": case "TriG": case "TriX": default: return name; } } /// <summary> /// Convert SPARQL results parser into internal syntax name /// </summary> /// <param name="parser">SPARQL Results Parser</param> /// <returns>Internal Syntax Name</returns> public static String GetSyntaxName(this ISparqlResultsReader parser) { if (parser is SparqlJsonParser) { return "SparqlResultsJson"; } else if (parser is SparqlXmlParser) { return "SparqlResultsXml"; } else { return parser.ToString(); } } /// <summary> /// Converts RDF parser into internal syntax name /// </summary> /// <param name="parser">RDF Parser</param> /// <returns>Internal Syntax Name</returns> public static String GetSyntaxName(this IRdfReader parser) { /*if (parser is HtmlPlusRdfAParser) { return "XHtmlRdfA"; } else*/ if (parser is Notation3Parser) { return "Notation3"; } else if (parser is NTriplesParser) { return "NTriples"; } else if (parser is RdfJsonParser) { return "RdfJson"; } else if (parser is RdfXmlParser) { return "RdfXml"; } else if (parser is TurtleParser) { return "Turtle"; } /*else if (parser is XmlPlusRdfAParser) { return "XmlRdfA"; }*/ else { return parser.ToString(); } } /// <summary> /// Converts RDF dataset parsers into internal syntax name /// </summary> /// <param name="parser">Dataset Parser</param> /// <returns>Internal Syntax Name</returns> public static String GetSyntaxName(this IStoreReader parser) { if (parser is NQuadsParser) { return "NQuads"; } else if (parser is TriGParser) { return "TriG"; } else if (parser is TriXParser) { return "TriX"; } else { return parser.ToString(); } } } }
31.158824
90
0.525203
[ "MIT" ]
dotnetrdf/dotNetRDF.Toolkit
Libraries/editor/Syntax/SyntaxExtensions.cs
5,297
C#
namespace Graphing.Review.Core { using System; using System.Collections.Generic; using System.Linq; public class PriorityQueue<TItem> { private readonly IDictionary<TItem, int> queue; public PriorityQueue() { this.queue = new Dictionary<TItem, int>(); } public void Enqueue(TItem item, int weight) { this.queue.Add(item, weight); } public bool Any() => this.queue.Keys.Any(); public TItem PeekMin() { if (!queue.Any()) return default(TItem); var item = queue.OrderBy(kvp => kvp.Value).FirstOrDefault(); return item.Key; } public TItem DequeueMin() { var item = this.PeekMin(); this.queue.Remove(item); return item; } } }
21.55
72
0.529002
[ "Apache-2.0" ]
droconnel22/CompetitiveCoding_DotNetCore
Graphing.Review.Core/PriorityQueue.cs
864
C#
using System; namespace Cake.Docker { /// <summary> /// /// </summary> [AttributeUsage(AttributeTargets.Property)] public class AutoPropertyAttribute: Attribute { /// <summary> /// Format of the output, i.e. "-s {1}" /// where {0} is property name and {1} is value. /// </summary> public string Format { get; set; } /// <summary> /// Outputs only when given value is true. /// </summary> public bool OnlyWhenTrue { get; set; } /// <summary> /// Whether it appears before command /// </summary> public bool PreCommand { get; set; } } }
25.769231
56
0.529851
[ "MIT" ]
KevM/Cake.Docker
src/Cake.Docker/AutoPropertyAttribute.cs
672
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Alamut.Data.NoSql; using Alamut.Data.Paging; namespace Alamut.Data.Repository { public interface ISmartRepository<TEntity> : IRepository<TEntity> where TEntity : class { /// <summary> /// gets an item (mapped to provided TDto) filter by provided predicate /// </summary> /// <typeparam name="TDto"></typeparam> /// <param name="predicate"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<TDto> Get<TDto>(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken = default); /// <summary> /// gets all items (mapped to provided TDto) /// </summary> /// <typeparam name="TDto"></typeparam> /// <returns></returns> Task<List<TDto>> GetAll<TDto>(CancellationToken cancellationToken = default); /// <summary> /// gets a list of items (mapped to provided TDto) filter by provided predicate /// </summary> /// <typeparam name="TDto"></typeparam> /// <param name="predicate"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<List<TDto>> GetMany<TDto>(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellationToken = default); /// <summary> /// gets a list of requested DTO in Paginated data-type filtered by provided criteria or default /// </summary> /// <param name="criteria"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<IPaginated<TDto>> GetPaginated<TDto>(CancellationToken cancellationToken); Task<IPaginated<TDto>> GetPaginated<TDto>(IPaginatedCriteria criteria, CancellationToken cancellationToken); Task<IPaginated<TDto>> GetPaginated<TDto>(DynamicPaginatedCriteria criteria, CancellationToken cancellationToken); /// <summary> /// maps the provided DTO to the Entity and add it to the current context /// </summary> /// <typeparam name="TDto"></typeparam> /// <param name="dto"></param> /// <returns>generated Entity based on provided DTO</returns> TEntity Add<TDto>(TDto dto); /// <summary> /// maps the provided DTO to the Entity and update it to the current context /// </summary> /// <param name="id">the key</param> /// <param name="dto"></param> /// <param name="cancellationToken"></param> /// <returns>generated Entity based on provided DTO</returns> Task<TEntity> UpdateById<TDto>(object id,TDto dto, CancellationToken cancellationToken = default); /// <summary> /// maps the provided DTO to the Entity and update it to the current context /// </summary> /// <param name="ids">the keys</param> /// <param name="dto"></param> /// <param name="cancellationToken"></param> /// <returns>generated Entity based on provided DTO</returns> Task<TEntity> UpdateById<TDto>(object[] ids,TDto dto, CancellationToken cancellationToken = default); } }
42.410256
129
0.625453
[ "MIT" ]
SorenZ/Alamut.Data
src/Alamut.Data/Repository/ISmartRepository[TEntity].cs
3,310
C#
namespace FoxyLink { public class GlobalConfiguration : IGlobalConfiguration { public static IGlobalConfiguration Configuration { get; } = new GlobalConfiguration(); internal GlobalConfiguration() { } } }
20.916667
94
0.653386
[ "MIT" ]
FoxyLinkIO/FoxyLink.RabbitMQ
src/FoxyLink.GlobalConfiguration/GlobalConfiguration.cs
253
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.ProjectOxford.Face; using System.Diagnostics; using Windows.Storage; using Microsoft.ProjectOxford.Face.Contract; using System.Linq; namespace DormRoomMonitor.FacialRecognition { class FaceApiRecognizer : IFaceRecognizer { const int RATE_LIMIT = 100; // ms #region Private members private static readonly Lazy<FaceApiRecognizer> _recognizer = new Lazy<FaceApiRecognizer>(() => new FaceApiRecognizer()); private FaceApiWhitelist _whitelist = null; private IFaceServiceClient _faceApiClient = null; private StorageFolder _whitelistFolder = null; #endregion #region Properties /// <summary> /// Face API Recognizer instance /// </summary> public static FaceApiRecognizer Instance { get { return _recognizer.Value; } } /// <summary> /// Whitelist Id on Cloud Face API /// </summary> public string WhitelistId { get; private set; } int numberOfCalls = 0; public IFaceServiceClient FaceApiClient { get { ++numberOfCalls; Debug.WriteLine("number of calls" + numberOfCalls); var log = new Log { message = "number of calls" + numberOfCalls }; GuildWebApi.updateLog(log); return _faceApiClient; } set => _faceApiClient = value; } #endregion #region Constructors /// <summary> /// Constructor /// Initial Face Api client /// </summary> private FaceApiRecognizer() { FaceApiClient = new FaceServiceClient(GeneralConstants.OxfordAPIKey, GeneralConstants.DEFAULT_API_ROOT); } #endregion #region Whitelist private void UpdateProgress(IProgress<int> progress, double progressCnt) { if (progress != null) { progress.Report((int)Math.Round(progressCnt)); } } /// <summary> /// Train whitelist until training finished /// </summary> /// <returns></returns> private async Task<bool> TrainingWhitelistAsync() { bool isSuccess = true; // Train whitelist after add all person Debug.WriteLine("Start training whitelist..."); var log = new Log { message = "Start training whitelist" }; GuildWebApi.updateLog(log); await FaceApiClient.TrainPersonGroupAsync(WhitelistId); await Task.Delay(RATE_LIMIT); TrainingStatus status; while (true) { status = await FaceApiClient.GetPersonGroupTrainingStatusAsync(WhitelistId); await Task.Delay(RATE_LIMIT); // if still running, continue to check status if (status.Status == Status.Running) { continue; } // if timeout or failed if (status.Status != Status.Succeeded) { isSuccess = false; } break; } return isSuccess; } public async Task<bool> CreateWhitelistFromFolderAsync(string whitelistId, StorageFolder whitelistFolder = null, IProgress<int> progress = null) { bool isSuccess = true; double progressCnt = 0; WhitelistId = whitelistId; _whitelist = new FaceApiWhitelist(WhitelistId); try { // whitelist folder default to picture library if (whitelistFolder == null) { whitelistFolder = await KnownFolders.PicturesLibrary.GetFolderAsync("WhiteList"); } _whitelistFolder = whitelistFolder; // detele person group if already exists try { // An exception is thrown if the person group doesn't exist await FaceApiClient.GetPersonGroupAsync(whitelistId); await Task.Delay(RATE_LIMIT); UpdateProgress(progress, ++progressCnt); await FaceApiClient.DeletePersonGroupAsync(whitelistId); await Task.Delay(RATE_LIMIT); UpdateProgress(progress, ++progressCnt); Debug.WriteLine("Deleted old group"); var log = new Log { message = "Deleted old group" }; GuildWebApi.updateLog(log); } catch (FaceAPIException ce) { // Group not found if (ce.ErrorCode == "PersonGroupNotFound") { Debug.WriteLine("The group doesn't exist"); var log = new Log { message = "The group doesn't exist" }; GuildWebApi.updateLog(log); } else { throw ce; } } await FaceApiClient.CreatePersonGroupAsync(WhitelistId, "White List"); await Task.Delay(RATE_LIMIT); UpdateProgress(progress, ++progressCnt); await BuildWhiteListAsync(progress, progressCnt); } catch (FaceAPIException ce) { isSuccess = false; Debug.WriteLine("ClientException in CreateWhitelistFromFolderAsync : " + ce.ErrorCode); var log = new Log { message = "ClientException in CreateWhitelistFromFolderAsync : " + ce.ErrorCode }; GuildWebApi.updateLog(log); } catch (Exception e) { isSuccess = false; Debug.WriteLine("Exception in CreateWhitelistFromFolderAsync : " + e.Message); var log = new Log { message = "Exception in CreateWhitelistFromFolderAsync : " + e.Message }; GuildWebApi.updateLog(log); } // progress to 100% UpdateProgress(progress, 100); return isSuccess; } /// <summary> /// Use whitelist folder to build whitelist Database /// </summary> /// <returns></returns> private async Task BuildWhiteListAsync(IProgress<int> progress, double progressCnt) { Debug.WriteLine("Start building whitelist from " + _whitelistFolder.Path); var log = new Log { message = "Start building whitelist from " + _whitelistFolder.Path }; GuildWebApi.updateLog(log); var personas = await GuildWebApi.getWhiteList(); var progressStep = (100.0 - progressCnt) / personas.Count; foreach (var persona in personas) { var personName = persona.name; // create new person var personId = await CreatePerson(personName); persona.faceApiId = personId; // iterate all images and add to whitelist foreach (var imageUrl in persona.imageUrls) { Debug.WriteLine("BuildWhiteList: Processing " + imageUrl); GuildWebApi.updateLog(new Log { message = "BuildWhiteList: Processing " + imageUrl }); try { var faceId = await DetectFaceFromImage(imageUrl); Debug.WriteLine("Face identified: " + faceId); await AddFace(personId, faceId, imageUrl); Debug.WriteLine("This image added to whitelist successfully!"); } catch (FaceRecognitionException fe) { switch (fe.ExceptionType) { case FaceRecognitionExceptionType.InvalidImage: Debug.WriteLine("WARNING: This file is not a valid image!"); break; case FaceRecognitionExceptionType.NoFaceDetected: Debug.WriteLine("WARNING: No face detected in this image"); GuildWebApi.updateLog(new Log { message = "WARNING: No face detected in this image: " + imageUrl }); break; //case FaceRecognitionExceptionType.MultipleFacesDetected: // Debug.WriteLine("WARNING: Multiple faces detected, ignored this image"); // break; } } // update progress progressCnt += progressStep; UpdateProgress(progress, progressCnt); } } PersonManager.personas = personas; await TrainingWhitelistAsync(); Debug.WriteLine("Whitelist created successfully!"); GuildWebApi.updateLog(new Log { message = "Whitelist created successfully!" }); } #endregion #region Face public async Task AddFaceByUrl(Guid personId, string imageUrl) { await FaceApiClient.AddPersonFaceAsync(WhitelistId, personId, imageUrl); await Task.Delay(RATE_LIMIT); } /// <summary> /// Add face to both Cloud Face API and local whitelist /// </summary> /// <param name="personId"></param> /// <param name="faceId"></param> /// <param name="imagePath"></param> /// <returns></returns> private async Task AddFace(Guid personId, Guid faceId, string imageUrl) { await FaceApiClient.AddPersonFaceAsync(WhitelistId, personId, imageUrl); await Task.Delay(RATE_LIMIT); /*await Task.Run(async () => { using (Stream imageStream = File.OpenRead(imagePath)) { await FaceApiClient.AddPersonFaceAsync(WhitelistId, personId, imageStream); await Task.Delay(RATE_LIMIT); } }); _whitelist.AddFace(personId, faceId, imagePath);*/ } /// <summary> /// Remove face from both Cloud Face API and local whitelist /// </summary> /// <param name="personId"></param> /// <param name="faceId"></param> /// <returns></returns> private async Task RemoveFace(Guid personId, Guid faceId) { await FaceApiClient.DeletePersonFaceAsync(WhitelistId, personId, faceId); await Task.Delay(RATE_LIMIT); _whitelist.RemoveFace(personId, faceId); } /// <summary> /// Detect face and return the face id of a image file /// </summary> /// <param name="imageFile"> /// image file to detect face /// Note: the image must only contains exactly one face /// </param> /// <returns>face id</returns> private async Task<Guid> DetectFaceFromImage(string imageUrl) { //var stream = await imageFile.OpenStreamForReadAsync(); var faces = await FaceApiClient.DetectAsync(imageUrl); await Task.Delay(RATE_LIMIT); if (faces == null || faces.Length < 1) { throw new FaceRecognitionException(FaceRecognitionExceptionType.NoFaceDetected); } else if (faces.Length > 1) { throw new FaceRecognitionException(FaceRecognitionExceptionType.MultipleFacesDetected); } return faces[0].FaceId; } /// <summary> /// Detect face and return the face id of a image file /// </summary> /// <param name="imageFile"> /// image file to detect face /// </param> /// <returns>face id</returns> private async Task<Guid[]> DetectFacesFromImage(StorageFile imageFile) { var stream = await imageFile.OpenStreamForReadAsync(); var faces = await FaceApiClient.DetectAsync(stream); await Task.Delay(RATE_LIMIT); if (faces == null || faces.Length < 1) { throw new FaceRecognitionException(FaceRecognitionExceptionType.NoFaceDetected); } return FaceApiUtils.FacesToFaceIds(faces); } /* public async Task<bool> AddImageToWhitelistAsync(StorageFile imageFile, string personName = null) { bool isSuccess = true; // imageFile should be valid image file if (!FaceApiUtils.ValidateImageFile(imageFile)) { isSuccess = false; } else { var filePath = imageFile.Path; // If personName is null/empty, use the folder name as person name if (string.IsNullOrEmpty(personName)) { personName = await FaceApiUtils.GetParentFolderNameAsync(imageFile); } // If person name doesn't exists, add it var personId = _whitelist.GetPersonIdByName(personName); if (personId == Guid.Empty) { var folder = await imageFile.GetParentAsync(); personId = await CreatePerson(personName); } // detect faces var faceId = await DetectFaceFromImage(imageFile); await AddFace(personId, faceId, imageFile.Path); // train whitelist isSuccess = await TrainingWhitelistAsync(); } return isSuccess; } */ public async Task<bool> RemoveImageFromWhitelistAsync(StorageFile imageFile, string personName = null) { bool isSuccess = true; if (!FaceApiUtils.ValidateImageFile(imageFile)) { isSuccess = false; } else { // If personName is null use the folder name as person name if (string.IsNullOrEmpty(personName)) { personName = await FaceApiUtils.GetParentFolderNameAsync(imageFile); } var personId = _whitelist.GetPersonIdByName(personName); var faceId = _whitelist.GetFaceIdByFilePath(imageFile.Path); if (personId == Guid.Empty || faceId == Guid.Empty) { isSuccess = false; } else { await RemoveFace(personId, faceId); // train whitelist isSuccess = await TrainingWhitelistAsync(); } } return isSuccess; } #endregion #region Person /// <summary> /// Create a person into Face API and whitelist /// </summary> /// <param name="personName"></param> /// <param name="personFolder"></param> /// <returns></returns> private async Task<Guid> CreatePerson(string personName) { try { await Task.Delay(RATE_LIMIT); var ret = await FaceApiClient.CreatePersonAsync(WhitelistId, personName); var personId = ret.PersonId; //_whitelist.AddPerson(personId, personName, personFolder.Path); return personId; } catch (FaceAPIException ex) { Debug.WriteLine("FaceAPIException" + ex.ErrorCode + " " + ex.ErrorMessage); var log = new Log { message = "FaceAPIException on creating " + personName + ex.ErrorCode + " " + ex.ErrorMessage }; GuildWebApi.updateLog(log); throw ex; } catch (Exception ex) { Debug.WriteLine(ex.Message); throw ex; } } private async Task RemovePerson(Guid personId) { await FaceApiClient.DeletePersonAsync(WhitelistId, personId); await Task.Delay(RATE_LIMIT); _whitelist.RemovePerson(personId); } /*public async Task<bool> AddPersonToWhitelistAsync(StorageFolder faceImagesFolder, string personName = null) { bool isSuccess = true; if (faceImagesFolder == null) { isSuccess = false; } else { // use folder name if do not have personName if (string.IsNullOrEmpty(personName)) { personName = faceImagesFolder.Name; } var personId = await CreatePerson(personName, faceImagesFolder); var files = await faceImagesFolder.GetFilesAsync(); // iterate all files and add to whitelist foreach (var file in files) { try { // detect faces var faceId = await DetectFaceFromImage(file); await AddFace(personId, faceId, file.Path); } catch (FaceRecognitionException fe) { switch (fe.ExceptionType) { case FaceRecognitionExceptionType.InvalidImage: Debug.WriteLine("WARNING: This file is not a valid image!"); break; case FaceRecognitionExceptionType.NoFaceDetected: Debug.WriteLine("WARNING: No face detected in this image"); break; case FaceRecognitionExceptionType.MultipleFacesDetected: Debug.WriteLine("WARNING: Multiple faces detected, ignored this image"); break; } } } // train whitelist isSuccess = await TrainingWhitelistAsync(); } return isSuccess; } */ public async Task<bool> RemovePersonFromWhitelistAsync(string personName) { bool isSuccess = true; var personId = _whitelist.GetPersonIdByName(personName); if (personId == Guid.Empty) { isSuccess = false; } else { // remove all faces belongs to this person var faceIds = _whitelist.GetAllFaceIdsByPersonId(personId); if (faceIds != null) { var faceIdsArr = faceIds.ToArray(); for (int i = 0; i < faceIdsArr.Length; i++) { await RemoveFace(personId, faceIdsArr[i]); } } // remove person await RemovePerson(personId); // train whitelist isSuccess = await TrainingWhitelistAsync(); } return isSuccess; } #endregion #region Face recognition public async Task<IdentifyResult[]> FaceRecognizeAsync(StorageFile imageFile) { var recogResult = new List<string>(); if (!FaceApiUtils.ValidateImageFile(imageFile)) { throw new FaceRecognitionException(FaceRecognitionExceptionType.InvalidImage); } // detect all faces in the image var faceIds = await DetectFacesFromImage(imageFile); ; // try to identify all faces to person var identificationResults = await FaceApiClient.IdentifyAsync(WhitelistId, faceIds); await Task.Delay(RATE_LIMIT); // add identified person name to result list foreach (var result in identificationResults) { if (result.Candidates.Length > 0) { //var personName = _whitelist.GetPersonNameById(result.Candidates[0].PersonId); Debug.WriteLine("Face ID Confidence: " + Math.Round(result.Candidates[0].Confidence * 100, 1) + "%"); var log = new Log { message = "Face ID Confidence: " + Math.Round(result.Candidates[0].Confidence * 100, 1) + "%", image = imageFile }; GuildWebApi.updateLog(log); //recogResult.Add(personName); } } return (from result in identificationResults where result.Candidates.Length > 0 select result).ToArray(); } #endregion } }
37.719931
156
0.502528
[ "MIT" ]
shypeleg/SergeyMonitor
DormRoomMonitor/FaceApiRecognizer.cs
21,955
C#
using System; using System.Collections.Generic; using System.Text; namespace FootballTeamGenerator.Common { public static class GlobalConstants { public static string InvalidStatExceptionMessage = "{0} should be between {1} and {2}."; public static string EmptyNameExceptionMessage = "A name should not be empty."; public static string RemovingMissingPlayerExceptionMessage = "Player {0} is not in {1} team."; public static string MissingTeamExceptionMessage = "Team {0} does not exist."; } }
35.933333
102
0.721707
[ "MIT" ]
MirelaMileva/C-Sharp-OOP
Encapsulation/FootballTeamGenerator/Common/GlobalConstants.cs
541
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. //--------------------------------------------------------------------------- // // // // This file was generated, please do not edit it directly. // // Please see MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Runtime.InteropServices; using MS.Internal.PresentationCore; #if PRESENTATION_CORE using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; #else using SR=System.Windows.SR; using SRID=System.Windows.SRID; #endif namespace System.Windows.Media { internal static partial class ValidateEnums { /// <summary> /// Returns whether or not an enumeration instance a valid value. /// This method is designed to be used with ValidateValueCallback, and thus /// matches it's prototype. /// </summary> /// <param name="valueObject"> /// Enumeration value to validate. /// </param> /// <returns> 'true' if the enumeration contains a valid value, 'false' otherwise. </returns> public static bool IsStretchValid(object valueObject) { Stretch value = (Stretch) valueObject; return (value == Stretch.None) || (value == Stretch.Fill) || (value == Stretch.Uniform) || (value == Stretch.UniformToFill); } } }
33.54902
101
0.57218
[ "MIT" ]
00mjk/wpf
src/Microsoft.DotNet.Wpf/src/Shared/MS/Internal/Generated/StretchValidation.cs
1,711
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using DotNetCoreSqlDb.Models; namespace DotNetCoreSqlDb { 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) { // Add framework services. services.AddMvc(); //services.AddDbContext<MyDatabaseContext>(options => // options.UseSqlite("Data Source=localdatabase.db")); // Use SQL Database if in Azure, otherwise, use SQLite if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production") services.AddDbContext<MyDatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection"))); else services.AddDbContext<MyDatabaseContext>(options => options.UseSqlite("Data Source=localdatabase.db")); // Automatically perform database migration services.BuildServiceProvider().GetService<MyDatabaseContext>().Database.Migrate(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Todos}/{action=Index}/{id?}"); }); } } }
34.164384
109
0.619888
[ "MIT" ]
zhangzhhjb/TestWebApp
Startup.cs
2,496
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 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor.Management.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Azure.Management.Monitor.Management; using Newtonsoft.Json; using System.Linq; /// <summary> /// The resource from which the rule collects its data. /// </summary> public partial class RuleDataSource { /// <summary> /// Initializes a new instance of the RuleDataSource class. /// </summary> public RuleDataSource() { } /// <summary> /// Initializes a new instance of the RuleDataSource class. /// </summary> /// <param name="resourceUri">the resource identifier of the resource /// the rule monitors.</param> public RuleDataSource(string resourceUri = default(string)) { ResourceUri = resourceUri; } /// <summary> /// Gets or sets the resource identifier of the resource the rule /// monitors. /// </summary> [JsonProperty(PropertyName = "resourceUri")] public string ResourceUri { get; set; } } }
32.021277
77
0.646512
[ "MIT" ]
azuresdkci1x/azure-sdk-for-net-1722
src/SDKs/Monitor/Management.Monitor/Generated/Management/Monitor/Models/RuleDataSource.cs
1,505
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class HealthManager : MonoBehaviour { public static HealthManager instance; public int currentHealth, maxHealth; public int lives = 3; public float invincibleLength = 2f; private float invincCounter; public Sprite[] healthBarImages; public int soundDeath, soundDeath2, soundHurt; public bool isDeath = false; public Animator anim; private void Awake() { instance = this; } // Start is called before the first frame update void Start() { ResetHealth(); } // Update is called once per frame void Update() { if (invincCounter > 0) { invincCounter -= Time.deltaTime; for (int i = 0; i < PlayerController_s.instance.playerPieces.Length; i++) { if (Mathf.Floor(invincCounter * 5f) % 2 == 0) //even or odd number, for flashing { PlayerController_s.instance.playerPieces[i].SetActive(true); } else { PlayerController_s.instance.playerPieces[i].SetActive(false); } if (invincCounter <= 0) { PlayerController_s.instance.playerPieces[i].SetActive(true); } } } } public void Hurt() { if (isDeath == false) { if (invincCounter <= 0) { currentHealth -= 1; if (currentHealth <= 0) { AudioManager.instance.PlaySfx(soundDeath); AudioManager.instance.PlaySfx(soundDeath2); currentHealth = 0; anim.SetBool("isDeath", true); isDeath = true; anim.SetTrigger("Death"); PlayerController_s.instance.Knockback(); PlayerController_s.instance.stopMove = true; GameManager.instance.Respawn(); } else { AudioManager.instance.PlaySfx(soundHurt); anim.SetTrigger("Hurt"); anim.SetBool("isDeath", false); PlayerController_s.instance.Knockback(); invincCounter = invincibleLength; } UpdateUI(); } } } public void HurtDeath() { if(isDeath == false) { if (invincCounter <= 0) { currentHealth = 0; anim.SetBool("isDeath", true); isDeath = true; anim.SetTrigger("Death"); PlayerController_s.instance.Knockback(); PlayerController_s.instance.stopMove = true; AudioManager.instance.PlaySfx(soundDeath); AudioManager.instance.PlaySfx(soundDeath2); GameManager.instance.Respawn(); UpdateUI(); } } } public void ResetHealth() { anim.SetBool("isDeath", false); currentHealth = maxHealth; isDeath = false; //PlayerController_s.instance.stopMove = true; //PlayerController.instance.stopMove = false; UIManager.instance.healthImage.enabled = true; UpdateUI(); } public void ResetHealth2() { anim.SetBool("isDeath", false); currentHealth = maxHealth; isDeath = false; UIManager.instance.healthImage.enabled = true; UpdateUI(); } public void AddHealth(int amountToHeal) { if (isDeath == false) { currentHealth += amountToHeal; if (currentHealth > maxHealth) { currentHealth = maxHealth; } UpdateUI(); } } public void UpdateUI() { //UIManager.instance.healthText.text = currentHealth.ToString(); UIManager.instance.healthText.text = lives.ToString(); switch (currentHealth) { case 5: UIManager.instance.healthImage.sprite = healthBarImages[4]; break; case 4: UIManager.instance.healthImage.sprite = healthBarImages[3]; break; case 3: UIManager.instance.healthImage.sprite = healthBarImages[2]; break; case 2: UIManager.instance.healthImage.sprite = healthBarImages[1]; break; case 1: UIManager.instance.healthImage.sprite = healthBarImages[0]; break; case 0: UIManager.instance.healthImage.sprite = healthBarImages[5]; break; } } public void PlayerKilled() { AudioManager.instance.PlaySfx(soundDeath); AudioManager.instance.PlaySfx(soundDeath2); anim.SetBool("isDeath", true); isDeath = true; anim.SetTrigger("Death"); currentHealth = 0; UpdateUI(); lives--; } }
27.835979
96
0.515111
[ "MIT" ]
uvg-cc3063/proyecto-libre-alejandro-diego-ukron
Assets/Scripts/Managers/HealthManager.cs
5,263
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Havit.WebApplicationTest.HavitWebBootstrapTests { public partial class TabsTest : System.Web.UI.Page { protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { TabContainersRepeater.DataSource = new int[] { 1, 2, 3 }; TabContainersRepeater.DataBind(); } } } }
20.391304
61
0.724947
[ "MIT" ]
havit/HavitFramework
WebApplicationTest/HavitWebBootstrapTests/TabsTest.aspx.cs
471
C#
using ShoppingCore.Application.ApplicationModelsMapper; using ShoppingCore.Application.ApplicationModels; using ShoppingCore.Application.Interfaces; using ShoppingCore.Domain.Customers; using ShoppingCore.Domain.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace ShoppingCore.Application.Customers.Queries.GetAllCustomers { public class GetAllCustomers : IGetAllCustomers { IPersistence<IEntity> _persistence; public GetAllCustomers(IPersistence<IEntity> persistence) { _persistence = persistence; } #region -good Ol'code- //public IEnumerable<IAppModel> Execute() //{ // var allCustomers = _persistence.Customers.List(); // foreach (var customer in allCustomers) // { // yield return ConvertToAppModel(customer); // } //} //public IEnumerable<T> Execute<T>() where T:IAppModel //{ // var allCustomers = _persistence.Customers.List(); // foreach (var customer in allCustomers) // { // yield return ConvertToAppModel<T>(customer); // } //} #endregion public IQueryable<CustomerModel> Execute() { var customers = _persistence.Customers.List().MapCustomerModel(); return customers; } //possible duplication of code private IAppModel ConvertToAppModel(IEntity entity) { if (entity is Customer) { var customer = entity as Customer; var customerModel = new CustomerModel() { UserID = customer.User.UserID, UserName = customer.User.UserName, Password = customer.User.Password, IsAutheticated = customer.User.IsAutheticated, AutheticationType = customer.User.AutheticationType, UserRole = customer.User.UserRole, CustomerID = customer.CustomerID, FirstName = customer.FirstName, MiddleName = customer.MiddleName, LastName = customer.LastName, Gender = customer.Gender, DateOfBirth = customer.DateOfBirth }; //customer.Addresses.ForEach(a => customerModel.Addresses.Add( // new AddressModel() // { // AddressLine1 = a.AddressLine1, // AddressLine2 = a.AddressLine2, // AddressLine3 = a.AddressLine3, // AddressLine4 = a.AddressLine4, // AddressLine5 = a.AddressLine5, // AddressType = a.AddressType, // City = a.City, // Country = a.Country, // District = a.District, // LandMark = a.LandMark, // PinCode = a.PinCode, // AddressID = a.AddressID, // CustomerID = customer.CustomerID // })); return customerModel; } else { return null; } } private T ConvertToAppModel<T>(IEntity entity) where T:IAppModel { if (typeof(T) == typeof(CustomerModel)) { if (entity is Customer) { var customer = entity as Customer; var customerModel = new CustomerModel() { UserID = customer.User.UserID, UserName = customer.User.UserName, Password = customer.User.Password, IsAutheticated = customer.User.IsAutheticated, AutheticationType = customer.User.AutheticationType, UserRole = customer.User.UserRole, CustomerID = customer.CustomerID, FirstName = customer.FirstName, MiddleName = customer.MiddleName, LastName = customer.LastName, Gender = customer.Gender, DateOfBirth = customer.DateOfBirth }; //customer.Addresses.ForEach(a => customerModel.Addresses.Add( // new AddressModel() // { // AddressLine1 = a.AddressLine1, // AddressLine2 = a.AddressLine2, // AddressLine3 = a.AddressLine3, // AddressLine4 = a.AddressLine4, // AddressLine5 = a.AddressLine5, // AddressType = a.AddressType, // City = a.City, // Country = a.Country, // District = a.District, // LandMark = a.LandMark, // PinCode = a.PinCode, // AddressID = a.AddressID, // CustomerID = customer.CustomerID // })); return (T)(object)customerModel;//Convert.ChangeType(customerModel, typeof(T)); } else { return default(T); } } else { return default(T); } } } }
30.77957
99
0.472314
[ "MIT" ]
chaitradangat/ShoppingCore
Application/ShoppingCore.Application/Customers/Queries/GetAllCustomers/GetAllCustomers.cs
5,727
C#
using Newtonsoft.Json; namespace DevicePortalCoreSDK.Models.OSInformation { /// <summary> /// Model class with information about the machine name. /// </summary> public class MachineNameInformation { /// <summary> /// The name of the computer. /// </summary> [JsonProperty("ComputerName")] public string ComputerName { get; set; } } }
23.588235
60
0.610973
[ "MIT" ]
minusoneteam/DevicePortalCoreSDK
src/DevicePortalCoreSDK/Models/OSInformation/MachineNameInformation.cs
403
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using DDDSample1.Domain.Workblocks; using System; namespace Tests { [TestClass] public class CreatingWorkblockDtoTest { [TestMethod] public void testSetParameters() { string key = "key1"; string vehicleDutyKey = "vdkey"; int startTime = 1; int endTime = 1; List<String> lTripKey = new List<string>() { "key1", "key2" }; CreatingWorkblockDto cwbdto = new CreatingWorkblockDto(key, vehicleDutyKey, lTripKey.ToArray(), startTime, endTime); Assert.AreEqual(cwbdto.Key, key); Assert.AreEqual(cwbdto.VehicleDutyKey, vehicleDutyKey); Assert.AreEqual(cwbdto.StartTime, startTime); Assert.AreEqual(cwbdto.EndTime, endTime); } } }
31.321429
128
0.633979
[ "MIT" ]
TRibeiro94/ISEP-ARQSI-2020
Semester_Project/MDV/Tests/UnitTests/Domain/Workblocks/CreatingWorkblockDtoTest.cs
877
C#
using UnityEngine; using UnityEngine.Networking; using UnityStandardAssets.Characters.FirstPerson; using UnityStandardAssets.CrossPlatformInput; public class MultiPlayerFPS : NetworkBehaviour { public GameObject FPSCamera; public GameObject model; public GameObject disc; public float throwForce = 10f; private NetworkManager NetworkMgr; // Use this for initialization void Start () { NetworkMgr = GameObject.Find("/VFNetworkManager").GetComponent<NetworkManager>(); if (NetworkMgr == null) Debug.LogError("Couldn't find NetworkManager!"); } override public void OnStartLocalPlayer() { GetComponent<RigidbodyFirstPersonController>().enabled = true; this.model.SetActive(false); Debug.Log("Activitating local camera"); this.FPSCamera.SetActive(true); } // Update is called once per frame void FixedUpdate () { if (CrossPlatformInputManager.GetButtonDown("Fire1")) { CmdFire(transform.position, transform.forward); } } [Command] public void CmdFire(Vector3 position, Vector3 direction) { GameObject newdisc = GameObject.Instantiate(disc); newdisc.GetComponent<FrisbeeFlight>().ThrowDisc(position, direction * throwForce); NetworkServer.Spawn(newdisc); } }
29.488889
90
0.700075
[ "MIT" ]
BahuMan/VirtualFrisbee
Assets/players/MultiPlayerFPS.cs
1,329
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using StarkPlatform.CodeAnalysis.Stark.Symbols; using StarkPlatform.CodeAnalysis.Stark.Syntax; using StarkPlatform.CodeAnalysis.Text; namespace StarkPlatform.CodeAnalysis.Stark.Symbols { /// <summary> /// Represents a label in method body /// </summary> internal abstract class LabelSymbol : Symbol, ILabelSymbol { /// <summary> /// Returns false because label can't be defined externally. /// </summary> public override bool IsExtern { get { return false; } } /// <summary> /// Returns false because label can't be sealed. /// </summary> public override bool IsSealed { get { return false; } } /// <summary> /// Returns false because label can't be abstract. /// </summary> public override bool IsAbstract { get { return false; } } /// <summary> /// Returns false because label can't be overridden. /// </summary> public override bool IsOverride { get { return false; } } /// <summary> /// Returns false because label can't be virtual. /// </summary> public override bool IsVirtual { get { return false; } } /// <summary> /// Returns false because label can't be static. /// </summary> public override bool IsStatic { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } /// <summary> /// Returns 'NotApplicable' because label can't be used outside the member body. /// </summary> public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Gets the locations where the symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public override ImmutableArray<Location> Locations { get { throw new NotSupportedException(); } } internal virtual SyntaxNodeOrToken IdentifierNodeOrToken { get { return default(SyntaxNodeOrToken); } } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitLabel(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitLabel(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitLabel(this); } /// <summary> /// Gets the immediately containing symbol of the <see cref="LabelSymbol"/>. /// It should be the <see cref="MethodSymbol"/> containing the label in its body. /// </summary> public virtual MethodSymbol ContainingMethod { get { throw new NotSupportedException(); } } /// <summary> /// Gets the immediately containing symbol of the <see cref="LabelSymbol"/>. /// It should be the <see cref="MethodSymbol"/> containing the label in its body. /// </summary> public override Symbol ContainingSymbol { get { throw new NotSupportedException(); } } /// <summary> /// Returns value 'Label' of the <see cref="SymbolKind"/> /// </summary> public override SymbolKind Kind { get { return SymbolKind.Label; } } #region ILabelSymbol Members IMethodSymbol ILabelSymbol.ContainingMethod { get { return this.ContainingMethod; } } #endregion #region ISymbol Members public override void Accept(SymbolVisitor visitor) { visitor.VisitLabel(this); } public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitLabel(this); } #endregion } }
27
161
0.529235
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Compilers/Stark/Portable/Symbols/LabelSymbol.cs
5,321
C#
using ReportPluginFramework; namespace Reports { public class DailyMeanDischarge : DailyMeanDischargeNamespace.ReportPluginBase, IFileReport { public override void AddReportSpecificTables(System.Data.DataSet dataSet) { DailyMeanDischargeNamespace.ReportSpecificTableBuilder.AddReportSpecificTables(dataSet); } } }
28
100
0.75
[ "Apache-2.0" ]
AquaticInformatics/time-series-custom-reports
src/Reports/DailyMeanDischarge/DailyMeanDischarge.cs
366
C#
using UnityEngine; public static class Ego { public static EgoComponent AddGameObject( GameObject gameObject ) { var egoComponent = AddGameObjectToChildren( gameObject.transform ); EgoEvents<AddedGameObject>.AddEvent( new AddedGameObject( gameObject, egoComponent ) ); return egoComponent; } private static EgoComponent AddGameObjectToChildren( Transform transform ) { for (int i = 0; i < transform.childCount; i++) { AddGameObjectToChildren( transform.GetChild( i ) ); } var egoComponent = transform.GetComponent<EgoComponent>(); if( egoComponent == null ) { egoComponent = transform.gameObject.AddComponent<EgoComponent>(); } egoComponent.CreateMask(); return egoComponent; } public static C AddComponent<C>( EgoComponent egoComponent ) where C : Component { C component = null; if( !egoComponent.TryGetComponents<C>( out component ) ) { component = egoComponent.gameObject.AddComponent<C>(); egoComponent.mask[ ComponentIDs.Get( typeof( C ) ) ] = true; EgoEvents<AddedComponent<C>>.AddEvent( new AddedComponent<C>( component, egoComponent ) ); } return component; } public static void DestroyGameObject( EgoComponent egoComponent ) { var gameObject = egoComponent.gameObject; EgoEvents<DestroyedGameObject>.AddEvent( new DestroyedGameObject( gameObject, egoComponent ) ); EgoCleanUp.Destroy( egoComponent.gameObject ); } public static bool DestroyComponent<C>( EgoComponent egoComponent ) where C : Component { C component = null; if( !egoComponent.TryGetComponents<C>( out component ) ){ return false; } var e = new DestroyedComponent<C>( component, egoComponent ); EgoEvents<DestroyedComponent<C>>.AddEvent( e ); EgoCleanUp<C>.Destroy( egoComponent, component ); return true; } public static void SetParent( EgoComponent parent, EgoComponent child ) { if( child == null ){ Debug.LogWarning( "Cannot set the Parent of a null Child" ); } EgoEvents<SetParent>.AddEvent( new SetParent( parent, child ) ); } }
30.432836
97
0.725846
[ "MIT" ]
andoowhy/EgoCS
Ego.cs
2,041
C#
/* Dataphor © Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ #define UseReferenceDerivation #define UseElaborable using System; using System.Text; using System.Threading; using System.Collections; using Alphora.Dataphor.DAE.Language; using Alphora.Dataphor.DAE.Language.D4; using Alphora.Dataphor.DAE.Compiling; using Alphora.Dataphor.DAE.Server; using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Runtime.Instructions; using Alphora.Dataphor.DAE.Device.ApplicationTransaction; using Schema = Alphora.Dataphor.DAE.Schema; namespace Alphora.Dataphor.DAE.Runtime.Instructions { // operator iUnion(table{}, table{}) : table{} public class UnionNode : BinaryTableNode { // EnforcePredicate private bool _enforcePredicate = true; public bool EnforcePredicate { get { return _enforcePredicate; } set { _enforcePredicate = value; } } protected override void DetermineModifiers(Plan plan) { base.DetermineModifiers(plan); EnforcePredicate = Boolean.Parse(LanguageModifiers.GetModifier(Modifiers, "EnforcePredicate", EnforcePredicate.ToString())); } public override void DetermineDataType(Plan plan) { DetermineModifiers(plan); if (Nodes[0].DataType.Is(Nodes[1].DataType)) Nodes[0] = Compiler.Upcast(plan, Nodes[0], Nodes[1].DataType); else if (Nodes[1].DataType.Is(Nodes[0].DataType)) Nodes[1] = Compiler.Upcast(plan, Nodes[1], Nodes[0].DataType); else { ConversionContext context = Compiler.FindConversionPath(plan, Nodes[0].DataType, Nodes[1].DataType); if (context.CanConvert) Nodes[0] = Compiler.Upcast(plan, Compiler.ConvertNode(plan, Nodes[0], context), Nodes[1].DataType); else { context = Compiler.FindConversionPath(plan, Nodes[1].DataType, Nodes[0].DataType); Compiler.CheckConversionContext(plan, context); Nodes[1] = Compiler.Upcast(plan, Compiler.ConvertNode(plan, Nodes[1], context), Nodes[0].DataType); } } _dataType = new Schema.TableType(); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; _tableVar.InheritMetaData(LeftTableVar.MetaData); _tableVar.JoinInheritMetaData(RightTableVar.MetaData); // Determine columns CopyTableVarColumns(LeftTableVar.Columns); Schema.TableVarColumn leftColumn; foreach (Schema.TableVarColumn rightColumn in RightTableVar.Columns) { leftColumn = TableVar.Columns[TableVar.Columns.IndexOfName(rightColumn.Name)]; leftColumn.IsDefaultRemotable = leftColumn.IsDefaultRemotable && rightColumn.IsDefaultRemotable; leftColumn.IsChangeRemotable = leftColumn.IsChangeRemotable && rightColumn.IsChangeRemotable; leftColumn.IsValidateRemotable = leftColumn.IsValidateRemotable && rightColumn.IsValidateRemotable; leftColumn.JoinInheritMetaData(rightColumn.MetaData); } DetermineRemotable(plan); // Determine key Schema.Key key = new Schema.Key(); key.IsInherited = true; foreach (Schema.TableVarColumn column in TableVar.Columns) key.Columns.Add(column); TableVar.Keys.Add(key); DetermineOrder(plan); // Determine orders CopyOrders(LeftTableVar.Orders); foreach (Schema.Order order in RightTableVar.Orders) if (!TableVar.Orders.Contains(order)) TableVar.Orders.Add(CopyOrder(order)); #if UseReferenceDerivation // NOTE: This isn't exactly the same, as the previous logic would copy source references from both tables, then target references from both tables. Shouldn't be an issue but.... #if UseElaborable if (plan.CursorContext.CursorCapabilities.HasFlag(CursorCapability.Elaborable)) #endif { CopyReferences(plan, LeftTableVar); CopyReferences(plan, RightTableVar); } #endif } private void DetermineOrder(Plan plan) { Order = Compiler.OrderFromKey(plan, _tableVar.Keys.MinimumKey(true)); } public override void DetermineCharacteristics(Plan plan) { base.DetermineCharacteristics(plan); // Set IsNilable for each column in the left and right tables based on PropagateXXXLeft and Right bool isNilable = (PropagateInsertLeft == PropagateAction.False) || !PropagateUpdateLeft || (PropagateInsertRight == PropagateAction.False) || !PropagateUpdateRight; if (isNilable) foreach (Schema.TableVarColumn column in TableVar.Columns) column.IsNilable = isNilable; } public override void DetermineCursorBehavior(Plan plan) { if ((LeftNode.CursorType == CursorType.Dynamic) || (RightNode.CursorType == CursorType.Dynamic)) _cursorType = CursorType.Dynamic; else _cursorType = CursorType.Static; _requestedCursorType = plan.CursorContext.CursorType; _cursorCapabilities = CursorCapability.Navigable | CursorCapability.BackwardsNavigable | ( (plan.CursorContext.CursorCapabilities & CursorCapability.Updateable) & ( (LeftNode.CursorCapabilities & CursorCapability.Updateable) | (RightNode.CursorCapabilities & CursorCapability.Updateable) ) ) | ( plan.CursorContext.CursorCapabilities & (LeftNode.CursorCapabilities | RightNode.CursorCapabilities) & CursorCapability.Elaborable ); _cursorIsolation = plan.CursorContext.CursorIsolation; DetermineOrder(plan); } public override Statement EmitStatement(EmitMode mode) { UnionExpression expression = new UnionExpression(); expression.LeftExpression = (Expression)Nodes[0].EmitStatement(mode); expression.RightExpression = (Expression)Nodes[1].EmitStatement(mode); expression.Modifiers = Modifiers; return expression; } public override object InternalExecute(Program program) { UnionTable table = new UnionTable(this, program); try { table.Open(); return table; } catch { table.Dispose(); throw; } } public override void DetermineRemotable(Plan plan) { base.DetermineRemotable(plan); _tableVar.ShouldValidate = _tableVar.ShouldValidate || LeftTableVar.ShouldValidate || RightTableVar.ShouldValidate; _tableVar.ShouldDefault = _tableVar.ShouldDefault || LeftTableVar.ShouldDefault || RightTableVar.ShouldDefault; _tableVar.ShouldChange = _tableVar.ShouldChange || LeftTableVar.ShouldChange || RightTableVar.ShouldChange; foreach (Schema.TableVarColumn column in _tableVar.Columns) { int columnIndex; Schema.TableVarColumn sourceColumn; columnIndex = LeftTableVar.Columns.IndexOfName(column.Name); if (columnIndex >= 0) { sourceColumn = LeftTableVar.Columns[columnIndex]; column.ShouldDefault = column.ShouldDefault || sourceColumn.ShouldDefault; _tableVar.ShouldDefault = _tableVar.ShouldDefault || column.ShouldDefault; column.ShouldValidate = column.ShouldValidate || sourceColumn.ShouldValidate; _tableVar.ShouldValidate = _tableVar.ShouldValidate || column.ShouldValidate; column.ShouldChange = column.ShouldChange || sourceColumn.ShouldChange; _tableVar.ShouldChange = _tableVar.ShouldChange || column.ShouldChange; } columnIndex = RightTableVar.Columns.IndexOfName(column.Name); if (columnIndex >= 0) { sourceColumn = RightTableVar.Columns[columnIndex]; column.ShouldDefault = column.ShouldDefault || sourceColumn.ShouldDefault; _tableVar.ShouldDefault = _tableVar.ShouldDefault || column.ShouldDefault; column.ShouldValidate = column.ShouldValidate || sourceColumn.ShouldValidate; _tableVar.ShouldValidate = _tableVar.ShouldValidate || column.ShouldValidate; column.ShouldChange = column.ShouldChange || sourceColumn.ShouldChange; _tableVar.ShouldChange = _tableVar.ShouldChange || column.ShouldChange; } } } protected override bool InternalDefault(Program program, Row oldRow, Row newRow, BitArray valueFlags, string columnName, bool isDescending) { if (isDescending) { BitArray localValueFlags = newRow.GetValueFlags(); bool changed = false; if (PropagateDefaultLeft) changed = LeftNode.Default(program, oldRow, newRow, valueFlags, columnName); if (PropagateDefaultRight) changed = RightNode.Default(program, oldRow, newRow, valueFlags, columnName) || changed; if (changed) for (int index = 0; index < newRow.DataType.Columns.Count; index++) if (!localValueFlags[index] && newRow.HasValue(index)) Change(program, oldRow, newRow, valueFlags, newRow.DataType.Columns[index].Name); return changed; } return false; } protected override bool InternalChange(Program program, Row oldRow, Row newRow, BitArray valueFlags, string columnName) { bool changed = false; if (PropagateChangeLeft) changed = LeftNode.Change(program, oldRow, newRow, valueFlags, columnName); if (PropagateChangeRight) changed = RightNode.Change(program, oldRow, newRow, valueFlags, columnName) || changed; return changed; } protected override bool InternalValidate(Program program, Row oldRow, Row newRow, BitArray valueFlags, string columnName, bool isDescending, bool isProposable) { if (isDescending) { bool changed = false; if (PropagateValidateLeft) changed = LeftNode.Validate(program, oldRow, newRow, valueFlags, columnName); if (PropagateValidateRight) changed = RightNode.Validate(program, oldRow, newRow, valueFlags, columnName) || changed; return changed; } return false; } protected void InternalInsertLeft(Program program, Row oldRow, Row newRow, BitArray valueFlags, bool uncheckedValue) { switch (PropagateInsertLeft) { case PropagateAction.True : LeftNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); break; case PropagateAction.Ensure : case PropagateAction.Ignore : using (Row leftRow = new Row(program.ValueManager, LeftNode.DataType.RowType)) { newRow.CopyTo(leftRow); using (Row currentRow = LeftNode.Select(program, leftRow)) { if (currentRow != null) { if (PropagateInsertLeft == PropagateAction.Ensure) LeftNode.Update(program, currentRow, newRow, valueFlags, false, uncheckedValue); } else LeftNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } } break; } } protected void InternalInsertRight(Program program, Row oldRow, Row newRow, BitArray valueFlags, bool uncheckedValue) { switch (PropagateInsertRight) { case PropagateAction.True : RightNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); break; case PropagateAction.Ensure : case PropagateAction.Ignore : using (Row rightRow = new Row(program.ValueManager, RightNode.DataType.RowType)) { newRow.CopyTo(rightRow); using (Row currentRow = RightNode.Select(program, rightRow)) { if (currentRow != null) { if (PropagateInsertRight == PropagateAction.Ensure) RightNode.Update(program, currentRow, newRow, valueFlags, false, uncheckedValue); } else RightNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } } break; } } protected override void InternalExecuteInsert(Program program, Row oldRow, Row newRow, BitArray valueFlags, bool uncheckedValue) { // Attempt to insert the row in the left node. if ((PropagateInsertLeft != PropagateAction.False) && (PropagateInsertRight != PropagateAction.False) && EnforcePredicate) { try { InternalInsertLeft(program, oldRow, newRow, valueFlags, uncheckedValue); } catch (DataphorException exception) { if ((exception.Severity == ErrorSeverity.User) || (exception.Severity == ErrorSeverity.Application)) { InternalInsertRight(program, oldRow, newRow, valueFlags, uncheckedValue); return; } throw; } // Attempt to insert the row in the right node. try { InternalInsertRight(program, oldRow, newRow, valueFlags, uncheckedValue); } catch (DataphorException exception) { if ((exception.Severity != ErrorSeverity.User) && (exception.Severity != ErrorSeverity.Application)) throw; } } else { InternalInsertLeft(program, oldRow, newRow, valueFlags, uncheckedValue); InternalInsertRight(program, oldRow, newRow, valueFlags, uncheckedValue); } } protected override void InternalExecuteUpdate(Program program, Row oldRow, Row newRow, BitArray valueFlags, bool checkConcurrency, bool uncheckedValue) { if (PropagateUpdateLeft && PropagateUpdateRight && EnforcePredicate) { // Attempt to update the row in the left node try { if (PropagateUpdateLeft) { using (Row leftRow = LeftNode.FullSelect(program, oldRow)) { if (leftRow != null) LeftNode.Delete(program, oldRow, checkConcurrency, uncheckedValue); } LeftNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } } catch (DataphorException exception) { if ((exception.Severity == ErrorSeverity.User) || (exception.Severity == ErrorSeverity.Application)) { if (PropagateUpdateRight) { using (Row rightRow = RightNode.FullSelect(program, oldRow)) { if (rightRow != null) RightNode.Delete(program, oldRow, checkConcurrency, uncheckedValue); } RightNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } return; } throw; } // Attempt to update the row in the right node try { if (PropagateUpdateRight) { using (Row rightRow = RightNode.FullSelect(program, oldRow)) { if (rightRow != null) RightNode.Delete(program, oldRow, checkConcurrency, uncheckedValue); } RightNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } } catch (DataphorException exception) { if ((exception.Severity != ErrorSeverity.User) && (exception.Severity != ErrorSeverity.Application)) throw; } } else { if (PropagateUpdateLeft) LeftNode.Update(program, oldRow, newRow, valueFlags, checkConcurrency, uncheckedValue); if (PropagateUpdateRight) RightNode.Update(program, oldRow, newRow, valueFlags, checkConcurrency, uncheckedValue); } } protected override void InternalExecuteDelete(Program program, Row row, bool checkConcurrency, bool uncheckedValue) { if (PropagateDeleteLeft) using (Row leftRow = LeftNode.FullSelect(program, row)) { if (leftRow != null) LeftNode.Delete(program, row, checkConcurrency, uncheckedValue); } if (PropagateDeleteRight) using (Row rightRow = RightNode.FullSelect(program, row)) { if (rightRow != null) RightNode.Delete(program, row, checkConcurrency, uncheckedValue); } } public override void JoinApplicationTransaction(Program program, Row row) { LeftNode.JoinApplicationTransaction(program, row); RightNode.JoinApplicationTransaction(program, row); } } }
34.570796
181
0.69314
[ "BSD-3-Clause" ]
ashalkhakov/Dataphor
Dataphor/DAE/Runtime.Instructions/UnionNode.cs
15,627
C#
using Oscar.BL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Oscar.UI.WPF.UserPages { /// <summary> /// Interaction logic for UserReview.xaml /// </summary> public partial class UserReview : Page { User user = new User(); List<Review> reviewList = new List<Review>(); List<Films> filmsList = new List<Films>(); public UserReview(User userInput) { InitializeComponent(); user = userInput; filmsList = DatabaseManager.Instance.FilmRepository.GetFilms().ToList(); ShowReviews(); } public void ShowReviews() { foreach (var film in filmsList) { reviewList = DatabaseManager.Instance.ReviewRepository.GetReviewsPerFilm(film).ToList(); foreach (var review in reviewList) { if (review.UserId == user.userId) { ListViewItem item = new ListViewItem(); item.Tag = review; item.Content = film.FilmTitle + " (" + review.ReviewScore + "): " + review.ReviewContent; lstUserReviews.Items.Add(item); } } } /* foreach (Review review in reviewList) { string filmTitle = ""; ListViewItem item = new ListViewItem(); if (review.UserId == user.userId) { item.Tag = review; item.Content = review. + " (" + review.ReviewScore + "): " + review.ReviewContent; lstReviews.Items.Add(item); } } */ } private void LstUserReviews_MouseDoubleClick(object sender, MouseButtonEventArgs e) { ListViewItem item = (ListViewItem)lstUserReviews.SelectedItem; Review review = (Review)item.Tag; txtReview.Text = ""; txtReview.Text = review.ReviewContent; } } }
28.847059
113
0.545269
[ "MIT" ]
IVIvk/Oscar
Syntra.Oscar/Oscar.UI.WPF/UserPages/UserReview.xaml.cs
2,454
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GameFinder.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings) (global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.387097
151
0.580675
[ "MIT" ]
mrousavy/GameFinder
GameFinder/Properties/Settings.Designer.cs
1,068
C#
namespace Cars.Data.Models { using Enums; using System; using System.Collections.Generic; public class Car { //--------------- Properties ---------------- public int Id { get; set; } public string Model { get; set; } public int Doors { get; set; } public Transmission Transmission { get; set; } public DateTime ProductionYear { get; set; } //-------- Engine -------- [FK] public int EngineId { get; set; } public Engine Engine { get; set; } //-------- Make ---------- [FK] public int MakeId { get; set; } public Make Make { get; set; } //---- LicensePlate ------ [FK] public int? LicensePlateId { get; set; } public LicensePlate LicensePlate { get; set; } //--------------- Collections --------------- public ICollection<CarDealership> CarsDealerships { get; set; } = new HashSet<CarDealership>(); } }
30.25
103
0.509298
[ "MIT" ]
radrex/SoftuniCourses
C# Web Developer/C# DB/02.Entity Framework Core/05.Entity Relations/Lab/Cars.Data/Models/Car.cs
970
C#
using ACE.Demo.Contracts.Events; using ACE.Demo.Contracts.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ACE; using ACE.Exceptions; using ACE.Demo.Contracts; namespace ACE.Demo.Model.Accounts { public class AccountHandler : HandlerBase, ICommandHandler<CreateAccount>, ICommandHandler<ChangeAccountAmount> { static AccountHandler() { AutoMapper.Mapper.CreateMap<ChangeAccountAmount, AccountAmountChanged>(); AutoMapper.Mapper.CreateMap<CreateAccount, Account>(); AutoMapper.Mapper.CreateMap<CreateAccount, AccountStatusCreated>(); } private IAccountWriteRepository _repository; public AccountHandler(IEventBus eventBus, IAccountWriteRepository repository) : base(eventBus) { _repository = repository; } public void Execute(ChangeAccountAmount command) { if (!_repository.ChangeAmount(command.AccountId, command.Change)) { throw new BusinessException(BusinessStatusCode.Forbidden, "账户余额不足。"); } EventBus.Publish(AutoMapper.Mapper.Map<AccountAmountChanged>(command)); } public void Execute(CreateAccount command) { if (!_repository.Create(AutoMapper.Mapper.Map<Account>(command))) { throw new BusinessException(BusinessStatusCode.Conflict, "账户已存在。"); } EventBus.Publish(AutoMapper.Mapper.Map<AccountStatusCreated>(command)); } } }
32.98
85
0.65373
[ "Apache-2.0" ]
hotjk/ace
ACE.Demo.Model.Write/Accounts/AccountHandler.cs
1,677
C#
using System; namespace CrimsonLibrary.Data.Models.Domain { public class Book : BaseEntity { public bool IsRead { get; set; } = true; public double Pages { get; set; } = 0; } }
18.818182
48
0.603865
[ "MIT" ]
CanaanGM/CrimsonLibrary
CrimsonLibrary/Data/Models/Domain/Book.cs
209
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the shield-2016-06-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Shield.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Shield.Model.Internal.MarshallTransformations { /// <summary> /// DisableApplicationLayerAutomaticResponse Request Marshaller /// </summary> public class DisableApplicationLayerAutomaticResponseRequestMarshaller : IMarshaller<IRequest, DisableApplicationLayerAutomaticResponseRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DisableApplicationLayerAutomaticResponseRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DisableApplicationLayerAutomaticResponseRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Shield"); string target = "AWSShield_20160616.DisableApplicationLayerAutomaticResponse"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-06-02"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetResourceArn()) { context.Writer.WritePropertyName("ResourceArn"); context.Writer.Write(publicRequest.ResourceArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DisableApplicationLayerAutomaticResponseRequestMarshaller _instance = new DisableApplicationLayerAutomaticResponseRequestMarshaller(); internal static DisableApplicationLayerAutomaticResponseRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DisableApplicationLayerAutomaticResponseRequestMarshaller Instance { get { return _instance; } } } }
37.394231
195
0.653638
[ "Apache-2.0" ]
aws/aws-sdk-net
sdk/src/Services/Shield/Generated/Model/Internal/MarshallTransformations/DisableApplicationLayerAutomaticResponseRequestMarshaller.cs
3,889
C#
/* * Copyright (c) 2020 LG Electronics Inc. * * SPDX-License-Identifier: MIT */ using System.Collections.Generic; using System.IO; using System; using UnityEngine; public partial class MeshLoader { private static Color GetColor(Assimp.Color4D color) { return (color == null) ? Color.clear : new Color(color.R, color.G, color.B, color.A); } private static List<string> MaterialSearchPaths = new List<string>() { "", "/textures/", "../", "../materials/", "../materials/textures/", "../../materials/", "../../materials/textures/" }; private static List<string> GetRootTexturePaths(in string parentPath) { var texturePaths = new List<string>(){}; foreach (var matPath in MaterialSearchPaths) { texturePaths.Add(Path.Combine(parentPath, matPath)); } return texturePaths; } class MeshMaterialSet { private readonly int _materialIndex; private readonly Mesh _mesh; private Material _material; public MeshMaterialSet(in Mesh mesh, in int materialIndex) { _mesh = mesh; _materialIndex = materialIndex; } public int MaterialIndex => _materialIndex; public Material Material { get => _material; set => _material = value; } public Mesh Mesh => _mesh; } class MeshMaterialList { private List<MeshMaterialSet> meshMatList = new List<MeshMaterialSet>(); public int Count => meshMatList.Count; public void Add(in MeshMaterialSet meshMatSet) { meshMatList.Add(meshMatSet); } public void SetMaterials(in List<Material> materials) { foreach (var meshMatSet in meshMatList) { meshMatSet.Material = materials[meshMatSet.MaterialIndex]; } } public MeshMaterialSet Get(in int index) { return meshMatList[index]; } } private static bool CheckFileSupport(in string fileExtension) { var isFileSupported = true; switch (fileExtension) { case ".dae": case ".obj": case ".stl": break; default: isFileSupported = false; break; } return isFileSupported; } private static Quaternion GetRotationByFileExtension(in string fileExtension, in string meshPath) { var eulerRotation = Quaternion.identity; switch (fileExtension) { case ".dae": case ".obj": case ".stl": eulerRotation = Quaternion.Euler(90, 0, 0) * Quaternion.Euler(0, 0, 0) * Quaternion.Euler(0, 0, 90); break; default: break; } return eulerRotation; } private static Matrix4x4 ConvertAssimpMatrix4x4ToUnity(in Assimp.Matrix4x4 assimpMatrix) { assimpMatrix.Decompose(out var scaling, out var rotation, out var translation); var pos = new Vector3(translation.X, translation.Y, translation.Z); var q = new Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W); var s = new Vector3(scaling.X, scaling.Y, scaling.Z); return Matrix4x4.TRS(pos, q, s); } private static readonly Assimp.AssimpContext importer = new Assimp.AssimpContext(); private static readonly Assimp.LogStream logstream = new Assimp.LogStream( delegate (String msg, String userData) { Debug.Log(msg); }); private static Assimp.Scene GetScene(in string targetPath, out Quaternion meshRotation) { meshRotation = Quaternion.identity; if (!File.Exists(targetPath)) { Debug.LogError("File doesn't exist: " + targetPath); return null; } var colladaIgnoreConfig = new Assimp.Configs.ColladaIgnoreUpDirectionConfig(true); importer.SetConfig(colladaIgnoreConfig); // logstream.Attach(); var fileExtension = Path.GetExtension(targetPath).ToLower(); if (!CheckFileSupport(fileExtension)) { Debug.LogWarning("Unsupported file extension: " + fileExtension + " -> " + targetPath); return null; } const Assimp.PostProcessSteps postProcessFlags = Assimp.PostProcessSteps.OptimizeGraph | Assimp.PostProcessSteps.OptimizeMeshes | Assimp.PostProcessSteps.CalculateTangentSpace | Assimp.PostProcessSteps.JoinIdenticalVertices | Assimp.PostProcessSteps.RemoveRedundantMaterials | Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.SortByPrimitiveType | Assimp.PostProcessSteps.ValidateDataStructure | Assimp.PostProcessSteps.FindInvalidData | Assimp.PostProcessSteps.MakeLeftHanded; var scene = importer.ImportFile(targetPath, postProcessFlags); if (scene == null) { return null; } // Rotate meshes for Unity world since all 3D object meshes are oriented to right handed coordinates meshRotation = GetRotationByFileExtension(fileExtension, targetPath); return scene; } }
23.825397
105
0.719742
[ "Apache-2.0", "MIT" ]
NamWoo/cloisim
Assets/Scripts/Tools/Mesh/Assimp.Common.cs
4,503
C#
// Copyright (c) 2019, WebsitePanel-Support.net. // Distributed by websitepanel-support.net // Build and fixed by Key4ce - IT Professionals // https://www.key4ce.com // // Original source: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.VPS.RemoteDesktop { public partial class Connect { /// <summary> /// litServerName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal litServerName; /// <summary> /// locTitle control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTitle; /// <summary> /// resolution control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal resolution; /// <summary> /// serverName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal serverName; /// <summary> /// username control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal username; /// <summary> /// password control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal password; /// <summary> /// AspForm control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm AspForm; } }
41.185841
85
0.599269
[ "BSD-3-Clause" ]
Key4ce/Websitepanel
WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/VPS/RemoteDesktop/Connect.aspx.designer.cs
4,654
C#
using System; namespace MvcApplication.Models { public class CreateModel { private string createIdFiled = string.Empty; public string CreateIdField { get { return createIdFiled; } set { this.createIdFiled = value; } } private string createTimeField = string.Empty; public string CreateTimeField { get { return createTimeField; } set { this.createTimeField = value; } } public int CreateId { get; set; } public DateTime CreateTime { get; set; } } public class ModifyModel { private string modifyIdField = string.Empty; public string ModifyIdField { get { return modifyIdField; } set { this.modifyIdField = value; } } private string modifyTimeField = string.Empty; public string ModifyTimeField { get { return modifyTimeField; } set { this.modifyTimeField = value; } } public int ModifyId { get; set; } public DateTime ModifyTime { get; set; } } }
23.609375
55
0.424884
[ "MIT" ]
qesadwzxc/SomethingFunny
TestProject/MvcApplication/Models/Base/CreateAndModifyModel.cs
1,513
C#
// ----------------------------------------------------------------------- // <copyright file="RoleDto.cs" company=""> // Copyright (c) 2015 OSky. All rights reserved. // </copyright> // <last-editor>Lmf</last-editor> // <last-date>2015-01-08 0:31</last-date> // ----------------------------------------------------------------------- using System.ComponentModel.DataAnnotations; using OSky.Core.Data; namespace OSky.UI.Dtos.Identity { public class RoleDto : IAddDto, IEditDto<int> { /// <summary> /// 获取或设置 主键,唯一标识 /// </summary> public int Id { get; set; } /// <summary> /// 获取或设置 角色名称 /// </summary> [Required, StringLength(50)] public string Name { get; set; } /// <summary> /// 获取或设置 角色描述 /// </summary> [StringLength(500)] public string Remark { get; set; } /// <summary> /// 获取或设置 是否是管理员 /// </summary> public bool IsAdmin { get; set; } /// <summary> /// 获取或设置 是否系统角色 /// </summary> public bool IsSystem { get; set; } /// <summary> /// 获取或设置 是否锁定 /// </summary> public bool IsLocked { get; set; } /// <summary> /// 获取或设置 是否选中 /// </summary> public bool Checked { get; set; } } }
24.25
75
0.444772
[ "Apache-2.0" ]
liumeifu/OSky
samples/OSky.UI.Core/Dtos/Identity/RoleDto.cs
1,500
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { /// <summary> /// Helper class that allows us to share lots of logic between the diagnostic analyzer and the /// code refactoring provider. Those can't share a common base class due to their own inheritance /// requirements with <see cref="DiagnosticAnalyzer"/> and <see cref="CodeRefactoringProvider"/>. /// </summary> internal abstract class UseExpressionBodyHelper<TDeclaration> : UseExpressionBodyHelper where TDeclaration : SyntaxNode { public override Option<CodeStyleOption<ExpressionBodyPreference>> Option { get; } public override LocalizableString UseExpressionBodyTitle { get; } public override LocalizableString UseBlockBodyTitle { get; } public override string DiagnosticId { get; } public override ImmutableArray<SyntaxKind> SyntaxKinds { get; } protected UseExpressionBodyHelper( string diagnosticId, LocalizableString useExpressionBodyTitle, LocalizableString useBlockBodyTitle, Option<CodeStyleOption<ExpressionBodyPreference>> option, ImmutableArray<SyntaxKind> syntaxKinds) { DiagnosticId = diagnosticId; Option = option; UseExpressionBodyTitle = useExpressionBodyTitle; UseBlockBodyTitle = useBlockBodyTitle; SyntaxKinds = syntaxKinds; } protected static AccessorDeclarationSyntax GetSingleGetAccessor(AccessorListSyntax accessorList) { if (accessorList != null && accessorList.Accessors.Count == 1 && accessorList.Accessors[0].AttributeLists.Count == 0 && accessorList.Accessors[0].IsKind(SyntaxKind.GetAccessorDeclaration)) { return accessorList.Accessors[0]; } return null; } protected static BlockSyntax GetBodyFromSingleGetAccessor(AccessorListSyntax accessorList) => GetSingleGetAccessor(accessorList)?.Body; public override BlockSyntax GetBody(SyntaxNode declaration) => GetBody((TDeclaration)declaration); public override ArrowExpressionClauseSyntax GetExpressionBody(SyntaxNode declaration) => GetExpressionBody((TDeclaration)declaration); public override bool CanOfferUseExpressionBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer) => CanOfferUseExpressionBody(optionSet, (TDeclaration)declaration, forAnalyzer); public override (bool canOffer, bool fixesError) CanOfferUseBlockBody(OptionSet optionSet, SyntaxNode declaration, bool forAnalyzer) => CanOfferUseBlockBody(optionSet, (TDeclaration)declaration, forAnalyzer); public sealed override SyntaxNode Update(SemanticModel semanticModel, SyntaxNode declaration, OptionSet options, ParseOptions parseOptions, bool useExpressionBody) => Update(semanticModel, (TDeclaration)declaration, options, parseOptions, useExpressionBody); public override Location GetDiagnosticLocation(SyntaxNode declaration) => GetDiagnosticLocation((TDeclaration)declaration); protected virtual Location GetDiagnosticLocation(TDeclaration declaration) => this.GetBody(declaration).Statements[0].GetLocation(); public bool CanOfferUseExpressionBody( OptionSet optionSet, TDeclaration declaration, bool forAnalyzer) { var currentOptionValue = optionSet.GetOption(Option); var preference = currentOptionValue.Value; var userPrefersExpressionBodies = preference != ExpressionBodyPreference.Never; var analyzerDisabled = currentOptionValue.Notification.Severity == ReportDiagnostic.Suppress; // If the user likes expression bodies, then we offer expression bodies from the diagnostic analyzer. // If the user does not like expression bodies then we offer expression bodies from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. if (userPrefersExpressionBodies == forAnalyzer || (!forAnalyzer && analyzerDisabled)) { var expressionBody = this.GetExpressionBody(declaration); if (expressionBody == null) { // They don't have an expression body. See if we could convert the block they // have into one. var options = declaration.SyntaxTree.Options; var conversionPreference = forAnalyzer ? preference : ExpressionBodyPreference.WhenPossible; return TryConvertToExpressionBody(declaration, options, conversionPreference, out var expressionWhenOnSingleLine, out var semicolonWhenOnSingleLine); } } return false; } protected virtual bool TryConvertToExpressionBody( TDeclaration declaration, ParseOptions options, ExpressionBodyPreference conversionPreference, out ArrowExpressionClauseSyntax expressionWhenOnSingleLine, out SyntaxToken semicolonWhenOnSingleLine) { return TryConvertToExpressionBodyWorker( declaration, options, conversionPreference, out expressionWhenOnSingleLine, out semicolonWhenOnSingleLine); } private bool TryConvertToExpressionBodyWorker( SyntaxNode declaration, ParseOptions options, ExpressionBodyPreference conversionPreference, out ArrowExpressionClauseSyntax expressionWhenOnSingleLine, out SyntaxToken semicolonWhenOnSingleLine) { var body = this.GetBody(declaration); return body.TryConvertToArrowExpressionBody( declaration.Kind(), options, conversionPreference, out expressionWhenOnSingleLine, out semicolonWhenOnSingleLine); } protected bool TryConvertToExpressionBodyForBaseProperty( BasePropertyDeclarationSyntax declaration, ParseOptions options, ExpressionBodyPreference conversionPreference, out ArrowExpressionClauseSyntax arrowExpression, out SyntaxToken semicolonToken) { if (this.TryConvertToExpressionBodyWorker( declaration, options, conversionPreference, out arrowExpression, out semicolonToken)) { return true; } var getAccessor = GetSingleGetAccessor(declaration.AccessorList); if (getAccessor?.ExpressionBody != null && BlockSyntaxExtensions.MatchesPreference(getAccessor.ExpressionBody.Expression, conversionPreference)) { arrowExpression = SyntaxFactory.ArrowExpressionClause(getAccessor.ExpressionBody.Expression); semicolonToken = getAccessor.SemicolonToken; return true; } return false; } public (bool canOffer, bool fixesError) CanOfferUseBlockBody( OptionSet optionSet, TDeclaration declaration, bool forAnalyzer) { var currentOptionValue = optionSet.GetOption(Option); var preference = currentOptionValue.Value; var userPrefersBlockBodies = preference == ExpressionBodyPreference.Never; var analyzerDisabled = currentOptionValue.Notification.Severity == ReportDiagnostic.Suppress; var expressionBodyOpt = this.GetExpressionBody(declaration); var canOffer = expressionBodyOpt?.TryConvertToBlock( SyntaxFactory.Token(SyntaxKind.SemicolonToken), false, out var block) == true; if (!canOffer) { return (canOffer, fixesError: false); } var languageVersion = ((CSharpParseOptions)declaration.SyntaxTree.Options).LanguageVersion; if (expressionBodyOpt.Expression.IsKind(SyntaxKind.ThrowExpression) && languageVersion < LanguageVersion.CSharp7) { // If they're using a throw expression in a declaration and it's prior to C# 7 // then always mark this as something that can be fixed by the analyzer. This way // we'll also get 'fix all' working to fix all these cases. return (canOffer, fixesError: true); } var isAccessorOrConstructor = declaration is AccessorDeclarationSyntax || declaration is ConstructorDeclarationSyntax; if (isAccessorOrConstructor && languageVersion < LanguageVersion.CSharp7) { // If they're using expression bodies for accessors/constructors and it's prior to C# 7 // then always mark this as something that can be fixed by the analyzer. This way // we'll also get 'fix all' working to fix all these cases. return (canOffer, fixesError: true); } else if (languageVersion < LanguageVersion.CSharp6) { // If they're using expression bodies prior to C# 6, then always mark this as something // that can be fixed by the analyzer. This way we'll also get 'fix all' working to fix // all these cases. return (canOffer, fixesError: true); } // If the user likes block bodies, then we offer block bodies from the diagnostic analyzer. // If the user does not like block bodies then we offer block bodies from the refactoring provider. // If the analyzer is disabled completely, the refactoring is enabled in both directions. canOffer = userPrefersBlockBodies == forAnalyzer || (!forAnalyzer && analyzerDisabled); return (canOffer, fixesError: false); } public TDeclaration Update( SemanticModel semanticModel, TDeclaration declaration, OptionSet options, ParseOptions parseOptions, bool useExpressionBody) { if (useExpressionBody) { TryConvertToExpressionBody( declaration, declaration.SyntaxTree.Options, ExpressionBodyPreference.WhenPossible, out var expressionBody, out var semicolonToken); var trailingTrivia = semicolonToken.TrailingTrivia .Where(t => t.Kind() != SyntaxKind.EndOfLineTrivia) .Concat(declaration.GetTrailingTrivia()); semicolonToken = semicolonToken.WithTrailingTrivia(trailingTrivia); return WithSemicolonToken( WithExpressionBody( WithBody(declaration, body: null), expressionBody), semicolonToken); } else { return WithSemicolonToken( WithExpressionBody( WithGenerateBody(semanticModel, declaration, options, parseOptions), expressionBody: null), default); } } protected abstract BlockSyntax GetBody(TDeclaration declaration); protected abstract ArrowExpressionClauseSyntax GetExpressionBody(TDeclaration declaration); protected abstract bool CreateReturnStatementForExpression(SemanticModel semanticModel, TDeclaration declaration); protected abstract SyntaxToken GetSemicolonToken(TDeclaration declaration); protected abstract TDeclaration WithSemicolonToken(TDeclaration declaration, SyntaxToken token); protected abstract TDeclaration WithExpressionBody(TDeclaration declaration, ArrowExpressionClauseSyntax expressionBody); protected abstract TDeclaration WithBody(TDeclaration declaration, BlockSyntax body); protected virtual TDeclaration WithGenerateBody( SemanticModel semanticModel, TDeclaration declaration, OptionSet options, ParseOptions parseOptions) { var expressionBody = GetExpressionBody(declaration); var semicolonToken = GetSemicolonToken(declaration); if (expressionBody.TryConvertToBlock( GetSemicolonToken(declaration), CreateReturnStatementForExpression(semanticModel, declaration), out var block)) { return WithBody(declaration, block); } return declaration; } protected TDeclaration WithAccessorList( SemanticModel semanticModel, TDeclaration declaration, OptionSet options, ParseOptions parseOptions) { var expressionBody = GetExpressionBody(declaration); var semicolonToken = GetSemicolonToken(declaration); // When converting an expression-bodied property to a block body, always attempt to // create an accessor with a block body (even if the user likes expression bodied // accessors. While this technically doesn't match their preferences, it fits with // the far more likely scenario that the user wants to convert this property into // a full property so that they can flesh out the body contents. If we keep around // an expression bodied accessor they'll just have to convert that to a block as well // and that means two steps to take instead of one. expressionBody.TryConvertToBlock( GetSemicolonToken(declaration), CreateReturnStatementForExpression(semanticModel, declaration), out var block); var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration); accessor = block != null ? accessor.WithBody(block) : accessor.WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); return WithAccessorList(declaration, SyntaxFactory.AccessorList( SyntaxFactory.SingletonList(accessor))); } protected virtual TDeclaration WithAccessorList(TDeclaration declaration, AccessorListSyntax accessorListSyntax) { throw new NotImplementedException(); } } }
49.779605
171
0.655719
[ "Apache-2.0" ]
DustinCampbell/roslyn
src/Features/CSharp/Portable/UseExpressionBody/Helpers/UseExpressionBodyHelper`1.cs
15,135
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. namespace System.Diagnostics { using System; using System.Collections; using System.Text; using System.Threading; using System.Security; using System.Security.Permissions; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. [Serializable] internal class StackFrameHelper : IDisposable { [NonSerialized] private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; // this field is here only for backwards compatibility of serialization format private MethodBase[] rgMethodBase; #pragma warning disable 414 // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of StackFrameHelper. private Object dynamicMethods; // Field is not used from managed. [NonSerialized] private IntPtr[] rgMethodHandle; private String[] rgAssemblyPath; private IntPtr[] rgLoadedPeAddress; private int[] rgiLoadedPeSize; private IntPtr[] rgInMemoryPdbAddress; private int[] rgiInMemoryPdbSize; // if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info private int[] rgiMethodToken; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; #if FEATURE_EXCEPTIONDISPATCHINFO [OptionalField] private bool[] rgiLastFrameFromForeignExceptionStackTrace; #endif // FEATURE_EXCEPTIONDISPATCHINFO private GetSourceLineInfoDelegate getSourceLineInfo; private int iFrameCount; #pragma warning restore 414 private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, out string sourceFile, out int sourceLine, out int sourceColumn); #if FEATURE_CORECLR private static Type s_symbolsType = null; private static MethodInfo s_symbolsMethodInfo = null; [ThreadStatic] private static int t_reentrancy = 0; #endif public StackFrameHelper(Thread target) { targetThread = target; rgMethodBase = null; rgMethodHandle = null; rgiMethodToken = null; rgiOffset = null; rgiILOffset = null; rgAssemblyPath = null; rgLoadedPeAddress = null; rgiLoadedPeSize = null; rgInMemoryPdbAddress = null; rgiInMemoryPdbSize = null; dynamicMethods = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; getSourceLineInfo = null; #if FEATURE_EXCEPTIONDISPATCHINFO rgiLastFrameFromForeignExceptionStackTrace = null; #endif // FEATURE_EXCEPTIONDISPATCHINFO // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; } // // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename, // rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already // done by GetStackFramesInternal (on Windows for old PDB format). // internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); #if FEATURE_CORECLR if (!fNeedFileInfo) return; // Check if this function is being reentered because of an exception in the code below if (t_reentrancy > 0) return; t_reentrancy++; try { if (s_symbolsMethodInfo == null) { s_symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (s_symbolsType == null) return; s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo"); if (s_symbolsMethodInfo == null) return; } if (getSourceLineInfo == null) { // Create an instance of System.Diagnostics.Stacktrace.Symbols object target = Activator.CreateInstance(s_symbolsType); // Create an instance delegate for the GetSourceLineInfo method getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); } for (int index = 0; index < iFrameCount; index++) { // If there was some reason not to try get get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. if (rgiMethodToken[index] != 0) { getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); } } } catch { } finally { t_reentrancy--; } #endif } void IDisposable.Dispose() { #if FEATURE_CORECLR if (getSourceLineInfo != null) { IDisposable disposable = getSourceLineInfo.Target as IDisposable; if (disposable != null) { disposable.Dispose(); } } #endif } [System.Security.SecuritySafeCritical] public virtual MethodBase GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! IntPtr mh = rgMethodHandle[i]; if (mh.IsNull()) return null; IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } public virtual int GetOffset(int i) { return rgiOffset[i];} public virtual int GetILOffset(int i) { return rgiILOffset[i];} public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i];} public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i];} public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i];} #if FEATURE_EXCEPTIONDISPATCHINFO public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i) { return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i]; } #endif // FEATURE_EXCEPTIONDISPATCHINFO public virtual int GetNumberOfFrames() { return iFrameCount;} public virtual void SetNumberOfFrames(int i) { iFrameCount = i;} // // serialization implementation // [OnSerializing] [SecuritySafeCritical] void OnSerializing(StreamingContext context) { // this is called in the process of serializing this object. // For compatibility with Everett we need to assign the rgMethodBase field as that is the field // that will be serialized rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length]; if (rgMethodHandle != null) { for (int i = 0; i < rgMethodHandle.Length; i++) { if (!rgMethodHandle[i].IsNull()) rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this)); } } } [OnSerialized] void OnSerialized(StreamingContext context) { // after we are done serializing null the rgMethodBase field rgMethodBase = null; } [OnDeserialized] [SecuritySafeCritical] void OnDeserialized(StreamingContext context) { // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length]; if (rgMethodBase != null) { for (int i = 0; i < rgMethodBase.Length; i++) { if (rgMethodBase[i] != null) rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value; } } rgMethodBase = null; } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. #if !FEATURE_CORECLR [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] #endif [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StackTrace { private StackFrame[] frames; private int m_iNumOfFrames; public const int METHODS_TO_SKIP = 0; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public StackTrace() { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(bool fNeedFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(int skipFrames) { if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(int skipFrames, bool fNeedFileInfo) { if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location. public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException("e"); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException("e"); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, int skipFrames) { if (e == null) throw new ArgumentNullException("e"); if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException("e"); if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace(StackFrame frame) { frames = new StackFrame[1]; frames[0] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } // Constructs a stack trace for the given thread // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")] public StackTrace(Thread targetThread, bool needFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null); } [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase(i); if (mb != null) { Type t = mb.DeclaringType; if (t == null) break; String ns = t.Namespace; if (ns == null) break; if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e) { m_iMethodsToSkip += iSkip; using (StackFrameHelper StackF = new StackFrameHelper(targetThread)) { StackF.InitializeSourceInfo(0, fNeedFileInfo, e); m_iNumOfFrames = StackF.GetNumberOfFrames(); if (m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if (m_iNumOfFrames != 0) { frames = new StackFrame[m_iNumOfFrames]; for (int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame(fDummy1, fDummy2); sfTemp.SetMethodBase(StackF.GetMethodBase(i)); sfTemp.SetOffset(StackF.GetOffset(i)); sfTemp.SetILOffset(StackF.GetILOffset(i)); #if FEATURE_EXCEPTIONDISPATCHINFO sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i)); #endif // FEATURE_EXCEPTIONDISPATCHINFO if (fNeedFileInfo) { sfTemp.SetFileName(StackF.GetFilename(i)); sfTemp.SetLineNumber(StackF.GetLineNumber(i)); sfTemp.SetColumnNumber(StackF.GetColumnNumber(i)); } frames[i] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if (e == null) m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames); m_iNumOfFrames -= m_iMethodsToSkip; if (m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames;} } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame(int index) { if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) return frames[index+m_iMethodsToSkip]; return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // [ComVisible(false)] public virtual StackFrame [] GetFrames() { if (frames == null || m_iNumOfFrames <= 0) return null; // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame [] array = new StackFrame[m_iNumOfFrames]; Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames); return array; } // Builds a readable representation of the stack trace // #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public override String ToString() { // Include a trailing newline for backwards compatibility return ToString(TraceFormat.TrailingNewLine); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal String ToString(TraceFormat traceFormat) { bool displayFilenames = true; // we'll try, but demand may fail String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if(traceFormat != TraceFormat.NoResourceLookup) { word_At = Environment.GetResourceString("Word_At"); inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber"); } bool fFirstFrame = true; StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame(iFrameIndex); MethodBase mb = sf.GetMethod(); if (mb != null) { // We want a newline at the end of every line except for the last if (fFirstFrame) fFirstFrame = false; else sb.Append(Environment.NewLine); sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); Type t = mb.DeclaringType; // if there is a type (non global method) print it if (t != null) { // Append t.FullName, replacing '+' with '.' string fullName = t.FullName; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; sb.Append(ch == '+' ? '.' : ch); } sb.Append('.'); } sb.Append(mb.Name); // deal with the generic portion of the method if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append('['); int k=0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(','); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append(']'); } ParameterInfo[] pi = null; #if FEATURE_CORECLR try { #endif pi = mb.GetParameters(); #if FEATURE_CORECLR } catch { // The parameter info cannot be loaded, so we don't // append the parameter list. } #endif if (pi != null) { // arguments printing sb.Append('('); bool fFirstParam = true; for (int j = 0; j < pi.Length; j++) { if (fFirstParam == false) sb.Append(", "); else fFirstParam = false; String typeName = "<UnknownType>"; if (pi[j].ParameterType != null) typeName = pi[j].ParameterType.Name; sb.Append(typeName); sb.Append(' '); sb.Append(pi[j].Name); } sb.Append(')'); } // source location printing if (displayFilenames && (sf.GetILOffset() != -1)) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. String fileName = null; // Getting the filename from a StackFrame is a privileged operation - we won't want // to disclose full path names to arbitrarily untrusted code. Rather than just omit // this we could probably trim to just the filename so it's still mostly usefull. try { fileName = sf.GetFileName(); } #if FEATURE_CAS_POLICY catch (NotSupportedException) { // Having a deprecated stack modifier on the callstack (such as Deny) will cause // a NotSupportedException to be thrown. Since we don't know if the app can // access the file names, we'll conservatively hide them. displayFilenames = false; } #endif // FEATURE_CAS_POLICY catch (SecurityException) { // If the demand for displaying filenames fails, then it won't // succeed later in the loop. Avoid repeated exceptions by not trying again. displayFilenames = false; } if (fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber()); } } #if FEATURE_EXCEPTIONDISPATCHINFO if (sf.GetIsLastFrameFromForeignExceptionStackTrace()) { sb.Append(Environment.NewLine); sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow")); } #endif // FEATURE_EXCEPTIONDISPATCHINFO } } if(traceFormat == TraceFormat.TrailingNewLine) sb.Append(Environment.NewLine); return sb.ToString(); } // This helper is called from within the EE to construct a string representation // of the current stack trace. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo) { // Note all the frames in System.Diagnostics will be skipped when capturing // a normal stack trace (not from an exception) so we don't need to explicitly // skip the GetManagedStackTraceStringHelper frame. StackTrace st = new StackTrace(0, fNeedFileInfo); return st.ToString(); } } }
39.273671
173
0.544782
[ "MIT" ]
Rayislandstyle/dotnet-coreclr
src/mscorlib/src/System/Diagnostics/Stacktrace.cs
30,280
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.Sql.V20200801Preview { /// <summary> /// A server vulnerability assessment. /// </summary> [AzureNativeResourceType("azure-native:sql/v20200801preview:ServerVulnerabilityAssessment")] public partial class ServerVulnerabilityAssessment : Pulumi.CustomResource { /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The recurring scans settings /// </summary> [Output("recurringScans")] public Output<Outputs.VulnerabilityAssessmentRecurringScansPropertiesResponse?> RecurringScans { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a ServerVulnerabilityAssessment resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ServerVulnerabilityAssessment(string name, ServerVulnerabilityAssessmentArgs args, CustomResourceOptions? options = null) : base("azure-native:sql/v20200801preview:ServerVulnerabilityAssessment", name, args ?? new ServerVulnerabilityAssessmentArgs(), MakeResourceOptions(options, "")) { } private ServerVulnerabilityAssessment(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:sql/v20200801preview:ServerVulnerabilityAssessment", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:sql/v20200801preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-native:sql:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-nextgen:sql:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-native:sql/v20180601preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20180601preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-native:sql/v20200202preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20200202preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-native:sql/v20201101preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20201101preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-native:sql/v20210201preview:ServerVulnerabilityAssessment"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20210201preview:ServerVulnerabilityAssessment"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ServerVulnerabilityAssessment resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ServerVulnerabilityAssessment Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ServerVulnerabilityAssessment(name, id, options); } } public sealed class ServerVulnerabilityAssessmentArgs : Pulumi.ResourceArgs { /// <summary> /// The recurring scans settings /// </summary> [Input("recurringScans")] public Input<Inputs.VulnerabilityAssessmentRecurringScansPropertiesArgs>? RecurringScans { get; set; } /// <summary> /// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the server for which the vulnerability assessment is defined. /// </summary> [Input("serverName", required: true)] public Input<string> ServerName { get; set; } = null!; /// <summary> /// Specifies the identifier key of the storage account for vulnerability assessment scan results. If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required. /// </summary> [Input("storageAccountAccessKey")] public Input<string>? StorageAccountAccessKey { get; set; } /// <summary> /// A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/). /// </summary> [Input("storageContainerPath", required: true)] public Input<string> StorageContainerPath { get; set; } = null!; /// <summary> /// A shared access signature (SAS Key) that has write access to the blob container specified in 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified, StorageContainerSasKey is required. /// </summary> [Input("storageContainerSasKey")] public Input<string>? StorageContainerSasKey { get; set; } /// <summary> /// The name of the vulnerability assessment. /// </summary> [Input("vulnerabilityAssessmentName")] public Input<string>? VulnerabilityAssessmentName { get; set; } public ServerVulnerabilityAssessmentArgs() { } } }
48.922535
220
0.647186
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Sql/V20200801Preview/ServerVulnerabilityAssessment.cs
6,947
C#
using System.Reactive.Linq; using System.Threading.Tasks; using Octokit.Reactive; using Octokit.Tests.Integration.fixtures; using Xunit; namespace Octokit.Tests.Integration.Reactive { public class ObservableRepositoryHooksClientTests { [Collection(RepositoriesHooksCollection.Name)] public class TheGetAllMethod { readonly RepositoriesHooksFixture _fixture; public TheGetAllMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task ReturnsAllHooksFromRepository() { var github = Helper.GetAuthenticatedClient(); var client = new ObservableRepositoryHooksClient(github); var hooks = await client.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName).ToList(); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); var actualHook = hooks[0]; AssertHook(_fixture.ExpectedHook, actualHook); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithoutStart() { var github = Helper.GetAuthenticatedClient(); var client = new ObservableRepositoryHooksClient(github); var options = new ApiOptions { PageSize = 5, PageCount = 1 }; var hooks = await client.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, options).ToList(); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithStart() { var github = Helper.GetAuthenticatedClient(); var client = new ObservableRepositoryHooksClient(github); var options = new ApiOptions { PageSize = 3, PageCount = 1, StartPage = 2 }; var hooks = await client.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, options).ToList(); Assert.Equal(1, hooks.Count); } [IntegrationTest] public async Task ReturnsDistinctResultsBasedOnStartPage() { var github = Helper.GetAuthenticatedClient(); var client = new ObservableRepositoryHooksClient(github); var startOptions = new ApiOptions { PageSize = 2, PageCount = 1 }; var firstPage = await client.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, startOptions).ToList(); var skipStartOptions = new ApiOptions { PageSize = 2, PageCount = 1, StartPage = 2 }; var secondPage = await client.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, skipStartOptions).ToList(); Assert.NotEqual(firstPage[0].Id, secondPage[0].Id); Assert.NotEqual(firstPage[1].Id, secondPage[1].Id); } static void AssertHook(RepositoryHook expectedHook, RepositoryHook actualHook) { Assert.Equal(expectedHook.Id, actualHook.Id); Assert.Equal(expectedHook.Active, actualHook.Active); Assert.Equal(expectedHook.Config, actualHook.Config); Assert.Equal(expectedHook.CreatedAt, actualHook.CreatedAt); Assert.Equal(expectedHook.Name, actualHook.Name); Assert.Equal(expectedHook.PingUrl, actualHook.PingUrl); Assert.Equal(expectedHook.TestUrl, actualHook.TestUrl); Assert.Equal(expectedHook.UpdatedAt, actualHook.UpdatedAt); Assert.Equal(expectedHook.Url, actualHook.Url); } } } }
35.310345
131
0.570801
[ "MIT" ]
7enderhead/octokit.net
Octokit.Tests.Integration/Reactive/ObservableRepositoryHooksClientTests.cs
4,098
C#
using UnityEngine; using System.IO; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { #region enum #endregion #region const #endregion #region public property #endregion #region private property /// <summary> /// The audio source. /// </summary> AudioSource audioSource; /// <summary> /// The notes. /// </summary> GameObject notes; /// <summary> /// The title panel. /// </summary> [SerializeField] GameObject titlePanel; /// <summary> /// The game panel. /// </summary> [SerializeField] GameObject gamePanel; /// <summary> /// The result panel. /// </summary> [SerializeField] GameObject resultPanel; /// <summary> /// The line object. /// </summary> [SerializeField] GameObject lineObject; /// <summary> /// The game score text. /// </summary> [SerializeField] Text gameScoreText; /// <summary> /// The result score text. /// </summary> [SerializeField] Text resultScoreText; /// <summary> /// Where game is playing or not. /// </summary> bool isPlaying = false; /// <summary> /// The array of timing. /// </summary> float[] timing; /// <summary> /// The length of the audio. /// </summary> float audioLength; /// <summary> /// The notes count. /// </summary> int notesCount = 0; /// <summary> /// The start time. /// </summary> float startTime = 0; /// <summary> /// The score. /// </summary> int score = 0; /// <summary> /// The time offset (for small adjestment). /// </summary> float timeOffset = -1f; #endregion #region public method /// <summary> /// Starts the game. /// </summary> public void StartGame() { titlePanel.SetActive(false); gamePanel.SetActive(true); resultPanel.SetActive(false); lineObject.SetActive(true); startTime = Time.time; audioSource.Play(); isPlaying = true; // Preload object notes = Resources.Load("Game/Notes") as GameObject; } /// <summary> /// Retries the game. /// </summary> public void RetryGame() { SceneManager.LoadScene(Scene.Game); } #endregion #region private method /// <summary> /// Checks the next notes. /// </summary> void CheckNextNotes() { while (timing[notesCount] + timeOffset < GetMusicTime() && timing[notesCount] != 0) { SpawnNotes(); notesCount++; } } /// <summary> /// Spawns the notes. /// </summary> void SpawnNotes() { Instantiate(notes, new Vector3(0, 10.0f, 0), Quaternion.identity); } /// <summary> /// Load the CSV. /// </summary> void LoadCSV() { int i = 0; TextAsset text = Resources.Load(Path.GetFileNameWithoutExtension(Config.TextFileName)) as TextAsset; StringReader reader = new StringReader(text.text); while (reader.Peek() > -1) { string line = reader.ReadLine(); timing[i] = float.Parse(line); i++; } } /// <summary> /// Gets the music time. /// </summary> /// <returns>The music time.</returns> float GetMusicTime() { return Time.time - startTime; } #endregion #region event void Start() { audioSource = GameObject.FindGameObjectWithTag(Tag.GameMusic).GetComponent<AudioSource>(); timing = new float[1024]; LoadCSV(); titlePanel.SetActive(true); gamePanel.SetActive(false); resultPanel.SetActive(false); lineObject.SetActive(false); audioLength = audioSource.clip.length; } void Update() { if (!isPlaying) { return; } CheckNextNotes(); gameScoreText.text = score.ToString(); // after end of audio + 1.0f if (GetMusicTime() - 1.0f >= audioLength) { isPlaying = false; gamePanel.SetActive(false); resultPanel.SetActive(true); lineObject.SetActive(false); resultScoreText.text = score.ToString(); } } /// <summary> /// Adds the score. /// </summary> public void AddScore() { score++; } /// <summary> /// Reduces the score. /// </summary> public void ReduceScore() { score--; } #endregion }
19.485356
108
0.536826
[ "MIT" ]
murapong/GGJIO2018
client/GGJIO2018/Assets/Scripts/Game/GameManager.cs
4,659
C#
namespace Publisher.CLI.Interfaces { public interface IPublisherContext { } }
15
38
0.7
[ "MIT" ]
LoveDuckie/blog-publisher
apps/Publisher/Publisher.CLI/Interfaces/IPublisherContext.cs
92
C#
using DSIS.Core.System; using DSIS.Core.System.Impl; namespace DSIS.CellImageBuilder.Descartes { public class RangeSystemSpace : ISystemSpace { private readonly ISystemSpace myHostSpace; private readonly int myFrom; private readonly int myTo; private readonly DefaultSystemSpace mySpace; public RangeSystemSpace(ISystemSpace hostSpace, int from, int to) { myHostSpace = hostSpace; myFrom = from; myTo = to; mySpace = new DefaultSystemSpace(myTo - myFrom + 1, Slice(myHostSpace.AreaLeftPoint), Slice(myHostSpace.AreaRightPoint), Slice(myHostSpace.InitialSubdivision)); } public double[] AreaLeftPoint { get { return mySpace.AreaLeftPoint; } } public double[] AreaRightPoint { get { return mySpace.AreaRightPoint; } } public bool Contains(double[] point) { return mySpace.Contains(point); } public bool ContainsRect(double[] left, double[] right) { return mySpace.ContainsRect(left, right); } public bool ContainedRect(double[] left, double[] right) { return mySpace.ContainedRect(left, right); } public int Dimension { get { return mySpace.Dimension; } } public long[] InitialSubdivision { get { return mySpace.InitialSubdivision; } } public T[] Slice<T>(T[] point) { var r = new T[myTo - myFrom + 1]; for (int i = myFrom; i <= myTo; i++) { r[i] = point[i]; } return r; } } }
23.028986
167
0.606671
[ "Apache-2.0" ]
jonnyzzz/phd-project
dsis/src/CellImageBuilders/CellImageBuilder.Descartes/src/RangeSystemSpace.cs
1,589
C#
namespace MySqlConnector.Protocol.Payloads.Replication.Events { public enum EventType { UnknownEvent = 0x00, StartEventV3 = 0x01, QueryEvent = 0x02, StopEvent = 0x03, RotateEvent = 0x04, IntvarEvent = 0x05, LoadEvent = 0x06, SlaveEvent = 0x07, CreateFileEvent = 0x08, AppendBlockEvent = 0x09, ExecLoadEvent = 0x0A, DeleteFileEvent = 0x0B, NewLoadEvent = 0x0C, RandEvent = 0x0D, UserVarEvent = 0x0E, FormatDescriptionEvent = 0x0F, XidEvent = 0x10, BeginLoadQueryEvent = 0x11, ExecuteLoadQueryEvent = 0x12, TableMapEvent = 0x13, WriteRowsEventv0 = 0x14, UpdateRowsEventv0 = 0x15, DeleteRowsEventv0 = 0x16, WriteRowsEventv1 = 0x17, UpdateRowsEventv1 = 0x18, DeleteRowsEventv1 = 0x19, IncidentEvent = 0x1A, HeartbeatEvent = 0x1B, IgnorableEvent = 0x1C, RowsQueryEvent = 0x1D, WriteRowsEventv2 = 0x1E, UpdateRowsEventv2 = 0x1F, DeleteRowsEventv2 = 0x20, GtidEvent = 0x21, AnonymousGtidEvent = 0x22, PreviousGtidsEvent = 0x23 } }
13.25641
61
0.704062
[ "MIT" ]
NxSoftware/MySqlConnector
src/MySqlConnector/Protocol/Payloads/Replication/Events/EventType.cs
1,034
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace MoneroClient.Wallet.DataTransfer { public class IncomingTransferResultDto { public IncomingTransferResultDto() { Transfers = new List<IncomingTransferDto>(); } [JsonProperty("transfers")] public IEnumerable<IncomingTransferDto> Transfers { get; set; } } public class IncomingTransferDto { [JsonProperty("amount")] public ulong Amount { get; set; } [JsonProperty("global_index")] public uint GlobalIndex { get; set; } [JsonProperty("key_image")] public string KeyImage { get; set; } [JsonProperty("spent")] public bool Spent { get; set; } [JsonProperty("subaddr_index")] public IncomingTransferSubaddrIndex SubaddrIndex { get; set; } [JsonProperty("tx_hash")] public string TxHash { get; set; } } public class IncomingTransferSubaddrIndex { [JsonProperty("major")] public uint Major { get; set; } [JsonProperty("minor")] public uint Minor { get; set; } } }
24.956522
71
0.612369
[ "MIT" ]
leonardochaia/xmr-tutorials
MoneroClient/Wallet/DataTransfer/IncomingTransfersDto.cs
1,148
C#
using Abp.Application.Navigation; using Abp.Localization; using TomsAbp.Authorization; namespace TomsAbp.Web.Startup { /// <summary> /// This class defines menus for the application. /// </summary> public class TomsAbpNavigationProvider : NavigationProvider { public override void SetNavigation(INavigationProviderContext context) { context.Manager.MainMenu .AddItem( new MenuItemDefinition( PageNames.Home, L("HomePage"), url: "", icon: "home", requiresAuthentication: true ) ).AddItem( new MenuItemDefinition( PageNames.Tenants, L("Tenants"), url: "Tenants", icon: "business", requiredPermissionName: PermissionNames.Pages_Tenants ) ).AddItem( new MenuItemDefinition( PageNames.Users, L("Users"), url: "Users", icon: "people", requiredPermissionName: PermissionNames.Pages_Users ) ).AddItem( new MenuItemDefinition( PageNames.Roles, L("Roles"), url: "Roles", icon: "local_offer", requiredPermissionName: PermissionNames.Pages_Roles ) ) .AddItem( new MenuItemDefinition( PageNames.About, L("About"), url: "About", icon: "info" ) ).AddItem( // Menu items below is just for demonstration! new MenuItemDefinition( "MultiLevelMenu", L("MultiLevelMenu"), icon: "menu" ).AddItem( new MenuItemDefinition( "AspNetBoilerplate", new FixedLocalizableString("ASP.NET Boilerplate") ).AddItem( new MenuItemDefinition( "AspNetBoilerplateHome", new FixedLocalizableString("Home"), url: "https://aspnetboilerplate.com?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateTemplates", new FixedLocalizableString("Templates"), url: "https://aspnetboilerplate.com/Templates?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateSamples", new FixedLocalizableString("Samples"), url: "https://aspnetboilerplate.com/Samples?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetBoilerplateDocuments", new FixedLocalizableString("Documents"), url: "https://aspnetboilerplate.com/Pages/Documents?ref=abptmpl" ) ) ).AddItem( new MenuItemDefinition( "AspNetZero", new FixedLocalizableString("ASP.NET Zero") ).AddItem( new MenuItemDefinition( "AspNetZeroHome", new FixedLocalizableString("Home"), url: "https://aspnetzero.com?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetZeroDescription", new FixedLocalizableString("Description"), url: "https://aspnetzero.com/?ref=abptmpl#description" ) ).AddItem( new MenuItemDefinition( "AspNetZeroFeatures", new FixedLocalizableString("Features"), url: "https://aspnetzero.com/?ref=abptmpl#features" ) ).AddItem( new MenuItemDefinition( "AspNetZeroPricing", new FixedLocalizableString("Pricing"), url: "https://aspnetzero.com/?ref=abptmpl#pricing" ) ).AddItem( new MenuItemDefinition( "AspNetZeroFaq", new FixedLocalizableString("Faq"), url: "https://aspnetzero.com/Faq?ref=abptmpl" ) ).AddItem( new MenuItemDefinition( "AspNetZeroDocuments", new FixedLocalizableString("Documents"), url: "https://aspnetzero.com/Documents?ref=abptmpl" ) ) ) ); } private static ILocalizableString L(string name) { return new LocalizableString(name, TomsAbpConsts.LocalizationSourceName); } } }
43.964286
96
0.385703
[ "MIT" ]
YLBTom/TomsAbp
aspnet-core/src/TomsAbp.Web.Mvc/Startup/TomsAbpNavigationProvider.cs
6,157
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; public struct ValX1<T> { public T t; public ValX1(T t) { this.t = t; } } public class RefX1<T> { public T t; public RefX1(T t) { this.t = t; } } public struct Gen<T> { public static int size = 10; public T[][] TArray; public void StoreTArray(T[] arr) { TArray = new T[size][]; int i, j; for (i = 0; (i < size); i++) { TArray[i] = new T[size]; for (j = 0; (j < size); j++) { TArray[i][j] = arr[(i * 10) + j]; } } } public void LoadTArray(out T[] arr) { arr = new T[size * size]; int i, j; for (i = 0; (i < size); i++) { for (j = 0; (j < size); j++) { arr[(i * 10) + j] = TArray[i][j]; } } } public bool VerifyTArray(T[] arr) { int i, j; for (i = 0; (i < size); i++) { for (j = 0; (j < size); j++) { if (!(arr[(i * 10) + j].Equals(TArray[i][j]))) { Console.WriteLine("Failed Verification of Element TArray[{0}][{1}]", i, j); return false; } } } return true; } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { int i = 0; int[] IntArr_in = new int[100]; for (i = 0; (i < (10 * 10)); i++) { IntArr_in[i] = i; } int[] IntArr_out; Gen<int> GenInt = new Gen<int>(); GenInt.StoreTArray(IntArr_in); GenInt.LoadTArray(out IntArr_out); Eval(GenInt.VerifyTArray(IntArr_out)); double[] DoubleArr_in = new double[100]; for (i = 0; (i < 10 * 10); i++) { DoubleArr_in[i] = i; } double[] DoubleArr_out; Gen<double> GenDouble = new Gen<double>(); GenDouble.StoreTArray(DoubleArr_in); GenDouble.LoadTArray(out DoubleArr_out); Eval(GenDouble.VerifyTArray(DoubleArr_out)); string[] StringArr_in = new String[100]; for (i = 0; (i < 10 * 10); i++) { StringArr_in[i] = i.ToString(); } String[] StringArr_out; Gen<String> GenString = new Gen<String>(); GenString.StoreTArray(StringArr_in); GenString.LoadTArray(out StringArr_out); Eval(GenString.VerifyTArray(StringArr_out)); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
20.863636
95
0.462185
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/Generics/Arrays/TypeParameters/Jagged/struct01.cs
3,213
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20170901.Inputs { /// <summary> /// Route Filter Rule Resource /// </summary> public sealed class RouteFilterRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The access type of the rule. Valid values are: 'Allow', 'Deny' /// </summary> [Input("access", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Network.V20170901.Access> Access { get; set; } = null!; [Input("communities", required: true)] private InputList<string>? _communities; /// <summary> /// The collection for bgp community values to filter on. e.g. ['12076:5010','12076:5020'] /// </summary> public InputList<string> Communities { get => _communities ?? (_communities = new InputList<string>()); set => _communities = value; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The rule type of the rule. Valid value is: 'Community' /// </summary> [Input("routeFilterRuleType", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Network.V20170901.RouteFilterRuleType> RouteFilterRuleType { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public RouteFilterRuleArgs() { } } }
31.168831
135
0.574167
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20170901/Inputs/RouteFilterRuleArgs.cs
2,400
C#
using System; using System.Collections; using UnityEngine; using UnityEngine.UI; public class UIGradientBackground : MonoBehaviour { // NOTE: // Loop type = ping pong #region Serialized Fields [SerializeField] private bool _playWhenEnable = false; [SerializeField] private Image _imageBG = null; [SerializeField] private float _loopTime = 0; [SerializeField] private AnimationCurve _aniCurve = default; [SerializeField] private Color _colorFrom = Color.white; [SerializeField] private Color _colorTo = Color.white; #endregion #region Mono Behaviour Hooks private void OnEnable() { if (_playWhenEnable) { Play(); } } private void OnDisable() { Stop(); } #endregion #region APIs public void Play() { StopAllCoroutines(); StartCoroutine(PlayAnimation()); } public void Stop() { StopAllCoroutines(); } #endregion #region Internal Methods private IEnumerator PlayAnimation() { float passedTime = 0; bool reverse = false; float loopTime = 0; float progress = 0; float curveValue = 0; while (true) { loopTime = Math.Max(0.05f, _loopTime); if (!reverse && passedTime >= loopTime) { reverse = true; passedTime = loopTime; } else if (reverse && passedTime <= 0) { reverse = false; passedTime = 0; } progress = passedTime / loopTime; curveValue = _aniCurve.Evaluate(progress); Color c = Color.Lerp(_colorFrom, _colorTo, curveValue); _imageBG.color = c; yield return new WaitForEndOfFrame(); passedTime += reverse ? -Time.deltaTime : Time.deltaTime; } } #endregion }
25.459459
69
0.581741
[ "MIT" ]
Davidccy/Unity-Marquee
Marquee/Assets/Scripts/UIGradientBackground.cs
1,886
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ManagedServiceIdentity; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Reflection; using System.Text; using Microsoft.Azure.Test.HttpRecorder; using Xunit; using CM=Microsoft.Azure.Management.Compute.Models; using NM=Microsoft.Azure.Management.Network.Models; namespace Compute.Tests { public class VMTestBase { static VMTestBase() { RecorderUtilities.JsonPathSanitizers.Add("$..accessSAS"); } protected const string TestPrefix = "crptestar"; protected const string PLACEHOLDER = "[PLACEHOLDEr1]"; protected const string ComputerName = "Test"; protected static readonly string DummyUserData1 = Convert.ToBase64String(Encoding.UTF8.GetBytes("Some User Data")); protected static readonly string DummyUserData2 = Convert.ToBase64String(Encoding.UTF8.GetBytes("Some new User Data")); protected ResourceManagementClient m_ResourcesClient; protected ComputeManagementClient m_CrpClient; protected StorageManagementClient m_SrpClient; protected NetworkManagementClient m_NrpClient; protected ManagedServiceIdentityClient m_MsiClient; protected bool m_initialized = false; protected object m_lock = new object(); protected string m_subId; protected string m_location; ImageReference m_windowsImageReference, m_linuxImageReference; protected void EnsureClientsInitialized(MockContext context) { if (!m_initialized) { lock (m_lock) { if (!m_initialized) { m_ResourcesClient = ComputeManagementTestUtilities.GetResourceManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_CrpClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_SrpClient = ComputeManagementTestUtilities.GetStorageManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_NrpClient = ComputeManagementTestUtilities.GetNetworkManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_MsiClient = ComputeManagementTestUtilities.GetManagedServiceIdentityClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); m_subId = m_CrpClient.SubscriptionId; if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"))) { m_location = ComputeManagementTestUtilities.DefaultLocation; } else { m_location = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION").Replace(" ", ""); } } } } } protected ImageReference FindVMImage(string publisher, string offer, string sku) { var images = m_CrpClient.VirtualMachineImages.List( location: m_location, publisherName: publisher, offer: offer, skus: sku, top: 1); var image = images.First(); return new ImageReference { Publisher = publisher, Offer = offer, Sku = sku, Version = image.Name }; } protected ImageReference GetPlatformVMImage(bool useWindowsImage, string sku = null) { if (useWindowsImage) { if (m_windowsImageReference == null) { Trace.TraceInformation("Querying available Windows Server image from PIR..."); m_windowsImageReference = FindVMImage("MicrosoftWindowsServer", "WindowsServer", sku ?? "2012-R2-Datacenter"); } return m_windowsImageReference; } if (m_linuxImageReference == null) { Trace.TraceInformation("Querying available Ubuntu image from PIR..."); // If this sku disappears, query latest with // GET https://management.azure.com/subscriptions/<subId>/providers/Microsoft.Compute/locations/SoutheastAsia/publishers/Canonical/artifacttypes/vmimage/offers/UbuntuServer/skus?api-version=2015-06-15 m_linuxImageReference = FindVMImage("Canonical", "UbuntuServer", sku ?? "19.04"); } return m_linuxImageReference; } protected DiagnosticsProfile GetDiagnosticsProfile(string storageAccountName) { return new DiagnosticsProfile { BootDiagnostics = new BootDiagnostics { Enabled = true, StorageUri = string.Format(Constants.StorageAccountBlobUriTemplate, storageAccountName) } }; } protected DiagnosticsProfile GetManagedDiagnosticsProfile() { return new DiagnosticsProfile { BootDiagnostics = new BootDiagnostics { Enabled = true } }; } protected DiskEncryptionSettings GetEncryptionSettings(bool addKek = false) { string testVaultId = @"/subscriptions/" + this.m_subId + @"/resourceGroups/RgTest1/providers/Microsoft.KeyVault/vaults/TestVault123"; string encryptionKeyFakeUri = @"https://testvault123.vault.azure.net/secrets/Test1/514ceb769c984379a7e0230bdd703272"; DiskEncryptionSettings diskEncryptionSettings = new DiskEncryptionSettings { DiskEncryptionKey = new KeyVaultSecretReference { SecretUrl = encryptionKeyFakeUri, SourceVault = new Microsoft.Azure.Management.Compute.Models.SubResource { Id = testVaultId } } }; if (addKek) { string nonExistentKekUri = @"https://testvault123.vault.azure.net/keys/TestKey/514ceb769c984379a7e0230bdd703272"; diskEncryptionSettings.KeyEncryptionKey = new KeyVaultKeyReference { KeyUrl = nonExistentKekUri, SourceVault = new Microsoft.Azure.Management.Compute.Models.SubResource { Id = testVaultId } }; } return diskEncryptionSettings; } protected string getDefaultDiskEncryptionSetId() { return "/subscriptions/e37510d7-33b6-4676-886f-ee75bcc01871/resourceGroups/RGforSDKtestResources/providers/Microsoft.Compute/diskEncryptionSets/DESforTest"; } protected StorageAccount CreateStorageAccount(string rgName, string storageAccountName) { try { // Create the resource Group. var resourceGroup = m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); var stoInput = new StorageAccountCreateParameters { Location = m_location, AccountType = AccountType.StandardGRS }; StorageAccount storageAccountOutput = m_SrpClient.StorageAccounts.Create(rgName, storageAccountName, stoInput); bool created = false; while (!created) { ComputeManagementTestUtilities.WaitSeconds(10); var stos = m_SrpClient.StorageAccounts.ListByResourceGroup(rgName); created = stos.Any( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, storageAccountName)); } return m_SrpClient.StorageAccounts.GetProperties(rgName, storageAccountName); } catch { m_ResourcesClient.ResourceGroups.Delete(rgName); throw; } } protected VirtualMachine CreateVM( string rgName, string asName, StorageAccount storageAccount, ImageReference imageRef, out VirtualMachine inputVM, Action<VirtualMachine> vmCustomizer = null, bool createWithPublicIpAddress = false, bool waitForCompletion = true, bool hasManagedDisks = false, string userData = null) { return CreateVM(rgName, asName, storageAccount.Name, imageRef, out inputVM, vmCustomizer, createWithPublicIpAddress, waitForCompletion, hasManagedDisks, userData: userData); } protected VirtualMachine CreateVM( string rgName, string asName, string storageAccountName, ImageReference imageRef, out VirtualMachine inputVM, Action<VirtualMachine> vmCustomizer = null, bool createWithPublicIpAddress = false, bool waitForCompletion = true, bool hasManagedDisks = false, bool hasDiffDisks = false, string vmSize = VirtualMachineSizeTypes.StandardA1V2, string osDiskStorageAccountType = "Standard_LRS", string dataDiskStorageAccountType = "Standard_LRS", bool? writeAcceleratorEnabled = null, IList<string> zones = null, string ppgName = null, string diskEncryptionSetId = null, bool? encryptionAtHostEnabled = null, string securityType = null, string dedicatedHostGroupReferenceId = null, string dedicatedHostGroupName = null, string dedicatedHostName = null, string userData = null, string capacityReservationGroupReferenceId = null) { try { // Create the resource Group, it might have been already created during StorageAccount creation. m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); PublicIPAddress getPublicIpAddressResponse = createWithPublicIpAddress ? null : CreatePublicIP(rgName); // Do not add Dns server for managed disks, as they cannot resolve managed disk url ( https://md-xyz ) without // explicitly setting up the rules for resolution. The VMs upon booting would need to contact the // DNS server to access the VMStatus agent blob. Without proper Dns resolution, The VMs cannot access the // VMStatus agent blob and there by fail to boot. bool addDnsServer = !hasManagedDisks; Subnet subnetResponse = CreateVNET(rgName, addDnsServer); NetworkInterface nicResponse = CreateNIC( rgName, subnetResponse, getPublicIpAddressResponse != null ? getPublicIpAddressResponse.IpAddress : null); string ppgId = ((ppgName != null) ? CreateProximityPlacementGroup(rgName, ppgName): null); string asetId = CreateAvailabilitySet(rgName, asName, hasManagedDisks, ppgId: ppgId); inputVM = CreateDefaultVMInput(rgName, storageAccountName, imageRef, asetId, nicResponse.Id, hasManagedDisks, vmSize, osDiskStorageAccountType, dataDiskStorageAccountType, writeAcceleratorEnabled, diskEncryptionSetId); if (hasDiffDisks) { OSDisk osDisk = inputVM.StorageProfile.OsDisk; osDisk.Caching = CachingTypes.ReadOnly; osDisk.DiffDiskSettings = new DiffDiskSettings { Option = DiffDiskOptions.Local, Placement = DiffDiskPlacement.ResourceDisk }; } if (dedicatedHostGroupReferenceId != null) { CreateDedicatedHostGroup(rgName, dedicatedHostGroupName, availabilityZone: null); CreateDedicatedHost(rgName, dedicatedHostGroupName, dedicatedHostName, "DSv3-Type1"); inputVM.HostGroup = new CM.SubResource { Id = dedicatedHostGroupReferenceId }; inputVM.AvailabilitySet = null; } if (!string.IsNullOrEmpty(capacityReservationGroupReferenceId)) { inputVM.CapacityReservation = new CapacityReservationProfile { CapacityReservationGroup = new CM.SubResource { Id = capacityReservationGroupReferenceId } }; inputVM.AvailabilitySet = null; } if (encryptionAtHostEnabled != null) { inputVM.SecurityProfile = new SecurityProfile { EncryptionAtHost = encryptionAtHostEnabled.Value }; } if (securityType != null && securityType.Equals("TrustedLaunch")) { if(inputVM.SecurityProfile != null) { inputVM.SecurityProfile.SecurityType = SecurityTypes.TrustedLaunch; inputVM.SecurityProfile.UefiSettings = new UefiSettings { VTpmEnabled = true, SecureBootEnabled = true }; } else { inputVM.SecurityProfile = new SecurityProfile { SecurityType = SecurityTypes.TrustedLaunch, UefiSettings = new UefiSettings { VTpmEnabled = true, SecureBootEnabled = true } }; } } if (zones != null) { inputVM.AvailabilitySet = null; // If no vmSize is provided and we are using the default value, change the default value for VMs with Zones. if(vmSize == VirtualMachineSizeTypes.StandardA0) { vmSize = VirtualMachineSizeTypes.StandardA1V2; } inputVM.HardwareProfile.VmSize = vmSize; inputVM.Zones = zones; } inputVM.UserData = userData; if (vmCustomizer != null) { vmCustomizer(inputVM); } string expectedVMReferenceId = Helpers.GetVMReferenceId(m_subId, rgName, inputVM.Name); VirtualMachine createOrUpdateResponse = null; if (waitForCompletion) { // CreateOrUpdate polls for the operation completion and returns once the operation reaches a terminal state createOrUpdateResponse = m_CrpClient.VirtualMachines.CreateOrUpdate(rgName, inputVM.Name, inputVM); } else { // BeginCreateOrUpdate returns immediately after the request is accepted by CRP createOrUpdateResponse = m_CrpClient.VirtualMachines.BeginCreateOrUpdate(rgName, inputVM.Name, inputVM); } Assert.True(createOrUpdateResponse.Name == inputVM.Name); Assert.True(createOrUpdateResponse.Location == inputVM.Location.ToLower().Replace(" ", "") || createOrUpdateResponse.Location.ToLower() == inputVM.Location.ToLower()); bool hasUserDefinedAvSet = inputVM.AvailabilitySet != null; if (hasUserDefinedAvSet) { Assert.True(createOrUpdateResponse.AvailabilitySet.Id.ToLowerInvariant() == asetId.ToLowerInvariant()); } if (zones != null) { Assert.True(createOrUpdateResponse.Zones.Count == 1); Assert.True(createOrUpdateResponse.Zones.FirstOrDefault() == zones.FirstOrDefault()); } // The intent here is to validate that the GET response is as expected. var getResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name); ValidateVM(inputVM, getResponse, expectedVMReferenceId, hasManagedDisks, writeAcceleratorEnabled: writeAcceleratorEnabled, hasDiffDisks: hasDiffDisks, hasUserDefinedAS: hasUserDefinedAvSet, expectedPpgReferenceId: ppgId, encryptionAtHostEnabled: encryptionAtHostEnabled, expectedDedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId); return getResponse; } catch { // Just trigger DeleteRG, rest would be taken care of by ARM m_ResourcesClient.ResourceGroups.BeginDelete(rgName); throw; } } protected PublicIPPrefix CreatePublicIPPrefix(string rgName, int prefixLength) { string publicIpPrefixName = ComputeManagementTestUtilities.GenerateName("piprefix"); var publicIpPrefix = new PublicIPPrefix() { Sku = new PublicIPPrefixSku("Standard"), Location = m_location, PrefixLength = prefixLength }; var putPublicIpPrefixResponse = m_NrpClient.PublicIPPrefixes.CreateOrUpdate(rgName, publicIpPrefixName, publicIpPrefix); var getPublicIpPrefixResponse = m_NrpClient.PublicIPPrefixes.Get(rgName, publicIpPrefixName); return getPublicIpPrefixResponse; } protected PublicIPAddress CreatePublicIP(string rgName) { // Create publicIP string publicIpName = ComputeManagementTestUtilities.GenerateName("pip"); string domainNameLabel = ComputeManagementTestUtilities.GenerateName("dn"); var publicIp = new PublicIPAddress() { Location = m_location, Tags = new Dictionary<string, string>() { {"key", "value"} }, PublicIPAllocationMethod = IPAllocationMethod.Dynamic, DnsSettings = new PublicIPAddressDnsSettings() { DomainNameLabel = domainNameLabel } }; var putPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.CreateOrUpdate(rgName, publicIpName, publicIp); var getPublicIpAddressResponse = m_NrpClient.PublicIPAddresses.Get(rgName, publicIpName); return getPublicIpAddressResponse; } protected Subnet CreateVNET(string rgName, bool addDnsServer = true, bool disablePEPolicies = false) { // Create Vnet // Populate parameter for Put Vnet string vnetName = ComputeManagementTestUtilities.GenerateName("vn"); string subnetName = ComputeManagementTestUtilities.GenerateName("sn"); var vnet = new VirtualNetwork() { Location = m_location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = !addDnsServer ? null : new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnetName, AddressPrefix = "10.0.0.0/24", PrivateEndpointNetworkPolicies = disablePEPolicies ? "Disabled" : null } } }; var putVnetResponse = m_NrpClient.VirtualNetworks.CreateOrUpdate(rgName, vnetName, vnet); var getSubnetResponse = m_NrpClient.Subnets.Get(rgName, vnetName, subnetName); return getSubnetResponse; } protected VirtualNetwork CreateVNETWithSubnets(string rgName, int subnetCount = 2) { // Create Vnet // Populate parameter for Put Vnet string vnetName = ComputeManagementTestUtilities.GenerateName("vn"); var vnet = new VirtualNetwork() { Location = m_location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, }; vnet.Subnets = new List<Subnet>(); for (int i = 1; i <= subnetCount; i++) { Subnet subnet = new Subnet() { Name = ComputeManagementTestUtilities.GenerateName("sn" + i), AddressPrefix = "10.0." + i + ".0/24", }; vnet.Subnets.Add(subnet); } var putVnetResponse = m_NrpClient.VirtualNetworks.CreateOrUpdate(rgName, vnetName, vnet); return putVnetResponse; } protected NetworkSecurityGroup CreateNsg(string rgName, string nsgName = null) { nsgName = nsgName ?? ComputeManagementTestUtilities.GenerateName("nsg"); var nsgParameters = new NetworkSecurityGroup() { Location = m_location }; var putNSgResponse = m_NrpClient.NetworkSecurityGroups.CreateOrUpdate(rgName, nsgName, nsgParameters); var getNsgResponse = m_NrpClient.NetworkSecurityGroups.Get(rgName, nsgName); return getNsgResponse; } protected NetworkInterface CreateNIC(string rgName, Subnet subnet, string publicIPaddress, string nicname = null, NetworkSecurityGroup nsg = null) { // Create Nic nicname = nicname ?? ComputeManagementTestUtilities.GenerateName("nic"); string ipConfigName = ComputeManagementTestUtilities.GenerateName("ip"); var nicParameters = new NetworkInterface() { Location = m_location, Tags = new Dictionary<string, string>() { { "key" ,"value" } }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, } }, NetworkSecurityGroup = nsg }; if (publicIPaddress != null) { nicParameters.IpConfigurations[0].PublicIPAddress = new Microsoft.Azure.Management.Network.Models.PublicIPAddress() { Id = publicIPaddress }; } var putNicResponse = m_NrpClient.NetworkInterfaces.CreateOrUpdate(rgName, nicname, nicParameters); var getNicResponse = m_NrpClient.NetworkInterfaces.Get(rgName, nicname); return getNicResponse; } protected NetworkInterface CreateMultiIpConfigNIC(string rgName, Subnet subnet, string nicname) { // Create Nic nicname = nicname ?? ComputeManagementTestUtilities.GenerateName("nic"); string ipConfigName = ComputeManagementTestUtilities.GenerateName("ip"); string ipConfigName2 = ComputeManagementTestUtilities.GenerateName("ip2"); var nicParameters = new NetworkInterface() { Location = m_location, Tags = new Dictionary<string, string>() { { "key" ,"value" } }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, Primary = true, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, }, new NetworkInterfaceIPConfiguration() { Name = ipConfigName2, Primary = false, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = subnet, } } }; var putNicResponse = m_NrpClient.NetworkInterfaces.CreateOrUpdate(rgName, nicname, nicParameters); var getNicResponse = m_NrpClient.NetworkInterfaces.Get(rgName, nicname); return getNicResponse; } protected static VirtualMachineNetworkInterfaceConfiguration CreateNICConfig(Subnet subnetResponse) { List<VirtualMachineNetworkInterfaceIPConfiguration> ipConfigs = new List<VirtualMachineNetworkInterfaceIPConfiguration>() { new VirtualMachineNetworkInterfaceIPConfiguration() { Name = ComputeManagementTestUtilities.GenerateName("ipConfig"), Primary = true, Subnet = new Microsoft.Azure.Management.Compute.Models.SubResource(subnetResponse.Id), PublicIPAddressConfiguration = new VirtualMachinePublicIPAddressConfiguration(ComputeManagementTestUtilities.GenerateName("ip"), deleteOption: DeleteOptions.Detach.ToString()) } }; VirtualMachineNetworkInterfaceConfiguration vmNicConfig = new VirtualMachineNetworkInterfaceConfiguration(ComputeManagementTestUtilities.GenerateName("nicConfig"), primary: true, deleteOption: DeleteOptions.Delete.ToString(), ipConfigurations: ipConfigs); return vmNicConfig; } private static string GetChildAppGwResourceId(string subscriptionId, string resourceGroupName, string appGwname, string childResourceType, string childResourceName) { return string.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationGateways/{2}/{3}/{4}", subscriptionId, resourceGroupName, appGwname, childResourceType, childResourceName); } protected ApplicationGateway CreateApplicationGateway(string rgName, Subnet subnet, string gatewayName = null) { gatewayName = gatewayName ?? ComputeManagementTestUtilities.GenerateName("gw"); var gatewayIPConfigName = ComputeManagementTestUtilities.GenerateName("gwIp"); var frontendIPConfigName = ComputeManagementTestUtilities.GenerateName("fIp"); var frontendPortName = ComputeManagementTestUtilities.GenerateName("fPort"); var backendAddressPoolName = ComputeManagementTestUtilities.GenerateName("pool"); var backendHttpSettingsName = ComputeManagementTestUtilities.GenerateName("setting"); var requestRoutingRuleName = ComputeManagementTestUtilities.GenerateName("rule"); var httpListenerName = ComputeManagementTestUtilities.GenerateName("listener"); var gatewayIPConfig = new ApplicationGatewayIPConfiguration() { Name = gatewayIPConfigName, Subnet = new Microsoft.Azure.Management.Network.Models.SubResource { Id = subnet.Id }, }; var frontendIPConfig = new ApplicationGatewayFrontendIPConfiguration() { Name = frontendIPConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Dynamic, Subnet = new Microsoft.Azure.Management.Network.Models.SubResource { Id = subnet.Id } }; ApplicationGatewayFrontendPort frontendPort = new ApplicationGatewayFrontendPort() { Name = frontendPortName, Port = 80 }; var backendAddressPool = new ApplicationGatewayBackendAddressPool() { Name = backendAddressPoolName, }; var backendHttpSettings = new ApplicationGatewayBackendHttpSettings() { Name = backendHttpSettingsName, Port = 80, Protocol = ApplicationGatewayProtocol.Http, CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Disabled, }; var httpListener = new ApplicationGatewayHttpListener() { Name = httpListenerName, FrontendPort = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "frontendPorts", frontendPortName) }, FrontendIPConfiguration = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "frontendIPConfigurations", frontendIPConfigName) }, SslCertificate = null, Protocol = ApplicationGatewayProtocol.Http }; var requestRoutingRules = new ApplicationGatewayRequestRoutingRule() { Name = requestRoutingRuleName, RuleType = ApplicationGatewayRequestRoutingRuleType.Basic, HttpListener = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "httpListeners", httpListenerName) }, BackendAddressPool = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "backendAddressPools", backendAddressPoolName) }, BackendHttpSettings = new Microsoft.Azure.Management.Network.Models.SubResource { Id = GetChildAppGwResourceId(m_subId, rgName, gatewayName, "backendHttpSettingsCollection", backendHttpSettingsName) } }; var appGw = new ApplicationGateway() { Location = m_location, Sku = new ApplicationGatewaySku() { Name = ApplicationGatewaySkuName.StandardSmall, Tier = ApplicationGatewayTier.Standard, Capacity = 2 }, GatewayIPConfigurations = new List<ApplicationGatewayIPConfiguration>() { gatewayIPConfig, }, FrontendIPConfigurations = new List<ApplicationGatewayFrontendIPConfiguration>() { frontendIPConfig, }, FrontendPorts = new List<ApplicationGatewayFrontendPort> { frontendPort, }, BackendAddressPools = new List<ApplicationGatewayBackendAddressPool> { backendAddressPool, }, BackendHttpSettingsCollection = new List<ApplicationGatewayBackendHttpSettings> { backendHttpSettings, }, HttpListeners = new List<ApplicationGatewayHttpListener> { httpListener, }, RequestRoutingRules = new List<ApplicationGatewayRequestRoutingRule>() { requestRoutingRules, } }; var putGwResponse = m_NrpClient.ApplicationGateways.CreateOrUpdate(rgName, gatewayName, appGw); var getGwResponse = m_NrpClient.ApplicationGateways.Get(rgName, gatewayName); return getGwResponse; } protected LoadBalancer CreatePublicLoadBalancerWithProbe(string rgName, PublicIPAddress publicIPAddress) { var loadBalancerName = ComputeManagementTestUtilities.GenerateName("lb"); var frontendIPConfigName = ComputeManagementTestUtilities.GenerateName("feip"); var backendAddressPoolName = ComputeManagementTestUtilities.GenerateName("beap"); var loadBalancingRuleName = ComputeManagementTestUtilities.GenerateName("lbr"); var loadBalancerProbeName = ComputeManagementTestUtilities.GenerateName("lbp"); var frontendIPConfigId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/frontendIPConfigurations/{frontendIPConfigName}"; var backendAddressPoolId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}"; var probeId = $"/subscriptions/{m_subId}/resourceGroups/{rgName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{loadBalancerProbeName}"; var putLBResponse = m_NrpClient.LoadBalancers.CreateOrUpdate(rgName, loadBalancerName, new LoadBalancer { Location = m_location, FrontendIPConfigurations = new List<FrontendIPConfiguration> { new FrontendIPConfiguration { Name = frontendIPConfigName, PublicIPAddress = publicIPAddress } }, BackendAddressPools = new List<BackendAddressPool> { new BackendAddressPool { Name = backendAddressPoolName } }, LoadBalancingRules = new List<LoadBalancingRule> { new LoadBalancingRule { Name = loadBalancingRuleName, LoadDistribution = "Default", FrontendIPConfiguration = new NM.SubResource { Id = frontendIPConfigId }, BackendAddressPool = new NM.SubResource { Id = backendAddressPoolId }, Protocol = "Tcp", FrontendPort = 80, BackendPort = 80, EnableFloatingIP = false, IdleTimeoutInMinutes = 5, Probe = new NM.SubResource { Id = probeId } } }, Probes = new List<Probe> { new Probe { Port = 3389, // RDP port IntervalInSeconds = 5, NumberOfProbes = 2, Name = loadBalancerProbeName, Protocol = "Tcp", } } }); var getLBResponse = m_NrpClient.LoadBalancers.Get(rgName, loadBalancerName); return getLBResponse; } protected string CreateAvailabilitySet(string rgName, string asName, bool hasManagedDisks = false, string ppgId = null) { // Setup availability set var inputAvailabilitySet = new AvailabilitySet { Location = m_location, Tags = new Dictionary<string, string>() { {"RG", "rg"}, {"testTag", "1"} }, PlatformFaultDomainCount = hasManagedDisks ? 1 : 3, PlatformUpdateDomainCount = hasManagedDisks ? 1 : 5, Sku = new CM.Sku { Name = hasManagedDisks ? AvailabilitySetSkuTypes.Aligned : AvailabilitySetSkuTypes.Classic } }; if(ppgId != null) { inputAvailabilitySet.ProximityPlacementGroup = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = ppgId }; } // Create an Availability Set and then create a VM inside this availability set var asCreateOrUpdateResponse = m_CrpClient.AvailabilitySets.CreateOrUpdate( rgName, asName, inputAvailabilitySet ); var asetId = Helpers.GetAvailabilitySetRef(m_subId, rgName, asCreateOrUpdateResponse.Name); return asetId; } static string CreateProximityPlacementGroup(string subId, string rgName, string ppgName, ComputeManagementClient client, string location) { // Setup ProximityPlacementGroup var inputProximityPlacementGroup = new ProximityPlacementGroup { Location = location, Tags = new Dictionary<string, string>() { {"RG", "rg"}, {"testTag", "1"}, }, ProximityPlacementGroupType = ProximityPlacementGroupType.Standard }; // Create a ProximityPlacementGroup and then create a VM inside this ProximityPlacementGroup ProximityPlacementGroup ppgCreateOrUpdateResponse = client.ProximityPlacementGroups.CreateOrUpdate( rgName, ppgName, inputProximityPlacementGroup ); return Helpers.GetProximityPlacementGroupRef(subId, rgName, ppgCreateOrUpdateResponse.Name); } protected string CreateProximityPlacementGroup(string rgName, string ppgName) { return CreateProximityPlacementGroup(m_subId, rgName, ppgName, m_CrpClient, m_location); } protected VirtualMachine CreateDefaultVMInput(string rgName, string storageAccountName, ImageReference imageRef, string asetId, string nicId = null, bool hasManagedDisks = false, string vmSize = "Standard_A1_v2", string osDiskStorageAccountType = "Standard_LRS", string dataDiskStorageAccountType = "Standard_LRS", bool? writeAcceleratorEnabled = null, string diskEncryptionSetId = null, VirtualMachineNetworkInterfaceConfiguration vmNicConfig = null, string networkApiVersion = null) { // Generate Container name to hold disk VHds string containerName = ComputeManagementTestUtilities.GenerateName(TestPrefix); var vhdContainer = "https://" + storageAccountName + ".blob.core.windows.net/" + containerName; var vhduri = vhdContainer + string.Format("/{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); var osVhduri = vhdContainer + string.Format("/os{0}.vhd", ComputeManagementTestUtilities.GenerateName(TestPrefix)); if (writeAcceleratorEnabled.HasValue) { // WriteAccelerator is only allowed on VMs with Managed disks Assert.True(hasManagedDisks); } var vm = new VirtualMachine { Location = m_location, Tags = new Dictionary<string, string>() { { "RG", "rg" }, { "testTag", "1" } }, HardwareProfile = new HardwareProfile { VmSize = vmSize }, StorageProfile = new StorageProfile { ImageReference = imageRef, OsDisk = new OSDisk { Caching = CachingTypes.None, WriteAcceleratorEnabled = writeAcceleratorEnabled, CreateOption = DiskCreateOptionTypes.FromImage, Name = "test", Vhd = hasManagedDisks ? null : new VirtualHardDisk { Uri = osVhduri }, ManagedDisk = !hasManagedDisks ? null : new ManagedDiskParameters { StorageAccountType = osDiskStorageAccountType, DiskEncryptionSet = diskEncryptionSetId == null ? null : new DiskEncryptionSetParameters() { Id = diskEncryptionSetId } } }, DataDisks = !hasManagedDisks ? null : new List<DataDisk>() { new DataDisk() { Caching = CachingTypes.None, WriteAcceleratorEnabled = writeAcceleratorEnabled, CreateOption = DiskCreateOptionTypes.Empty, Lun = 0, DiskSizeGB = 30, ManagedDisk = new ManagedDiskParameters() { StorageAccountType = dataDiskStorageAccountType, DiskEncryptionSet = diskEncryptionSetId == null ? null : new DiskEncryptionSetParameters() { Id = diskEncryptionSetId } } } }, }, OsProfile = new OSProfile { AdminUsername = "Foo12", AdminPassword = PLACEHOLDER, ComputerName = ComputerName } }; if (!string.IsNullOrEmpty(asetId)) { vm.AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource() { Id = asetId }; } CM.NetworkProfile vmNetworkProfile = new CM.NetworkProfile(); if (!string.IsNullOrEmpty(nicId)) { vmNetworkProfile.NetworkInterfaces = new List<NetworkInterfaceReference> { new NetworkInterfaceReference { Id = nicId } }; } if (vmNicConfig != null) { vmNetworkProfile.NetworkInterfaceConfigurations = new List<VirtualMachineNetworkInterfaceConfiguration> { vmNicConfig }; } if (!string.IsNullOrEmpty(networkApiVersion)) { vmNetworkProfile.NetworkApiVersion = networkApiVersion; } vm.NetworkProfile = vmNetworkProfile; if(dataDiskStorageAccountType == StorageAccountTypes.UltraSSDLRS) { vm.AdditionalCapabilities = new AdditionalCapabilities { UltraSSDEnabled = true }; } typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Name").SetValue(vm, ComputeManagementTestUtilities.GenerateName("vm")); typeof(Microsoft.Azure.Management.Compute.Models.Resource).GetRuntimeProperty("Type").SetValue(vm, ComputeManagementTestUtilities.GenerateName("Microsoft.Compute/virtualMachines")); return vm; } protected DedicatedHostGroup CreateDedicatedHostGroup( string rgName, string dedicatedHostGroupName, int? availabilityZone = 1) { m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); DedicatedHostGroup dedicatedHostGroup = new DedicatedHostGroup() { Location = m_location, Zones = availabilityZone == null ? null : new List<string> { availabilityZone.ToString() }, PlatformFaultDomainCount = 1, SupportAutomaticPlacement = true }; return m_CrpClient.DedicatedHostGroups.CreateOrUpdate(rgName, dedicatedHostGroupName, dedicatedHostGroup); } protected DedicatedHost CreateDedicatedHost(string rgName, string dedicatedHostGroupName, string dedicatedHostName, string dedicatedHostSku) { //Check if DedicatedHostGroup already exist and if does not exist, create one. DedicatedHostGroup existingDHG = m_CrpClient.DedicatedHostGroups.Get(rgName, dedicatedHostGroupName); if (existingDHG == null) { existingDHG = CreateDedicatedHostGroup(rgName, dedicatedHostGroupName); } return m_CrpClient.DedicatedHosts.CreateOrUpdate(rgName, dedicatedHostGroupName, dedicatedHostName, new DedicatedHost() { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } }, Sku = new CM.Sku() { Name = dedicatedHostSku } }); } protected CapacityReservationGroup CreateCapacityReservationGroup(string rgName, string capacityReservationGroupName, List<string> availabilityZones = null) { m_ResourcesClient.ResourceGroups.CreateOrUpdate( rgName, new ResourceGroup { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } } }); CapacityReservationGroup capacityReservationGroup = new CapacityReservationGroup() { Location = m_location, Zones = availabilityZones }; return m_CrpClient.CapacityReservationGroups.CreateOrUpdate(rgName, capacityReservationGroupName, capacityReservationGroup); } protected CapacityReservation CreateCapacityReservation(string rgName, string capacityReservationGroupName, string capacityReservationName, string vmSize, string availabilityZone = null, int reservedCount = 1) { //Check if CapacityReservationGroup already exist and if does not exist, create one. CapacityReservationGroup existingCRG = m_CrpClient.CapacityReservationGroups.Get(rgName, capacityReservationGroupName); if (existingCRG == null) { existingCRG = CreateCapacityReservationGroup(rgName, capacityReservationGroupName); } return m_CrpClient.CapacityReservations.CreateOrUpdate(rgName, capacityReservationGroupName, capacityReservationName, new CapacityReservation() { Location = m_location, Tags = new Dictionary<string, string>() { { rgName, DateTime.UtcNow.ToString("u") } }, Sku = new CM.Sku() { Name = vmSize, Capacity = reservedCount }, Zones = string.IsNullOrEmpty(availabilityZone) ? null : new List<string> { availabilityZone }, }); } protected void ValidateVM(VirtualMachine vm, VirtualMachine vmOut, string expectedVMReferenceId, bool hasManagedDisks = false, bool hasUserDefinedAS = true, bool? writeAcceleratorEnabled = null, bool hasDiffDisks = false, string expectedLocation = null, string expectedPpgReferenceId = null, bool? encryptionAtHostEnabled = null, string expectedDedicatedHostGroupReferenceId = null) { Assert.True(vmOut.LicenseType == vm.LicenseType); Assert.True(!string.IsNullOrEmpty(vmOut.ProvisioningState)); Assert.True(vmOut.HardwareProfile.VmSize == vm.HardwareProfile.VmSize); Assert.True(vmOut.ExtensionsTimeBudget == vm.ExtensionsTimeBudget); Assert.NotNull(vmOut.StorageProfile.OsDisk); if (vm.StorageProfile.OsDisk != null) { Assert.True(vmOut.StorageProfile.OsDisk.Name == vm.StorageProfile.OsDisk.Name); Assert.True(vmOut.StorageProfile.OsDisk.Caching == vm.StorageProfile.OsDisk.Caching); if (hasManagedDisks) { // vhd is null for managed disks Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk); Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); if (vm.StorageProfile.OsDisk.ManagedDisk != null && vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType != null) { Assert.True(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType == vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.StorageAccountType); } if (vm.StorageProfile.OsDisk.ManagedDisk != null && vm.StorageProfile.OsDisk.ManagedDisk.Id != null) { Assert.True(vmOut.StorageProfile.OsDisk.ManagedDisk.Id == vm.StorageProfile.OsDisk.ManagedDisk.Id); } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.ManagedDisk.Id); } if (hasDiffDisks) { Assert.True(vmOut.StorageProfile.OsDisk.DiffDiskSettings.Option == vm.StorageProfile.OsDisk.DiffDiskSettings.Option); } else { Assert.Null(vm.StorageProfile.OsDisk.DiffDiskSettings); } if(encryptionAtHostEnabled != null) { Assert.True(vmOut.SecurityProfile.EncryptionAtHost == vm.SecurityProfile.EncryptionAtHost); } else { Assert.Null(vmOut.SecurityProfile?.EncryptionAtHost); } if (writeAcceleratorEnabled.HasValue) { Assert.Equal(writeAcceleratorEnabled.Value, vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } else { Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } } else { Assert.NotNull(vmOut.StorageProfile.OsDisk.Vhd); Assert.Equal(vm.StorageProfile.OsDisk.Vhd.Uri, vmOut.StorageProfile.OsDisk.Vhd.Uri); if (vm.StorageProfile.OsDisk.Image != null && vm.StorageProfile.OsDisk.Image.Uri != null) { Assert.Equal(vm.StorageProfile.OsDisk.Image.Uri, vmOut.StorageProfile.OsDisk.Image.Uri); } } } if (vm.StorageProfile.DataDisks != null && vm.StorageProfile.DataDisks.Any()) { if(vm.StorageProfile.DataDisks.Any(dd => dd.ManagedDisk != null && dd.ManagedDisk.StorageAccountType == StorageAccountTypes.UltraSSDLRS)) { Assert.NotNull(vm.AdditionalCapabilities); Assert.NotNull(vm.AdditionalCapabilities.UltraSSDEnabled); Assert.True(vm.AdditionalCapabilities.UltraSSDEnabled.Value); } else if (vm.AdditionalCapabilities == null) { Assert.Null(vmOut.AdditionalCapabilities); } foreach (var dataDisk in vm.StorageProfile.DataDisks) { var dataDiskOut = vmOut.StorageProfile.DataDisks.FirstOrDefault(d => dataDisk.Lun == d.Lun); Assert.NotNull(dataDiskOut); Assert.Equal(dataDiskOut.DiskSizeGB, dataDisk.DiskSizeGB); Assert.Equal(dataDiskOut.CreateOption, dataDisk.CreateOption); if (dataDisk.Caching != null) { Assert.Equal(dataDiskOut.Caching, dataDisk.Caching); } if (dataDisk.Name != null) { Assert.Equal(dataDiskOut.Name, dataDisk.Name); } // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above. // ReSharper disable PossibleNullReferenceException if (hasManagedDisks) { Assert.NotNull(dataDiskOut.ManagedDisk); Assert.NotNull(dataDiskOut.ManagedDisk.StorageAccountType); if (dataDisk.ManagedDisk != null && dataDisk.ManagedDisk.StorageAccountType != null) { Assert.True(dataDiskOut.ManagedDisk.StorageAccountType == dataDisk.ManagedDisk.StorageAccountType); } Assert.NotNull(dataDiskOut.ManagedDisk.Id); if (writeAcceleratorEnabled.HasValue) { Assert.Equal(writeAcceleratorEnabled.Value, dataDiskOut.WriteAcceleratorEnabled); } else { Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } } else { Assert.NotNull(dataDiskOut.Vhd); Assert.NotNull(dataDiskOut.Vhd.Uri); if (dataDisk.Image != null && dataDisk.Image.Uri != null) { Assert.NotNull(dataDiskOut.Image); Assert.Equal(dataDisk.Image.Uri, dataDiskOut.Image.Uri); } Assert.Null(vmOut.StorageProfile.OsDisk.WriteAcceleratorEnabled); } // ReSharper enable PossibleNullReferenceException } } if(vm.OsProfile != null && vm.OsProfile.Secrets != null && vm.OsProfile.Secrets.Any()) { foreach (var secret in vm.OsProfile.Secrets) { Assert.NotNull(secret.VaultCertificates); var secretOut = vmOut.OsProfile.Secrets.FirstOrDefault(s => string.Equals(secret.SourceVault.Id, s.SourceVault.Id)); Assert.NotNull(secretOut); // Disabling resharper null-ref check as it doesn't seem to understand the not-null assert above. // ReSharper disable PossibleNullReferenceException Assert.NotNull(secretOut.VaultCertificates); var VaultCertComparer = new VaultCertComparer(); Assert.True(secretOut.VaultCertificates.SequenceEqual(secret.VaultCertificates, VaultCertComparer)); // ReSharper enable PossibleNullReferenceException } } if (hasUserDefinedAS) { Assert.NotNull(vmOut.AvailabilitySet); Assert.True(vm.AvailabilitySet.Id.ToLowerInvariant() == vmOut.AvailabilitySet.Id.ToLowerInvariant()); } Assert.Equal(vm.Location, vmOut.Location, StringComparer.OrdinalIgnoreCase); ValidatePlan(vm.Plan, vmOut.Plan); Assert.NotNull(vmOut.VmId); if(expectedPpgReferenceId != null) { Assert.NotNull(vmOut.ProximityPlacementGroup); Assert.Equal(expectedPpgReferenceId, vmOut.ProximityPlacementGroup.Id, StringComparer.OrdinalIgnoreCase); } else { Assert.Null(vmOut.ProximityPlacementGroup); } if (expectedDedicatedHostGroupReferenceId != null) { Assert.NotNull(vmOut.HostGroup); Assert.Equal(expectedDedicatedHostGroupReferenceId, vmOut.HostGroup.Id, StringComparer.OrdinalIgnoreCase); } else { Assert.Null(vmOut.HostGroup); } } protected void ValidateVMInstanceView(VirtualMachine vmIn, VirtualMachine vmOut, bool hasManagedDisks = false, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null, string expectedDedicatedHostReferenceId = null) { Assert.NotNull(vmOut.InstanceView); ValidateVMInstanceView(vmIn, vmOut.InstanceView, hasManagedDisks, expectedComputerName, expectedOSName, expectedOSVersion, expectedDedicatedHostReferenceId); } protected void ValidateVMInstanceView(VirtualMachine vmIn, VirtualMachineInstanceView vmInstanceView, bool hasManagedDisks = false, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null, string expectedDedicatedHostReferenceId = null) { ValidateVMInstanceView(vmInstanceView, hasManagedDisks, !hasManagedDisks ? vmIn.StorageProfile.OsDisk.Name : null, expectedComputerName, expectedOSName, expectedOSVersion, expectedDedicatedHostReferenceId: expectedDedicatedHostReferenceId); } private void ValidateVMInstanceView(VirtualMachineInstanceView vmInstanceView, bool hasManagedDisks = false, string osDiskName = null, string expectedComputerName = null, string expectedOSName = null, string expectedOSVersion = null, string expectedDedicatedHostReferenceId = null) { Assert.Contains(vmInstanceView.Statuses, s => !string.IsNullOrEmpty(s.Code)); if (!hasManagedDisks) { Assert.NotNull(vmInstanceView.Disks); Assert.True(vmInstanceView.Disks.Any()); if (osDiskName != null) { Assert.Contains(vmInstanceView.Disks, x => x.Name == osDiskName); } DiskInstanceView diskInstanceView = vmInstanceView.Disks.First(); Assert.NotNull(diskInstanceView); Assert.NotNull(diskInstanceView.Statuses[0].DisplayStatus); Assert.NotNull(diskInstanceView.Statuses[0].Code); Assert.NotNull(diskInstanceView.Statuses[0].Level); //Assert.NotNull(diskInstanceView.Statuses[0].Message); // TODO: it's null somtimes. //Assert.NotNull(diskInstanceView.Statuses[0].Time); // TODO: it's null somtimes. } // Below three properties might not be populated in time. /* if (expectedComputerName != null) { Assert.Equal(expectedComputerName, vmInstanceView.ComputerName, StringComparer.OrdinalIgnoreCase); } if (expectedOSName != null) { Assert.Equal(expectedOSName, vmInstanceView.OsName, StringComparer.OrdinalIgnoreCase); } if (expectedOSVersion != null) { Assert.Equal(expectedOSVersion, vmInstanceView.OsVersion, StringComparer.OrdinalIgnoreCase); } */ if (expectedDedicatedHostReferenceId != null) { Assert.Equal(expectedDedicatedHostReferenceId, vmInstanceView.AssignedHost, StringComparer.OrdinalIgnoreCase); } } protected void ValidatePlan(Microsoft.Azure.Management.Compute.Models.Plan inputPlan, Microsoft.Azure.Management.Compute.Models.Plan outPutPlan) { if (inputPlan == null || outPutPlan == null ) { Assert.Equal(inputPlan, outPutPlan); return; } Assert.Equal(inputPlan.Name, outPutPlan.Name); Assert.Equal(inputPlan.Publisher, outPutPlan.Publisher); Assert.Equal(inputPlan.Product, outPutPlan.Product); Assert.Equal(inputPlan.PromotionCode, outPutPlan.PromotionCode); } /// <remarks> /// BootDiagnosticsInstanceView properties will be null if VM is enabled with managed boot diagnostics /// </remarks> protected void ValidateBootDiagnosticsInstanceView(BootDiagnosticsInstanceView bootDiagnosticsInstanceView, bool hasError, bool enabledWithManagedBootDiagnostics = false) { // VM with managed boot diagnostics will not return blob URIs or status in BootDiagnosticsInstanceView if (enabledWithManagedBootDiagnostics) { Assert.Null(bootDiagnosticsInstanceView.ConsoleScreenshotBlobUri); Assert.Null(bootDiagnosticsInstanceView.SerialConsoleLogBlobUri); Assert.Null(bootDiagnosticsInstanceView.Status); return; } if (hasError) { Assert.Null(bootDiagnosticsInstanceView.ConsoleScreenshotBlobUri); Assert.Null(bootDiagnosticsInstanceView.SerialConsoleLogBlobUri); Assert.NotNull(bootDiagnosticsInstanceView.Status); } else { Assert.NotNull(bootDiagnosticsInstanceView.ConsoleScreenshotBlobUri); Assert.NotNull(bootDiagnosticsInstanceView.SerialConsoleLogBlobUri); Assert.Null(bootDiagnosticsInstanceView.Status); } } protected static void ValidateBootDiagnosticsData(RetrieveBootDiagnosticsDataResult bootDiagnosticsData) { Assert.NotNull(bootDiagnosticsData); Assert.NotNull(bootDiagnosticsData.ConsoleScreenshotBlobUri); Assert.NotNull(bootDiagnosticsData.SerialConsoleLogBlobUri); } } }
46.156425
267
0.556252
[ "MIT" ]
BaherAbdullah/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/tests/ScenarioTests/VMTestBase.cs
66,096
C#
using System; namespace DailyForecastClassLibrary { class Program { static void Main(string[] args) { } } }
12.153846
39
0.512658
[ "MIT" ]
tialedencan/zadaca
DZ4/Homework4/DailyForecastClassLibrary/Program.cs
160
C#
// <copyright file="DropdownPage.cs" company="Objectivity Bespoke Software Specialists"> // Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved. // </copyright> // <license> // The MIT License (MIT) // 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. // </license> namespace Ocaramba.Tests.NUnitExtentReports.PageObjects { using Ocaramba; using Ocaramba.Extensions; using Ocaramba.Tests.NUnitExtentReports.ExtentLogger; using Ocaramba.Tests.PageObjects; using Ocaramba.Types; using Ocaramba.WebElements; public class DropdownPage : ProjectPageBase { private readonly ElementLocator dropDownLocator = new ElementLocator( Locator.Id, "dropdown"); public DropdownPage(DriverContext driverContext) : base(driverContext) { } public void SelectByIndex(int index) { ExtentTestLogger.Debug("DropdownPage: Selecting element on dropdown by index: " + index); Select select = this.Driver.GetElement<Select>(this.dropDownLocator, 300); select.SelectByIndex(index); } public void SelectByValue(string value) { ExtentTestLogger.Debug("DropdownPage: Selecting element on dropdown by value: " + value); Select select = this.Driver.GetElement<Select>(this.dropDownLocator, 300); select.SelectByValue(value); } public void SelectByText(string text, int timeout) { ExtentTestLogger.Debug("DropdownPage: Selecting element on dropdown by visible text: " + text); Select select = this.Driver.GetElement<Select>(this.dropDownLocator); select.SelectByText(text, timeout); } public string SelectedOption() { ExtentTestLogger.Debug("DropdownPage: Getting selected option"); Select select = this.Driver.GetElement<Select>(this.dropDownLocator); return select.SelectElement().SelectedOption.Text; } } }
44.014085
107
0.68544
[ "MIT" ]
ObjectivityLtd/Ocaramba
Ocaramba.Tests.NUnitExtentReports/PageObject/DropdownPage.cs
3,127
C#
using System; namespace NiTiS.Additions; public static class EnumInfo { public static string GetSpecialName(this Enum enam) { Type enumType = enam.GetType(); string? name = enumType.GetEnumName(enam); try { EnumInfoAttribute enumInfo = (EnumInfoAttribute)enumType.GetMember(enam.ToString())[0].GetCustomAttributes(typeof(EnumInfoAttribute), false)[0]; if (enumInfo != null) return enumInfo.Name; } catch (Exception) { } return name ?? ""; } public static string GetSpecialDescription(this Enum enam) { Type enumType = enam.GetType(); try { EnumInfoAttribute enumInfo = (EnumInfoAttribute)enumType.GetMember(enam.ToString())[0].GetCustomAttributes(typeof(EnumInfoAttribute), false)[0]; if (enumInfo != null) { return enumInfo.Description; } return ""; } catch (Exception) { return ""; } } }
23.722222
147
0.702576
[ "MIT" ]
NiTiS-Dev/NiTiSCore
Core/NiTiS.Additions/EnumInfo.cs
856
C#
using System; using System.ComponentModel.DataAnnotations; namespace WEB.Models { public class FieldDTO { [Required] public Guid FieldId { get; set; } [Required] public Guid EntityId { get; set; } [DisplayFormat(ConvertEmptyStringToNull = false)] [MaxLength(50)] public string Name { get; set; } [DisplayFormat(ConvertEmptyStringToNull = false)] [MaxLength(100)] public string Label { get; set; } [Required] public FieldType FieldType { get; set; } [Required] public int Length { get; set; } public byte? MinLength { get; set; } [Required] public byte Precision { get; set; } [Required] public byte Scale { get; set; } [Required] public bool KeyField { get; set; } [Required] public bool IsUnique { get; set; } [Required] public bool IsNullable { get; set; } [Required] public bool ShowInSearchResults { get; set; } [Required] public SearchType SearchType { get; set; } public int? SortPriority { get; set; } [Required] public bool SortDescending { get; set; } [Required] public int FieldOrder { get; set; } public Guid? LookupId { get; set; } [Required] public EditPageType EditPageType { get; set; } [MaxLength(50)] public string ControllerInsertOverride { get; set; } [MaxLength(50)] public string ControllerUpdateOverride { get; set; } [MaxLength(50)] public string EditPageDefault { get; set; } [MaxLength(500)] public string CalculatedFieldDefinition { get; set; } [MaxLength(250)] public string RegexValidation { get; set; } public EntityDTO Entity { get; set; } public LookupDTO Lookup { get; set; } } public partial class ModelFactory { public FieldDTO Create(Field field) { if (field == null) return null; var fieldDTO = new FieldDTO(); fieldDTO.FieldId = field.FieldId; fieldDTO.EntityId = field.EntityId; fieldDTO.Name = field.Name; fieldDTO.Label = field.Label; fieldDTO.FieldType = field.FieldType; fieldDTO.Length = field.Length; fieldDTO.MinLength = field.MinLength; fieldDTO.Precision = field.Precision; fieldDTO.Scale = field.Scale; fieldDTO.KeyField = field.KeyField; fieldDTO.IsUnique = field.IsUnique; fieldDTO.IsNullable = field.IsNullable; fieldDTO.ShowInSearchResults = field.ShowInSearchResults; fieldDTO.SearchType = field.SearchType; fieldDTO.SortPriority = field.SortPriority; fieldDTO.SortDescending = field.SortDescending; fieldDTO.FieldOrder = field.FieldOrder; fieldDTO.LookupId = field.LookupId; fieldDTO.EditPageType = field.EditPageType; fieldDTO.ControllerInsertOverride = field.ControllerInsertOverride; fieldDTO.ControllerUpdateOverride = field.ControllerUpdateOverride; fieldDTO.EditPageDefault = field.EditPageDefault; fieldDTO.CalculatedFieldDefinition = field.CalculatedFieldDefinition; fieldDTO.RegexValidation = field.RegexValidation; fieldDTO.Lookup = Create(field.Lookup); fieldDTO.Entity = Create(field.Entity); return fieldDTO; } public void Hydrate(Field field, FieldDTO fieldDTO) { field.EntityId = fieldDTO.EntityId; field.Name = fieldDTO.Name; field.Label = fieldDTO.Label; field.FieldType = fieldDTO.FieldType; field.Length = fieldDTO.Length; field.MinLength = fieldDTO.MinLength; field.Precision = fieldDTO.Precision; field.Scale = fieldDTO.Scale; field.KeyField = fieldDTO.KeyField; field.IsUnique = fieldDTO.IsUnique; field.IsNullable = fieldDTO.IsNullable; field.ShowInSearchResults = fieldDTO.ShowInSearchResults; field.SearchType = fieldDTO.SearchType; field.SortPriority = fieldDTO.SortPriority; field.SortDescending = fieldDTO.SortDescending; field.FieldOrder = fieldDTO.FieldOrder; field.LookupId = fieldDTO.LookupId; field.EditPageType = fieldDTO.EditPageType; field.ControllerInsertOverride = fieldDTO.ControllerInsertOverride; field.ControllerUpdateOverride = fieldDTO.ControllerUpdateOverride; field.EditPageDefault = fieldDTO.EditPageDefault; field.CalculatedFieldDefinition = fieldDTO.CalculatedFieldDefinition; field.RegexValidation = fieldDTO.RegexValidation; } } }
32.821192
81
0.611582
[ "MIT" ]
capesean/codegenerator
codegenerator/Models/DTOs/FieldDTO.cs
4,956
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 Xunit; using System; using System.Reflection; using System.Text; namespace System.Reflection.Tests { public class GetTypeTests { //Try to Load a type from currently executing Assembly and return True or false depending on whether type is loaded or not private static bool LoadType(string ptype) { Assembly asm = GetExecutingAssembly(); Type type = null; type = asm.GetType(ptype); if (type == null) { return false; } else if (!type.FullName.Equals(ptype)) { return false; } return true; } //Load Type PublicClass from itself [Fact] public void GetTypeTest1() { string type = "System.Reflection.GetTypesTests.Data.PublicClass"; //Try to Load Type Assert.True(LoadType(type)); } //Load Type NonPublicClass from itself [Fact] public void GetTypeTest2() { string type = "System.Reflection.GetTypesTests.Data.NonPublicClass"; //Try to Load Type Assert.True(LoadType(type)); } //Load Type FriendClass from itself [Fact] public void GetTypeTest3() { string type = "System.Reflection.GetTypesTests.Data.FriendClass"; //Try to Load Type Assert.True(LoadType(type)); } //Load Type PublicEnum from itself [Fact] public void GetTypeTest4() { string type = "System.Reflection.GetTypesTests.Data.PublicEnum"; //Try to Load Type Assert.True(LoadType(type)); } //Load Type PublicStruct from itself [Fact] public void GetTypeTest5() { string type = "System.Reflection.GetTypesTests.Data.PublicStruct"; //Try to Load Type Assert.True(LoadType(type)); } private static Assembly GetExecutingAssembly() { Assembly currentasm = null; Type t = typeof(GetTypeTests); TypeInfo ti = t.GetTypeInfo(); currentasm = ti.Assembly; return currentasm; } } } namespace System.Reflection.GetTypesTests.Data { // Metadata for Reflection public class PublicClass { public int[] intArray; public class PublicNestedClass { } protected class ProtectedNestedClass { } internal class FriendNestedClass { } private class PrivateNestedClass { } } public class GenericPublicClass<T> { public T[] array; public class PublicNestedClass { } protected class ProtectedNestedClass { } internal class FriendNestedClass { } private class PrivateNestedClass { } } //include metadata for non public class internal class NonPublicClass { public class PublicNestedClass { } protected class ProtectedNestedClass { } internal class FriendNestedClass { } private class PrivateNestedClass { } } //include metadata for non public class internal class FriendClass { public class PublicNestedClass { } protected class ProtectedNestedClass { } internal class FriendNestedClass { } private class PrivateNestedClass { } } public enum PublicEnum { RED = 1, BLUE = 2, GREEN = 3 } public struct PublicStruct { } }
24.159236
130
0.582652
[ "MIT" ]
OceanYan/corefx
src/System.Reflection/tests/Assembly/Assembly_GetTypeTests.cs
3,793
C#
using System; namespace TestAPI.Areas.HelpPage.ModelDescriptions { public class ParameterAnnotation { public Attribute AnnotationAttribute { get; set; } public string Documentation { get; set; } } }
20.727273
58
0.692982
[ "MIT" ]
OasesOng/TestVS
TestAPI/TestAPI/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs
228
C#
using Newtonsoft.Json; using Orleans; using System; using System.Collections.Generic; namespace Storage.Couchbase { public class CouchbaseGrainStorageOptions { public List<Uri> Uris { get; set; } public string BucketName { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool DeleteStateOnClear { get; set; } public TypeNameHandling? TypeNameHandling { get; set; } public bool IndentJson { get; set; } public bool UseFullAssemblyNames { get; set; } /// <summary> /// Stage of silo lifecycle where storage should be initialized. Storage must be initialized prior to use. /// </summary> public int InitStage { get; set; } = DEFAULT_INIT_STAGE; public const int DEFAULT_INIT_STAGE = ServiceLifecycleStage.ApplicationServices; } }
27.242424
115
0.657397
[ "MIT" ]
jaypetrin/Orleans.Persistence.Couchbase
src/Storage.Couchbase/CouchbaseGrainStorageOptions.cs
901
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using L2ScriptMaker.Extensions; using L2ScriptMaker.Extensions.VbCompatibleHelper; namespace L2ScriptMaker.Modules.ZeroScripts.L2J { public partial class L2J_NpcPos : Form { public L2J_NpcPos() { InitializeComponent(); } private struct NpcSpawn { // `id` int(11) NOT NULL auto_increment, // `location` varchar(40) NOT NULL default '', // `count` int(9) NOT NULL default '0', // `npc_templateid` int(9) NOT NULL default '0', // `locx` int(9) NOT NULL default '0', // `locy` int(9) NOT NULL default '0', // `locz` int(9) NOT NULL default '0', // `randomx` int(9) NOT NULL default '0', // `randomy` int(9) NOT NULL default '0', // `heading` int(9) NOT NULL default '0', // `respawn_delay` int(9) NOT NULL default '0', // `loc_id` int(9) NOT NULL default '0', // `periodOfDay` decimal(2,0) default '0', public int npc_templateid; public int locx; public int locy; public int locz; public int heading; public int respawn_delay; public bool periodOfDay; } private void ButtonPTStoL2J_Click(object sender, EventArgs e) { string sTemp; string[] aTemp; int iCount = 0; int iCountLimit = 100; if (!string.IsNullOrEmpty(TextBoxL2JMaxLines.Text)) { try { iCountLimit = Conversions.ToInteger(Conversions.ToUInteger(TextBoxL2JMaxLines.Text)); } catch (Exception ex) { MessageBox.Show("Wrong MaxLines count number"); return; } } System.IO.StreamReader inSpawnFile; // LOADING npc_pch.txt if (System.IO.File.Exists("npc_pch.txt") == false) { MessageBox.Show("npc_pch.txt not found", "Need npc_pch.txt", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var aNpcPch = new string[40001]; inSpawnFile = new System.IO.StreamReader("npc_pch.txt", System.Text.Encoding.Default, true, 1); ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length); ToolStripStatusLabel.Text = "Loading npc_pch.txt ..."; while (inSpawnFile.EndOfStream != true) { sTemp = inSpawnFile.ReadLine().Trim(); ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position); if (string.IsNullOrEmpty(sTemp) | sTemp.StartsWith("//") == true | sTemp.StartsWith("[") == false) continue; // [pet_wolf_a] = 1012077 sTemp = sTemp.Replace(" ", "").Replace(Conversions.ToString((char)9), ""); aTemp = sTemp.Split(Conversions.ToChar("=")); try { aNpcPch[Conversions.ToInteger(aTemp[1]) - 1000000] = aTemp[0]; } catch (Exception ex) { MessageBox.Show("Error in loading npc_pch.txt. Last reading line:" + Constants.vbNewLine + sTemp); inSpawnFile.Close(); return; } } inSpawnFile.Close(); ToolStripProgressBar.Value = 0; OpenFileDialog.Filter = "PTS spawn (npcpos.txt)|npcpos.txt|All files|*.*"; if (OpenFileDialog.ShowDialog() == DialogResult.Cancel) return; inSpawnFile = new System.IO.StreamReader(OpenFileDialog.FileName, System.Text.Encoding.Default, true, 1); var outFile = new System.IO.StreamWriter("spawnlist_new.sql", false, System.Text.Encoding.Unicode, 1); ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length); ToolStripStatusLabel.Text = "Loading npcpos.txt..."; var sLastZoneName = default(string); int iTemp; string sTempSpawn = ""; string sTempNpc; char bIsNight = Conversions.ToChar("0"); bool bEventNpc = false; string sLastNpcName; while (inSpawnFile.EndOfStream != true) { sTemp = inSpawnFile.ReadLine().Trim(); ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position); if (string.IsNullOrEmpty(sTemp) | sTemp.StartsWith("//") == true) continue; // npcmaker_ex_begin [oren22_2219_a01] name=[oren22_2219_a01m1] ai=[default_maker] maximum_npc=50 // npcmaker_ex_begin [rune09_npc2116_05] name=[rune09_npc2116_0502] ai=[on_day_night_spawn] ai_parameters={[IsNight]=1} maximum_npc=1 // npcmaker_ex_begin [schuttgart03_npc2312_tb02] name=[schuttgart03_npc2312_tb02m1] ai=[event_maker] ai_parameters={[EventName]=[event_treasure_box]} maximum_npc=9 if (sTemp.StartsWith("npcmaker_begin") == true | sTemp.StartsWith("npcmaker_ex_begin") == true) { aTemp = sTemp.Split((char)9); sLastZoneName = aTemp[1].Replace("[", "").Replace("]", ""); if (sTemp.IndexOf("[IsNight]=1") > 0) bIsNight = Conversions.ToChar("1"); else bIsNight = Conversions.ToChar("0"); if ((Libraries.GetNeedParamFromStr(sTemp, "ai") ?? "") == "[event_maker]" & sTemp.IndexOf("[EventName]=") > 0) bEventNpc = true; else bEventNpc = false; continue; } // npc_ex_begin [xel_trainer_mage] pos={88347;56413;-3495;49152} total=1 respawn=90sec ai_parameters={[trainer_id]=1;[direction]=49152} is_chase_pc=1000 npc_ex_end if (sTemp.StartsWith("npc_begin") == true | sTemp.StartsWith("npc_ex_begin") == true) { sTempSpawn = ""; aTemp = sTemp.Split((char)9); sTempNpc = aTemp[1].Replace("[", "").Replace("]", ""); sLastNpcName = aTemp[1]; // 1 - area name sTempSpawn += "('" + sLastZoneName + "',"; // 2 - total sTempNpc = Libraries.GetNeedParamFromStr(sTemp, "total"); if (string.IsNullOrEmpty(Libraries.GetNeedParamFromStr(sTemp, "total"))) { if (CheckBoxShowAll.Checked == true) outFile.WriteLine("-- npc name " + sLastNpcName + " not found count"); continue; } sTempSpawn += Libraries.GetNeedParamFromStr(sTemp, "total") + ","; // 3 - npcname iTemp = Array.IndexOf(aNpcPch, aTemp[1]); if (iTemp == -1) { if (CheckBoxShowAll.Checked == true) outFile.WriteLine("-- npc name " + sLastNpcName + " not found in npc_pch"); continue; } sTempSpawn += Conversions.ToString(iTemp) + ","; // 4,5,6,7,8,9 - x,y,z,0,0,heading sTempNpc = Libraries.GetNeedParamFromStr(sTemp, "pos").Replace("{", "").Replace("}", ""); if ((sTempNpc ?? "") == "anywhere") { // pos=anywhere if (CheckBoxShowAll.Checked == true) outFile.WriteLine("-- npc name " + sLastNpcName + " use anywhere spawn. No supported."); continue; } aTemp = sTempNpc.Split(Conversions.ToChar(";")); sTempSpawn += aTemp[0] + ","; sTempSpawn += aTemp[1] + ","; sTempSpawn += aTemp[2] + ","; sTempSpawn += "0,0,"; sTempSpawn += aTemp[3] + ","; // 10 - respawn time sTempNpc = Libraries.GetNeedParamFromStr(sTemp, "respawn"); if ((sTempNpc ?? "") == "no") { // respawn=no if (CheckBoxShowAll.Checked == true) outFile.WriteLine("-- npc name " + sLastNpcName + " respawn=no"); continue; } if (sTempNpc.IndexOf("sec") > 0) sTempNpc = sTempNpc.Replace("sec", ""); else if (sTempNpc.IndexOf("min") > 0) { sTempNpc = sTempNpc.Replace("min", ""); sTempNpc = (Conversions.ToInteger(sTempNpc) * 60).ToString(); } else if (sTempNpc.IndexOf("hour") > 0) { sTempNpc = sTempNpc.Replace("hour", ""); sTempNpc = (Conversions.ToInteger(sTempNpc) * 60 * 60).ToString(); } sTempSpawn += sTempNpc + ","; // 10 - loc_id,periodOfDay sTempSpawn += "0,"; // periodOfDay sTempSpawn += Conversions.ToString(bIsNight); sTempSpawn += ")"; if (bEventNpc == true & (CheckBoxSaveEventNpc.Checked == false & CheckBoxShowAll.Checked == true)) { outFile.WriteLine("-- " + sTempSpawn + Constants.vbTab + "-- Event npc: " + sLastNpcName); continue; } if (iCount == 0) sTempSpawn = "INSERT INTO `spawnlist` VALUES" + Constants.vbNewLine + sTempSpawn; iCount += 1; if (iCount >= iCountLimit) { sTempSpawn += ";"; iCount = 0; } else sTempSpawn += ","; if (CheckBoxShowNpcName.Checked == true) sTempSpawn += Constants.vbTab + "-- " + sLastNpcName; outFile.WriteLine(sTempSpawn); } } ToolStripProgressBar.Value = 0; inSpawnFile.Close(); outFile.Close(); MessageBox.Show("Completed."); } private void ButtonStart_Click(object sender, EventArgs e) { string sSpawnListFile; string sTemp; string[] aTemp; System.IO.StreamReader inSpawnFile; // LOADING npc_pch.txt if (System.IO.File.Exists("npc_pch.txt") == false) { MessageBox.Show("npc_pch.txt not found", "Need npc_pch.txt", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var aNpcPch = new string[40001]; inSpawnFile = new System.IO.StreamReader("npc_pch.txt", System.Text.Encoding.Default, true, 1); ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length); ToolStripStatusLabel.Text = "Loading npc_pch.txt ..."; while (inSpawnFile.EndOfStream != true) { sTemp = inSpawnFile.ReadLine().Trim(); ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position); if (!string.IsNullOrEmpty(sTemp) & sTemp.StartsWith("//") == false) { // [pet_wolf_a] = 1012077 sTemp = sTemp.Replace(" ", "").Replace(Conversions.ToString((char)9), ""); aTemp = sTemp.Split(Conversions.ToChar("=")); try { aNpcPch[Conversions.ToInteger(aTemp[1]) - 1000000] = aTemp[0]; } catch (Exception ex) { MessageBox.Show("Error in loading npc_pch.txt. Last reading line:" + Constants.vbNewLine + sTemp); inSpawnFile.Close(); return; } } } inSpawnFile.Close(); ToolStripProgressBar.Value = 0; OpenFileDialog.Filter = "L2J Spawn (spawnlist.sql)|spawnlist.sql|All files|*.*"; if (OpenFileDialog.ShowDialog() == DialogResult.Cancel) return; sSpawnListFile = OpenFileDialog.FileName; inSpawnFile = new System.IO.StreamReader(sSpawnListFile, System.Text.Encoding.Default, true, 1); var outFile = new System.IO.StreamWriter("npcpos_l2j.txt", false, System.Text.Encoding.Unicode, 1); ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length); ToolStripStatusLabel.Text = "Loading spawnlist.sql..."; string sCurZoneName = ""; // Dim aZone() As String = {} string sPrevZoneName = null; string sTempTerritory; string sTempNpcName; int iNpcCount = 0; var aNpcSpawn = new NpcSpawn[1]; var aNpcMiss = new int[1]; var iXMin = default(int); // Dim iTemp As Integer var iXMax = default(int); var iYMin = default(int); var iYMax = default(int); var iZMin = default(int); var iZMax = default(int); while (inSpawnFile.EndOfStream != true) { sTemp = inSpawnFile.ReadLine().Trim(); ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position); if (!string.IsNullOrEmpty(sTemp) & sTemp.StartsWith("(") == true) { // ---------- Prepare for importing // `id` int(11) NOT NULL auto_increment, // `location` varchar(40) NOT NULL default '', // `count` int(9) NOT NULL default '0', // `npc_templateid` int(9) NOT NULL default '0', // `locx` int(9) NOT NULL default '0', // `locy` int(9) NOT NULL default '0', // `locz` int(9) NOT NULL default '0', // `randomx` int(9) NOT NULL default '0', // `randomy` int(9) NOT NULL default '0', // `heading` int(9) NOT NULL default '0', // `respawn_delay` int(9) NOT NULL default '0', // `loc_id` int(9) NOT NULL default '0', // `periodOfDay` decimal(2,0) default '0', // (1,'partisan_agit_2121_01',1,35372,44368,107440,-2032,0,0,0,60,0,0), // (2,'partisan_agit_2121_01',1,35372,44768,108604,-2034,0,0,44231,60,0,0), sTemp = sTemp.Substring(Strings.InStr(sTemp, "("), Strings.InStr(sTemp, ")") - Strings.InStr(sTemp, "(") - 1); sTemp = sTemp.Replace("'", ""); aTemp = sTemp.Split(Conversions.ToChar(",")); // 0 1 2 3 4 5 6 7 8 9 10 11 12 // (1,'partisan_agit_2121_01',1,35372,44368,107440,-2032, 0,0, 0,60,0,0), sCurZoneName = aTemp[1]; if (sPrevZoneName == null) sPrevZoneName = sCurZoneName; if ((sCurZoneName ?? "") != (sPrevZoneName ?? "")) { // Write new zone with // territory_begin [FantasyIsle_0] {{-59734;-57397;-2532;-1732};{-58734;-57397;-2532;-1732};{-58734;-56397;-2532;-1732};{-59734;-56397;-2532;-1732}} territory_end // npcmaker_begin [FantasyIsle_0] initial_spawn=all maximum_npc=1 // npcmaker_ex_begin [rune09_npc2116_05] name=[rune09_npc2116_0502] ai=[on_day_night_spawn] ai_parameters={[IsNight]=1} maximum_npc=1 // npc_ex_begin [maid_of_ridia] pos={47108;-36189;-1624;-22192} total=1 respawn=1min npc_ex_end // npcmaker_ex_end sPrevZoneName = sPrevZoneName.Replace(" ", "_").ToLower(); // Generate TERRITORY AREA iXMin = iXMin - 200; iXMax = iXMax + 200; iYMin = iYMin - 200; iYMax = iYMax + 200; iZMin = iZMin - 100; iZMax = iZMax + 100 + 700; sTempTerritory = ""; sTempTerritory = sTempTerritory + "{" + Conversions.ToString(iXMin) + ";" + Conversions.ToString(iYMin) + ";" + Conversions.ToString(iZMin) + ";" + Conversions.ToString(iZMax) + "};"; sTempTerritory = sTempTerritory + "{" + Conversions.ToString(iXMax) + ";" + Conversions.ToString(iYMin) + ";" + Conversions.ToString(iZMin) + ";" + Conversions.ToString(iZMax) + "};"; sTempTerritory = sTempTerritory + "{" + Conversions.ToString(iXMax) + ";" + Conversions.ToString(iYMax) + ";" + Conversions.ToString(iZMin) + ";" + Conversions.ToString(iZMax) + "};"; sTempTerritory = sTempTerritory + "{" + Conversions.ToString(iXMin) + ";" + Conversions.ToString(iYMax) + ";" + Conversions.ToString(iZMin) + ";" + Conversions.ToString(iZMax) + "}"; outFile.WriteLine("territory_begin" + Constants.vbTab + "[" + sPrevZoneName + "]" + Constants.vbTab + "{" + sTempTerritory + "}" + Constants.vbTab + "territory_end"); outFile.WriteLine("npcmaker_begin" + Constants.vbTab + "[" + sPrevZoneName + "]" + Constants.vbTab + "initial_spawn=all" + Constants.vbTab + "maximum_npc=" + Conversions.ToString(iNpcCount)); for (int iTemp = 0, loopTo = iNpcCount - 1; iTemp <= loopTo; iTemp++) { // Checking exising npc in NpcPch if (aNpcPch[Conversions.ToInteger(aNpcSpawn[iTemp].npc_templateid)] == null) { // MessageBox.Show("Npc [" & aTemp(3) & "] not found!", "NPC not found", MessageBoxButtons.OK, MessageBoxIcon.Error) if (Array.IndexOf(aNpcMiss, aNpcSpawn[iTemp].npc_templateid) == -1) { aNpcMiss[aNpcMiss.Length - 1] = aNpcSpawn[iTemp].npc_templateid; Array.Resize(ref aNpcMiss, aNpcMiss.Length + 1); } sTempNpcName = "[_need_" + Conversions.ToString(aNpcSpawn[iTemp].npc_templateid) + "_]"; } else sTempNpcName = aNpcPch[Conversions.ToInteger(aNpcSpawn[iTemp].npc_templateid)]; // npc_begin [fantasy_isle_paddies] pos={-59234;-56897;-2032;0} total=1 respawn=60sec npc_end outFile.WriteLine("npc_begin" + Constants.vbTab + sTempNpcName + Constants.vbTab + "pos={" + Conversions.ToString(aNpcSpawn[iTemp].locx) + "," + Conversions.ToString(aNpcSpawn[iTemp].locy) + "," + Conversions.ToString(aNpcSpawn[iTemp].locz) + "," + Conversions.ToString(aNpcSpawn[iTemp].heading) + "}" + Constants.vbTab + "total=1" + Constants.vbTab + "respawn=" + Conversions.ToString(aNpcSpawn[iTemp].respawn_delay) + "sec" + Constants.vbTab + "npc_end"); } // npcmaker_end outFile.WriteLine("npcmaker_end"); iNpcCount = 0; Array.Clear(aNpcSpawn, 0, aNpcSpawn.Length); Array.Resize(ref aNpcSpawn, 1); sPrevZoneName = sCurZoneName; } // ADD new Npc to Array Array.Resize(ref aNpcSpawn, iNpcCount + 1); // Dim iXMin As Integer, iXMax As Integer // Dim iYMin As Integer, iYMax As Integer // Dim iZMin As Integer, iZMax As Integer aNpcSpawn[iNpcCount].npc_templateid = Conversions.ToInteger(aTemp[3]); aNpcSpawn[iNpcCount].locx = Conversions.ToInteger(aTemp[4]); aNpcSpawn[iNpcCount].locy = Conversions.ToInteger(aTemp[5]); aNpcSpawn[iNpcCount].locz = Conversions.ToInteger(aTemp[6]); aNpcSpawn[iNpcCount].heading = Conversions.ToInteger(aTemp[9]); aNpcSpawn[iNpcCount].respawn_delay = Conversions.ToInteger(aTemp[10]); if (iNpcCount == 0) iXMin = aNpcSpawn[iNpcCount].locx; if (iNpcCount == 0) iXMax = aNpcSpawn[iNpcCount].locx; if (iNpcCount == 0) iYMin = aNpcSpawn[iNpcCount].locy; if (iNpcCount == 0) iYMax = aNpcSpawn[iNpcCount].locy; if (iNpcCount == 0) iZMin = aNpcSpawn[iNpcCount].locz; if (iNpcCount == 0) iZMax = aNpcSpawn[iNpcCount].locz; if (aNpcSpawn[iNpcCount].locx < iXMin) iXMin = aNpcSpawn[iNpcCount].locx; if (aNpcSpawn[iNpcCount].locx > iXMax) iXMax = aNpcSpawn[iNpcCount].locx; if (aNpcSpawn[iNpcCount].locy < iYMin) iYMin = aNpcSpawn[iNpcCount].locy; if (aNpcSpawn[iNpcCount].locy > iYMax) iYMax = aNpcSpawn[iNpcCount].locy; if (aNpcSpawn[iNpcCount].locz < iZMin) iZMin = aNpcSpawn[iNpcCount].locz; if (aNpcSpawn[iNpcCount].locz > iZMax) iZMax = aNpcSpawn[iNpcCount].locz; iNpcCount = iNpcCount + 1; } } ToolStripProgressBar.Value = 0; inSpawnFile.Close(); outFile.Close(); if (aNpcMiss.Length > 0) { outFile = new System.IO.StreamWriter("npcpos_l2j.log", false, System.Text.Encoding.Unicode, 1); outFile.WriteLine("Missed NPC. Required for NpcPos:"); var loopTo1 = aNpcMiss.Length - 2; for (iNpcCount = 0; iNpcCount <= loopTo1; iNpcCount++) outFile.WriteLine("npc_id=" + Conversions.ToString(aNpcMiss[iNpcCount])); outFile.Close(); } MessageBox.Show("Completed. With [" + Conversions.ToString(iNpcCount) + "] missed npc's."); } private void ButtonQuit_Click(object sender, EventArgs e) { this.Dispose(); } } }
36.741414
464
0.644636
[ "Apache-2.0" ]
Max4aters/L2ScriptMaker
L2ScriptMaker/Modules/ZeroScripts/L2J/L2J_NpcPos.cs
18,189
C#
using System; using NetOffice; namespace NetOffice.VisioApi.Enums { /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/ff767414(v=office.14).aspx </remarks> [SupportByVersionAttribute("Visio", 14,15)] [EntityTypeAttribute(EntityType.IsEnum)] public enum VisResizeDirection { /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>0</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirE = 0, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirNE = 1, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>2</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirN = 2, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>3</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirNW = 3, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>4</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirW = 4, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>5</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirSW = 5, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>6</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirS = 6, /// <summary> /// SupportByVersion Visio 14, 15 /// </summary> /// <remarks>7</remarks> [SupportByVersionAttribute("Visio", 14,15)] visResizeDirSE = 7 } }
26.362319
126
0.607477
[ "MIT" ]
NetOffice/NetOffice
Source/Visio/Enums/VisResizeDirection.cs
1,819
C#
namespace Cedar.CommandHandling.Http.TypeResolution { /// <summary> /// Represents a parsed media type. Example, given a media type 'application/vnd.foo.bar.v2+json' /// an implementation would then result in Typename='foo.bar', Version='2' and SerializationType = 'json' /// </summary> public class ParsedMediaType { /// <summary> /// Gets the name of the type as extracted from the media type. /// </summary> /// <value> /// The name of the type. /// </value> public readonly string CommandName; /// <summary> /// Gets the version of the type as extracted from the media type. If no version /// is parsed, then it will be null. /// </summary> /// <value> /// The version of the media type. /// </value> public readonly int? Version; /// <summary> /// Gets the serialization type. /// </summary> public readonly string SerializationType; /// <summary> /// Initializes a new instance of the <see cref="ParsedMediaType"/> class. /// </summary> /// <param name="commandName">The command type name.</param> /// <param name="version">The version.</param> /// <param name="serializationType">Type of the serialization.</param> public ParsedMediaType(string commandName, int? version, string serializationType) { CommandName = commandName; Version = version; SerializationType = serializationType; } } }
36.818182
113
0.572222
[ "MIT" ]
heynickc/Cedar.CommandHandling
src/Cedar.CommandHandling.Http.Client/TypeResolution/ParsedMediaType.cs
1,620
C#
using System; using Foundation; using UIKit; using NotificationCenter; using WebKit; namespace ExtensionsDemo { public partial class ExtensionsDemoViewController : UIViewController { WKWebView webView; public ExtensionsDemoViewController (IntPtr handle) : base (handle) { } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); var controller = NCWidgetController.GetWidgetController (); controller.SetHasContent (true, "com.xamarin.ExtensionsDemo.EvolveCountdownWidget"); } public override void ViewDidLoad () { base.ViewDidLoad (); webView = new WKWebView (View.Frame, new WKWebViewConfiguration ()); View.AddSubview (webView); var url = new NSUrl ("https://evolve.xamarin.com"); var request = new NSUrlRequest (url); webView.LoadRequest (request); } } }
22.315789
87
0.737028
[ "MIT" ]
Art-Lav/ios-samples
ios8/ExtensionsDemo/ExtensionsDemo/ExtensionsDemoViewController.cs
850
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.DynamicProxy.Generators.Emitters.SimpleAST { using System; using System.Reflection; using System.Reflection.Emit; using Castle.DynamicProxy.Tokens; public class MethodTokenExpression : Expression { private readonly MethodInfo method; private readonly Type declaringType; public MethodTokenExpression(MethodInfo method) { this.method = method; declaringType = method.DeclaringType; } public override void Emit(IMemberEmitter member, ILGenerator gen) { gen.Emit(OpCodes.Ldtoken, method); if (declaringType == null) { throw new GeneratorException("declaringType can't be null for this situation"); } gen.Emit(OpCodes.Ldtoken, declaringType); var minfo = MethodBaseMethods.GetMethodFromHandle; gen.Emit(OpCodes.Call, minfo); gen.Emit(OpCodes.Castclass, typeof(MethodInfo)); } } }
30.958333
83
0.748318
[ "Apache-2.0" ]
CalosChen/Core
src/Castle.Core/DynamicProxy/Generators/Emitters/SimpleAST/MethodTokenExpression.cs
1,486
C#
using System.Linq; using BenchmarkDotNet.Attributes; using Marten.Testing; namespace MartenBenchmarks { [SimpleJob(warmupCount: 2)] public class BulkLoading { public static Target[] Docs = Target.GenerateRandomData(1000).ToArray(); [GlobalSetup] public void Setup() { BenchmarkStore.Store.Advanced.Clean.DeleteDocumentsFor(typeof(Target)); } [Benchmark] [MemoryDiagnoser] public void BulkInsertDocuments() { BenchmarkStore.Store.Advanced.Clean.DeleteDocumentsFor(typeof(Target)); BenchmarkStore.Store.BulkInsert(Docs); } } }
24.444444
83
0.642424
[ "MIT" ]
jacobpovar/marten
src/MartenBenchmarks/BulkLoading.cs
660
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("Installer")] [assembly: AssemblyDescription("Installer for Tailviewer")] [assembly: AssemblyProduct("Tailviewer")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
42.210526
93
0.781796
[ "MIT" ]
Kittyfisto/SharpTail
src/Installer/Properties/AssemblyInfo.cs
1,606
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OfficeDevPnP.Core.Extensions; namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers { /// <summary> /// Type resolver for Navigation Node from model to schema /// </summary> internal class NavigationNodeFromModelToSchemaTypeResolver : ITypeResolver { public string Name => this.GetType().Name; public bool CustomCollectionResolver => false; public object Resolve(object source, Dictionary<string, IResolver> resolvers = null, bool recursive = false) { Array result = null; Object modelSource = source as Model.StructuralNavigation; if (modelSource == null) { modelSource = source as Model.NavigationNode; } if (modelSource != null) { Model.NavigationNodeCollection sourceNodes = modelSource.GetPublicInstancePropertyValue("NavigationNodes") as Model.NavigationNodeCollection; if (sourceNodes != null) { var navigationNodeTypeName = $"{PnPSerializationScope.Current?.BaseSchemaNamespace}.NavigationNode, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}"; var navigationNodeType = Type.GetType(navigationNodeTypeName, true); result = Array.CreateInstance(navigationNodeType, sourceNodes.Count); resolvers = new Dictionary<string, IResolver>(); resolvers.Add($"{navigationNodeType}.NavigationNode1", new NavigationNodeFromModelToSchemaTypeResolver()); for (Int32 c = 0; c < sourceNodes.Count; c++) { var targetNodeItem = Activator.CreateInstance(navigationNodeType); PnPObjectsMapper.MapProperties(sourceNodes[c], targetNodeItem, resolvers, recursive); result.SetValue(targetNodeItem, c); } } } return (result); } } }
38.561404
177
0.620109
[ "MIT" ]
3v1lW1th1n/PnP-Sites-Core
Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/Resolvers/NavigationNodeFromModelToSchemaTypeResolver.cs
2,200
C#