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
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.adoxio_specialeventlicencedarea /// </summary> public partial class MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea class. /// </summary> public MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea class. /// </summary> public MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea(int? adoxioSetting = default(int?), string _adoxioSpecialeventidValue = default(string), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string _createdonbehalfbyValue = default(string), string _owningbusinessunitValue = default(string), int? utcconversiontimezonecode = default(int?), int? adoxioLicencedareanumberofminors = default(int?), string _adoxioSpecialeventlocationidValue = default(string), string adoxioLicencedareadescription = default(string), string adoxioSpecialeventlicencedareaid = default(string), string _owninguserValue = default(string), string _createdbyValue = default(string), string _owningteamValue = default(string), bool? adoxioMinorpresent = default(bool?), string _modifiedonbehalfbyValue = default(string), int? adoxioLicencedareamaxnumberofguests = default(int?), int? timezoneruleversionnumber = default(int?), int? statecode = default(int?), int? statuscode = default(int?), int? importsequencenumber = default(int?), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string adoxioEventname = default(string), string versionnumber = default(string), string _owneridValue = default(string), string _modifiedbyValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser owninguser = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMteam owningteam = default(MicrosoftDynamicsCRMteam), MicrosoftDynamicsCRMprincipal ownerid = default(MicrosoftDynamicsCRMprincipal), MicrosoftDynamicsCRMbusinessunit owningbusinessunit = default(MicrosoftDynamicsCRMbusinessunit), IList<MicrosoftDynamicsCRMsyncerror> adoxioSpecialeventlicencedareaSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMasyncoperation> adoxioSpecialeventlicencedareaAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>), IList<MicrosoftDynamicsCRMmailboxtrackingfolder> adoxioSpecialeventlicencedareaMailboxTrackingFolders = default(IList<MicrosoftDynamicsCRMmailboxtrackingfolder>), IList<MicrosoftDynamicsCRMprocesssession> adoxioSpecialeventlicencedareaProcessSession = default(IList<MicrosoftDynamicsCRMprocesssession>), IList<MicrosoftDynamicsCRMbulkdeletefailure> adoxioSpecialeventlicencedareaBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> adoxioSpecialeventlicencedareaPrincipalObjectAttributeAccesses = default(IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess>), MicrosoftDynamicsCRMadoxioSpecialevent adoxioSpecialEventId = default(MicrosoftDynamicsCRMadoxioSpecialevent), MicrosoftDynamicsCRMadoxioSpecialeventlocation adoxioSpecialEventLocationId = default(MicrosoftDynamicsCRMadoxioSpecialeventlocation), IList<MicrosoftDynamicsCRMadoxioSpecialeventschedule> adoxioSpecialeventareaEventschedules = default(IList<MicrosoftDynamicsCRMadoxioSpecialeventschedule>)) { AdoxioSetting = adoxioSetting; this._adoxioSpecialeventidValue = _adoxioSpecialeventidValue; Overriddencreatedon = overriddencreatedon; this._createdonbehalfbyValue = _createdonbehalfbyValue; this._owningbusinessunitValue = _owningbusinessunitValue; Utcconversiontimezonecode = utcconversiontimezonecode; AdoxioLicencedareanumberofminors = adoxioLicencedareanumberofminors; this._adoxioSpecialeventlocationidValue = _adoxioSpecialeventlocationidValue; AdoxioLicencedareadescription = adoxioLicencedareadescription; AdoxioSpecialeventlicencedareaid = adoxioSpecialeventlicencedareaid; this._owninguserValue = _owninguserValue; this._createdbyValue = _createdbyValue; this._owningteamValue = _owningteamValue; AdoxioMinorpresent = adoxioMinorpresent; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; AdoxioLicencedareamaxnumberofguests = adoxioLicencedareamaxnumberofguests; Timezoneruleversionnumber = timezoneruleversionnumber; Statecode = statecode; Statuscode = statuscode; Importsequencenumber = importsequencenumber; Modifiedon = modifiedon; AdoxioEventname = adoxioEventname; Versionnumber = versionnumber; this._owneridValue = _owneridValue; this._modifiedbyValue = _modifiedbyValue; Createdon = createdon; Createdby = createdby; Createdonbehalfby = createdonbehalfby; Modifiedby = modifiedby; Modifiedonbehalfby = modifiedonbehalfby; Owninguser = owninguser; Owningteam = owningteam; Ownerid = ownerid; Owningbusinessunit = owningbusinessunit; AdoxioSpecialeventlicencedareaSyncErrors = adoxioSpecialeventlicencedareaSyncErrors; AdoxioSpecialeventlicencedareaAsyncOperations = adoxioSpecialeventlicencedareaAsyncOperations; AdoxioSpecialeventlicencedareaMailboxTrackingFolders = adoxioSpecialeventlicencedareaMailboxTrackingFolders; AdoxioSpecialeventlicencedareaProcessSession = adoxioSpecialeventlicencedareaProcessSession; AdoxioSpecialeventlicencedareaBulkDeleteFailures = adoxioSpecialeventlicencedareaBulkDeleteFailures; AdoxioSpecialeventlicencedareaPrincipalObjectAttributeAccesses = adoxioSpecialeventlicencedareaPrincipalObjectAttributeAccesses; AdoxioSpecialEventId = adoxioSpecialEventId; AdoxioSpecialEventLocationId = adoxioSpecialEventLocationId; AdoxioSpecialeventareaEventschedules = adoxioSpecialeventareaEventschedules; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_setting")] public int? AdoxioSetting { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_adoxio_specialeventid_value")] public string _adoxioSpecialeventidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "overriddencreatedon")] public System.DateTimeOffset? Overriddencreatedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningbusinessunit_value")] public string _owningbusinessunitValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "utcconversiontimezonecode")] public int? Utcconversiontimezonecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_licencedareanumberofminors")] public int? AdoxioLicencedareanumberofminors { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_adoxio_specialeventlocationid_value")] public string _adoxioSpecialeventlocationidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_licencedareadescription")] public string AdoxioLicencedareadescription { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedareaid")] public string AdoxioSpecialeventlicencedareaid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owninguser_value")] public string _owninguserValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningteam_value")] public string _owningteamValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_minorpresent")] public bool? AdoxioMinorpresent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_licencedareamaxnumberofguests")] public int? AdoxioLicencedareamaxnumberofguests { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "timezoneruleversionnumber")] public int? Timezoneruleversionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statecode")] public int? Statecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statuscode")] public int? Statuscode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_eventname")] public string AdoxioEventname { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "versionnumber")] public string Versionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owninguser")] public MicrosoftDynamicsCRMsystemuser Owninguser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningteam")] public MicrosoftDynamicsCRMteam Owningteam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ownerid")] public MicrosoftDynamicsCRMprincipal Ownerid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public MicrosoftDynamicsCRMbusinessunit Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_SyncErrors")] public IList<MicrosoftDynamicsCRMsyncerror> AdoxioSpecialeventlicencedareaSyncErrors { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> AdoxioSpecialeventlicencedareaAsyncOperations { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_MailboxTrackingFolders")] public IList<MicrosoftDynamicsCRMmailboxtrackingfolder> AdoxioSpecialeventlicencedareaMailboxTrackingFolders { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_ProcessSession")] public IList<MicrosoftDynamicsCRMprocesssession> AdoxioSpecialeventlicencedareaProcessSession { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_BulkDeleteFailures")] public IList<MicrosoftDynamicsCRMbulkdeletefailure> AdoxioSpecialeventlicencedareaBulkDeleteFailures { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventlicencedarea_PrincipalObjectAttributeAccesses")] public IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> AdoxioSpecialeventlicencedareaPrincipalObjectAttributeAccesses { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_SpecialEventId")] public MicrosoftDynamicsCRMadoxioSpecialevent AdoxioSpecialEventId { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_SpecialEventLocationId")] public MicrosoftDynamicsCRMadoxioSpecialeventlocation AdoxioSpecialEventLocationId { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "adoxio_specialeventarea_eventschedules")] public IList<MicrosoftDynamicsCRMadoxioSpecialeventschedule> AdoxioSpecialeventareaEventschedules { get; set; } } }
51.645695
3,358
0.686991
[ "Apache-2.0" ]
asanchezr/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMadoxioSpecialeventlicencedarea.cs
15,597
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Configuration; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using SFA.DAS.Encoding; using SFA.DAS.Reservations.Infrastructure.Configuration; namespace SFA.DAS.Reservations.Infrastructure.AzureConfigurationProvider { public class AzureTableStorageConfigurationProvider : ConfigurationProvider { private readonly string[] _configName; private readonly string _environment; private readonly string _version; private readonly CloudStorageAccount _storageAccount; private const string EncodingConfigKey = "SFA.DAS.Encoding"; public AzureTableStorageConfigurationProvider(string connection,string[] configName, string environment, string version) { _configName = configName; _environment = environment; _version = version; _storageAccount = CloudStorageAccount.Parse(connection); } public override void Load() { if (_environment.Equals("DEV", StringComparison.CurrentCultureIgnoreCase)) { return; } var table = GetTable(); foreach (var config in _configName) { var configParams = config.Split(":"); var configDefaultSectionName = configParams.Length > 1 ? configParams[1] : string.Empty; var operation = GetOperation(configParams[0], _environment, _version); var result = table.ExecuteAsync(operation).Result; var configItem = (ConfigurationItem)result.Result; if (config == EncodingConfigKey) { Data.Add(nameof(EncodingConfig), configItem.Data); continue; } var data = new StorageConfigParser().ParseConfig(configItem, configDefaultSectionName); data.ToList().ForEach(x => Data.Add(x.Key, x.Value)); } } private CloudTable GetTable() { var tableClient = _storageAccount.CreateCloudTableClient(); return tableClient.GetTableReference("Configuration"); } private TableOperation GetOperation(string serviceName, string environmentName, string version) { return TableOperation.Retrieve<ConfigurationItem>(environmentName, $"{serviceName}_{version}"); } } }
35.943662
128
0.633229
[ "MIT" ]
FeatureToggleStudy/das-reservations
src/SFA.DAS.Reservations.Infrastructure/AzureConfigurationProvider/AzureTableStorageConfigurationProvider.cs
2,554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; namespace HelpfulWebsite_2.Application.WeatherForecasts.Queries.GetWeatherForecasts { public class GetWeatherForecastsQuery : IRequest<IEnumerable<WeatherForecast>> { } public class GetWeatherForecastsQueryHandler : IRequestHandler<GetWeatherForecastsQuery, IEnumerable<WeatherForecast>> { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<IEnumerable<WeatherForecast>> Handle(GetWeatherForecastsQuery request, CancellationToken cancellationToken) { var rng = new Random(); var vm = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }); return Task.FromResult(vm); } } }
31.972222
127
0.64987
[ "MIT" ]
CameronHunter000/HelpfulWebsite2
src/Application/WeatherForecasts/Queries/GetWeatherForecasts/GetWeatherForecastsQuery.cs
1,153
C#
using IdentityServer4.Models; namespace Indice.AspNetCore.Identity.Models { /// <summary> /// View model for the error page /// </summary> public class ErrorViewModel { /// <summary> /// Creates a new <see cref="ErrorViewModel"/>. /// </summary> public ErrorViewModel() { } /// <summary> /// Creates a new <see cref="ErrorViewModel"/>. /// </summary> /// <param name="error">The error message</param> public ErrorViewModel(string error) { Error = new ErrorMessage { Error = error }; } /// <summary> /// The error message /// </summary> public ErrorMessage Error { get; set; } } }
24.666667
57
0.531081
[ "MIT" ]
ChristosAsvestopoulos/Indice.AspNet
src/Indice.AspNetCore.Identity/Models/ErrorViewModel.cs
742
C#
// Copyright 2018 Andrew White // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Finbuckle.MultiTenant; using Finbuckle.MultiTenant.Options; using Microsoft.Extensions.DependencyInjection; using Xunit; public class MultiTenantOptionsFactoryShould { [Theory] [InlineData("")] [InlineData(null)] [InlineData("name")] public void CreateOptionsWithTenantAction(string name) { var ti = new TenantInfo("test-id-123", null, null, null, null); var tc = new MultiTenantContext(); tc.TenantInfo = ti; var tca = new TestMultiTenantContextAccessor(tc); var services = new ServiceCollection(); services.AddTransient<IMultiTenantContextAccessor>(_sp => tca); services.Configure<InMemoryStoreOptions>(name, o => o.DefaultConnectionString = $"{name}_begin"); services.PostConfigure<InMemoryStoreOptions>(name, o => o.DefaultConnectionString += "end"); var sp = services.BuildServiceProvider(); Action<InMemoryStoreOptions, TenantInfo> tenantConfig = (o, _ti) => o.DefaultConnectionString += $"_{_ti.Id}_"; var factory = ActivatorUtilities. CreateInstance<MultiTenantOptionsFactory<InMemoryStoreOptions>>(sp, new [] { tenantConfig }); var options = factory.Create(name); Assert.Equal($"{name}_begin_{ti.Id}_end", options.DefaultConnectionString); } [Fact] public void IgnoreNullTenantInfo() { var tca = new TestMultiTenantContextAccessor(new MultiTenantContext()); var services = new ServiceCollection(); services.AddTransient<IMultiTenantContextAccessor>(_sp => tca); services.Configure<InMemoryStoreOptions>(o => o.DefaultConnectionString = "begin"); services.PostConfigure<InMemoryStoreOptions>(o => o.DefaultConnectionString += "end"); var sp = services.BuildServiceProvider(); Action<InMemoryStoreOptions, TenantInfo> tenantConfig = (o, _ti) => o.DefaultConnectionString += $"_{_ti.Id}_"; var factory = ActivatorUtilities. CreateInstance<MultiTenantOptionsFactory<InMemoryStoreOptions>>(sp, new [] { tenantConfig }); var options = factory.Create(""); Assert.Equal($"beginend", options.DefaultConnectionString); } [Fact] public void IgnoreNullMultiTenantContext() { var tca = new TestMultiTenantContextAccessor(null); var services = new ServiceCollection(); services.AddTransient<IMultiTenantContextAccessor>(_sp => tca); services.Configure<InMemoryStoreOptions>(o => o.DefaultConnectionString = "begin"); services.PostConfigure<InMemoryStoreOptions>(o => o.DefaultConnectionString += "end"); var sp = services.BuildServiceProvider(); Action<InMemoryStoreOptions, TenantInfo> tenantConfig = (o, _ti) => o.DefaultConnectionString += $"_{_ti.Id}_"; var factory = ActivatorUtilities. CreateInstance<MultiTenantOptionsFactory<InMemoryStoreOptions>>(sp, new [] { tenantConfig }); var options = factory.Create(""); Assert.Equal($"beginend", options.DefaultConnectionString); } }
42.272727
119
0.688978
[ "Apache-2.0" ]
GordonBlahut/Finbuckle.MultiTenant
test/Finbuckle.MultiTenant.Core.Test/Options/MultiTenantOptionsFactoryShould.cs
3,720
C#
using NUnit.Framework; using Rebus.Tests.Contracts.Activation; namespace Rebus.LightInject.Tests { [TestFixture] public class LightInjectRealContainerTests : RealContainerTests<LightInjectContainerAdapterFactory> { } }
21.545455
103
0.78481
[ "MIT" ]
lucasantarelli/rebus
Rebus.LightInject.Tests/LightInjectRealContainerTests.cs
239
C#
using System; namespace LCUSharp.Websocket { /// <summary> /// Handles operations relating to capturing and processing league events via WebSockets. /// </summary> public interface ILeagueEventHandler { /// <summary> /// EventHandler used for the Websocket's received messages. /// </summary> EventHandler<LeagueEvent> MessageReceived { get; set; } /// <summary> /// EventHandler used for the Websocket's error messages. /// </summary> EventHandler<string> ErrorReceived { get; set; } /// <summary> /// Connects to the WebSocket server. /// </summary> void Connect(); /// <summary> /// Disconnects from the WebSocket server. /// </summary> void Disconnect(); /// <summary> /// Initializes the web socket listener. /// </summary> /// <param name="port">The league client's port.</param> /// <param name="token">The user's Basic authentication token.</param> void ChangeSettings(int port, string token); /// <summary> /// Subscribes the event handler to the specified event uri. /// </summary> /// <param name="uri">The league client event uri.</param> /// <param name="eventHandler">The event handler.</param> void Subscribe(string uri, EventHandler<LeagueEvent> eventHandler); /// <summary> /// Unsubscribes the event handlers subscribed to the specified event uri. /// </summary> /// <param name="uri">The uri to unsubscribe from.</param> void Unsubscribe(string uri); /// <summary> /// Unsubcribes all event handlers. /// </summary> void UnsubscribeAll(); } }
31.982143
93
0.58124
[ "MIT" ]
MManoah/league-practice-tool
LCUSharp/Websocket/ILeagueEventHandler.cs
1,793
C#
namespace KeLi.HelloDapper.SQLite.Models { public class Student : IRecord { public string Email { get; set; } public string Address { get; set; } public int Id { get; set; } public string Name { get; set; } public string Remark { get; set; } } }
20.133333
43
0.569536
[ "MIT" ]
kelicto/HelloDapper
KeLi.HelloDapper.SQLite/Models/Student.cs
304
C#
using System; using System.Collections.Generic; using System.Text; namespace P03_FootballBetting.Data.Models { public class Town { public int TownId { get; set; } public string Name { get; set; } public int CountryId { get; set; } public Country Country { get; set; } public ICollection<Team> Teams { get; set; } public Town() { this.Teams = new HashSet<Team>(); } } }
18.56
52
0.573276
[ "MIT" ]
nelov87/MS-SQL-Databases-Advanced---Entity-Framework
05. Entity Relations/P03_FootballBetting/P03_FootballBetting/Data/Models/Town.cs
466
C#
//Problem 9. Frequent number //Write a program that finds the most frequent number in an array. //Example: //input result //4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 4 (5 times) using System; class FrequentNumber { static void Main() { Console.Write("Enter size of array: "); int n = int.Parse(Console.ReadLine()); Console.WriteLine("Enter {0} numbers: ", n); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); } Array.Sort(arr); int longestSeq = 1; int currentSeq = 1; int number = 0; for (int i = 0; i < arr.Length - 1; i++) { if (arr[i] == arr[i + 1]) { currentSeq++; if (currentSeq > longestSeq) { longestSeq = currentSeq; number = arr[i]; } } else { currentSeq = 1; } } Console.WriteLine("The most repetitive number is: {0}", number); } }
24.541667
76
0.42275
[ "MIT" ]
vtoshkova/Telerik-Academy-2015
C# - Part 2/01. ArraysHW/09. FrequentNumber/FrequentNumber.cs
1,180
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 appstream-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppStream.Model { /// <summary> /// Describes a connector that enables persistent storage for users. /// </summary> public partial class StorageConnector { private StorageConnectorType _connectorType; private List<string> _domains = new List<string>(); private string _resourceIdentifier; /// <summary> /// Gets and sets the property ConnectorType. /// <para> /// The type of storage connector. /// </para> /// </summary> [AWSProperty(Required=true)] public StorageConnectorType ConnectorType { get { return this._connectorType; } set { this._connectorType = value; } } // Check to see if ConnectorType property is set internal bool IsSetConnectorType() { return this._connectorType != null; } /// <summary> /// Gets and sets the property Domains. /// <para> /// The names of the domains for the account. /// </para> /// </summary> [AWSProperty(Max=50)] public List<string> Domains { get { return this._domains; } set { this._domains = value; } } // Check to see if Domains property is set internal bool IsSetDomains() { return this._domains != null && this._domains.Count > 0; } /// <summary> /// Gets and sets the property ResourceIdentifier. /// <para> /// The ARN of the storage connector. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string ResourceIdentifier { get { return this._resourceIdentifier; } set { this._resourceIdentifier = value; } } // Check to see if ResourceIdentifier property is set internal bool IsSetResourceIdentifier() { return this._resourceIdentifier != null; } } }
30.755102
108
0.586928
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AppStream/Generated/Model/StorageConnector.cs
3,014
C#
using System; using System.Diagnostics; using System.Linq; using Amazon.Lambda.Core; namespace ZoolWay.Aloxi.AlexaAdapter { public static class Log { private const string LV_ERROR = "ERROR"; private const string LV_INFO = " INFO"; private const string LV_WARN = " WARN"; private const string LV_DEBUG = "DEBUG"; private static string configuredLevel = InitConfiguredLogLevel(); public static void Error(ILambdaContext context, string message) { LambdaLog(context, LV_ERROR, message); TraceLog(LV_ERROR, message); } public static void Info(ILambdaContext context, string message) { LambdaLog(context, LV_INFO, message); TraceLog(LV_INFO, message); } public static void Warn(ILambdaContext context, string message) { LambdaLog(context, LV_WARN, message); TraceLog(LV_WARN, message); } public static void Debug(ILambdaContext context, string message) { LambdaLog(context, LV_DEBUG, message); TraceLog(LV_DEBUG, message); } public static bool IsDebugEnabled() { return LevelMatches(LV_DEBUG, LV_INFO, LV_WARN, LV_ERROR); } private static void LambdaLog(ILambdaContext context, string level, string message) { if ((level == "DEBUG") && (!LevelMatches("DEBUG", "INFO", "WARN", "ERROR"))) return; if ((level == "INFO") && (!LevelMatches("INFO", "WARN", "ERROR"))) return; if ((level == "WARN") && (!LevelMatches("WARN", "ERROR"))) return; if ((level == "ERROR") && (!LevelMatches("ERROR"))) return; if (String.IsNullOrWhiteSpace(context?.AwsRequestId)) { LambdaLogger.Log($"{level.ToUpper(),5} {message}\n"); } else { LambdaLogger.Log($"{level.ToUpper(),5} RequestId: {context.AwsRequestId} {message}\n"); } } [Conditional("TRACE")] private static void TraceLog(string level, string message) { Trace.WriteLine($"[{DateTime.Now.TimeOfDay.TotalSeconds:F1}][{level.ToUpper(),5}] {message}"); } private static string InitConfiguredLogLevel() { return Environment.GetEnvironmentVariable("LAMBDA_LOG") ?? "WARN"; } private static bool LevelMatches(params string[] acceptLevels) { return acceptLevels.Contains(configuredLevel); } } }
32.987342
106
0.579432
[ "MIT" ]
ZoolWay/Aloxi
Aloxi.AlexaAdapter/Log.cs
2,608
C#
// Copyright 2012 Max Toro Q. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; namespace MvcAccount { public static partial class AccountResources { static string GetResource(string resourceKey) { CultureInfo culture = CultureInfo.CurrentUICulture; return GetUserResourceString(resourceKey, culture) ?? Resources.AccountResources.ResourceManager.GetString(resourceKey, culture); } static string GetUserResourceString(string resourceKey, CultureInfo culture) { string classKey = AccountConfiguration.Current().ResourceClassKey; if (!classKey.HasValue()) { return null; } return HttpContext.GetGlobalResourceObject(classKey, resourceKey, culture) as string; } } }
31.931818
94
0.720996
[ "Apache-2.0" ]
maxtoroq/MvcAccount
src/MvcAccount/AccountResources.cs
1,407
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Windows.Forms; using System.IO; using System.Diagnostics; namespace SirJoshSpeedyComputer { public static class Updater { public static WebClient downloader = new WebClient() { Proxy = null }; public const string BaseURL = "http://www.sirjosh3917.com/apps/speedycomputer/"; public const string UpdateExe = "updatedSpeedyComputer.exe"; public static void FetchAvailability(string baseurl) { try { if (downloader.DownloadData(baseurl + "needdownload.php?id=" + (UpdateConfig.UpdateString))[0] == 97) { downloader.DownloadFile(baseurl + "exedownload.php?id=" + (UpdateConfig.UpdateString), UpdateExe); if (File.ReadAllText(UpdateExe) != "NUA") { MessageBox.Show("An update has been downloaded. To proceed, please close this box."); //start new cmd.exe process to delete the old and rename the new ProcessStartInfo Info = new ProcessStartInfo(); Info.Arguments = "/C choice /C Y /N /D Y /T 2 & Del \"" + System.AppDomain.CurrentDomain.FriendlyName + "\"& Rename " + UpdateExe + " SirJoshSpeedyComputer.exe & pause"; Info.WindowStyle = ProcessWindowStyle.Hidden; Info.CreateNoWindow = true; Info.FileName = "cmd.exe"; Process.Start(Info); Application.Exit(); } else { File.Delete(UpdateExe); } } else { MessageBox.Show("No updates available."); } } catch { //Just plain quit if any errors MessageBox.Show("Error occured while updating."); } } private static char[] _byte2char(byte[] l) { string chars = ""; foreach(var i in l) { chars += Convert.ToChar(i).ToString(); } return chars.ToCharArray(); } } }
34.339623
112
0.661538
[ "MIT" ]
SirJosh3917/SirJoshSpeedyComputer
SirJosh Speedy Computer/SirJosh Speedy Computer/Updater.cs
1,822
C#
using System; using System.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; // ReSharper disable HeapView.ObjectAllocation.Evident // TODO: migrate to xUnit namespace Nexusat.Utils.CalendarGenerator.Tests { [TestClass] public class CalendarTests { /// <summary> /// Gets or sets the test context which provides /// information about and functionality for the current test run. /// </summary> // ReSharper disable once UnusedAutoPropertyAccessor.Local // ReSharper disable once MemberCanBePrivate.Global public TestContext TestContext { get; set; } [TestMethod] public void EmptyCalendarTest() { var calendar = Calendar.EmptyCalendar; Assert.IsNotNull(calendar); Assert.AreSame(Calendar.EmptyCalendar, calendar, "Empty calendar is a singleton"); var xml = calendar.ToXml(); TestContext.WriteLine($"Calendar XML Definition:\n{xml}"); Assert.IsNull(calendar.GetDayInfo(DateTime.Now), "Empty calendar doesn't provide any info"); var defaultDayInfo = new DayInfo(); var days = calendar.GenerateCalendarDays( new DateTime(2020, 1, 1), new DateTime(2020, 12, 31), defaultDayInfo); Assert.AreEqual(366, days.Count); xml = days.ToXml(); Assert.IsNotNull(xml); TestContext.WriteLine($"\n\nCalendar Days:\n{xml}"); } [TestMethod] public void WeekdayTest() { // Setup var calendar = SetupFullCalendar(); TestFullCalendar(calendar); } private static void TestFullCalendar(ICalendar calendar) { var monday = DateTime.Parse("2020-11-02"); var tuesday = DateTime.Parse("2020-11-03"); var wednesday = DateTime.Parse("2020-11-04"); var thursday = DateTime.Parse("2020-11-05"); var friday = DateTime.Parse("2020-11-06"); var saturday = DateTime.Parse("2020-11-07"); var sunday = DateTime.Parse("2020-11-08"); // Exercise and Assert Assert.IsTrue(calendar.GetDayInfo(monday).IsWorkingDay); Assert.IsTrue(calendar.GetDayInfo(tuesday).IsWorkingDay); Assert.IsTrue(calendar.GetDayInfo(wednesday).IsWorkingDay); Assert.IsTrue(calendar.GetDayInfo(thursday).IsWorkingDay); Assert.IsTrue(calendar.GetDayInfo(friday).IsWorkingDay); Assert.IsFalse(calendar.GetDayInfo(saturday).IsWorkingDay); Assert.IsFalse(calendar.GetDayInfo(sunday).IsWorkingDay); } private static Calendar SetupFullCalendar() { var rules = new CalendarRules { {DayRulePolicy.Fallthrough, DayRuleParser.Parse("* * * * [[working day]] 08:30-17:30")}, {DayRulePolicy.Fallthrough, DayRuleParser.Parse("* * * 6..7 [[non working day]]")} }; return new Calendar("Five Working Days Calendar", rules, "calendar description", "this is a very long description"); } [TestMethod] public void XmlSerializationTest() { var calendar = SetupFullCalendar(); var xml = calendar.ToXml(); TestContext.WriteLine(xml); Assert.IsNotNull(xml); var calendar2 = CalendarSerializer.LoadFromXml(xml); TestFullCalendar(calendar2); } [TestMethod] public void JsonSerializationTest() { var calendar = SetupFullCalendar(); var json = calendar.ToJson(true); TestContext.WriteLine(json); Assert.IsNotNull(json); var calendar2 = CalendarSerializer.LoadFromJson(json); TestFullCalendar(calendar2); } [TestMethod] public void GenerateCalendarDaysTest() { var calendar = SetupFullCalendar(); var defaultDayInfo = new DayInfo("Default"); var calendarDays = calendar.GenerateCalendarDays(new DateTime(2020, 1, 1), new DateTime(2020, 12, 31), defaultDayInfo); Assert.IsNotNull(calendarDays); Assert.AreEqual(366, calendarDays.Count); } [TestMethod] public void CalendarDaysToXmlTest() { var calendar = SetupFullCalendar(); var defaultDayInfo = new DayInfo("info"); var calendarDays = calendar.GenerateCalendarDays(new DateTime(2020, 1, 1), new DateTime(2020, 12, 31), defaultDayInfo); var xmlSettings = new XmlWriterSettings {Indent = true}; var xml = calendarDays.ToXml(xmlSettings); Assert.IsNotNull(xml); TestContext.WriteLine(xml); } [TestMethod] public void CalendarDaysToJsonTest() { var calendar = SetupFullCalendar(); var defaultDayInfo = new DayInfo("info"); var calendarDays = calendar.GenerateCalendarDays(new DateTime(2020, 1, 1), new DateTime(2020, 12, 31), defaultDayInfo); var json = calendarDays.ToJson(true); Assert.IsNotNull(json); TestContext.WriteLine(json); } [TestMethod] public void CalendarAddRulesTest() { var calendar = SetupFullCalendar(); var calendar2 = SetupFullCalendar(); var ruleCount = calendar.CalendarRules.Count; calendar.AddRules(calendar2); Assert.AreEqual(ruleCount * 2, calendar.CalendarRules.Count); } } }
35.974843
116
0.592308
[ "MIT" ]
MrBogomips/Nexusat.Utils.CalendarGenerator
Nexusat.Utils.CalendarGenerator.Tests/CalendarTests.cs
5,720
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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseLocalFunction; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseLocalFunction { public partial class UseLocalFunctionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseLocalFunctionDiagnosticAnalyzer(), new CSharpUseLocalFunctionCodeFixProvider()); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingBeforeCSharp7() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenAfter() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; fibonacci = null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingIfWrittenInside() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { fibonacci = null; if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForErrorType() { await TestMissingAsync( @"class C { void M() { // Func can't be bound. Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForMultipleVariables() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }, fib2 = x => x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMissingForField() { await TestMissingAsync( @"using System; class C { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_AnonymousMethod() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_Block_ExtraParens() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = ((Func<int, int>)(v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); })); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_AnonymousMethod() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }); } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)(v => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = (Func<int, int>)((int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2)); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_WrongName() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fib = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_InitializedToOtherValue() { await TestMissingAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = GetCallback(); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_NoInitializer() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultLiteral() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default; fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }", // 7.1 is required for default literals, so 7.2 should be sufficient // and is used in other tests parseOptions: CSharp72ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_Block_DefaultExpression_var() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]fibonacci = default(Func<int, int>); fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_Block() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_AnonymousMethod() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = delegate (int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SimpleLambda_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = v => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaNoType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_ParenLambdaWithType_ExprBody() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = null; fibonacci = (int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }", @"using System; class C { void M() { static int fibonacci(int v) => v <= 1 ? 1 : fibonacci(v - 1, v - 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = v => { Func<bool, bool> isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll3() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> fibonacci = null; fibonacci = v => { Func<bool, bool> {|FixAllInDocument:isTrue|} = null; isTrue = b => b; return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { bool isTrue(bool b) => b; return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestFixAll4() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> {|FixAllInDocument:fibonacci|} = null; fibonacci = v => { Func<int, int> fibonacciHelper = null; fibonacciHelper = n => fibonacci.Invoke(n - 1) + fibonacci(arg: n - 2); return fibonacciHelper(v); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { int fibonacciHelper(int n) => fibonacci(n - 1) + fibonacci(v: n - 2); return fibonacciHelper(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestTrivia() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { // Leading trivia Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; // Trailing trivia } }", @"using System; class C { void M() { // Leading trivia static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } // Trailing trivia } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestInWithParameters() { await TestInRegularAndScriptAsync( @" delegate void D(in int p); class C { void M() { D [||]lambda = (in int p) => throw null; } }", @" delegate void D(in int p); class C { void M() { void lambda(in int p) => throw null; } }", // Run with 7.2 to get read-only references parseOptions: CSharp72ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestRefReadOnlyWithReturnType() { await TestInRegularAndScriptAsync( @" delegate ref readonly int D(); class C { void M() { D [||]lambda = () => throw null; } }", @" delegate ref readonly int D(); class C { void M() { static ref readonly int lambda() => throw null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestMissingIfConvertedToNonDelegate() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(object expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToDelegate() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { Func<string, Task> [||]f = x => { return Task.CompletedTask; }; Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }", @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { static Task f(string x) { return Task.CompletedTask; } Func<string, Task> actual = null; AssertSame(f, actual); } public static void AssertSame(Func<string, Task> expected, object actual) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Delegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestNotAvailableIfConvertedToSystemMulticastDelegate() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(MulticastDelegate expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate0() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<object, string> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<object, string> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate1() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate2() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<string, string> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static string f(string x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23118, "https://github.com/dotnet/roslyn/issues/23118")] public async Task TestAvailableIfConvertedToCoContraVariantDelegate3() { await TestInRegularAndScript1Async( @"using System; class Program { static void Main(string[] args) { Func<object, object> [||]f = x => """"; M(f); } public static void M(Func<string, object> expected) { } }", @"using System; class Program { static void Main(string[] args) { static object f(object x) => """"; M(f); } public static void M(Func<string, object> expected) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfAdded() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var doubleDelegate = local + local; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInMemberAccess1() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; var str = local.ToString(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestMissingIfUsedInMemberAccess2() { await TestMissingAsync( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate[||]local = x => x; Console.Write(local.Invoke(t)); var str = local.ToString(); local.Invoke(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(22672, "https://github.com/dotnet/roslyn/issues/22672")] public async Task TestMissingIfUsedInExpressionTree() { await TestMissingAsync( @"using System; using System.Linq.Expressions; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; Expression<Action> expression = () => local(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24344, "https://github.com/dotnet/roslyn/issues/24344")] public async Task TestMissingIfUsedInExpressionTree2() { await TestMissingAsync( @"using System; using System.Linq.Expressions; public class C { void Method(Action action) { } Expression<Action> Example() { Action [||]action = () => Method(null); return () => Method(action); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { MyDelegate [||]local = x => x; local.Invoke(); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller() { static T local(T x = null) => x; local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod3() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local.Invoke(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23150, "https://github.com/dotnet/roslyn/issues/23150")] public async Task TestWithInvokeMethod4() { await TestInRegularAndScript1Async( @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { MyDelegate [||]local = x => x; Console.Write(local.Invoke(t)); var val = local.Invoke(t); local(t); } } }", @"using System; class Enclosing<T> where T : class { delegate T MyDelegate(T t = null); public class Class { public void Caller(T t) { static T local(T x = null) => x; Console.Write(local(t)); var val = local(t); local(t); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => local.Invoke(); } }", @"using System; class C { void M() { static void local() => local(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364807853")] public async Task TestWithRecursiveInvokeMethod2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]local = null; local = () => { local.Invoke(); } } }", @"using System; class C { void M() { static void local() { local(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364935495")] public async Task TestWithNestedInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = s => s; a.Invoke(a.Invoke(null)); } }", @"using System; class C { void M() { static string a(string s) => s; a(a(null)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNestedRecursiveInvokeMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string, string> [||]a = null; a = s => a.Invoke(a.Invoke(s)); } }", @"using System; class C { void M() { static string a(string s) => a(a(s)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter1() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364655480")] public async Task TestWithDefaultParameter2() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = (string s) => s; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") => s; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDefaultParameter3() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { MyDelegate [||]local = delegate (string s) { return s; }; } }", @"class C { delegate string MyDelegate(string arg = ""hello""); void M() { static string local(string s = ""hello"") { return s; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24760, "https://github.com/dotnet/roslyn/issues/24760#issuecomment-364764542")] public async Task TestWithUnmatchingParameterList1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (a, b) => { }; } }", @"using System; class C { void M() { static void x(object a, object b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithUnmatchingParameterList2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action [||]x = (string a, int b) => { }; } }", @"using System; class C { void M() { static void x(string a, int b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task<int>> [||]f = async delegate () { return 0; }; } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task<int> f() { return 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithParameterlessAnonymousMethod() { await TestInRegularAndScript1Async( @"using System; class C { void M() { EventHandler [||]handler = delegate { }; E += handler; } event EventHandler E; }", @"using System; class C { void M() { static void handler(object sender, EventArgs e) { } E += handler; } event EventHandler E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { }; x(arg1: null, 0, 0); x.Invoke(arg1: null, 0, 0); } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { } x(a1: null, 0, 0); x(a1: null, 0, 0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(24764, "https://github.com/dotnet/roslyn/issues/24764")] public async Task TestWithNamedArguments2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2, a3) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); }; } }", @"using System; class C { void M() { static void x(string a1, int a2, int a3) { x(null, a3: 0, a2: 0); x(null, a3: 0, a2: 0); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (int a1, string a2, string a3, a4) => { }; x(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(null, arg3: 0, arg2: 0, arg4: 0); x.Invoke(0, null, null, null, null, null); } }", @"using System; class C { void M() { static void x(int a1, string a2, string a3, object a4) { } x(null, a3: 0, a2: 0, arg4: 0); x(null, a3: 0, a2: 0, arg4: 0); x(0, null, null, null, null, null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedArgumentsAndBrokenCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Action<string, int, int> [||]x = (a1, a2) => { x(null, arg3: 0, arg2: 0); x.Invoke(null, arg3: 0, arg2: 0); x.Invoke(); }; } }", @"using System; class C { void M() { static void x(string a1, int a2) { x(null, arg3: 0, a2: 0); x(null, arg3: 0, a2: 0); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArguments() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { MyDelegate [||]x = null; x = (a1, a2, a3) => { x(null, arg3: 42); return x.Invoke(null, arg3: 42); }; } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { static string x(string a1, int a2 = 2, int a3 = 3) { x(null, a3: 42); return x(null, a3: 42); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNamedAndDefaultArgumentsAndNestedRecursiveInvocations_FixAll() { await TestInRegularAndScript1Async( @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { var x = (MyDelegate)delegate { MyDelegate {|FixAllInDocument:a|} = null; a = (string a1, int a2, int a3) => { MyDelegate b = null; b = (b1, b2, b3) => b.Invoke(arg1: b(null), arg2: a(arg1: a.Invoke(null)).Length, arg3: 42) + b(arg1: b.Invoke(null), arg3: a(arg1: a.Invoke(null)).Length, arg2: 42); return b(arg1: a1, b(arg1: a1).Length); }; return a(arg1: null); }; x(arg1: null); } }", @"class C { delegate string MyDelegate(string arg1, int arg2 = 2, int arg3 = 3); void M() { string x(string arg1, int arg2 = 2, int arg3 = 3) { string a(string a1, int a2 = 2, int a3 = 3) { string b(string b1, int b2 = 2, int b3 = 3) => b(b1: b(null), b2: a(a1: a(null)).Length, b3: 42) + b(b1: b(null), b3: a(a1: a(null)).Length, b2: 42); return b(b1: a1, b(b1: a1).Length); } return a(a1: null); } x(arg1: null); } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiToken() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { Func<int, int[]> [||]onUpdateSolutionCancel = a => { return null; }; } }", @"using System; class C { void Goo() { static int[] onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine2MultiTokenAsync() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void Goo() { Func<int, Task<int[]>> [||]onUpdateSolutionCancel = async a => { return null; }; } }", @"using System; using System.Threading.Tasks; class C { void Goo() { static async Task<int[]> onUpdateSolutionCancel(int a) { return null; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine3() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSimpleInitialization_SingleLine4Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action)(() => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine2Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async a => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine3() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)((int a) => { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestCastInitialization_SingleLine4Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; var [||]onUpdateSolutionCancel = (Action<int>)(async delegate (int a) { buildCancelled = true; }); } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine1() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = () => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel() { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine2Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async a => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine3() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = (int a) => { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [WorkItem(23872, "https://github.com/dotnet/roslyn/issues/23872")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestSplitInitialization_SingleLine4Async() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var buildCancelled = false; Action<int> [||]onUpdateSolutionCancel = null; onUpdateSolutionCancel = async delegate (int a) { buildCancelled = true; }; } }", @"using System; class C { void Goo() { var buildCancelled = false; async void onUpdateSolutionCancel(int a) { buildCancelled = true; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged1() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Class<T> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged2() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged3() { await TestMissingAsync( @"public class Class<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public void Caller() { void Some<T>(T t) { MyDelegate [||]local = x => x; Callee(local); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestNotAvailableIfTypeParameterChanged4() { await TestMissingAsync( @"using System; class Enclosing<T> { delegate T MyDelegate(T t); static void Callee(MyDelegate d) => d(default); public class Goo<T> { public class Class<U> { public void Caller() { MyDelegate [||]local = x => x; Callee(local); } } } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/27950"), Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged1() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<T> : DelegateEnclosing<T> { static void Callee(MyDelegate d) => d(default); public void Caller() { static T local(T x) => x; Callee(local); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] [WorkItem(23149, "https://github.com/dotnet/roslyn/issues/23149")] public async Task TestAvailableIfTypeParameterNotChanged2() { await TestInRegularAndScript1Async( @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { MyDelegate [||]local = x => x; Callee(local); } }", @"using System; class DelegateEnclosing<T> { protected delegate T MyDelegate(T t); } class Enclosing<U> : DelegateEnclosing<U> { static void Callee(MyDelegate d) => d(default); public void Caller() { static U local(U x) => x; Callee(local); } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedIfAssignedToVar() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<string> [||]f = () => null; var f2 = f; } }", @"using System; class C { void M() { static string f() => null; var f2 = (Func<string>)f; } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference1() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(26526, "https://github.com/dotnet/roslyn/issues/26526")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForGenericTypeInference2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } void Method(string o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithCastIntroducedForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(); class C { void M() { static string f() => null; Method((Func<string>)f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestAvailableWithoutCastIfUnnecessaryForOverloadResolution() { await TestInRegularAndScript1Async( @"using System; delegate string CustomDelegate(object arg); class C { void M() { Func<string> [||]f = () => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }", @"using System; delegate string CustomDelegate(object arg); class C { void M() { static string f() => null; Method(f); } void Method(Func<string> o) { } void Method(CustomDelegate o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f = () => null); Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration2() { await TestMissingAsync( @"using System; class C { void M() { Func<string> [||]f) = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestNotAvailableWithInvalidDeclaration3() { await TestMissingAsync( @"using System; class C { void M() { Func<string>) [||]f = () => null; Method(f); } void Method(Func<string> o) { } } "); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o)) { } }", @"using System; class C { void M() { static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o)) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithInvalidUnrelatedCode2() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => null; (Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { static string f(int _) => null; (Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithObsoleteCode() { await TestInRegularAndScript1Async( @"using System; class C { void M() { Func<int, string> [||]f = _ => S(); Method(f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { string f(int _) => S(); Method((Func<int, string>)f); } [System.Obsolete] string S() { return null; } void Method<T>(Func<T, string> o) { } }"); } [WorkItem(29793, "https://github.com/dotnet/roslyn/issues/29793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithDeclarationWarning() { await TestInRegularAndScript1Async( @"using System; class C { void M() { #warning Declaration Warning Func<int, string> [||]f = _ => null; Method(f); } void Method<T>(Func<T, string> o) { } }", @"using System; class C { void M() { #warning Declaration Warning static string f(int _) => null; Method((Func<int, string>)f); } void Method<T>(Func<T, string> o) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestMakeStaticIfNoCaptures() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { static int fibonacci(int v) { if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestDoNotMakeStaticIfCaptures() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { Func<int, int> [||]fibonacci = v => { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); }; } }", @"using System; class C { void M() { int fibonacci(int v) { M(); if (v <= 1) { return 1; } return fibonacci(v - 1, v - 2); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithAsyncLambdaExpression_MakeStatic() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { Func<Task> [||]f = async () => await Task.Yield(); } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task f() => await Task.Yield(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseLocalFunction)] public async Task TestWithNullableParameterAndReturn() { await TestInRegularAndScriptAsync( @"#nullable enable using System; class Program { static void Main(string[] args) { Func<string?, string?> [||]f = s => s; } }", @"#nullable enable using System; class Program { static void Main(string[] args) { static string? f(string? s) => s; } }"); } } }
20.93662
161
0.537789
[ "Apache-2.0" ]
20chan/roslyn
src/EditorFeatures/CSharpTest/UseLocalFunction/UseLocalFunctionTests.cs
77,300
C#
using RabbitMQ.Domain.Common.Commands.Inputs; using RabbitMQ.Domain.Core.QueueLogs.Queries.Results; using RabbitMQ.Domain.Emails.Enums; using System; using System.Collections.Generic; namespace RabbitMQ.Domain.Emails.Commands.Inputs { public class EmailCommand : NotificationCommand { public override byte NumberAttempts { get; set; } public override Guid PaymentId { get; set; } public EEmailTemplate EmailTemplate { get; set; } public List<QueueLogQueryResult> QueueLogs { get; set; } public EmailCommand(Guid paymentId, EEmailTemplate emailTemplate, List<QueueLogQueryResult> queueLogs = null) { NumberAttempts = 1; PaymentId = paymentId; EmailTemplate = emailTemplate; QueueLogs = queueLogs ?? new List<QueueLogQueryResult>(); } public override void AddNumberAttempt() => NumberAttempts++; } }
35.576923
117
0.690811
[ "MIT" ]
lsantoss/RabbitMQ
RabbitMQ/RabbitMQ.Domain/Emails/Commands/Inputs/EmailCommand.cs
927
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; namespace Azure.ResourceManager.AppPlatform.Models { /// <summary> The settings of Application Configuration Service. </summary> public partial class ConfigurationServiceSettings { /// <summary> Initializes a new instance of ConfigurationServiceSettings. </summary> public ConfigurationServiceSettings() { } /// <summary> Initializes a new instance of ConfigurationServiceSettings. </summary> /// <param name="gitProperty"> Property of git environment. </param> internal ConfigurationServiceSettings(ConfigurationServiceGitProperty gitProperty) { GitProperty = gitProperty; } /// <summary> Property of git environment. </summary> internal ConfigurationServiceGitProperty GitProperty { get; set; } /// <summary> Repositories of Application Configuration Service git property. </summary> public IList<ConfigurationServiceGitRepository> GitPropertyRepositories { get { if (GitProperty is null) GitProperty = new ConfigurationServiceGitProperty(); return GitProperty.Repositories; } } } }
34.04878
96
0.661891
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/appplatform/Azure.ResourceManager.AppPlatform/src/Generated/Models/ConfigurationServiceSettings.cs
1,396
C#
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. using System; using CoreWf; using CoreWf.Hosting; using CoreWf.Tracking; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Xml.Linq; using Test.Common.TestObjects.Activities; using Test.Common.TestObjects.Runtime; using Test.Common.TestObjects.Utilities; using Test.Common.TestObjects.Utilities.Validation; namespace TestCases.Runtime.Common { public static class RuntimeHelper { private static readonly TimeSpan s_DEFAULT_TIMEOUT = TimeSpan.FromMinutes(1.0); public static void InvokeActivity(Activity activity) { //Can we get default timeout used by product? InvokeActivity(activity, s_DEFAULT_TIMEOUT); } public static void InvokeActivity(Activity activity, TimeSpan timeout) { //Log.Info("Using ActivityInvoke()"); WorkflowInvoker.Invoke(activity, timeout); } public static void InvokeActivity(Activity activity, SymbolResolver symbolResolver) { InvokeActivity(activity, symbolResolver, s_DEFAULT_TIMEOUT); } public static IDictionary<string, object> InvokeActivity(Activity activity, IDictionary<string, object> dictionary) { return InvokeActivity(activity, dictionary, s_DEFAULT_TIMEOUT); } public static IDictionary<string, object> InvokeActivity(Activity activity, IDictionary<string, object> dictionary, TimeSpan timeout) { return WorkflowInvoker.Invoke(activity, dictionary, timeout); } public static WorkflowApplication CreateWorkflow(Activity activity, Dictionary<string, object> inputs, params object[] extensions) { WorkflowApplication instance = new WorkflowApplication(activity, inputs); if (extensions != null) { for (int i = 0; i < extensions.Length; i++) { instance.Extensions.Add(extensions[i]); } } return instance; } public static WorkflowApplication CreateWorkflowApplication(Activity activity, AutoResetEvent completedOrAbortedEvent) { WorkflowApplication instance = new WorkflowApplication(activity) { Completed = (arg) => { completedOrAbortedEvent.Set(); }, Aborted = (arg) => { completedOrAbortedEvent.Set(); } }; return instance; } public static IDictionary<string, object> RunWorkflow(WorkflowApplication instance) { ManualResetEvent mre = new ManualResetEvent(false); Exception workflowException = null; IDictionary<string, object> outputs = null; instance.Completed = delegate (WorkflowApplicationCompletedEventArgs e) { if (e.TerminationException != null) { workflowException = e.TerminationException; } outputs = e.Outputs; mre.Set(); }; instance.Run(); mre.WaitOne(); if (workflowException != null) { throw workflowException; } return outputs; } public static IDictionary<string, object> ExecuteWorkflow(Activity activity) { return (RunWorkflow(CreateWorkflow(activity, null))); } public static void RunInAllOptions(Activity activity) { InvokeActivity(activity); ExecuteWorkflow(activity); } public static void HandleException(Exception e) { Console.WriteLine(e); //Log.Info(e); } public static void ValidateWorkflow(Guid workflowInstanceId, TestActivity testWorkflowDefinition) { ActualTrace actualTrace = TestTraceManager.Instance.GetInstanceActualTrace(workflowInstanceId); ExpectedTrace expectedTrace = testWorkflowDefinition.GetExpectedTrace(); actualTrace.Validate(testWorkflowDefinition.GetExpectedTrace()); } //public static void AddAPersistenceProvider(WorkflowApplication instance, Type persistenceProviderFactoryType) //{ // PersistenceProviderHelper helper = new PersistenceProviderHelper(persistenceProviderFactoryType); // instance.InstanceStore = helper.CreateWorkflowInstanceStore(); //} //public static void AddTrackingProvider(WorkflowApplication instance) //{ // TestTrackingDataManager.GetInstance(instance.Id).InstantiateTrackingParticipants(TestConfiguration.Current.TrackingServiceConfigurations); // foreach (TrackingParticipant trackingParticipant in TestTrackingDataManager.GetInstance(instance.Id).GetTrackingParticipants()) // { // instance.Extensions.Add(trackingParticipant); // } //} //public static PersistenceProvider GetPersistenceProvider(Type persistenceProviderFactoryType, Guid instanceId) //{ // PersistenceProviderHelper persistenceProviderHelper = new PersistenceProviderHelper(persistenceProviderFactoryType); // PersistenceProviderFactory persistenceProviderFactory = persistenceProviderHelper.CreateInstancePersistenceProviderFactory(true, true); // return persistenceProviderFactory.CreateProvider(instanceId); //} //This method is used to create a dummy parameter instance public static object GetAParameterInstance(ParameterInfo paraInfo) { //For those types that without a default constructor if (paraInfo.ParameterType == typeof(Bookmark)) { return new Bookmark("Read1"); } if (paraInfo.ParameterType == typeof(BookmarkScope)) { return new BookmarkScope(Guid.NewGuid()); } if (paraInfo.ParameterType == typeof(AsyncCallback)) { return null; } if (paraInfo.ParameterType == typeof(WorkflowInstanceRecord)) { return new WorkflowInstanceRecord(Guid.NewGuid(), "Dummy", "Dummy"); } if (paraInfo.ParameterType == typeof(WorkflowApplicationInstance)) { return GetADummyWorkflowApplicationInstance(); } if (paraInfo.ParameterType == typeof(string)) { return "temp"; } if (paraInfo.ParameterType == typeof(TimeSpan)) { return new TimeSpan(0, 0, 5); } if (paraInfo.ParameterType == typeof(IAsyncResult)) { return new CompletedAsyncResult(null, null); } //if (paraInfo.ParameterType == typeof(InstanceStore)) //{ // return new SqlWorkflowInstanceStore(); //} //if (paraInfo.ParameterType == typeof(DynamicUpdateMap)) //{ // return GetADummyDynamicUpdateMap(); //} if (paraInfo.ParameterType == typeof(IDictionary<XName, object>)) { return new Dictionary<XName, object>(); } if (paraInfo.IsOut) { return null; } //Use the default constructor return Activator.CreateInstance(paraInfo.ParameterType); } public static void MakeAGenericMethod(ref MethodInfo methodInfo) { if (methodInfo.ContainsGenericParameters) { Type[] argumentType = methodInfo.GetGenericArguments(); for (int i = 0; i < argumentType.Length; i++) { argumentType[i] = typeof(System.Object); } methodInfo = methodInfo.MakeGenericMethod(argumentType); } } public static void CallAndValidateAllMethods(object objectToCall, Type exceptionType, List<string> methodsToExclude = null, string exceptionMessage = "") { Type typeToGetMethod = objectToCall.GetType(); MethodInfo[] methodInfos = typeToGetMethod.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); bool failed = false; foreach (MethodInfo methodInfo in methodInfos) { //Exclude properties if (!methodInfo.Name.StartsWith("get_") && !methodInfo.Name.StartsWith("set_")) { if (methodsToExclude == null || !IsInMethods(methodInfo.Name, methodsToExclude)) { InvokeAndVerifyAMethod(objectToCall, exceptionType, exceptionMessage, typeToGetMethod, ref failed, methodInfo); } } } if (failed == true) { throw new Exception("At least one method invoke validation failed, see the trace for the details"); } } public static void CallAndValidateMethods(object objectToCall, Type exceptionType, List<string> methodsToInclude, string exceptionMessage = "") { Type typeToGetMethod = objectToCall.GetType(); MethodInfo[] methodInfos = typeToGetMethod.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); bool failed = false; foreach (MethodInfo methodInfo in methodInfos) { //Exclude properties if (!methodInfo.Name.StartsWith("get_") && !methodInfo.Name.StartsWith("set_")) { if (IsInMethods(methodInfo.Name, methodsToInclude)) { InvokeAndVerifyAMethod(objectToCall, exceptionType, exceptionMessage, typeToGetMethod, ref failed, methodInfo); } } } if (failed == true) { throw new Exception("At least one method invoke validation failed, see the trace for the details"); } } public static bool IsInMethods(string name, List<string> methods) { if (methods == null) { return false; } foreach (string method in methods) { //We need an exact match for non Async End method if (name.Equals(method)) { return true; } else if (name.StartsWith(method) && method.Equals("End")) { return true; } } return false; } private static void InvokeAndVerifyAMethod(object objectToCall, Type expectedExceptionType, string expectedExceptionMessage, Type typeToCall, ref bool failed, MethodInfo methodInfo) { failed = false; MakeAGenericMethod(ref methodInfo); object[] methodParameters = null; ParameterInfo[] paraInfos = methodInfo.GetParameters(); if (paraInfos.Length != 0) { methodParameters = new object[paraInfos.Length]; for (int i = 0; i < paraInfos.Length; i++) { methodParameters[i] = RuntimeHelper.GetAParameterInstance(paraInfos[i]); } } try { methodInfo.Invoke(objectToCall, methodParameters); } catch (TargetInvocationException exception) { if (exception.InnerException.GetType() != expectedExceptionType) { failed = true; } else if (expectedExceptionMessage != string.Empty && exception.InnerException.Message.CompareTo(expectedExceptionMessage) != 0) { failed = true; } return; } catch (Exception) { failed = true; return; } } public static void ValidateActivityTree(IEnumerable<Activity> expectedActivities, IEnumerable<Activity> actualActivities) { List<Activity> internalExpectedActivities = new List<Activity>(); List<Activity> internalActualActivities = new List<Activity>(); internalExpectedActivities.AddRange(expectedActivities); internalActualActivities.AddRange(actualActivities); internalExpectedActivities.Sort((Activity x, Activity y) => x.DisplayName.CompareTo(y.DisplayName)); internalActualActivities.Sort((Activity x, Activity y) => x.DisplayName.CompareTo(y.DisplayName)); StringBuilder sbExpectedActivities = new StringBuilder(); StringBuilder sbActualActivities = new StringBuilder(); string strExpectedActivities; string strActualActivities; foreach (Activity activity in internalExpectedActivities) { sbExpectedActivities.AppendLine(activity.DisplayName); } strExpectedActivities = sbExpectedActivities.ToString(); foreach (Activity activity in internalActualActivities) { sbActualActivities.AppendLine(activity.DisplayName); } strActualActivities = sbActualActivities.ToString(); if (!strExpectedActivities.Equals(strActualActivities)) { throw new Exception("Expected and Actual Activities are not the same"); } } private static WorkflowApplicationInstance GetADummyWorkflowApplicationInstance() { WorkflowIdentity wfIdentity = new WorkflowIdentity("GetAWorkflowApplicationInstanceParameter", new Version(1, 0), null); TestSequence wfDefinition = new TestSequence() { Activities = { new TestWriteLine("testWriteLine1", "In TestWriteLine1"), new TestReadLine<string>("ReadLine1", "testReadLine1"), new TestWriteLine("testWriteLine2", "In TestWriteLine2") }, }; WorkflowApplicationInstance waInstance; JsonFileInstanceStore.FileInstanceStore jsonStore = new JsonFileInstanceStore.FileInstanceStore(".\\~"); using (TestWorkflowRuntime workflowRuntime = TestRuntime.CreateTestWorkflowRuntime(wfDefinition, null, jsonStore, PersistableIdleAction.Unload)) { //PersistenceProviderHelper pphelper = new PersistenceProviderHelper(workflowRuntime.PersistenceProviderFactoryType); //InstanceStore store = pphelper.CreateWorkflowInstanceStore(); workflowRuntime.ExecuteWorkflow(); workflowRuntime.WaitForIdle(); workflowRuntime.UnloadWorkflow(); workflowRuntime.WaitForUnloaded(); Guid worklfowInstanceId = workflowRuntime.CurrentWorkflowInstanceId; waInstance = WorkflowApplication.GetInstance(worklfowInstanceId, jsonStore); waInstance.Abandon(); } return waInstance; } } }
37.927885
189
0.588921
[ "MIT" ]
OIgnat/corewf
src/test/TestCases.Runtime/Common/RuntimeHelper.cs
15,778
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_14.Boat_Simulator { class BoatSimulator { static void Main(string[] args) { char firstBoat = Console.ReadLine().FirstOrDefault(); char secondBoat = Console.ReadLine().FirstOrDefault(); int numberOfMoves = int.Parse(Console.ReadLine()); int goal = 50; long firstBoatProgress = 0; long secondBoatProgress = 0; for (int i = 0; i < numberOfMoves; i++) { string currentLine = Console.ReadLine(); if (currentLine == "UPGRADE") { firstBoat = (char)(firstBoat + 3); secondBoat = (char)(secondBoat + 3); continue; } if (i % 2 == 0) //first boat { firstBoatProgress += currentLine.Length + 1; if (firstBoatProgress > goal) { Console.WriteLine(firstBoat); return; } } else { secondBoatProgress += currentLine.Length + 1; if (secondBoatProgress > goal) { Console.WriteLine(secondBoat); return; } } } if (firstBoatProgress > secondBoatProgress) { Console.WriteLine(firstBoat); } else { Console.WriteLine(secondBoat); } } } }
26.985075
66
0.439159
[ "MIT" ]
Supbads/Softuni-Education
07 ProgrammingFundamentals 05.17/05. Data-Types-and-Variables-More-Exercises/Problem_14. Boat Simulator/BoatSimulator.cs
1,810
C#
using RimDev.AspNetCore.FeatureFlags; namespace appFeatureFlags.Models { public class ShowBoxHome : Feature { public override string Description { get; } = "Show the home center box."; } }
23.222222
82
0.698565
[ "MIT" ]
MonicaGantali/Learning_DevOps
CHAP13/appFeatureFlags/Models/FeaturesFlags.cs
209
C#
/* This file is a part of JustLogic product which is distributed under the BSD 3-clause "New" or "Revised" License Copyright (c) 2015. All rights reserved. Authors: Vladyslav Taranov. 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 JustLogic 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. */ using JustLogic.Core; using System.Collections.Generic; using UnityEngine; [UnitMenu("WWW/Get Url")] [UnitFriendlyName("WWW.Get Url")] [UnitUsage(typeof(System.String), HideExpressionInActionsList = true)] public class JLWwwGetUrl : JLExpression { [Parameter(ExpressionType = typeof(WWW))] public JLExpression OperandValue; public override object GetAnyResult(IExecutionContext context) { WWW opValue = OperandValue.GetResult<WWW>(context); return opValue.url; } }
39.907407
79
0.77587
[ "BSD-3-Clause" ]
AqlaSolutions/JustLogic
Assets/JustLogicUnits/Generated/WWW/JLWwwGetUrl.cs
2,155
C#
using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Formats; using NuKeeper.Abstractions.Logging; using NuKeeper.Abstractions.RepositoryInspection; using System; using System.Collections.Generic; using System.Linq; namespace NuKeeper.Update.Selection { public class UpdateSelection : IUpdateSelection { private readonly INuKeeperLogger _logger; private FilterSettings _settings; private DateTime? _maxPublishedDate; public UpdateSelection(INuKeeperLogger logger) { _logger = logger; } public IReadOnlyCollection<PackageUpdateSet> Filter( IReadOnlyCollection<PackageUpdateSet> candidates, FilterSettings settings) { _settings = settings ?? throw new ArgumentNullException(nameof(settings)); if (candidates == null) { throw new ArgumentNullException(nameof(candidates)); } if (settings.MinimumAge != TimeSpan.Zero) { _maxPublishedDate = DateTime.UtcNow.Subtract(settings.MinimumAge); } var filtered = ApplyFilters(candidates); var capped = filtered .Take(settings.MaxPackageUpdates) .ToList(); LogPackageCounts(candidates.Count, filtered.Count, capped.Count); return capped; } private IReadOnlyCollection<PackageUpdateSet> ApplyFilters( IReadOnlyCollection<PackageUpdateSet> all) { var filtered = all .Where(MatchesMinAge) .ToList(); if (filtered.Count < all.Count) { var agoFormat = TimeSpanFormat.Ago(_settings.MinimumAge); _logger.Normal($"Filtered by minimum package age '{agoFormat}' from {all.Count} to {filtered.Count}"); } return filtered; } private void LogPackageCounts(int candidates, int filtered, int capped) { var message = $"Selection of package updates: {candidates} candidates"; if (filtered < candidates) { message += $", filtered to {filtered}"; } if (capped < filtered) { message += $", capped at {capped}"; } _logger.Minimal(message); } private bool MatchesMinAge(PackageUpdateSet packageUpdateSet) { if (!_maxPublishedDate.HasValue) { return true; } var published = packageUpdateSet.Selected.Published; if (!published.HasValue) { return true; } return published.Value.UtcDateTime <= _maxPublishedDate.Value; } } }
29.091837
118
0.573483
[ "Apache-2.0" ]
CrispyDrone/NuKeeper
NuKeeper.Update/Selection/UpdateSelection.cs
2,851
C#
using Reddit_Wallpaper_Changer.Model; using System; using System.Threading.Tasks; namespace Reddit_Wallpaper_Changer.Wallpaper { public interface IImageInfoProvider { Task<ImageInfo> GetImageInfoAsync(string searchUrl, int wallpaperGrabType, IProgress<string> progress); } }
24.75
111
0.784512
[ "MIT" ]
Rawns/RWC-Source
Reddit Wallpaper Changer/Wallpaper/IImageInfoProvider.cs
299
C#
using CommandLine; using GVFS.Common; using GVFS.Common.FileSystem; using GVFS.Common.Git; using GVFS.Common.Http; using GVFS.Common.NamedPipes; using GVFS.Common.Tracing; using System; using System.IO; using System.Linq; using System.Text; namespace GVFS.CommandLine { [Verb(CloneVerb.CloneVerbName, HelpText = "Clone a git repo and mount it as a GVFS virtual repo")] public class CloneVerb : GVFSVerb { private const string CloneVerbName = "clone"; [Value( 0, Required = true, MetaName = "Repository URL", HelpText = "The url of the repo")] public string RepositoryURL { get; set; } [Value( 1, Required = false, Default = "", MetaName = "Enlistment Root Path", HelpText = "Full or relative path to the GVFS enlistment root")] public override string EnlistmentRootPathParameter { get; set; } [Option( "cache-server-url", Required = false, Default = null, HelpText = "The url or friendly name of the cache server")] public string CacheServerUrl { get; set; } [Option( 'b', "branch", Required = false, HelpText = "Branch to checkout after clone")] public string Branch { get; set; } [Option( "single-branch", Required = false, Default = false, HelpText = "Use this option to only download metadata for the branch that will be checked out")] public bool SingleBranch { get; set; } [Option( "no-mount", Required = false, Default = false, HelpText = "Use this option to only clone, but not mount the repo")] public bool NoMount { get; set; } [Option( "no-prefetch", Required = false, Default = false, HelpText = "Use this option to not prefetch commits after clone")] public bool NoPrefetch { get; set; } [Option( "local-cache-path", Required = false, HelpText = "Use this option to override the path for the local GVFS cache. The default location is the .gvfsCache folder in the root of the volume.")] public string LocalCacheRoot { get; set; } protected override string VerbName { get { return CloneVerbName; } } public override void Execute() { int exitCode = 0; this.ValidatePathParameter(this.EnlistmentRootPathParameter); this.ValidatePathParameter(this.LocalCacheRoot); string fullEnlistmentRootPathParameter; string normalizedEnlistmentRootPath = this.GetCloneRoot(out fullEnlistmentRootPathParameter); if (!string.IsNullOrWhiteSpace(this.LocalCacheRoot)) { string fullLocalCacheRootPath = Path.GetFullPath(this.LocalCacheRoot); string errorMessage; string normalizedLocalCacheRootPath; if (!GVFSPlatform.Instance.FileSystem.TryGetNormalizedPath(fullLocalCacheRootPath, out normalizedLocalCacheRootPath, out errorMessage)) { this.ReportErrorAndExit($"Failed to determine normalized path for '--local-cache-path' path {fullLocalCacheRootPath}: {errorMessage}"); } if (normalizedLocalCacheRootPath.StartsWith( Path.Combine(normalizedEnlistmentRootPath, GVFSConstants.WorkingDirectoryRootName), StringComparison.OrdinalIgnoreCase)) { this.ReportErrorAndExit("'--local-cache-path' cannot be inside the src folder"); } } this.CheckKernelDriverSupported(normalizedEnlistmentRootPath); this.CheckNotInsideExistingRepo(normalizedEnlistmentRootPath); this.BlockEmptyCacheServerUrl(this.CacheServerUrl); try { GVFSEnlistment enlistment; Result cloneResult = new Result(false); CacheServerInfo cacheServer = null; ServerGVFSConfig serverGVFSConfig = null; using (JsonTracer tracer = new JsonTracer(GVFSConstants.GVFSEtwProviderName, "GVFSClone")) { cloneResult = this.TryCreateEnlistment(fullEnlistmentRootPathParameter, normalizedEnlistmentRootPath, out enlistment); if (cloneResult.Success) { tracer.AddLogFileEventListener( GVFSEnlistment.GetNewGVFSLogFileName(enlistment.GVFSLogsRoot, GVFSConstants.LogFileTypes.Clone), EventLevel.Informational, Keywords.Any); tracer.WriteStartEvent( enlistment.EnlistmentRoot, enlistment.RepoUrl, this.CacheServerUrl, new EventMetadata { { "Branch", this.Branch }, { "LocalCacheRoot", this.LocalCacheRoot }, { "SingleBranch", this.SingleBranch }, { "NoMount", this.NoMount }, { "NoPrefetch", this.NoPrefetch }, { "Unattended", this.Unattended }, { "IsElevated", GVFSPlatform.Instance.IsElevated() }, { "NamedPipeName", enlistment.NamedPipeName }, { nameof(this.EnlistmentRootPathParameter), this.EnlistmentRootPathParameter }, { nameof(fullEnlistmentRootPathParameter), fullEnlistmentRootPathParameter }, }); CacheServerResolver cacheServerResolver = new CacheServerResolver(tracer, enlistment); cacheServer = cacheServerResolver.ParseUrlOrFriendlyName(this.CacheServerUrl); string resolvedLocalCacheRoot; if (string.IsNullOrWhiteSpace(this.LocalCacheRoot)) { resolvedLocalCacheRoot = LocalCacheResolver.GetDefaultLocalCacheRoot(enlistment); } else { resolvedLocalCacheRoot = Path.GetFullPath(this.LocalCacheRoot); } // if (enlistment.RepoUrl == string.Empty) { // this.Output.WriteLine("Clone parameters:"); // this.Output.WriteLine(" Repo URL: " + enlistment.RepoUrl); // this.Output.WriteLine(" Branch: " + (string.IsNullOrWhiteSpace(this.Branch) ? "Default" : this.Branch)); // this.Output.WriteLine(" Cache Server: " + cacheServer); // this.Output.WriteLine(" Local Cache: " + resolvedLocalCacheRoot); // this.Output.WriteLine(" Destination: " + enlistment.EnlistmentRoot); // } string authErrorMessage; if (!this.TryAuthenticate(tracer, enlistment, out authErrorMessage)) { this.ReportErrorAndExit(tracer, "Cannot clone because authentication failed: " + authErrorMessage); } RetryConfig retryConfig = this.GetRetryConfig(tracer, enlistment, TimeSpan.FromMinutes(RetryConfig.FetchAndCloneTimeoutMinutes)); serverGVFSConfig = this.QueryGVFSConfig(tracer, enlistment, retryConfig); cacheServer = this.ResolveCacheServer(tracer, cacheServer, cacheServerResolver, serverGVFSConfig); this.ValidateClientVersions(tracer, enlistment, serverGVFSConfig, showWarnings: true); this.ShowStatusWhileRunning( () => { cloneResult = this.TryClone(tracer, enlistment, cacheServer, retryConfig, serverGVFSConfig, resolvedLocalCacheRoot); return cloneResult.Success; }, "Cloning", normalizedEnlistmentRootPath); } if (!cloneResult.Success) { tracer.RelatedError(cloneResult.ErrorMessage); } } if (cloneResult.Success) { if (!this.NoPrefetch) { ReturnCode result = this.Execute<PrefetchVerb>( enlistment, verb => { verb.Commits = true; verb.SkipVersionCheck = true; verb.ResolvedCacheServer = cacheServer; verb.ServerGVFSConfig = serverGVFSConfig; }); if (result != ReturnCode.Success) { this.Output.WriteLine("\r\nError during prefetch @ {0}", fullEnlistmentRootPathParameter); exitCode = (int)result; } } if (this.NoMount) { this.Output.WriteLine("\r\nIn order to mount, first cd to within your enlistment, then call: "); this.Output.WriteLine("gvfs mount"); } else { this.Execute<MountVerb>( enlistment, verb => { verb.SkipMountedCheck = true; verb.SkipVersionCheck = true; verb.ResolvedCacheServer = cacheServer; verb.DownloadedGVFSConfig = serverGVFSConfig; }); } } else { this.Output.WriteLine("\r\nCannot clone @ {0}", fullEnlistmentRootPathParameter); this.Output.WriteLine("Error: {0}", cloneResult.ErrorMessage); exitCode = (int)ReturnCode.GenericError; } } catch (AggregateException e) { this.Output.WriteLine("Cannot clone @ {0}:", fullEnlistmentRootPathParameter); foreach (Exception ex in e.Flatten().InnerExceptions) { this.Output.WriteLine("Exception: {0}", ex.ToString()); } exitCode = (int)ReturnCode.GenericError; } catch (VerbAbortedException) { throw; } catch (Exception e) { this.ReportErrorAndExit("Cannot clone @ {0}: {1}", fullEnlistmentRootPathParameter, e.ToString()); } Environment.Exit(exitCode); } private static bool IsForceCheckoutErrorCloneFailure(string checkoutError) { if (string.IsNullOrWhiteSpace(checkoutError) || checkoutError.Contains("Already on")) { return false; } return true; } private Result TryCreateEnlistment( string fullEnlistmentRootPathParameter, string normalizedEnlistementRootPath, out GVFSEnlistment enlistment) { enlistment = null; // Check that EnlistmentRootPath is empty before creating a tracer and LogFileEventListener as // LogFileEventListener will create a file in EnlistmentRootPath if (Directory.Exists(normalizedEnlistementRootPath) && Directory.EnumerateFileSystemEntries(normalizedEnlistementRootPath).Any()) { if (fullEnlistmentRootPathParameter.Equals(normalizedEnlistementRootPath, StringComparison.OrdinalIgnoreCase)) { return new Result($"Clone directory '{fullEnlistmentRootPathParameter}' exists and is not empty"); } return new Result($"Clone directory '{fullEnlistmentRootPathParameter}' ['{normalizedEnlistementRootPath}'] exists and is not empty"); } string gitBinPath = GVFSPlatform.Instance.GitInstallation.GetInstalledGitBinPath(); if (string.IsNullOrWhiteSpace(gitBinPath)) { return new Result(GVFSConstants.GitIsNotInstalledError); } string hooksPath = this.GetGVFSHooksPathAndCheckVersion(tracer: null, hooksVersion: out _); enlistment = new GVFSEnlistment( normalizedEnlistementRootPath, this.RepositoryURL, gitBinPath, hooksPath, authentication: null); return new Result(true); } private Result TryClone( JsonTracer tracer, GVFSEnlistment enlistment, CacheServerInfo cacheServer, RetryConfig retryConfig, ServerGVFSConfig serverGVFSConfig, string resolvedLocalCacheRoot) { Result pipeResult; using (NamedPipeServer pipeServer = this.StartNamedPipe(tracer, enlistment, out pipeResult)) { if (!pipeResult.Success) { return pipeResult; } using (GitObjectsHttpRequestor objectRequestor = new GitObjectsHttpRequestor(tracer, enlistment, cacheServer, retryConfig)) { GitRefs refs = objectRequestor.QueryInfoRefs(this.SingleBranch ? this.Branch : null); if (refs == null) { return new Result("Could not query info/refs from: " + Uri.EscapeUriString(enlistment.RepoUrl)); } if (this.Branch == null) { this.Branch = refs.GetDefaultBranch(); EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Informational, "CloneDefaultRemoteBranch", metadata); } else { if (!refs.HasBranch(this.Branch)) { EventMetadata metadata = new EventMetadata(); metadata.Add("Branch", this.Branch); tracer.RelatedEvent(EventLevel.Warning, "CloneBranchDoesNotExist", metadata); string errorMessage = string.Format("Remote branch {0} not found in upstream origin", this.Branch); return new Result(errorMessage); } } if (!enlistment.TryCreateEnlistmentFolders()) { string error = "Could not create enlistment directory"; tracer.RelatedError(error); return new Result(error); } string localCacheError; if (!this.TryDetermineLocalCacheAndInitializePaths(tracer, enlistment, serverGVFSConfig, cacheServer, resolvedLocalCacheRoot, out localCacheError)) { tracer.RelatedError(localCacheError); return new Result(localCacheError); } Directory.CreateDirectory(enlistment.GitObjectsRoot); Directory.CreateDirectory(enlistment.GitPackRoot); Directory.CreateDirectory(enlistment.BlobSizesRoot); return this.CreateClone(tracer, enlistment, objectRequestor, refs, this.Branch); } } } private NamedPipeServer StartNamedPipe(ITracer tracer, GVFSEnlistment enlistment, out Result errorResult) { try { errorResult = new Result(true); return AllowAllLocksNamedPipeServer.Create(tracer, enlistment); } catch (PipeNameLengthException) { errorResult = new Result("Failed to clone. Path exceeds the maximum number of allowed characters"); return null; } } private string GetCloneRoot(out string fullEnlistmentRootPathParameter) { fullEnlistmentRootPathParameter = null; try { string repoName = this.RepositoryURL.Substring(this.RepositoryURL.LastIndexOf('/') + 1); fullEnlistmentRootPathParameter = string.IsNullOrWhiteSpace(this.EnlistmentRootPathParameter) ? Path.Combine(Environment.CurrentDirectory, repoName) : this.EnlistmentRootPathParameter; fullEnlistmentRootPathParameter = Path.GetFullPath(fullEnlistmentRootPathParameter); string errorMessage; string enlistmentRootPath; if (!GVFSPlatform.Instance.FileSystem.TryGetNormalizedPath(fullEnlistmentRootPathParameter, out enlistmentRootPath, out errorMessage)) { this.ReportErrorAndExit("Unable to determine normalized path of clone root: " + errorMessage); return null; } return enlistmentRootPath; } catch (IOException e) { this.ReportErrorAndExit("Unable to determine clone root: " + e.ToString()); return null; } } private void CheckKernelDriverSupported(string normalizedEnlistmentRootPath) { string warning; string error; if (!GVFSPlatform.Instance.KernelDriver.IsSupported(normalizedEnlistmentRootPath, out warning, out error)) { this.ReportErrorAndExit($"Error: {error}"); } else if (!string.IsNullOrEmpty(warning)) { this.Output.WriteLine(); this.Output.WriteLine($"WARNING: {warning}"); } } private void CheckNotInsideExistingRepo(string normalizedEnlistmentRootPath) { string errorMessage; string existingEnlistmentRoot; if (GVFSPlatform.Instance.TryGetGVFSEnlistmentRoot(normalizedEnlistmentRootPath, out existingEnlistmentRoot, out errorMessage)) { this.ReportErrorAndExit("Error: You can't clone inside an existing GVFS repo ({0})", existingEnlistmentRoot); } } private bool TryDetermineLocalCacheAndInitializePaths( ITracer tracer, GVFSEnlistment enlistment, ServerGVFSConfig serverGVFSConfig, CacheServerInfo currentCacheServer, string localCacheRoot, out string errorMessage) { errorMessage = null; LocalCacheResolver localCacheResolver = new LocalCacheResolver(enlistment); string error; string localCacheKey; if (!localCacheResolver.TryGetLocalCacheKeyFromLocalConfigOrRemoteCacheServers( tracer, serverGVFSConfig, currentCacheServer, localCacheRoot, localCacheKey: out localCacheKey, errorMessage: out error)) { errorMessage = "Error determining local cache key: " + error; return false; } EventMetadata metadata = new EventMetadata(); metadata.Add("localCacheRoot", localCacheRoot); metadata.Add("localCacheKey", localCacheKey); metadata.Add(TracingConstants.MessageKey.InfoMessage, "Initializing cache paths"); tracer.RelatedEvent(EventLevel.Informational, "CloneVerb_TryDetermineLocalCacheAndInitializePaths", metadata); enlistment.InitializeCachePathsFromKey(localCacheRoot, localCacheKey); return true; } private Result CreateClone( ITracer tracer, GVFSEnlistment enlistment, GitObjectsHttpRequestor objectRequestor, GitRefs refs, string branch) { Result initRepoResult = this.TryInitRepo(tracer, refs, enlistment); if (!initRepoResult.Success) { return initRepoResult; } PhysicalFileSystem fileSystem = new PhysicalFileSystem(); string errorMessage; if (!this.TryCreateAlternatesFile(fileSystem, enlistment, out errorMessage)) { return new Result("Error configuring alternate: " + errorMessage); } GitRepo gitRepo = new GitRepo(tracer, enlistment, fileSystem); GVFSContext context = new GVFSContext(tracer, fileSystem, gitRepo, enlistment); GVFSGitObjects gitObjects = new GVFSGitObjects(context, objectRequestor); if (!this.TryDownloadCommit( refs.GetTipCommitId(branch), enlistment, objectRequestor, gitObjects, gitRepo, out errorMessage)) { return new Result(errorMessage); } if (!GVFSVerb.TrySetRequiredGitConfigSettings(enlistment) || !GVFSVerb.TrySetOptionalGitConfigSettings(enlistment)) { return new Result("Unable to configure git repo"); } CacheServerResolver cacheServerResolver = new CacheServerResolver(tracer, enlistment); if (!cacheServerResolver.TrySaveUrlToLocalConfig(objectRequestor.CacheServer, out errorMessage)) { return new Result("Unable to configure cache server: " + errorMessage); } GitProcess git = new GitProcess(enlistment); string originBranchName = "origin/" + branch; GitProcess.Result createBranchResult = git.CreateBranchWithUpstream(branch, originBranchName); if (createBranchResult.ExitCodeIsFailure) { return new Result("Unable to create branch '" + originBranchName + "': " + createBranchResult.Errors + "\r\n" + createBranchResult.Output); } File.WriteAllText( Path.Combine(enlistment.WorkingDirectoryRoot, GVFSConstants.DotGit.Head), "ref: refs/heads/" + branch); if (!this.TryDownloadRootGitAttributes(enlistment, gitObjects, gitRepo, out errorMessage)) { return new Result(errorMessage); } this.CreateGitScript(enlistment); string installHooksError; if (!HooksInstaller.InstallHooks(context, out installHooksError)) { tracer.RelatedError(installHooksError); return new Result(installHooksError); } GitProcess.Result forceCheckoutResult = git.ForceCheckout(branch); if (forceCheckoutResult.ExitCodeIsFailure && forceCheckoutResult.Errors.IndexOf("unable to read tree") > 0) { // It is possible to have the above TryDownloadCommit() fail because we // already have the commit and root tree we intend to check out, but // don't have a tree further down the working directory. If we fail // checkout here, its' because we don't have these trees and the // read-object hook is not available yet. Force downloading the commit // again and retry the checkout. if (!this.TryDownloadCommit( refs.GetTipCommitId(branch), enlistment, objectRequestor, gitObjects, gitRepo, out errorMessage, checkLocalObjectCache: false)) { return new Result(errorMessage); } forceCheckoutResult = git.ForceCheckout(branch); } if (forceCheckoutResult.ExitCodeIsFailure) { string[] errorLines = forceCheckoutResult.Errors.Split('\n'); StringBuilder checkoutErrors = new StringBuilder(); foreach (string gitError in errorLines) { if (IsForceCheckoutErrorCloneFailure(gitError)) { checkoutErrors.AppendLine(gitError); } } if (checkoutErrors.Length > 0) { string error = "Could not complete checkout of branch: " + branch + ", " + checkoutErrors.ToString(); tracer.RelatedError(error); return new Result(error); } } if (!RepoMetadata.TryInitialize(tracer, enlistment.DotGVFSRoot, out errorMessage)) { tracer.RelatedError(errorMessage); return new Result(errorMessage); } try { RepoMetadata.Instance.SaveCloneMetadata(tracer, enlistment); this.LogEnlistmentInfoAndSetConfigValues(tracer, git, enlistment); } catch (Exception e) { tracer.RelatedError(e.ToString()); return new Result(e.Message); } finally { RepoMetadata.Shutdown(); } // Prepare the working directory folder for GVFS last to ensure that gvfs mount will fail if gvfs clone has failed Exception exception; string prepFileSystemError; if (!GVFSPlatform.Instance.KernelDriver.TryPrepareFolderForCallbacks(enlistment.WorkingDirectoryRoot, out prepFileSystemError, out exception)) { EventMetadata metadata = new EventMetadata(); metadata.Add(nameof(prepFileSystemError), prepFileSystemError); if (exception != null) { metadata.Add("Exception", exception.ToString()); } tracer.RelatedError(metadata, $"{nameof(this.CreateClone)}: TryPrepareFolderForCallbacks failed"); return new Result(prepFileSystemError); } return new Result(true); } private void CreateGitScript(GVFSEnlistment enlistment) { FileInfo gitCmd = new FileInfo(Path.Combine(enlistment.EnlistmentRoot, "git.cmd")); using (FileStream fs = gitCmd.Create()) using (StreamWriter writer = new StreamWriter(fs)) { writer.Write( @" @echo OFF echo . echo ^ echo This repo was cloned using GVFS, and the git repo is in the 'src' directory echo Switching you to the 'src' directory and rerunning your git command echo  @echo ON cd src git %* "); } gitCmd.Attributes = FileAttributes.Hidden; } private Result TryInitRepo(ITracer tracer, GitRefs refs, Enlistment enlistmentToInit) { string repoPath = enlistmentToInit.WorkingDirectoryRoot; GitProcess.Result initResult = GitProcess.Init(enlistmentToInit); if (initResult.ExitCodeIsFailure) { string error = string.Format("Could not init repo at to {0}: {1}", repoPath, initResult.Errors); tracer.RelatedError(error); return new Result(error); } GitProcess.Result remoteAddResult = new GitProcess(enlistmentToInit).RemoteAdd("origin", enlistmentToInit.RepoUrl); if (remoteAddResult.ExitCodeIsFailure) { string error = string.Format("Could not add remote to {0}: {1}", repoPath, remoteAddResult.Errors); tracer.RelatedError(error); return new Result(error); } File.WriteAllText( Path.Combine(repoPath, GVFSConstants.DotGit.PackedRefs), refs.ToPackedRefs()); return new Result(true); } private class Result { public Result(bool success) { this.Success = success; this.ErrorMessage = string.Empty; } public Result(string errorMessage) { this.Success = false; this.ErrorMessage = errorMessage; } public bool Success { get; } public string ErrorMessage { get; } } } }
42.912134
171
0.521808
[ "MIT" ]
yijunyu/VFSForGit
GVFS/GVFS/CommandLine/CloneVerb.cs
30,768
C#
using System; namespace Auth0SystemWeb.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.756098
131
0.50866
[ "MIT" ]
mdewey/Auth0-Dotnet-Api
Auth0SystemWeb/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,097
C#
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; namespace mantis_tests { public class HelperBase { protected IWebDriver driver; protected ApplicationManager manager; public HelperBase(ApplicationManager manager) { this.manager = manager; driver = manager.Driver; } public void Type(By locator, string text) { if (text != null) { driver.FindElement(locator).Click(); driver.FindElement(locator).Clear(); driver.FindElement(locator).SendKeys(text); } } public bool IsElementPresent(By by) { try { driver.FindElement(by); return true; } catch(NoSuchElementException) { return false; } } public void WaitElement(By by, int sec = 3) { new WebDriverWait(driver, TimeSpan.FromSeconds(sec)).Until(drv => drv.FindElement(by)); } public void OpenMainPage() { manager.Driver.Url = "http://localhost/mantisbt-2.25.0/mantisbt-2.25.0/login_page.php"; } } }
24.941176
99
0.52044
[ "Apache-2.0" ]
pivnaya/csharp_training
mantis-tests/mantis-tests/appmanager/HelperBase.cs
1,274
C#
using System; using System.Collections.Generic; using System.Text; namespace WC2150Shared { public static class Data { public const ushort BUFFER_SIZE = 256; public const byte MOVE = 1; public const byte JOIN = 2; public const byte START = 3; public const byte WELCOME = 4; public const byte SHOOT = 5; public const byte DEATH = 6; public const byte YOU_DEAD = 7; public const byte BAD_MOVE = 8; } }
23.190476
46
0.620123
[ "Apache-2.0" ]
RatajVaver/WarCode2150
WC2150Shared/Data.cs
489
C#
using Core.Utilities.IoC; using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using System.Text.RegularExpressions; using System.Linq; namespace Core.CrossCuttingConcerns.Caching.Microsoft { class MemoryCacheManager : ICacheManager { IMemoryCache _memoryCache; public MemoryCacheManager() { _memoryCache = ServiceTool.ServiceProvider.GetService<IMemoryCache>(); } public void Add(string key, object value, int duration) { _memoryCache.Set(key, value, TimeSpan.FromMinutes(duration)); } public T Get<T>(string key) { return _memoryCache.Get<T>(key); } public object Get(string key) { return _memoryCache.Get(key); } public bool IsAdd(string key) { return _memoryCache.TryGetValue(key, out _); } public void Remove(string key) { _memoryCache.Remove(key); } public void RemoveByPattern(string pattern) { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List<ICacheEntry> cacheCollectionValues = new List<ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } } } }
32.820896
146
0.635744
[ "MIT" ]
OnurAkkepenekk/Where
Where/Core/CrossCuttingConcerns/Caching/Microsoft/MemoryCacheManager.cs
2,201
C#
using ScriptableObjectArchitecture; using UnityEngine; using UnityEngine.Animations; public class CharacterBehaviour : MonoBehaviour { public Character CharacterTemplate; public Faction CharacterFaction; [SerializeField] private FloatReference _characterSpecificHealth; [SerializeField] private GameObjectVariable _currentTarget; [SerializeField] private GameObjectVariable _currentPlayer; [SerializeField] private GameObject _targetHighlight; [SerializeField] private TurnController _turnController; private LookAtConstraint _lookAtConstraint; private void Start() { _lookAtConstraint = GetComponent<LookAtConstraint>(); _currentTarget.AddListener(HandleTargetChanged); if (_characterSpecificHealth.IsValueDefined) { CharacterTemplate.InitializeHealth(_characterSpecificHealth.Value); } else { CharacterTemplate.InitializeHealth(); } } private void OnDestroy(){ _currentTarget.RemoveListener(HandleTargetChanged); } public void HandleDamageTaken(float incomingDamage) { CharacterTemplate.Health.Value = Mathf.Clamp(CharacterTemplate.Health.Value - incomingDamage, 0, 100f); Debug.Log($"{CharacterTemplate.CharacterName} health: {CharacterTemplate.Health.Value}"); _turnController.EndTurn(); } private void HandleTargetChanged() { _targetHighlight.SetActive(false); if (_currentTarget.Value == null){ return; } // highlight the targeted enemy if (_currentTarget.Value == this.gameObject) { _targetHighlight.SetActive(true); } // player looks at the current target if (_currentPlayer.Value == this.gameObject) { AddOrSetConstraintSource(_currentTarget.Value.transform); } else // everyone else looks at player { AddOrSetConstraintSource(_currentPlayer.Value.transform); } _lookAtConstraint.constraintActive = true; } private void AddOrSetConstraintSource(Transform target) { if (_lookAtConstraint.sourceCount == 0) { _lookAtConstraint.AddSource(new ConstraintSource { sourceTransform = target, weight = 1.0f}); } else { _lookAtConstraint.SetSource(0, new ConstraintSource { sourceTransform = target, weight = 1.0f}); } } }
31.607595
111
0.667201
[ "MIT" ]
dstrawberrygirl/SODemo
Assets/Scripts/CharacterBehaviour.cs
2,497
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Alb.Inputs { public sealed class LoadBalancerSubnetMappingArgs : Pulumi.ResourceArgs { /// <summary> /// The allocation ID of the Elastic IP address. /// </summary> [Input("allocationId")] public Input<string>? AllocationId { get; set; } [Input("outpostId")] public Input<string>? OutpostId { get; set; } /// <summary> /// A private ipv4 address within the subnet to assign to the internal-facing load balancer. /// </summary> [Input("privateIpv4Address")] public Input<string>? PrivateIpv4Address { get; set; } /// <summary> /// The id of the subnet of which to attach to the load balancer. You can specify only one subnet per Availability Zone. /// </summary> [Input("subnetId", required: true)] public Input<string> SubnetId { get; set; } = null!; public LoadBalancerSubnetMappingArgs() { } } }
31.97561
128
0.632342
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/Alb/Inputs/LoadBalancerSubnetMappingArgs.cs
1,311
C#
using BiliBili3.Controls; using BiliBili3.Helper; using BiliBili3.Modules; using BiliBili3.Pages; using BiliBili3.Pages.FindMore; using BiliBili3.Pages.Live; using BiliBili3.Pages.Music; using BiliBili3.Views; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.Foundation; using Windows.UI; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace BiliBili3 { public enum NavigateMode { Main, Info, Home, Play, Bg } public delegate void MessageHandel(object par, params object[] par1); public delegate void NavigateHandel(Type page, params object[] par); public delegate void LoginedHandel(); public delegate void ChangeBgHandel(); public delegate void ShowOrHideBarHandel(bool show); public static class MessageCenter { public static event EventHandler<object> HasMessaged; public static event MessageHandel ChanageThemeEvent; public static event LoginedHandel Logined; public static event ChangeBgHandel ChangeBg; public static event EventHandler HideAdEvent; public static void SendHideAd() { HideAdEvent?.Invoke(null,null); } public static void SendMessage(object par) { if (HasMessaged!=null) { HasMessaged(null, par); } } public static void SendLogined() { Logined(); } public static void SendChangedBg() { ChangeBg(); } public static void SendChanageThemeEvent(object par, params object[] par1) { ChanageThemeEvent(par, par1); } public static event NavigateHandel InfoNavigateToEvent; public static event NavigateHandel PlayNavigateToEvent; public static event NavigateHandel MianNavigateToEvent; public static event NavigateHandel HomeNavigateToEvent; public static event NavigateHandel BgNavigateToEvent; public async static void SendNavigateTo(NavigateMode mode, Type page, params object[] par) { switch (mode) { case NavigateMode.Main: MianNavigateToEvent(page, par); break; case NavigateMode.Info: if (page.FullName.Contains("WebPage") &&await HandelUrl(par[0].ToString())) { return; } InfoNavigateToEvent(page, par); break; case NavigateMode.Play: if (!page.FullName.Contains("MusicMiniPlayerPage")) { MusicHelper.Pause(); } //&&SettingHelper.IsPc() if (page==typeof(LiveRoomPage)) { PlayNavigateToEvent(typeof(LiveRoomPC), par); return; } PlayNavigateToEvent(page, par); break; case NavigateMode.Home: HomeNavigateToEvent(page, par); break; case NavigateMode.Bg: BgNavigateToEvent(page, par); break; default: break; } } public static void ShowMiniVideo(string vid) { MiniVideoDialog miniVideoDialog = new MiniVideoDialog(); miniVideoDialog.ShowAsync(vid); } /// <summary> ///统一处理Url /// </summary> /// <param name="par"></param> public async static Task<bool> HandelUrl(string url) { /* * 视频 * https://www.bilibili.com/video/av3905642 * https://m.bilibili.com/video/av3905642.html * https://www.bilibili.com/playlist/video/pl688?aid=19827477 * bilibili://video/19239064 * bilibili://?av=4284663 * https://m.bilibili.com/playlist/pl733016988?avid=68818070 */ var video = Utils.RegexMatch(url.Replace("aid", "av").Replace("/","").Replace("=",""), @"av(\d+)"); if (video!="") { InfoNavigateToEvent(typeof(VideoViewPage), video); return true; } video = Utils.RegexMatch(url, @"bilibili://video/(\d+)"); if (video != "") { InfoNavigateToEvent(typeof(VideoViewPage), video); return true; } video = Utils.RegexMatch(url, @"avid=(\d+)"); if (video != "") { InfoNavigateToEvent(typeof(VideoViewPage), video); return true; } /* * 番剧/影视 * https://bangumi.bilibili.com/anime/21680 * https://www.bilibili.com/bangumi/play/ss21715 * https://www.bilibili.com/bangumi/play/ep150706 * https://m.bilibili.com/bangumi/play/ep150706 * http://m.bilibili.com/bangumi/play/ss21715 * bilibili://bangumi/season/21715 * https://bangumi.bilibili.com/movie/12364 */ var bangumi = Utils.RegexMatch(url.Replace("movie","ss").Replace("anime", "ss").Replace("season", "ss").Replace("/",""), @"ss(\d+)"); if (bangumi != "") { InfoNavigateToEvent(typeof(BanInfoPage), bangumi); return true; } bangumi = Utils.RegexMatch(url, @"ep(\d+)"); if (bangumi != "") { InfoNavigateToEvent(typeof(BanInfoPage),await Utils.BangumiEpidToSid(bangumi)); return true; } /* * 点评 * https://www.bilibili.com/bangumi/media/md11592/ * https://bangumi.bilibili.com/review/media/11592 * bilibili://pgc/review/11592 */ var review = Utils.RegexMatch(url.Replace("media", "md").Replace("review", "md").Replace("/", ""), @"md(\d+)"); if (review != "") { //InfoNavigateToEvent(typeof(BanInfoPage), review); await new Windows.UI.Popups.MessageDialog("请求打开点评"+ review).ShowAsync(); return true; } /* * 直播 * http://live.bilibili.com/live/5619438.html * http://live.bilibili.com/h5/5619438 * http://live.bilibili.com/5619438 * bilibili://live/5619438 */ var live = Utils.RegexMatch(url.Replace("h5", "live").Replace("live.bilibili.com", "live").Replace("/", ""), @"live(\d+)"); if (live != "") { if (!SettingHelper.IsPc()) { PlayNavigateToEvent(typeof(LiveRoomPage), live); } else { PlayNavigateToEvent(typeof(LiveRoomPC), live); } return true; } /* * 小视频 * http://vc.bilibili.com/mobile/detail?vc=1399466&bilifrom=1 * http://vc.bilibili.com/video/1357956 * bilibili://clip/1399466 */ var clip = Utils.RegexMatch(url.Replace("vc=", "clip").Replace("vc.bilibili.com/video", "clip").Replace("/", ""), @"clip(\d+)"); if (clip != "") { MiniVideoDialog miniVideoDialog = new MiniVideoDialog(); miniVideoDialog.ShowAsync(clip); return true; } /* * 专栏 * http://www.bilibili.com/read/cv242568 * https://www.bilibili.com/read/mobile/242568 * bilibili://article/242568 */ var article = Utils.RegexMatch(url.Replace("read/mobile/", "article").Replace("read/cv", "article").Replace("/", ""), @"article(\d+)"); if (article != "") { InfoNavigateToEvent(typeof(ArticleContentPage), "https://www.bilibili.com/read/app/" + article); return true; } /* * 音频 * https://m.bilibili.com/audio/au247991 * bilibili://music/detail/247991 */ var music = Utils.RegexMatch(url.Replace("music/detail/", "au").Replace("/", ""), @"au(\d+)"); if (music != "") { InfoNavigateToEvent(typeof(MusicInfoPage), music); return true; } /* * 歌单 * https://m.bilibili.com/audio/am78723 * bilibili://music/menu/detail/78723 */ var musicmenu = Utils.RegexMatch(url.Replace("menu/detail/", "am").Replace("/", ""), @"am(\d+)"); if (musicmenu != "") { InfoNavigateToEvent(typeof(MusicMenuPage), musicmenu); return true; } /* * 相簿及动态 * http://h.bilibili.com/ywh/h5/2403422 * http://h.bilibili.com/2403422 * bilibili://album/2403422 * https://t.bilibili.com/84935538081511530 * bilibili://following/detail/314560419758546547 */ var album = Utils.RegexMatch(url.Replace("bilibili://following/detail/", "album").Replace("h.bilibili.com/ywh/h5/", "album").Replace("h.bilibili.com", "album").Replace("t.bilibili.com", "album").Replace("/", ""), @"album(\d+)"); if (album != "") { InfoNavigateToEvent(typeof(DynamicInfoPage), album); return true; } /* * 用户中心 * http://space.bilibili.com/7251681 * https://m.bilibili.com/space/7251681 * https://space.bilibili.com/1360010 * bilibili://author/2622476 */ var user = Utils.RegexMatch(url.Replace("space.bilibili.com", "space").Replace("author", "space").Replace("/", ""), @"space(\d+)"); if (user != "") { InfoNavigateToEvent(typeof(UserInfoPage), user); return true; } /* * 话题/频道 * https://www.bilibili.com/tag/7868838/feed * bilibili://tag/0/?name=bilibili%e5%a5%bd%e4%b9%a1%e9%9f%b3 */ var topic = Utils.RegexMatch(url, @"tag/(.*?)/feed"); if (topic != "") { InfoNavigateToEvent(typeof(DynamicTopicPage), new object[] { "", topic }); return true; } var topic1 = Utils.RegexMatch(url+"/", @"tag/.*?/\?name=(.*?)/"); if (topic1 != "") { var data = Uri.UnescapeDataString(topic1); InfoNavigateToEvent(typeof(DynamicTopicPage), new object[] { data, "" }); return true; } /* * 播单 * https://www.bilibili.com/playlist/detail/pl792 */ /* * 投稿 * bilibili://uper/user_center/add_archive/ */ var add_archive = url.Contains("/add_archive"); if (add_archive) { //InfoNavigateToEvent(typeof(DynamicTopicPage), new object[] { "", topic }); InfoNavigateToEvent(typeof(WebPage), new object[] { "https://member.bilibili.com/v2#/upload/video/frame" }); return true; } /* * 我的追番 * bilibili://main/favorite?tab=bangumi&fav_sub_tab=watching&from=21 */ if (url.Contains("favorite?tab=bangumi")) { InfoNavigateToEvent(typeof(FollowSeasonPage), SeasonType.bangumi); return true; } /* * 赛事 * bilibili://pegasus/channel/v2/9222?tab=5709 */ if (url.Contains("bilibili://pegasus/channel/v2/9222")) { InfoNavigateToEvent(typeof(WebPage), new object[] { "https://www.bilibili.com/v/game/match" }); return true; } return false; } public static event ShowOrHideBarHandel ShowOrHideBarEvent; public static void ShowOrHideBar(bool show) { ShowOrHideBarEvent(show); } public async static void OpenNewWindow(Type page, params object[] par) { CoreApplicationView newView = CoreApplication.CreateNewView(); int newViewId = 0; await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Frame frame = new Frame(); frame.Navigate(page, par); Window.Current.Content = frame; Window.Current.Activate(); newViewId = ApplicationView.GetForCurrentView().Id; ChangeTheme(frame); ChangeTitbarColor(ApplicationView.GetForCurrentView()); var bounds = ApplicationView.GetForCurrentView().VisibleBounds; ApplicationView.PreferredLaunchViewSize = new Size(bounds.Width, bounds.Height); ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; ApplicationView.GetForCurrentView().Consolidated += (sender, args) => { frame.Navigate(typeof(BlankPage));//跳转到空白页 //newView.CoreWindow.Close(); //Window.Current.Close(); //出现线程错误 //Debug.WriteLine("????"); }; }); //ApplicationView.GetForCurrentView().IsViewModeSupported(ApplicationViewMode.CompactOverlay) bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId); } private static void ChangeTheme(Frame f) { string ThemeName = SettingHelper.Get_Theme(); ResourceDictionary newDictionary = new ResourceDictionary(); switch (ThemeName) { case "Dark": f.RequestedTheme = ElementTheme.Dark; break; case "Red": newDictionary.Source = new Uri("ms-appx:///Theme/RedTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "Blue": newDictionary.Source = new Uri("ms-appx:///Theme/BlueTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "Green": newDictionary.Source = new Uri("ms-appx:///Theme/GreenTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "Pink": newDictionary.Source = new Uri("ms-appx:///Theme/PinkTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "Purple": newDictionary.Source = new Uri("ms-appx:///Theme/PurpleTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "Yellow": newDictionary.Source = new Uri("ms-appx:///Theme/YellowTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; case "EMT": newDictionary.Source = new Uri("ms-appx:///Theme/EMTTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); // img_Hello.Source = new BitmapImage(new Uri("ms-appx:///Assets/Logo/EMT.png")); f.RequestedTheme = ElementTheme.Dark; f.RequestedTheme = ElementTheme.Light; break; } //tuic.To = this.ActualWidth; //storyboardPopOut.Begin(); //ChangeTitbarColor(); } private static void ChangeTitbarColor(ApplicationView v) { var titleBar = v.TitleBar; titleBar.BackgroundColor = ((SolidColorBrush)Application.Current.Resources["Bili-ForeColor"]).Color; titleBar.ForegroundColor = Color.FromArgb(255, 254, 254, 254);//Colors.White纯白用不了。。。 titleBar.ButtonHoverBackgroundColor = ((SolidColorBrush)Application.Current.Resources["Bili-ForeColor-Dark"]).Color; titleBar.ButtonBackgroundColor = ((SolidColorBrush)Application.Current.Resources["Bili-ForeColor"]).Color; titleBar.ButtonForegroundColor = Color.FromArgb(255, 254, 254, 254); titleBar.InactiveBackgroundColor = ((SolidColorBrush)Application.Current.Resources["Bili-ForeColor"]).Color; titleBar.ButtonInactiveBackgroundColor = ((SolidColorBrush)Application.Current.Resources["Bili-ForeColor"]).Color; } public static event EventHandler<string> NetworkError; public static void SendNetworkError(string msg) { NetworkError?.Invoke(null, msg); } public static event EventHandler<Exception> ShowError; public static void SendShowError(Exception ex) { ShowError?.Invoke(null, ex); } } }
37.806202
240
0.529321
[ "MIT" ]
CodeForCSharp/biliuwp
BiliBili3/Helper/MessageCenter.cs
19,654
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace workIT.Data.Tables { using System; using System.Collections.Generic; public partial class Entity_HasPathway { public int Id { get; set; } public int EntityId { get; set; } public int PathwayId { get; set; } public int PathwayRelationshipTypeId { get; set; } public System.DateTime Created { get; set; } public virtual Entity Entity { get; set; } public virtual Pathway Pathway { get; set; } } }
33.888889
85
0.533333
[ "Apache-2.0" ]
CredentialEngine/Import_From_Registry
src/workIT.Data/Tables/Entity_HasPathway.cs
915
C#
namespace SoundFingerprinting.Audio.Bass { public class BassSoundCaptureService : ISoundCaptureService { private readonly IBassServiceProxy proxy; private readonly IBassStreamFactory streamFactory; private readonly IBassResampler bassResampler; public BassSoundCaptureService() : this( BassServiceProxy.Instance, new BassStreamFactory(BassServiceProxy.Instance), new BassResampler( BassServiceProxy.Instance, new BassStreamFactory(BassServiceProxy.Instance), new SamplesAggregator())) { // no op } internal BassSoundCaptureService(IBassServiceProxy proxy, IBassStreamFactory streamFactory, IBassResampler bassResampler) { this.proxy = proxy; this.streamFactory = streamFactory; this.bassResampler = bassResampler; } public float[] ReadMonoSamples(int sampleRate, int secondsToRecord) { const int DefaultResamplerQuality = 4; if (!IsRecordingSupported()) { throw new BassException("No recording device could be found un running machine"); } int stream = streamFactory.CreateStreamFromMicrophone(sampleRate); return bassResampler.Resample(stream, sampleRate, secondsToRecord, 0, DefaultResamplerQuality, mixerStream => new ContinuousStreamSamplesProvider(new BassSamplesProvider(proxy, mixerStream))); } private bool IsRecordingSupported() { return proxy.GetRecordingDevice() != -1; } } }
37.577778
204
0.633353
[ "MIT" ]
AddictedCS/soundfingerprinting.audio.bass
src/SoundFingerprinting.Audio.Bass/BassSoundCaptureService.cs
1,691
C#
using Drexel.Configurables.External; namespace Drexel.DataSources.FolderData { /// <summary> /// Represents a factory which produces <see cref="IFolderDataWatcher"/>s. /// </summary> public interface IFolderDataWatcherFactory { /// <summary> /// Produces an <see cref="IFolderDataWatcher"/> using the specified <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path of the directory to watch. /// </param> /// <returns> /// An <see cref="IFolderDataWatcher"/> instance. /// </returns> IFolderDataWatcher MakeFolderDataWatcher(FilePath path); } }
30.636364
101
0.603858
[ "MIT" ]
ltnublet/Drexel.DataSource
Drexel.DataSources.FolderData/IFolderDataWatcherFactory.cs
676
C#
using PocketBar.Managers.Interfaces; using PocketBar.Models; using PocketBar.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PocketBar.Managers { public class CategoriesManager : ICategoriesManager { private ICocktailService cocktailService; private List<Category> categories; public CategoriesManager(ICocktailService service) { this.cocktailService = service; } public async Task<List<Category>> GetCategories() { if (categories == null || categories.Count == 0) { try { var response = await cocktailService.ApiService.GetAllCategoriesAsync(); categories = response.Categories.ToList(); } catch (Exception e) { throw e; } } return categories; } public async Task<List<Cocktail>> GetCocktailsByCategory(string category) { try { var response = await cocktailService.ApiService.GetCocktailsByCategoryAsync(category); return response.Drinks.ToList(); } catch (Exception e) { throw e; } } } }
20.622642
90
0.710887
[ "MIT" ]
BaristaStudio/PocketBar
PocketBar/PocketBar/Managers/CategoriesManager.cs
1,095
C#
using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Ordering.Application.Contracts.Infrastructure; using Ordering.Application.Models; using SendGrid; using SendGrid.Helpers.Mail; namespace Ordering.Infrastructure.Mail { public class EmailService : IEmailService { public EmailSettings _emailSettings { get; } public ILogger<EmailService> _logger { get; } public EmailService(IOptions<EmailSettings> emailSettings, ILogger<EmailService> logger) { _emailSettings = emailSettings.Value; _logger = logger; } public async Task<bool> SendEmail(Email email) { var client = new SendGridClient(_emailSettings.ApiKey); var subject = email.Subject; var to = new EmailAddress(email.To); var emailBody = email.Body; var from = new EmailAddress { Email = _emailSettings.FromAddress, Name = _emailSettings.FromName }; var sendGridMessage = MailHelper.CreateSingleEmail(from, to, subject, emailBody, emailBody); var response = await client.SendEmailAsync(sendGridMessage); _logger.LogInformation("Email sent."); if (response.StatusCode == System.Net.HttpStatusCode.Accepted || response.StatusCode == System.Net.HttpStatusCode.OK) return true; _logger.LogError("Email sending failed."); return false; } } }
32.479167
129
0.64272
[ "MIT" ]
nqbjnh/AspnetMicroservices
src/Services/Ordering/Ordering.Infrastructure/Mail/MailService.cs
1,561
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class ParameterHelpers { public static ImmutableArray<ParameterSymbol> MakeParameters( Binder binder, Symbol owner, BaseParameterListSyntax syntax, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier) { return MakeParameters<ParameterSyntax, ParameterSymbol, Symbol>( binder, owner, syntax.Parameters, out arglistToken, diagnostics, allowRefOrOut, allowThis, addRefReadOnlyModifier, suppressUseSiteDiagnostics: false, lastIndex: syntax.Parameters.Count - 1, parameterCreationFunc: (Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag declarationDiagnostics) => { return SourceParameterSymbol.Create( context, owner, parameterType, syntax, refKind, syntax.Identifier, ordinal, isParams: paramsKeyword.Kind() != SyntaxKind.None, isExtensionMethodThis: ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None, addRefReadOnlyModifier, declarationDiagnostics); }); } public static ImmutableArray<FunctionPointerParameterSymbol> MakeFunctionPointerParameters( Binder binder, FunctionPointerMethodSymbol owner, SeparatedSyntaxList<FunctionPointerParameterSyntax> parametersList, BindingDiagnosticBag diagnostics, bool suppressUseSiteDiagnostics) { return MakeParameters<FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>( binder, owner, parametersList, out _, diagnostics, allowRefOrOut: true, allowThis: false, addRefReadOnlyModifier: true, suppressUseSiteDiagnostics, parametersList.Count - 2, parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType, FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal, SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier, BindingDiagnosticBag diagnostics) => { // Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers, // these modreqs are the only locations where this can be encoded. If that changes, we should update this. Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer"); ImmutableArray<CustomModifier> customModifiers = refKind switch { RefKind.In => CreateInModifiers(binder, diagnostics, syntax), RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax), _ => ImmutableArray<CustomModifier>.Empty }; if (parameterType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location); } return new FunctionPointerParameterSymbol( parameterType, refKind, ordinal, owner, customModifiers); }, parsingFunctionPointer: true); } private static ImmutableArray<TParameterSymbol> MakeParameters<TParameterSyntax, TParameterSymbol, TOwningSymbol>( Binder binder, TOwningSymbol owner, SeparatedSyntaxList<TParameterSyntax> parametersList, out SyntaxToken arglistToken, BindingDiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier, bool suppressUseSiteDiagnostics, int lastIndex, Func<Binder, TOwningSymbol, TypeWithAnnotations, TParameterSyntax, RefKind, int, SyntaxToken, SyntaxToken, bool, BindingDiagnosticBag, TParameterSymbol> parameterCreationFunc, bool parsingFunctionPointer = false) where TParameterSyntax : BaseParameterSyntax where TParameterSymbol : ParameterSymbol where TOwningSymbol : Symbol { Debug.Assert(!parsingFunctionPointer || owner is FunctionPointerMethodSymbol); arglistToken = default(SyntaxToken); int parameterIndex = 0; int firstDefault = -1; var builder = ArrayBuilder<TParameterSymbol>.GetInstance(); var mustBeLastParameter = (ParameterSyntax)null; foreach (var parameterSyntax in parametersList) { if (parameterIndex > lastIndex) break; CheckParameterModifiers(parameterSyntax, diagnostics, parsingFunctionPointer); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); if (refKind == RefKind.Out && parameterSyntax is ParameterSyntax { ExclamationExclamationToken: var exExToken, Identifier: var identifier } && exExToken.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_NullCheckingOnOutParameter, exExToken.GetLocation(), identifier.ValueText); } if (thisKeyword.Kind() != SyntaxKind.None && !allowThis) { diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation()); } if (parameterSyntax is ParameterSyntax concreteParam) { if (mustBeLastParameter == null && (concreteParam.Modifiers.Any(SyntaxKind.ParamsKeyword) || concreteParam.Identifier.Kind() == SyntaxKind.ArgListKeyword)) { mustBeLastParameter = concreteParam; } if (concreteParam.IsArgList) { arglistToken = concreteParam.Identifier; // The native compiler produces "Expected type" here, in the parser. Roslyn produces // the somewhat more informative "arglist not valid" error. if (paramsKeyword.Kind() != SyntaxKind.None || refnessKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) { // CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } continue; } if (concreteParam.Default != null && firstDefault == -1) { firstDefault = parameterIndex; } } Debug.Assert(parameterSyntax.Type != null); var parameterType = binder.BindType(parameterSyntax.Type, diagnostics, suppressUseSiteDiagnostics: suppressUseSiteDiagnostics); if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out)) { Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None); // error CS0631: ref and out are not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation()); } if (parameterSyntax is ParameterSyntax { ExclamationExclamationToken: var exExToken1, Identifier: var identifier1 } && exExToken1.Kind() == SyntaxKind.ExclamationExclamationToken) { if (owner.IsAbstract || owner.IsPartialDefinition() || owner.IsExtern) { diagnostics.Add(ErrorCode.ERR_MustNullCheckInImplementation, identifier1.GetLocation(), identifier1.ValueText); } } TParameterSymbol parameter = parameterCreationFunc(binder, owner, parameterType, parameterSyntax, refKind, parameterIndex, paramsKeyword, thisKeyword, addRefReadOnlyModifier, diagnostics); ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics); builder.Add(parameter); ++parameterIndex; } if (mustBeLastParameter != null && mustBeLastParameter != parametersList[lastIndex]) { diagnostics.Add( mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword ? ErrorCode.ERR_VarargsLast : ErrorCode.ERR_ParamsLast, mustBeLastParameter.GetLocation()); } ImmutableArray<TParameterSymbol> parameters = builder.ToImmutableAndFree(); if (!parsingFunctionPointer) { var methodOwner = owner as MethodSymbol; var typeParameters = (object)methodOwner != null ? methodOwner.TypeParameters : default(ImmutableArray<TypeParameterSymbol>); Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod); bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) && methodOwner?.MethodKind == MethodKind.LocalFunction; binder.ValidateParameterNameConflicts(typeParameters, parameters.Cast<TParameterSymbol, ParameterSymbol>(), allowShadowingNames, diagnostics); } return parameters; } #nullable enable internal static void EnsureIsReadOnlyAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray<ParameterSymbol> parameters) { EnsureIsReadOnlyAttributeExists(moduleBuilder.Compilation, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder); } internal static void EnsureIsReadOnlyAttributeExists(CSharpCompilation? compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } EnsureIsReadOnlyAttributeExists(compilation, parameters, diagnostics, modifyCompilation, moduleBuilder: null); } private static void EnsureIsReadOnlyAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) { foreach (var parameter in parameters) { if (parameter.RefKind == RefKind.In) { if (moduleBuilder is { }) { moduleBuilder.EnsureIsReadOnlyAttributeExists(); } else { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } } internal static void EnsureNativeIntegerAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray<ParameterSymbol> parameters) { EnsureNativeIntegerAttributeExists(moduleBuilder.Compilation, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder); } internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation? compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } EnsureNativeIntegerAttributeExists(compilation, parameters, diagnostics, modifyCompilation, moduleBuilder: null); } private static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.ContainsNativeInteger()) { if (moduleBuilder is { }) { moduleBuilder.EnsureNativeIntegerAttributeExists(); } else { compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } } internal static void EnsureNullableAttributeExists(PEModuleBuilder moduleBuilder, Symbol container, ImmutableArray<ParameterSymbol> parameters) { EnsureNullableAttributeExists(moduleBuilder.Compilation, container, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder); } internal static void EnsureNullableAttributeExists(CSharpCompilation? compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation) { // These parameters might not come from a compilation (example: lambdas evaluated in EE). // During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead. if (compilation == null) { return; } EnsureNullableAttributeExists(compilation, container, parameters, diagnostics, modifyCompilation, moduleBuilder: null); } private static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder) { if (parameters.Length > 0 && compilation.ShouldEmitNullableAttributes(container)) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.NeedsNullableAttribute()) { if (moduleBuilder is { }) { moduleBuilder.EnsureNullableAttributeExists(); } else { compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation); } } } } } private static Location GetParameterLocation(ParameterSymbol parameter) => parameter.GetNonNullSyntaxNode().Location; #nullable disable private static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams) { var seenThis = false; var seenRef = false; var seenOut = false; var seenParams = false; var seenIn = false; foreach (var modifier in parameter.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.ThisKeyword: if (seenThis) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else { seenThis = true; } break; case SyntaxKind.RefKeyword: if (seenRef) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenRef = true; } break; case SyntaxKind.OutKeyword: if (seenOut) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenOut = true; } break; case SyntaxKind.ParamsKeyword when !parsingFunctionPointerParams: if (seenParams) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword)); } else if (seenThis) { diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation()); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenIn) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else { seenParams = true; } break; case SyntaxKind.InKeyword: if (seenIn) { diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else if (seenOut) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword)); } else if (seenRef) { diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword)); } else if (seenParams) { diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword)); } else { seenIn = true; } break; case SyntaxKind.ParamsKeyword when parsingFunctionPointerParams: case SyntaxKind.ReadOnlyKeyword when parsingFunctionPointerParams: diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, modifier.GetLocation(), SyntaxFacts.GetText(modifier.Kind())); break; default: throw ExceptionUtilities.UnexpectedValue(modifier.Kind()); } } } private static void ReportParameterErrors( Symbol owner, BaseParameterSyntax parameterSyntax, ParameterSymbol parameter, SyntaxToken thisKeyword, SyntaxToken paramsKeyword, int firstDefault, BindingDiagnosticBag diagnostics) { int parameterIndex = parameter.Ordinal; bool isDefault = parameterSyntax is ParameterSyntax { Default: { } }; if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0) { // Report CS1100 on "this". Note that is a change from Dev10 // which reports the error on the type following "this". // error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name); } else if (parameter.IsParams && owner.IsOperator()) { // error CS1670: params is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalParams, paramsKeyword.GetLocation()); } else if (parameter.IsParams && !parameter.TypeWithAnnotations.IsSZArray()) { // error CS0225: The params parameter must be a single dimensional array diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, paramsKeyword.GetLocation()); } else if (parameter.TypeWithAnnotations.IsStatic) { Debug.Assert(parameter.ContainingSymbol is FunctionPointerMethodSymbol or { ContainingType: not null }); // error CS0721: '{0}': static types cannot be used as parameters diagnostics.Add( ErrorFacts.GetStaticClassParameterCode(parameter.ContainingSymbol.ContainingType?.IsInterfaceType() ?? false), owner.Locations.IsEmpty ? parameterSyntax.GetLocation() : owner.Locations[0], parameter.Type); } else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams) { // error CS1737: Optional parameters must appear after all required parameters Location loc = ((ParameterSyntax)(BaseParameterSyntax)parameterSyntax).Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc); } else if (parameter.RefKind != RefKind.None && parameter.TypeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true)) { // CS1601: Cannot make reference to variable of type 'System.TypedReference' diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type); } } internal static bool ReportDefaultParameterErrors( Binder binder, Symbol owner, ParameterSyntax parameterSyntax, SourceParameterSymbol parameter, BoundExpression defaultExpression, BoundExpression convertedExpression, BindingDiagnosticBag diagnostics) { bool hasErrors = false; // SPEC VIOLATION: The spec says that the conversion from the initializer to the // parameter type is required to be either an identity or a nullable conversion, but // that is not right: // // void M(short myShort = 10) {} // * not an identity or nullable conversion but should be legal // // void M(object obj = (dynamic)null) {} // * an identity conversion, but should be illegal // // void M(MyStruct? myStruct = default(MyStruct)) {} // * a nullable conversion, but must be illegal because we cannot generate metadata for it // // Even if the expression is thoroughly illegal, we still want to bind it and // stick it in the parameter because we want to be able to analyze it for // IntelliSense purposes. TypeSymbol parameterType = parameter.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteInfo); diagnostics.Add(defaultExpression.Syntax, useSiteInfo); var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); // CONSIDER: We are inconsistent here regarding where the error is reported; is it // CONSIDER: reported on the parameter name, or on the value of the initializer? // CONSIDER: Consider making this consistent. if (refKind == RefKind.Ref || refKind == RefKind.Out) { // error CS1741: A ref or out parameter cannot have a default value diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation()); hasErrors = true; } else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword) { // error CS1751: Cannot specify a default value for a parameter array diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation()); hasErrors = true; } else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword) { // Only need to report CS1743 for the first parameter. The caller will // have reported CS1100 if 'this' appeared on another parameter. if (parameter.Ordinal == 0) { // error CS1743: Cannot specify a default value for the 'this' parameter diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation()); hasErrors = true; } } else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression)) { // error CS1736: Default parameter value for '{0}' must be a compile-time constant diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText); hasErrors = true; } else if (!conversion.Exists || conversion.IsUserDefined || conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic()) { // If we had no implicit conversion, or a user-defined conversion, report an error. // // Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it. // CONSIDER: We could. Doesn't hurt anything. // error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}' diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Display, parameterType); hasErrors = true; } else if (conversion.IsReference && (object)defaultExpression.Type != null && defaultExpression.Type.SpecialType == SpecialType.System_String || conversion.IsBoxing) { // We don't allow object x = "hello", object x = 123, dynamic x = "hello", IEnumerable<char> x = "hello", etc. // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText, parameterType); hasErrors = true; } else if (((conversion.IsNullable && !defaultExpression.Type.IsNullableType()) || (conversion.IsObjectCreation && convertedExpression.Type.IsNullableType())) && !(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType())) { // We can do: // M(int? x = default(int)) // M(int? x = default(int?)) // M(MyEnum? e = default(enum)) // M(MyEnum? e = default(enum?)) // M(MyStruct? s = default(MyStruct?)) // // but we cannot do: // // M(MyStruct? s = default(MyStruct)) // error CS1770: // A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(), (defaultExpression.IsImplicitObjectCreation() ? convertedExpression.Type.StrippedType() : defaultExpression.Type), parameterSyntax.Identifier.ValueText); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics); // Certain contexts allow default parameter values syntactically but they are ignored during // semantic analysis. They are: // 1. Explicitly implemented interface methods; since the method will always be called // via the interface, the defaults declared on the implementation will not // be seen at the call site. // // UNDONE: 2. The "actual" side of a partial method; the default values are taken from the // UNDONE: "declaring" side of the method. // // UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument // UNDONE: to an indexer. // // 4. A user-defined operator; it is syntactically impossible to omit the argument. if (owner.IsExplicitInterfaceImplementation() || owner.IsPartialImplementation() || owner.IsOperator()) { // CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText); } return hasErrors; } private static bool IsValidDefaultValue(BoundExpression expression) { // SPEC VIOLATION: // By the spec an optional parameter initializer is required to be either: // * a constant, // * new S() where S is a value type // * default(S) where S is a value type. // // The native compiler considers default(T) to be a valid // initializer regardless of whether T is a value type // reference type, type parameter type, and so on. // We should consider simply allowing this in the spec. // // Also when valuetype S has a parameterless constructor, // new S() is clearly not a constant expression and should produce an error if (expression.ConstantValue != null) { return true; } switch (expression.Kind) { case BoundKind.DefaultLiteral: case BoundKind.DefaultExpression: return true; case BoundKind.ObjectCreationExpression: return IsValidDefaultValue((BoundObjectCreationExpression)expression); case BoundKind.Conversion: var conversion = (BoundConversion)expression; return conversion is { Conversion.IsObjectCreation: true, Operand: BoundObjectCreationExpression { WasTargetTyped: true } operand } && IsValidDefaultValue(operand); default: return false; } } private static bool IsValidDefaultValue(BoundObjectCreationExpression expression) { return expression.Constructor.IsDefaultValueTypeConstructor() && expression.InitializerExpressionOpt == null; } internal static MethodSymbol FindContainingGenericMethod(Symbol symbol) { for (Symbol current = symbol; (object)current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Method) { MethodSymbol method = (MethodSymbol)current; if (method.MethodKind != MethodKind.AnonymousFunction) { return method.IsGenericMethod ? method : null; } } } return null; } private static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword) { var refKind = RefKind.None; refnessKeyword = default(SyntaxToken); paramsKeyword = default(SyntaxToken); thisKeyword = default(SyntaxToken); foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.OutKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Out; } break; case SyntaxKind.RefKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.Ref; } break; case SyntaxKind.InKeyword: if (refKind == RefKind.None) { refnessKeyword = modifier; refKind = RefKind.In; } break; case SyntaxKind.ParamsKeyword: paramsKeyword = modifier; break; case SyntaxKind.ThisKeyword: thisKeyword = modifier; break; } } return refKind; } // https://github.com/dotnet/roslyn/issues/58335: consider whether we should adjust the set of locations where we call this internal static void ReportParameterNullCheckingErrors(DiagnosticBag diagnostics, ParameterSymbol parameter) { if (!parameter.IsNullChecked) { return; } Location location = parameter.Locations.FirstOrNone(); // https://github.com/dotnet/roslyn/issues/58335: can we simplify with the other overload? if (Binder.GetWellKnownTypeMember(parameter.DeclaringCompilation, WellKnownMember.System_ArgumentNullException__ctorString, out UseSiteInfo<AssemblySymbol> useSiteInfo) is null) { diagnostics.Add(useSiteInfo.DiagnosticInfo, location); } if (parameter.IsDiscard) { diagnostics.Add(ErrorCode.ERR_DiscardCannotBeNullChecked, location); } var annotations = parameter.FlowAnalysisAnnotations; if ((annotations & FlowAnalysisAnnotations.NotNull) == 0 && NullableWalker.GetParameterState(parameter.TypeWithAnnotations, annotations, applyParameterNullCheck: false).State.MayBeNull() && !isTypeParameterWithPossiblyNonNullableType(parameter.TypeWithAnnotations, annotations)) { diagnostics.Add(ErrorCode.WRN_NullCheckingOnNullableType, location, parameter); } if (parameter.Type.IsNonNullableValueType() && !parameter.Type.IsPointerOrFunctionPointer()) { diagnostics.Add(ErrorCode.ERR_NonNullableValueTypeIsNullChecked, location, parameter); } // For type parameters, we only want to give the warning if no type argument would result in a non-nullable type. static bool isTypeParameterWithPossiblyNonNullableType(TypeWithAnnotations typeWithAnnotations, FlowAnalysisAnnotations annotations) { if (!typeWithAnnotations.Type.IsTypeParameter()) { return false; } // We avoid checking the nullable annotations, etc. of constraints due to implementation complexity, // and consider it acceptable to miss "!! on nullable type" warnings in scenarios like `void M<T, U>(U u!!) where U : T?`. if (typeWithAnnotations.NullableAnnotation.IsAnnotated()) { return false; } // `void M<T>([AllowNull] T t!!)` if ((annotations & FlowAnalysisAnnotations.AllowNull) != 0) { return false; } return true; } } internal static ImmutableArray<CustomModifier> ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (addRefReadOnlyModifier && refKind == RefKind.In) { return CreateInModifiers(binder, diagnostics, syntax); } else { return ImmutableArray<CustomModifier>.Empty; } } internal static ImmutableArray<CustomModifier> CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_InAttribute, binder, diagnostics, syntax); } internal static ImmutableArray<CustomModifier> CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { return CreateModifiers(WellKnownType.System_Runtime_InteropServices_OutAttribute, binder, diagnostics, syntax); } private static ImmutableArray<CustomModifier> CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { var modifierType = binder.GetWellKnownType(modifier, diagnostics, syntax); return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)); } } }
50.276451
241
0.573552
[ "MIT" ]
CryoMyst/roslyn
src/Compilers/CSharp/Portable/Symbols/Source/ParameterHelpers.cs
44,195
C#
using System; using UnityEngine; using System.Collections; using System.Linq; [CreateAssetMenu(fileName = "Hats Data")] public class HatsData : ScriptableObject { [Serializable] public struct Hat { public string Name; public GameObject Prefab; public Sprite Icon; } [SerializeField] public Hat[] Hats; public GameObject GetPrefab(string name) { return Hats.FirstOrDefault(h => h.Name == name).Prefab; } public Hat GetHat(string name) { return Hats.FirstOrDefault(h => h.Name == name); } }
19.4
63
0.639175
[ "Apache-2.0" ]
bshishov/LudumDare36
Assets/Scripts/Data/HatsData.cs
584
C#
namespace Npgsql6.Tests; public class Npgsql6DbFactoryFixture : IDbFactoryFixture { public DbProviderFactory Factory => NpgsqlFactory.Instance; public string ConnectionString => "host=localhost;user id=root;password=test;database=npgsql6"; }
30.625
96
0.820408
[ "MIT" ]
mysql-net/AdoNetApiTest
tests/Npgsql6.Tests/Npgsql6DbFactoryFixture.cs
245
C#
using System.Runtime.Serialization; namespace MbDotNet.Enums { public enum ProxyMode { [EnumMember(Value = "proxyOnce")] ProxyOnce, [EnumMember(Value = "proxyAlways")] ProxyAlways, [EnumMember(Value = "proxyTransparent")] ProxyTransparent } }
19
49
0.585139
[ "MIT" ]
DraKOCDS/MbDotNet
MbDotNet/Enums/ProxyMode.cs
325
C#
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 OWNER 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ namespace MatterHackers.MatterControl.PartPreviewWindow { public class HelpSearchResult { public string Name { get; set; } public string Path { get; set; } } }
44.736842
79
0.802353
[ "BSD-2-Clause" ]
Bhalddin/MatterControl
MatterControlLib/PartPreviewWindow/HelpSearchResult.cs
1,702
C#
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; using BehaviorsTestApplication.Views; namespace BehaviorsTestApplication { public class App : Application { public override void Initialize() { AvaloniaXamlLoader.Load(this); } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktopLifetime) { desktopLifetime.MainWindow = new MainWindow(); } else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewLifetime) { singleViewLifetime.MainView = new MainView(); } base.OnFrameworkInitializationCompleted(); } } }
31.09375
104
0.666332
[ "MIT" ]
jp2masa/AvaloniaBehaviors
samples/BehaviorsTestApplication/App.xaml.cs
1,000
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Navigation; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratedFileItem : BaseItem { private readonly IThreadingContext _threadingContext; private readonly string _languageName; public SourceGeneratedFileItem( IThreadingContext threadingContext, DocumentId documentId, string hintName, string languageName, Workspace workspace) : base(name: hintName) { _threadingContext = threadingContext; DocumentId = documentId; HintName = hintName; _languageName = languageName; Workspace = workspace; } public DocumentId DocumentId { get; } public string HintName { get; } public Workspace Workspace { get; } public override ImageMoniker IconMoniker => _languageName switch { LanguageNames.CSharp => KnownMonikers.CSFileNode, LanguageNames.VisualBasic => KnownMonikers.VBFileNode, _ => KnownMonikers.Document }; public override object GetBrowseObject() { return new BrowseObject(this); } public override IInvocationController InvocationController => new InvocationControllerImpl(_threadingContext); private sealed class InvocationControllerImpl : IInvocationController { private readonly IThreadingContext _threadingContext; public InvocationControllerImpl(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public bool Invoke(IEnumerable<object> items, InputSource inputSource, bool preview) { return _threadingContext.JoinableTaskFactory.Run(async () => { var didNavigate = false; foreach (var item in items.OfType<SourceGeneratedFileItem>()) { var documentNavigationService = item.Workspace.Services.GetService<IDocumentNavigationService>(); if (documentNavigationService != null) { // TODO: we're navigating back to the top of the file, do we have a way to just bring it to the focus and that's it? // TODO: Use a threaded-wait-dialog here so we can cancel navigation. didNavigate |= await documentNavigationService.TryNavigateToPositionAsync( item._threadingContext, item.Workspace, item.DocumentId, position: 0, CancellationToken.None).ConfigureAwait(false); } } return didNavigate; }); } } } }
39.033708
148
0.621474
[ "MIT" ]
AlexanderSemenyak/roslyn
src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItem.cs
3,476
C#
// <auto-generated /> using System; using CodeFirstMigration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; #nullable disable namespace CodeFirstMigration.Migrations { [DbContext(typeof(CustomerContext))] [Migration("20220401210459_InitialCreate")] partial class InitialCreate { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "6.0.3") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); modelBuilder.Entity("CodeFirstMigration.Customer", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Address") .HasColumnType("nvarchar(max)"); b.Property<int>("Age") .HasColumnType("int"); b.Property<string>("CardNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("FirstName") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Customers"); }); #pragma warning restore 612, 618 } } }
31.678571
84
0.580045
[ "MIT" ]
AhmedJoum/CodeMazeGuides
dotnet-efcore/DotnetEfNotFoundError/CodeFirstMigration/Migrations/20220401210459_InitialCreate.Designer.cs
1,776
C#
using System; using AeroGear.Mobile.Auth.Credentials; namespace Auth.Tests.Storage { public class MockCredential : ICredential { public MockCredential() { } public string AccessToken => "testAccessToken"; public string IdentityToken => "testIdentityToken"; public string RefreshToken => "testRefreshToken"; public bool IsAuthorized => true; public bool IsExpired => false; public string SerializedCredential => "testSerialized"; } }
21
63
0.651429
[ "Apache-2.0" ]
aerogear/aerogear-xamarin-sdk
Auth/Auth.Tests/Storage/MockCredential.cs
527
C#
using System; using System.Runtime.Serialization; using Volo.Abp; namespace Abp.Elasticsearch { /// <summary> /// ElasticSearch Exception /// </summary> public class ElasticSearchException : AbpException { /// <summary> /// Constructor. /// </summary> public ElasticSearchException() { } /// <summary> /// Constructor for serializing. /// </summary> public ElasticSearchException(SerializationInfo serializationInfo, StreamingContext context) : base(serializationInfo, context) { } /// <summary> /// Constructor. /// </summary> /// <param name="message">Exception message</param> public ElasticSearchException(string message) : base(message) { } /// <summary> /// Constructor. /// </summary> /// <param name="message">Exception message</param> /// <param name="innerException">Inner exception</param> public ElasticSearchException(string message, Exception innerException) : base(message, innerException) { } } }
23.94
100
0.561404
[ "MIT" ]
Meowv/Abp.Elasticsearch
src/Abp.Elasticsearch/ElasticSearchException.cs
1,199
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.Relay.V20180101Preview { public static class GetNamespace { /// <summary> /// Description of a namespace resource. /// </summary> public static Task<GetNamespaceResult> InvokeAsync(GetNamespaceArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetNamespaceResult>("azure-native:relay/v20180101preview:getNamespace", args ?? new GetNamespaceArgs(), options.WithVersion()); } public sealed class GetNamespaceArgs : Pulumi.InvokeArgs { /// <summary> /// The namespace name /// </summary> [Input("namespaceName", required: true)] public string NamespaceName { get; set; } = null!; /// <summary> /// Name of the Resource group within the Azure subscription. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetNamespaceArgs() { } } [OutputType] public sealed class GetNamespaceResult { /// <summary> /// The time the namespace was created. /// </summary> public readonly string CreatedAt; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// Resource location. /// </summary> public readonly string Location; /// <summary> /// Identifier for Azure Insights metrics. /// </summary> public readonly string MetricId; /// <summary> /// Resource name. /// </summary> public readonly string Name; public readonly string ProvisioningState; /// <summary> /// Endpoint you can use to perform Service Bus operations. /// </summary> public readonly string ServiceBusEndpoint; /// <summary> /// SKU of the namespace. /// </summary> public readonly Outputs.SkuResponse? Sku; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; /// <summary> /// The time the namespace was updated. /// </summary> public readonly string UpdatedAt; [OutputConstructor] private GetNamespaceResult( string createdAt, string id, string location, string metricId, string name, string provisioningState, string serviceBusEndpoint, Outputs.SkuResponse? sku, ImmutableDictionary<string, string>? tags, string type, string updatedAt) { CreatedAt = createdAt; Id = id; Location = location; MetricId = metricId; Name = name; ProvisioningState = provisioningState; ServiceBusEndpoint = serviceBusEndpoint; Sku = sku; Tags = tags; Type = type; UpdatedAt = updatedAt; } } }
28.456
181
0.568175
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Relay/V20180101Preview/GetNamespace.cs
3,557
C#
using System.Threading.Tasks; namespace ServerlessBlog.Runtime { public interface IWebPageComposer { Task<string> GetHomepage(); Task<string> GetPost(string urlName); Task<string> GetArchive(int year, int month); Task<string> GetCategory(string category); } }
19.3125
53
0.669903
[ "MIT" ]
JamesRandall/AzureFromTheTrenches.ServerlessBlog
ServerlessBlog.Runtime/IWebPageComposer.cs
311
C#
namespace WhoKilledCamelCase.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
30.777778
67
0.750903
[ "MIT" ]
jorupp/WhoKilledCamelCase
WhoKilledCamelCase/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
277
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; namespace AdaptiveCards.Rendering.Wpf { /// <summary> /// Context state for a render pass /// </summary> public class AdaptiveRenderContext { private readonly Dictionary<string, SolidColorBrush> _colors = new Dictionary<string, SolidColorBrush>(); public List<Task> AssetTasks { get; } = new List<Task>(); public AdaptiveRenderContext(Action<object, AdaptiveActionEventArgs> actionCallback, Action<object, MissingInputEventArgs> missingDataCallback, Action<object, AdaptiveMediaEventArgs> mediaClickCallback) { if (actionCallback != null) OnAction += (obj, args) => actionCallback(obj, args); if (missingDataCallback != null) OnMissingInput += (obj, args) => missingDataCallback(obj, args); if (mediaClickCallback != null) OnMediaClick += (obj, args) => mediaClickCallback(obj, args); } public AdaptiveHostConfig Config { get; set; } = new AdaptiveHostConfig(); public IList<AdaptiveWarning> Warnings { get; } = new List<AdaptiveWarning>(); public AdaptiveElementRenderers<FrameworkElement, AdaptiveRenderContext> ElementRenderers { get; set; } public ResourceDictionary Resources { get; set; } public AdaptiveActionHandlers ActionHandlers { get; set; } public AdaptiveFeatureRegistration FeatureRegistration { get; set; } public ResourceResolver ResourceResolvers { get; set; } public bool IsRenderingSelectAction { get; set; } public IDictionary<Uri, MemoryStream> CardAssets { get; set; } = new Dictionary<Uri, MemoryStream>(); public IDictionary<string, Func<string>> InputBindings = new Dictionary<string, Func<string>>(); public event EventHandler<AdaptiveActionEventArgs> OnAction; public event EventHandler<AdaptiveMediaEventArgs> OnMediaClick; /// <summary> /// Event fires when missing input for submit/http actions /// </summary> public event EventHandler<MissingInputEventArgs> OnMissingInput; public void InvokeAction(FrameworkElement ui, AdaptiveActionEventArgs args) { // ToggleVisibility is a renderer-handled action if (args.Action is AdaptiveToggleVisibilityAction toggleVisibilityAction) { ToggleVisibility(toggleVisibilityAction.TargetElements); return; } else if (args.Action is AdaptiveShowCardAction && Config.Actions.ShowCard.ActionMode == ShowCardActionMode.Inline) { ToggleShowCardVisibility((Button)ui); return; } else if (args.Action is AdaptiveSubmitAction) { var submitAction = (args.Action as AdaptiveSubmitAction); if (submitAction.AssociatedInputs == AdaptiveAssociatedInputs.Auto) { if (!ValidateInputs(submitAction)) { return; } } } else if (args.Action is AdaptiveExecuteAction) { var executeAction = (args.Action as AdaptiveExecuteAction); if (executeAction.AssociatedInputs == AdaptiveAssociatedInputs.Auto) { if (!ValidateInputs(executeAction)) { return; } } } OnAction?.Invoke(ui, args); } public void MissingInput(AdaptiveAction sender, MissingInputEventArgs args) { OnMissingInput?.Invoke(sender, args); } public void ClickMedia(FrameworkElement ui, AdaptiveMediaEventArgs args) { OnMediaClick?.Invoke(ui, args); } /// <summary> /// All remote assets should be resolved through this method for tracking /// </summary> public async Task<BitmapImage> ResolveImageSource(Uri url) { var completeTask = new TaskCompletionSource<object>(); AssetTasks.Add(completeTask.Task); try { // Load the stream from the pre-populated CardAssets or try to load from the ResourceResolver var streamTask = CardAssets.TryGetValue(url, out var s) ? Task.FromResult(s) : ResourceResolvers.LoadAssetAsync(url); Debug.WriteLine($"ASSETS: Starting asset down task for {url}"); var source = new BitmapImage(); var stream = await streamTask; if (stream != null) { stream.Position = 0; source.BeginInit(); source.CacheOption = BitmapCacheOption.OnLoad; source.StreamSource = stream; source.EndInit(); Debug.WriteLine($"ASSETS: Finished loading asset for {url} ({stream.Length} bytes)"); } completeTask.SetResult(new object()); return source; } catch (Exception e) { Debug.WriteLine($"ASSETS: Failed to load asset for {url}. {e.Message}"); completeTask.SetException(e); return null; } } public SolidColorBrush GetColorBrush(string color) { lock (_colors) { if (_colors.TryGetValue(color, out var brush)) return brush; brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)); _colors[color] = brush; return brush; } } // This dictionary exists for setting the ids to elements without messing with the Name property to avoid crashes with weird ids internal IDictionary<string, FrameworkElement> RenderedElementsWithId = new Dictionary<string, FrameworkElement>(); public IDictionary<Button, FrameworkElement> ActionShowCards = new Dictionary<Button, FrameworkElement>(); // contains showcard peers in actions set, and the AdaptiveInternalID is internal id of the actions set public IDictionary<AdaptiveInternalID, List<FrameworkElement>> PeerShowCardsInActionSet = new Dictionary<AdaptiveInternalID, List<FrameworkElement>>(); public virtual Style GetStyle(string styleName) { while (!String.IsNullOrEmpty(styleName)) { Style style = this.Resources.TryGetValue<Style>(styleName); if (style != null) return style; var iPos = styleName.LastIndexOf('.'); if (iPos <= 0) break; styleName = styleName.Substring(0, iPos); } // Debug.WriteLine($"Unable to find Style {styleName} from the supplied ResourceDictionary"); return null; } public AdaptiveTypedElement GetRendereableElement(AdaptiveTypedElement element) { AdaptiveTypedElement rendereableElement = null; var oldAncestorHasFallback = AncestorHasFallback; var elementHasFallback = element != null && element.Fallback != null && (element.Fallback.Type != AdaptiveFallbackElement.AdaptiveFallbackType.None); AncestorHasFallback = AncestorHasFallback || elementHasFallback; try { if (AncestorHasFallback && !element.MeetsRequirements(FeatureRegistration)) { throw new AdaptiveFallbackException("Element requirements aren't met"); } var renderer = ElementRenderers.Get(element.GetType()); if (renderer != null) { rendereableElement = element; } } catch (AdaptiveFallbackException) { if (!elementHasFallback) { throw; } } if (rendereableElement == null) { // Since no renderer exists for this element, add warning and render fallback (if available) if (element.Fallback != null && element.Fallback.Type != AdaptiveFallbackElement.AdaptiveFallbackType.None) { if (element.Fallback.Type == AdaptiveFallbackElement.AdaptiveFallbackType.Drop) { Warnings.Add(new AdaptiveWarning(-1, $"Dropping element '{element.Type}' for fallback")); } else if (element.Fallback.Type == AdaptiveFallbackElement.AdaptiveFallbackType.Content && element.Fallback.Content != null) { // Render fallback content Warnings.Add(new AdaptiveWarning(-1, $"Performing fallback for '{element.Type}' (fallback element type '{element.Fallback.Content.Type}')")); RenderingFallback = true; rendereableElement = GetRendereableElement(element.Fallback.Content); RenderingFallback = false; } } else if (AncestorHasFallback && !RenderingFallback) { throw new AdaptiveFallbackException(); } else { Warnings.Add(new AdaptiveWarning(-1, $"No renderer for element '{element.Type}'")); } } AncestorHasFallback = oldAncestorHasFallback; return rendereableElement; } /// <summary> /// Helper to deal with casting /// </summary> public FrameworkElement Render(AdaptiveTypedElement element) { FrameworkElement frameworkElementOut = null; var oldAncestorHasFallback = AncestorHasFallback; var elementHasFallback = element != null && element.Fallback != null && (element.Fallback.Type != AdaptiveFallbackElement.AdaptiveFallbackType.None); AncestorHasFallback = AncestorHasFallback || elementHasFallback; try { if (AncestorHasFallback && !element.MeetsRequirements(FeatureRegistration)) { throw new AdaptiveFallbackException("Element requirements aren't met"); } // Inputs should render read-only if interactivity is false if (!Config.SupportsInteractivity && element is AdaptiveInput input) { var tb = AdaptiveTypedElementConverter.CreateElement<AdaptiveTextBlock>(); tb.Text = input.GetNonInteractiveValue() ?? "*[Input]*"; tb.Color = AdaptiveTextColor.Accent; tb.Wrap = true; InputValues.Add(input.Id, null); Warnings.Add(new AdaptiveWarning(-1, $"Rendering non-interactive input element '{element.Type}'")); frameworkElementOut = Render(tb); } if (frameworkElementOut == null) { var renderer = ElementRenderers.Get(element.GetType()); if (renderer != null) { var rendered = renderer.Invoke(element, this); if (!String.IsNullOrEmpty(element.Id)) { // The element is added to the dictionary if it's an action or if it's a card element and the height is auto // as stretch items are enclosed in a panel that is added in AdaptiveContainerRenderer.AddContainerElements if (!(element is AdaptiveElement) || (element is AdaptiveElement adaptiveElement && adaptiveElement.Height == AdaptiveHeight.Auto)) { RenderedElementsWithId.Add(element.Id, rendered); } } frameworkElementOut = rendered; } } } catch (AdaptiveFallbackException) { if (!elementHasFallback) { throw; } } // If a container failed to render any of the children elements perform fallback if (frameworkElementOut == null && (element is AdaptiveCollectionElement)) { if (element.Fallback != null && element.Fallback.Type != AdaptiveFallbackElement.AdaptiveFallbackType.None) { if (element.Fallback.Type == AdaptiveFallbackElement.AdaptiveFallbackType.Drop) { Warnings.Add(new AdaptiveWarning(-1, $"Dropping element '{element.Type}' for fallback")); } else if (element.Fallback.Type == AdaptiveFallbackElement.AdaptiveFallbackType.Content && element.Fallback.Content != null) { // Render fallback content Warnings.Add(new AdaptiveWarning(-1, $"Performing fallback for '{element.Type}' (fallback element type '{element.Fallback.Content.Type}')")); RenderingFallback = true; frameworkElementOut = Render(element.Fallback.Content); RenderingFallback = false; } } else if (AncestorHasFallback && !RenderingFallback) { throw new AdaptiveFallbackException(); } else { Warnings.Add(new AdaptiveWarning(-1, $"No renderer for element '{element.Type}'")); } } AncestorHasFallback = oldAncestorHasFallback; return frameworkElementOut; } private bool AncestorHasFallback = false; private bool RenderingFallback = false; public string Lang { get; set; } public FrameworkElement CardRoot { get; set; } public AdaptiveRenderArgs RenderArgs { get; set; } public FontColorConfig GetForegroundColors(AdaptiveTextColor textColor) { switch (textColor) { case AdaptiveTextColor.Accent: return RenderArgs.ForegroundColors.Accent; case AdaptiveTextColor.Attention: return RenderArgs.ForegroundColors.Attention; case AdaptiveTextColor.Dark: return RenderArgs.ForegroundColors.Dark; case AdaptiveTextColor.Good: return RenderArgs.ForegroundColors.Good; case AdaptiveTextColor.Light: return RenderArgs.ForegroundColors.Light; case AdaptiveTextColor.Warning: return RenderArgs.ForegroundColors.Warning; case AdaptiveTextColor.Default: default: return RenderArgs.ForegroundColors.Default; } } /// <summary> /// Casts framework element to a TagContent element /// </summary> /// <param name="element">Rendered element that contains tag</param> /// <returns>Casted tag content</returns> private TagContent GetTagContent(FrameworkElement element) { if ((element != null) && (element.Tag != null) && (element.Tag is TagContent tagContent)) { return tagContent; } return null; } /// <summary> /// Changes the visibility of the specified elements as defined /// </summary> /// <param name="targetElements">Taget elements to change visibility</param> public void ToggleVisibility(IEnumerable<AdaptiveTargetElement> targetElements) { HashSet<Grid> elementContainers = new HashSet<Grid>(); foreach (AdaptiveTargetElement targetElement in targetElements) { var element = RenderedElementsWithId[targetElement.ElementId]; if (element != null && element is FrameworkElement elementFrameworkElement) { bool isCurrentlyVisible = (elementFrameworkElement.Visibility == Visibility.Visible); // if we read something with the format {"elementId": <id>", "isVisible": true} or // we just read the id and the element is not visible; // otherwise if we read something with the format {"elementId": <id>", "isVisible": false} or // we just read the id and the element is visible bool newVisibility = (targetElement.IsVisible.HasValue && targetElement.IsVisible.Value) || (!targetElement.IsVisible.HasValue && !isCurrentlyVisible); TagContent tagContent = GetTagContent(elementFrameworkElement); RendererUtil.SetVisibility(elementFrameworkElement, newVisibility, tagContent); if (tagContent != null) { elementContainers.Add(tagContent.ParentContainerElement); } } } foreach (Grid elementContainer in elementContainers) { ResetSeparatorVisibilityInsideContainer(elementContainer); } } /// <summary> /// Gets the actual rendered element as elements with 'stretch' height are contained inside a StackPanel /// </summary> /// <param name="element">Element or StackPanel that contains rendered element</param> /// <returns>Actual rendered element</returns> private FrameworkElement GetRenderedElement(FrameworkElement element) { if (element is StackPanel containerPanel) { UIElement uiElement = containerPanel.Children[0]; if (uiElement is FrameworkElement frameworkElement) { return frameworkElement; } } return element; } private void HandleSeparatorAndSpacing(bool isFirstVisible, FrameworkElement element, TagContent tagContent) { // Hide the spacing / separator for the first element // Separators and spacings are added as a grid Grid separator = tagContent.Separator; if (separator != null) { separator.Visibility = isFirstVisible ? Visibility.Collapsed : Visibility.Visible; } } /// <summary> /// Hides the first separator and fixes the visibility for the other visible separators /// </summary> /// <param name="uiContainer">Renderered element container</param> public void ResetSeparatorVisibilityInsideContainer(Grid uiContainer) { bool isFirstVisible = true; foreach (FrameworkElement element in uiContainer.Children) { if (element.Visibility == Visibility.Visible) { TagContent tagContent = GetTagContent(element); if (tagContent != null) { HandleSeparatorAndSpacing(isFirstVisible, element, tagContent); isFirstVisible = false; } } } } public void ToggleShowCardVisibility(Button uiAction) { FrameworkElement card = ActionShowCards[uiAction]; var id = uiAction.GetContext() as AdaptiveInternalID; if (id == null) { Warnings.Add(new AdaptiveWarning(-1, $"Toggling visibility event handling is dropped " + $"since the action set the button belongs to has null internal id")); return; } var peers = PeerShowCardsInActionSet[id]; if (card != null && peers != null) { var targetVisibility = card.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible; // need to make sure we collapse all showcards before showing this one foreach (var showCard in peers) { showCard.Visibility = Visibility.Collapsed; } card.Visibility = targetVisibility; } } private bool ValidateInputs(AdaptiveAction submitAction) { bool allInputsValid = true, firstInvalidInputFound = false; Dictionary<string, Func<string>> newInputBindings = new Dictionary<string, Func<string>>(); // We clear the InputBindings collection to clear all the results InputBindings.Clear(); List<string> inputsToValidate = RetrieveInputList(submitAction); // Iterate through all the elements and validate them foreach (string inputId in inputsToValidate) { AdaptiveInputValue inputValue = InputValues[inputId]; bool inputIsValid = inputValue.Validate(); allInputsValid = allInputsValid && inputIsValid; // If the validation failed, set focus to the first element that failed if (!allInputsValid && !firstInvalidInputFound) { inputValue.SetFocus(); firstInvalidInputFound = true; } inputValue.ChangeVisualCueVisibility(inputIsValid); // Add the input value to the inputs bindings newInputBindings.Add(inputId, () => inputValue.GetValue()); } // If the validation succeeded, then copy the result to the InputBindings if (allInputsValid) { foreach (string key in newInputBindings.Keys) { InputBindings.Add(key, newInputBindings[key]); } } return allInputsValid; } private List<string> RetrieveInputList(AdaptiveAction submitAction) { List<string> inputList = new List<string>(); AdaptiveInternalID submitActionCardId = SubmitActionCardId[submitAction]; // While the card is not the main card, iterate through them // It's important to note that as we go from deep most upwards then we have to add the // inputs at the begining of the list to focus on the first one on validation while (!submitActionCardId.Equals(new AdaptiveInternalID())) { // Copy the inputs into the result if (InputsInCard.ContainsKey(submitActionCardId)) { inputList.InsertRange(0, InputsInCard[submitActionCardId]); } // Move to the parent card submitActionCardId = ParentCards[submitActionCardId]; } return inputList; } public void AddInputToCard(AdaptiveInternalID cardId, string inputId) { if (!InputsInCard.ContainsKey(cardId)) { InputsInCard.Add(cardId, new List<string>()); } InputsInCard[cardId].Add(inputId); } // Dictionary where all the parent cards point to their parent cards, the parent for the main card must have ID = Invalid public Dictionary<AdaptiveInternalID, AdaptiveInternalID> ParentCards { get; set; } = new Dictionary<AdaptiveInternalID, AdaptiveInternalID>(); // Dictionary where we tie every Action.Submit or Action.Exectute to the card where it is contained, this help us knowing where should we start validating from public Dictionary<AdaptiveAction, AdaptiveInternalID> SubmitActionCardId { get; set; } = new Dictionary<AdaptiveAction, AdaptiveInternalID>(); // Dictionary where we tie every input.Id (string) with the card internal Id private Dictionary<AdaptiveInternalID, List<string>> InputsInCard = new Dictionary<AdaptiveInternalID, List<string>>(); public Dictionary<string, AdaptiveInputValue> InputValues = new Dictionary<string, AdaptiveInputValue>(); } }
41.96
167
0.569471
[ "MIT" ]
AdrianaDJ/AdaptiveCards
source/dotnet/Library/AdaptiveCards.Rendering.Wpf/AdaptiveRenderContext.cs
25,176
C#
namespace Universidad { class Tamano { int largo; int ancho; public Tamano(int largo, int ancho) { this.largo = largo; this.ancho = ancho; } } }
15.857143
43
0.463964
[ "Apache-2.0" ]
antoanio/programacionIIIaap
Universidad/Universidad/Tamano.cs
224
C#
namespace KclLibraryGUI { partial class MaterialCollisionPicker { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.listView1 = new System.Windows.Forms.ListView(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); this.SuspendLayout(); // // listView1 // this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader3, this.columnHeader2}); this.listView1.FullRowSelect = true; this.listView1.HideSelection = false; this.listView1.Location = new System.Drawing.Point(6, 30); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(506, 393); this.listView1.TabIndex = 0; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged); // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(230, 3); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(228, 21); this.comboBox1.TabIndex = 1; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // columnHeader1 // this.columnHeader1.Text = "Material"; this.columnHeader1.Width = 204; // // columnHeader2 // this.columnHeader2.Text = "Type"; this.columnHeader2.Width = 200; // // numericUpDown1 // this.numericUpDown1.Location = new System.Drawing.Point(58, 4); this.numericUpDown1.Maximum = new decimal(new int[] { 65535, 0, 0, 0}); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(120, 20); this.numericUpDown1.TabIndex = 2; this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); // // columnHeader3 // this.columnHeader3.Text = "ID"; this.columnHeader3.Width = 114; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(7, 6); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(21, 13); this.label1.TabIndex = 3; this.label1.Text = "ID:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(184, 6); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 13); this.label2.TabIndex = 4; this.label2.Text = "Preset:"; // // MaterialCollisionPicker // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.numericUpDown1); this.Controls.Add(this.comboBox1); this.Controls.Add(this.listView1); this.Name = "MaterialCollisionPicker"; this.Size = new System.Drawing.Size(512, 426); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; } }
42.848276
157
0.585225
[ "MIT" ]
KillzXGaming/KCollisionLibrary
KclLibraryGUI/MaterialSelection/MaterialCollisionPicker.Designer.cs
6,215
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.Cache.V20150801.Outputs { [OutputType] public sealed class RedisAccessKeysResponse { /// <summary> /// The current primary key that clients can use to authenticate with Redis cache. /// </summary> public readonly string? PrimaryKey; /// <summary> /// The current secondary key that clients can use to authenticate with Redis cache. /// </summary> public readonly string? SecondaryKey; [OutputConstructor] private RedisAccessKeysResponse( string? primaryKey, string? secondaryKey) { PrimaryKey = primaryKey; SecondaryKey = secondaryKey; } } }
28.722222
92
0.647969
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Cache/V20150801/Outputs/RedisAccessKeysResponse.cs
1,034
C#
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System.Collections.Generic; using Encog.ML.EA.Codec; using Encog.ML.EA.Genome; using Encog.ML.EA.Opp; using Encog.ML.EA.Opp.Selection; using Encog.ML.EA.Population; using Encog.ML.EA.Rules; using Encog.ML.EA.Score; using Encog.ML.EA.Sort; using Encog.ML.EA.Species; using Encog.Neural.Networks.Training; namespace Encog.ML.EA.Train { /// <summary> /// This interface defines the basic functionality of an Evolutionary Algorithm. /// An evolutionary algorithm is one that applies operations to a population of /// potential "solutions". /// </summary> public interface IEvolutionaryAlgorithm { /// <summary> /// Get the comparator that is used to choose the "true best" genome. This /// uses the real score, and not the adjusted score. /// </summary> IGenomeComparer BestComparer { get; set; } /// <summary> /// The current best genome. This genome is safe to use while the EA /// is running. Genomes are not modified. They simply produce /// "offspring". /// </summary> IGenome BestGenome { get; } /// <summary> /// The CODEC that is used to transform between genome and phenome. /// </summary> IGeneticCODEC CODEC { get; set; } /// <summary> /// The current score. This value should either be minimized or /// maximized, depending on the score function. /// </summary> double Error { get; } /// <summary> /// The current iteration number. Also sometimes referred to as /// generation or epoch. /// </summary> int IterationNumber { get; } /// <summary> /// The maximum size an individual genome can be. This is an /// arbitrary number defined by the genome. Lower numbers are less /// complex. /// </summary> int MaxIndividualSize { get; } /// <summary> /// The maximum number to try certain genetic operations. This /// prevents endless loops. /// </summary> int MaxTries { get; } /// <summary> /// The operators. /// </summary> OperationList Operators { get; } /// <summary> /// The population. /// </summary> IPopulation Population { get; set; } /// <summary> /// The rules holder, contains rewrite and constraint rules. /// </summary> IRuleHolder Rules { get; set; } /// <summary> /// The score adjusters. This allows bonuses and penalties to be /// applied for desirable or undesirable traits. /// </summary> IList<IAdjustScore> ScoreAdjusters { get; } /// <summary> /// The score function. /// </summary> ICalculateScore ScoreFunction { get; } /// <summary> /// The selection operator. Used to choose genomes. /// </summary> ISelectionOperator Selection { get; set; } /// <summary> /// Get the comparator that is used to choose the "best" genome for /// selection, as opposed to the "true best". This uses the adjusted score, /// and not the score. /// </summary> IGenomeComparer SelectionComparer { get; set; } /// <summary> /// True if exceptions that occur during genetic operations should be /// ignored. /// </summary> bool ShouldIgnoreExceptions { get; set; } /// <summary> /// The speciation method. /// </summary> ISpeciation Speciation { get; set; } /// <summary> /// True if any genome validators should be applied. /// </summary> bool ValidationMode { get; set; } /// <summary> /// Add an operation. /// </summary> /// <param name="probability">The probability of using this operator.</param> /// <param name="opp">The operator to add.</param> void AddOperation(double probability, IEvolutionaryOperator opp); /// <summary> /// Add a score adjuster. Score adjusters are used to adjust the adjusted /// score of a genome. This allows bonuses and penalties to be applied for /// desirable or undesirable traits. /// </summary> /// <param name="scoreAdjust">The score adjustor to add.</param> void AddScoreAdjuster(IAdjustScore scoreAdjust); /// <summary> /// Calculate the score for a genome. /// </summary> /// <param name="g">The genome to calculate the score for.</param> void CalculateScore(IGenome g); /// <summary> /// Called when training is finished. This allows the EA to properly shut /// down. /// </summary> void FinishTraining(); /// <summary> /// Perform a training iteration. Also called generations or epochs. /// </summary> void Iteration(); } }
34.367816
88
0.584114
[ "BSD-3-Clause" ]
asad4237/encog-dotnet-core
encog-core-cs/ML/EA/Train/IEvolutionaryAlgorithm.cs
5,980
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace XS.Blog.WebUI.XSBlog.Daily { public partial class DailyList { /// <summary> /// rptDaily 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Repeater rptDaily; /// <summary> /// pager 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::Wuqi.Webdiyer.AspNetPager pager; } }
25.117647
81
0.403981
[ "MIT" ]
ctxsdhy/XSBlog
Blog/XS.Blog.WebUI/XSBlog/Daily/DailyList.aspx.designer.cs
1,124
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.Bot.Builder.TemplateManager; using RestaurantBookingSkill.Responses.Cancel; namespace RestaurantBookingSkill { public class CancelResponses : TemplateManager { // Constants public const string _confirmPrompt = "Cancel.ConfirmCancelPrompt"; public const string _cancelConfirmed = "Cancel.CancelConfirmed"; public const string _cancelDenied = "Cancel.CancelDenied"; // Fields private static LanguageTemplateDictionary _responseTemplates = new LanguageTemplateDictionary { ["default"] = new TemplateIdMap { { _confirmPrompt, (context, data) => CancelStrings.CANCEL_PROMPT }, { _cancelConfirmed, (context, data) => CancelStrings.CANCEL_CONFIRMED }, { _cancelDenied, (context, data) => CancelStrings.CANCEL_DENIED }, }, ["en"] = new TemplateIdMap { }, ["fr"] = new TemplateIdMap { }, }; public CancelResponses() { Register(new DictionaryRenderer(_responseTemplates)); } } }
34.457143
101
0.637645
[ "MIT" ]
ConnectionMaster/botframework-components
skills/csharp/experimental/restaurantbookingskill/Responses/Cancel/CancelResponses.cs
1,208
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.IO; using System.Threading; using System.Threading.Tasks; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Backup { public interface IBackupArchiveStore { Task UploadAsync(DomainId backupId, Stream stream, CancellationToken ct = default); Task DownloadAsync(DomainId backupId, Stream stream, CancellationToken ct = default); Task DeleteAsync(DomainId backupId, CancellationToken ct = default); } }
32.407407
78
0.518857
[ "MIT" ]
Dakraid/squidex
backend/src/Squidex.Domain.Apps.Entities/Backup/IBackupArchiveStore.cs
877
C#
using MSD.Product.Domain.Dtos.Common; using MSD.Product.Domain.Dtos.ProductDtos; using MSD.Product.Domain.Interfaces.Repositories.Common; using MSD.Product.Infra.Api.Dtos; using System.Threading.Tasks; namespace MSD.Product.Domain.Interfaces.Repositories { public interface IProductRepositoryApi : IRepositoryBase { Task<ApiResult<PagedResult<Models.Product>>> SearchAsync(string value = null, int page = 1); Task<ApiResult<ProductDto>> GetByExternalIdAsync(string externalId); } }
34.133333
100
0.773438
[ "Apache-2.0" ]
spaki/microservices-demo
MSD.Product/MSD.Product.Domain/Interfaces/Repositories/IProductRepositoryApi.cs
514
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary>Collection of Inbound Environment Endpoints</summary> [System.ComponentModel.TypeConverter(typeof(InboundEnvironmentEndpointCollectionTypeConverter))] public partial class InboundEnvironmentEndpointCollection { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointCollection" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollection" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollection DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new InboundEnvironmentEndpointCollection(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointCollection" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollection" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollection DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new InboundEnvironmentEndpointCollection(content); } /// <summary> /// Creates a new instance of <see cref="InboundEnvironmentEndpointCollection" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollection FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointCollection" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal InboundEnvironmentEndpointCollection(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpoint[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpoint>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).NextLink, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointCollection" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal InboundEnvironmentEndpointCollection(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpoint[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpoint>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.InboundEnvironmentEndpointTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IInboundEnvironmentEndpointCollectionInternal)this).NextLink, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Collection of Inbound Environment Endpoints [System.ComponentModel.TypeConverter(typeof(InboundEnvironmentEndpointCollectionTypeConverter))] public partial interface IInboundEnvironmentEndpointCollection { } }
72.242857
657
0.721673
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/Functions/generated/api/Models/Api20190801/InboundEnvironmentEndpointCollection.PowerShell.cs
9,975
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("KeyRevolver")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("KeyRevolver")] [assembly: System.Reflection.AssemblyTitleAttribute("KeyRevolver")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.958333
80
0.648016
[ "MIT" ]
GeorgiPopovIT/C-Advanced-Exercises
StackAndQueue/KeyRevolver/obj/Debug/netcoreapp3.1/KeyRevolver.AssemblyInfo.cs
983
C#
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; using SimpleLogin.Models; using SimpleLogin.Persistance; namespace SimpleLogin.Controllers { public class AccountController : Controller { private readonly IAuthManager _authManager; public AccountController(IUserManager userManager, IAuthManager authManager) { _authManager = authManager; } [HttpGet] public IActionResult Login(string returnUrl = "") { var model = new LoginViewModel { ReturnUrl = returnUrl }; return View(model); } [HttpPost] public IActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { var result = _authManager.Login(model); if (result) { return !string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl) ? (IActionResult)Redirect(model.ReturnUrl) : RedirectToAction("Index", "Home"); } } ModelState.AddModelError("", "Invalid login attempt"); return View(model); } private void SignInCookie(LoginViewModel model, User user) { var claims = new List<Claim> {new Claim(ClaimTypes.Name, user.UserName)}; string[] roles = user.Roles.Split(","); claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var props = new AuthenticationProperties {IsPersistent = model.RememberMe}; HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props).Wait(); } [HttpGet] public IActionResult Register() { var model = new RegisterViewModel(); return View(model); } [HttpPost] public IActionResult Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new User { UserName = model.Username, FirstName = model.FirstName, LastName = model.LastName, EmailId = model.EmailId, Mobile = model.Mobile }; var result = _authManager.Add(user,model.Password); if (result) { return RedirectToAction("Index", "Home"); } } ModelState.AddModelError("", "Registration unsuccessful!"); return View(model); } [HttpGet] public async Task<IActionResult> Logout() { await _authManager.LogoutAsync(); return RedirectToAction("Index", "Home"); } } }
31.392157
112
0.566521
[ "MIT" ]
BarbFlegel/Hands-On-Design-Patterns-with-C-and-.NET-Core
Chapter7/SimpleLogin-Authentication/SimpleLogin/Controllers/AccountController.cs
3,204
C#
using System.Collections.Generic; namespace Speckle.GSA.API.GwaSchema { public class GsaPolyline : GsaRecord { public string Name { get => name; set { name = value; } } public Colour Colour; public int? GridPlaneIndex; public int NumDim; public List<double> Values; public string Units = ""; public GsaPolyline() : base() { //Defaults Version = 1; } } }
19.571429
61
0.627737
[ "Apache-2.0" ]
arup-group/speckle-sharp
ConnectorGSA/Speckle.GSA.API/GwaSchema/Geometry/GsaPolyline.cs
413
C#
using System; using System.Globalization; namespace Gamma.Binding.Converters { public class GuidToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(value == null) return null; return ((Guid)value).ToString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if(targetType == typeof(Guid)) { return new Guid((string)value); } if(targetType == typeof(Guid?)) { if(String.IsNullOrWhiteSpace((string)value)) return null; return new Guid((string)value); } return null; } } }
19.676471
97
0.693572
[ "Apache-2.0" ]
Art8m/QSProjects
Binding/Gamma.Binding/Binding/Converters/GuidToStringConverter.cs
671
C#
namespace KeepFitStore.Services { using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Http; using AutoMapper; using KeepFitStore.Data; using KeepFitStore.Domain; using KeepFitStore.Models.InputModels.Jobs; using KeepFitStore.Services.Contracts; using KeepFitStore.Services.PhotoKeeper; using KeepFitStore.Services.CustomExceptions; using KeepFitStore.Services.CustomExceptions.Messsages; public class JobApplicantService : IJobApplicantService { private readonly KeepFitDbContext context; private readonly IMapper mapper; private readonly IMyCloudinary cloudinary; public JobApplicantService(KeepFitDbContext context, IMapper mapper, IMyCloudinary cloudinary) { this.context = context; this.mapper = mapper; this.cloudinary = cloudinary; } public async Task<int> AddApplicantAsync(CreateJobApplicantInputModel inputModel, IFormFile image) { var jobPosition = await this.context .Positions .SingleOrDefaultAsync(x => x.Name == inputModel.Position); if (jobPosition == null) { throw new JobPositionNotFoundException(string.Format( ExceptionMessages.InvalidJobPosition, inputModel.Position)); } var entity = this.mapper.Map<JobApplicant>(inputModel); entity.Position = jobPosition; entity.ImageUrl = this.cloudinary.UploadImage(image); this.context.Applicants.Add(entity); var rowsAdded = await this.context.SaveChangesAsync(); return rowsAdded; } public async Task<IEnumerable<TViewModel>> GetAllAsync<TViewModel>() { var allApplicants = await this.context .Applicants .Include(x => x.Position) .AsNoTracking() .ToListAsync(); var viewModel = this.mapper.Map<IEnumerable<TViewModel>>(allApplicants); return viewModel; } } }
33.212121
106
0.639142
[ "MIT" ]
SonicTheCat/KeepFitStore
KeepFitStore/KeepFitStore.Services/JobApplicantService.cs
2,194
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.CloudTrail")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS CloudTrail. AWS CloudTrail is a web service that records AWS API calls for your account and delivers log files to you. The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, the request parameters, and the response elements returned by the AWS service.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.31")]
52.4375
414
0.755662
[ "Apache-2.0" ]
Singh400/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/CloudTrail/Properties/AssemblyInfo.cs
1,678
C#
using LiveSplit.Model; using System; namespace LiveSplit.UI.Components { public class TitleFactory : IComponentFactory { public string ComponentName => "Title"; public string Description => "Shows the current run title, run category, and game icon."; public ComponentCategory Category => ComponentCategory.Information; public IComponent Create(LiveSplitState state) => new Title(); public string UpdateName => ComponentName; public string XMLURL => "http://livesplit.org/update/Components/update.LiveSplit.Title.xml"; public string UpdateURL => "http://livesplit.org/update/"; public Version Version => Version.Parse("1.7.5"); } }
28.64
100
0.687151
[ "MIT" ]
mysidia/LiveSplit-Sid
LiveSplit/Components/LiveSplit.Title/UI/Components/TitleFactory.cs
718
C#
using System; using System.Collections.Generic; using System.Text; namespace OccupancyTypes { public static class OccTypeGroupReader { public static IOccupancyTypeGroup ReadOccupancyTypeGroup(string filePath) { //calling the CA occTypes and passing in the path will read the file and create //all the occtypes. Consequences_Assist.ComputableObjects.OccupancyTypes oldGroup = new Consequences_Assist.ComputableObjects.OccupancyTypes(filePath); //now i need to translate the CA version of the group and the list of occtypes into the FDA version List<IOccupancyType> occtypes = new List<IOccupancyType>(); foreach(Consequences_Assist.ComputableObjects.OccupancyType ot in oldGroup.OccupancyTypes) { IOccupancyType newOcctype = OccupancyTypeFactory.Factory(ot); occtypes.Add(newOcctype); } return new OccupancyTypeGroup(occtypes); } } }
36.214286
143
0.682446
[ "MIT" ]
HydrologicEngineeringCenter/HEC-FDA
OccupancyTypes/OccTypeGroupReader.cs
1,016
C#
using System.ComponentModel.DataAnnotations; namespace Bing.Samples.MultipleVersionWithGroup.V2.Models { /// <summary> /// 人 /// </summary> public class Person { /// <summary> /// 人 /// </summary> public int Id { get; set; } /// <summary> /// 姓 /// </summary> [Required] [StringLength(25)] public string FirstName { get; set; } /// <summary> /// 名 /// </summary> [Required] [StringLength(25)] public string LastName { get; set; } /// <summary> /// 邮箱 /// </summary> public string Email { get; set; } } }
19.8
57
0.464646
[ "MIT" ]
bing-framework/Bing.Extensions.Swashbuckle
samples/Bing.Samples.MultipleVersionWithGroup/V2/Models/Person.cs
707
C#
namespace Minesweeper { using System; using System.Collections.Generic; public class Mines { public static void Main() { const int BOARD_ROWS = 5; const int BOARD_COLUMNS = 10; const int MAXIMUM_OPENED_CELLS = 35; int openedCells = 0; char[,] questionsPlayBoard = CreatePlayBoard('?', BOARD_ROWS, BOARD_COLUMNS); char[,] bombsPlayBoard = PutBombs(BOARD_ROWS, BOARD_COLUMNS); List<Score> highScores = new List<Score>(6); string command = string.Empty; int row = 0; int col = 0; bool isBombOpened = false; bool isPlayBoardDrawn = false; bool allCellsOpened = false; do { if (!isPlayBoardDrawn) { Console.WriteLine("Let's play Minesweeper. Try to find all fields without mines. " + "Command 'top' shows high scores, 'restart' initiates a new game, 'exit' exits the application."); DrawPlayBoard(questionsPlayBoard); isPlayBoardDrawn = true; } Console.Write("Enter row and col, separated by a space: "); command = Console.ReadLine().Trim(); if (command.Length == 3) { if (int.TryParse(command[0].ToString(), out row) && string.IsNullOrWhiteSpace(command[1].ToString()) && int.TryParse(command[2].ToString(), out col) && row < questionsPlayBoard.GetLength(0) && col < questionsPlayBoard.GetLength(1)) { command = "turn"; } } switch (command) { case "top": DrawHighScores(highScores); break; case "restart": questionsPlayBoard = CreatePlayBoard('?', BOARD_ROWS, BOARD_COLUMNS); bombsPlayBoard = PutBombs(BOARD_ROWS, BOARD_COLUMNS); DrawPlayBoard(questionsPlayBoard); isBombOpened = false; isPlayBoardDrawn = true; break; case "exit": Console.WriteLine("Bye, bye!"); break; case "turn": if (bombsPlayBoard[row, col] != '*') { if (bombsPlayBoard[row, col] == '-') { UpdatePlayBoards(questionsPlayBoard, bombsPlayBoard, row, col); openedCells++; } if (MAXIMUM_OPENED_CELLS == openedCells) { allCellsOpened = true; } else { DrawPlayBoard(questionsPlayBoard); } } else { isBombOpened = true; } break; default: Console.WriteLine("\nError! Invalid choise!\n"); break; } if (isBombOpened) { DrawPlayBoard(bombsPlayBoard); Console.Write("\nYou died with {0} points. Enter your name: ", openedCells); string nickname = Console.ReadLine(); Score score = new Score(nickname, openedCells); if (highScores.Count < 5) { highScores.Add(score); } else { for (int i = 0; i < highScores.Count; i++) { if (highScores[i].PlayerPoints < score.PlayerPoints) { highScores.Insert(i, score); highScores.RemoveAt(highScores.Count - 1); break; } } } highScores.Sort((Score x1, Score x2) => x2.PlayerName.CompareTo(x1.PlayerName)); highScores.Sort((Score x1, Score x2) => x2.PlayerPoints.CompareTo(x1.PlayerPoints)); DrawHighScores(highScores); questionsPlayBoard = CreatePlayBoard('?', BOARD_ROWS, BOARD_COLUMNS); bombsPlayBoard = PutBombs(BOARD_ROWS, BOARD_COLUMNS); openedCells = 0; isBombOpened = false; isPlayBoardDrawn = false; } if (allCellsOpened) { Console.WriteLine("\nCongratulations! You have opened all 35 cells without stepping on mine."); DrawPlayBoard(bombsPlayBoard); Console.WriteLine("Enter your name: "); string name = Console.ReadLine(); Score score = new Score(name, openedCells); highScores.Add(score); DrawHighScores(highScores); questionsPlayBoard = CreatePlayBoard('?', BOARD_ROWS, BOARD_COLUMNS); bombsPlayBoard = PutBombs(BOARD_ROWS, BOARD_COLUMNS); openedCells = 0; allCellsOpened = false; isPlayBoardDrawn = false; } } while (command != "exit"); Console.WriteLine("Made in Bulgaria!"); Console.Read(); } private static void DrawHighScores(List<Score> highScores) { Console.WriteLine("\nHigh scores:"); if (highScores.Count > 0) { for (int i = 0; i < highScores.Count; i++) { Console.WriteLine("{0}. {1} --> {2} cells", i + 1, highScores[i].PlayerName, highScores[i].PlayerPoints); } Console.WriteLine(); } else { Console.WriteLine("Empty scores!\n"); } } private static void UpdatePlayBoards(char[,] questionsBoard, char[,] bombsBoard, int row, int col) { char bombsNearBy = CountBombsNearBy(bombsBoard, row, col); bombsBoard[row, col] = bombsNearBy; questionsBoard[row, col] = bombsNearBy; } private static void DrawPlayBoard(char[,] playBoard) { int row = playBoard.GetLength(0); int col = playBoard.GetLength(1); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); Console.WriteLine(" ---------------------"); for (int i = 0; i < row; i++) { Console.Write("{0} | ", i); for (int j = 0; j < col; j++) { Console.Write(string.Format("{0} ", playBoard[i, j])); } Console.Write("|"); Console.WriteLine(); } Console.WriteLine(" ---------------------\n"); } private static char[,] CreatePlayBoard(char mark, int rows, int cols) { char[,] playBoard = new char[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { playBoard[i, j] = mark; } } return playBoard; } private static char[,] PutBombs(int rows, int cols) { char[,] bombsPlayBoard = CreatePlayBoard('-', rows, cols); List<int> bombs = new List<int>(); while (bombs.Count < 15) { int random = new Random().Next(50); if (!bombs.Contains(random)) { bombs.Add(random); } } foreach (int item in bombs) { int col = item / cols; int row = item % cols; if (row == 0 && item != 0) { col--; row = cols; } else { row++; } bombsPlayBoard[col, row - 1] = '*'; } return bombsPlayBoard; } private static char CountBombsNearBy(char[,] playBoard, int row, int col) { int count = 0; int rows = playBoard.GetLength(0); int cols = playBoard.GetLength(1); if (row - 1 >= 0) { if (playBoard[row - 1, col] == '*') { count++; } } if (row + 1 < rows) { if (playBoard[row + 1, col] == '*') { count++; } } if (col - 1 >= 0) { if (playBoard[row, col - 1] == '*') { count++; } } if (col + 1 < cols) { if (playBoard[row, col + 1] == '*') { count++; } } if ((row - 1 >= 0) && (col - 1 >= 0)) { if (playBoard[row - 1, col - 1] == '*') { count++; } } if ((row - 1 >= 0) && (col + 1 < cols)) { if (playBoard[row - 1, col + 1] == '*') { count++; } } if ((row + 1 < rows) && (col - 1 >= 0)) { if (playBoard[row + 1, col - 1] == '*') { count++; } } if ((row + 1 < rows) && (col + 1 < cols)) { if (playBoard[row + 1, col + 1] == '*') { count++; } } return char.Parse(count.ToString()); } } }
33.537736
125
0.382654
[ "MIT" ]
MarinMarinov/High-Quality-Code
HW02Naming Identifiers/Task04.RefactorGameMineSweeper/MainProgram.cs
10,667
C#
// <auto-generated /> using System; using LiveKraken.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace LiveKraken.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20200204172907_RoleSeed")] partial class RoleSeed { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.1") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("LiveKraken.Models.Game", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Games"); }); modelBuilder.Entity("LiveKraken.Models.Role", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("RoleName") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Roles"); b.HasData( new { Id = new Guid("9ab9538a-9925-4fd6-89df-8e49ddd4daca"), RoleName = "user" }); }); modelBuilder.Entity("LiveKraken.Models.User", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Followers") .HasColumnType("nvarchar(max)"); b.Property<string>("Following") .HasColumnType("nvarchar(max)"); b.Property<byte[]>("PasswordHash") .IsRequired() .HasColumnType("varbinary(max)"); b.Property<byte[]>("PasswordSalt") .IsRequired() .HasColumnType("varbinary(max)"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<string>("Username") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("Users"); }); modelBuilder.Entity("LiveKraken.Models.User", b => { b.HasOne("LiveKraken.Models.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
33.86087
117
0.46379
[ "MIT" ]
MetalDestructor/LiveKraken
LiveKraken/LiveKraken.Data/Migrations/20200204172907_RoleSeed.Designer.cs
3,896
C#
using NeutronNetwork.Internal; using NeutronNetwork.Internal.Packets; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using UnityEngine; namespace NeutronNetwork.Helpers { public static class ReflectionHelper { public static T GetAttribute<T>(string methodName, object instance) where T : Attribute { var method = GetMethod(methodName, instance); if (method != null) return method.GetCustomAttribute<T>(); else return null; } public static T[] GetAttributes<T>(object instance) where T : Attribute { var methods = GetMethods(instance); if (methods.Length > 0) { List<T> attributes = new List<T>(); for (int i = 0; i < methods.Length; i++) { T attr = methods[i].GetCustomAttribute<T>(); if (attr != null) attributes.Add(attr); else continue; } return attributes.ToArray(); } else return null; } public static (T, MethodInfo)[] GetAttributesWithMethod<T>(object instance) where T : Attribute { var methods = GetMethods(instance); if (methods.Length > 0) { List<(T, MethodInfo)> attributes = new List<(T, MethodInfo)>(); for (int i = 0; i < methods.Length; i++) { T attr = methods[i].GetCustomAttribute<T>(); if (attr != null) attributes.Add((attr, methods[i])); else continue; } return attributes.ToArray(); } else return default; } public static (T, FieldInfo)[] GetAttributesWithField<T>(object instance) where T : Attribute { var fields = GetFields(instance); if (fields.Length > 0) { List<(T, FieldInfo)> attributes = new List<(T, FieldInfo)>(); for (int i = 0; i < fields.Length; i++) { T attr = fields[i].GetCustomAttribute<T>(); if (attr != null) attributes.Add((attr, fields[i])); else continue; } return attributes.ToArray(); } else return default; } public static (T, PropertyInfo)[] GetAttributesWithProperty<T>(object instance) where T : Attribute { var properties = GetProperties(instance); if (properties.Length > 0) { List<(T, PropertyInfo)> attributes = new List<(T, PropertyInfo)>(); for (int i = 0; i < properties.Length; i++) { T attr = properties[i].GetCustomAttribute<T>(); if (attr != null) attributes.Add((attr, properties[i])); else continue; } return attributes.ToArray(); } else return default; } public static T[][] GetMultipleAttributes<T>(object instance) where T : Attribute { var methods = GetMethods(instance); if (methods.Length > 0) { List<T[]> attributes = new List<T[]>(); for (int i = 0; i < methods.Length; i++) { T[] attrs = methods[i].GetCustomAttributes<T>().ToArray(); if (attrs.Length > 0) attributes.Add(attrs); else continue; } return attributes.ToArray(); } else return null; } public static (T[], MethodInfo)[] GetMultipleAttributesWithMethod<T>(object instance) where T : Attribute { var methods = GetMethods(instance); if (methods.Length > 0) { List<(T[], MethodInfo)> attributes = new List<(T[], MethodInfo)>(); for (int i = 0; i < methods.Length; i++) { T[] attrs = methods[i].GetCustomAttributes<T>().ToArray(); if (attrs.Length > 0) attributes.Add((attrs, methods[i])); else continue; } return attributes.ToArray(); } else return null; } public static (T[], FieldInfo)[] GetMultipleAttributesWithField<T>(object instance) where T : Attribute { var fields = GetFields(instance); if (fields.Length > 0) { List<(T[], FieldInfo)> attributes = new List<(T[], FieldInfo)>(); for (int i = 0; i < fields.Length; i++) { T[] attrs = fields[i].GetCustomAttributes<T>().ToArray(); if (attrs.Length > 0) attributes.Add((attrs, fields[i])); else continue; } return attributes.ToArray(); } else return null; } public static (T[], PropertyInfo)[] GetMultipleAttributesWithProperty<T>(object instance) where T : Attribute { var properties = GetProperties(instance); if (properties.Length > 0) { List<(T[], PropertyInfo)> attributes = new List<(T[], PropertyInfo)>(); for (int i = 0; i < properties.Length; i++) { T[] attrs = properties[i].GetCustomAttributes<T>().ToArray(); if (attrs.Length > 0) attributes.Add((attrs, properties[i])); else continue; } return attributes.ToArray(); } else return null; } public static MethodInfo GetMethod(string name, object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetMethod(name, flags); } public static MethodInfo[] GetMethods(object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetMethods(flags); } public static FieldInfo GetField(string name, object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetField(name, flags); } public static FieldInfo[] GetFields(object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetFields(flags); } public static PropertyInfo GetProperty(string name, object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetProperty(name, flags); } public static PropertyInfo[] GetProperties(object instance, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) { return instance.GetType().GetProperties(flags); } #pragma warning disable IDE1006 public static void iRPC(byte[] buffer, RPCInvoker remoteProceduralCall, NeutronPlayer player) #pragma warning restore IDE1006 { using (NeutronStream stream = Neutron.PooledNetworkStreams.Pull()) { NeutronStream.IReader reader = stream.Reader; reader._autoDispose = true; reader.SetBuffer(buffer); switch (remoteProceduralCall.Type) { case MethodType.Async | MethodType.Void: case MethodType.Void: remoteProceduralCall.iRPCVoid(reader, player); break; default: LogHelper.Error($"iRPC: Type not implemented!"); break; } } } #pragma warning disable IDE1006 public static void gRPC(NeutronPlayer player, byte[] buffer, RPCInvoker remoteProceduralCall, bool isServer, bool isMine, Neutron instance) #pragma warning restore IDE1006 { using (NeutronStream stream = Neutron.PooledNetworkStreams.Pull()) { NeutronStream.IReader reader = stream.Reader; reader._autoDispose = true; reader.SetBuffer(buffer); switch (remoteProceduralCall.Type) { case MethodType.Async | MethodType.Void: case MethodType.Void: remoteProceduralCall.gRPCVoid(reader, isServer, isMine, player, instance); break; default: LogHelper.Error($"gRPC: Type not implemented!"); break; } } } } }
37.688716
167
0.494631
[ "MIT" ]
RuanCardoso/Neutron-Unity-Network
Runtime/Commons/Helpers And Extensions/Helpers/ReflectionHelper.cs
9,686
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Serialization { using System; using System.Text; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; internal sealed class XmlAttributeComparer : IComparer { public int Compare(object? o1, object? o2) { XmlAttribute a1 = (XmlAttribute)o1!; XmlAttribute a2 = (XmlAttribute)o2!; int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal); if (ns == 0) { return string.Compare(a1.Name, a2.Name, StringComparison.Ordinal); } return ns; } } internal sealed class XmlFacetComparer : IComparer { public int Compare(object? o1, object? o2) { XmlSchemaFacet f1 = (XmlSchemaFacet)o1!; XmlSchemaFacet f2 = (XmlSchemaFacet)o2!; return string.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal); } } internal sealed class QNameComparer : IComparer { public int Compare(object? o1, object? o2) { XmlQualifiedName qn1 = (XmlQualifiedName)o1!; XmlQualifiedName qn2 = (XmlQualifiedName)o2!; int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal); if (ns == 0) { return string.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal); } return ns; } } internal sealed class XmlSchemaObjectComparer : IComparer { private readonly QNameComparer _comparer = new QNameComparer(); public int Compare(object? o1, object? o2) { return _comparer.Compare(NameOf((XmlSchemaObject?)o1), NameOf((XmlSchemaObject?)o2)); } internal static XmlQualifiedName NameOf(XmlSchemaObject? o) { if (o is XmlSchemaAttribute) { return ((XmlSchemaAttribute)o).QualifiedName; } else if (o is XmlSchemaAttributeGroup) { return ((XmlSchemaAttributeGroup)o).QualifiedName; } else if (o is XmlSchemaComplexType) { return ((XmlSchemaComplexType)o).QualifiedName; } else if (o is XmlSchemaSimpleType) { return ((XmlSchemaSimpleType)o).QualifiedName; } else if (o is XmlSchemaElement) { return ((XmlSchemaElement)o).QualifiedName; } else if (o is XmlSchemaGroup) { return ((XmlSchemaGroup)o).QualifiedName; } else if (o is XmlSchemaGroupRef) { return ((XmlSchemaGroupRef)o).RefName; } else if (o is XmlSchemaNotation) { return ((XmlSchemaNotation)o).QualifiedName; } else if (o is XmlSchemaSequence) { XmlSchemaSequence s = (XmlSchemaSequence)o; if (s.Items.Count == 0) return new XmlQualifiedName(".sequence", Namespace(o)); return NameOf(s.Items[0]); } else if (o is XmlSchemaAll) { XmlSchemaAll a = (XmlSchemaAll)o; if (a.Items.Count == 0) return new XmlQualifiedName(".all", Namespace(o)); return NameOf(a.Items); } else if (o is XmlSchemaChoice) { XmlSchemaChoice c = (XmlSchemaChoice)o; if (c.Items.Count == 0) return new XmlQualifiedName(".choice", Namespace(o)); return NameOf(c.Items); } else if (o is XmlSchemaAny) { return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList)); } else if (o is XmlSchemaIdentityConstraint) { return ((XmlSchemaIdentityConstraint)o).QualifiedName; } return new XmlQualifiedName("?", Namespace(o)); } internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) { ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(NameOf(items[i])); } list.Sort(new QNameComparer()); return (XmlQualifiedName)list[0]!; } internal static string? Namespace(XmlSchemaObject? o) { while (o != null && !(o is XmlSchema)) { o = o.Parent; } return o == null ? "" : ((XmlSchema)o).TargetNamespace; } } internal sealed class SchemaObjectWriter { private readonly StringBuilder _w = new StringBuilder(); private int _indentLevel = -1; private void WriteIndent() { for (int i = 0; i < _indentLevel; i++) { _w.Append(' '); } } private void WriteAttribute(string localName, string ns, string? value) { if (value == null || value.Length == 0) return; _w.Append(','); _w.Append(ns); if (ns != null && ns.Length != 0) _w.Append(':'); _w.Append(localName); _w.Append('='); _w.Append(value); } private void WriteAttribute(string localName, string ns, XmlQualifiedName value) { if (value.IsEmpty) return; WriteAttribute(localName, ns, value.ToString()); } private void WriteStartElement(string name) { NewLine(); _indentLevel++; _w.Append('['); _w.Append(name); } private void WriteEndElement() { _w.Append(']'); _indentLevel--; } private void NewLine() { _w.Append(Environment.NewLine); WriteIndent(); } private string GetString() { return _w.ToString(); } private void WriteAttribute(XmlAttribute a) { if (a.Value != null) { WriteAttribute(a.Name, a.NamespaceURI, a.Value); } } private void WriteAttributes(XmlAttribute[]? a, XmlSchemaObject o) { if (a == null) return; ArrayList attrs = new ArrayList(); for (int i = 0; i < a.Length; i++) { attrs.Add(a[i]); } attrs.Sort(new XmlAttributeComparer()); for (int i = 0; i < attrs.Count; i++) { XmlAttribute attribute = (XmlAttribute)attrs[i]!; WriteAttribute(attribute); } } [return: NotNullIfNotNull("list")] internal static string? ToString(NamespaceList? list) { if (list == null) return null; switch (list.Type) { case NamespaceList.ListType.Any: return "##any"; case NamespaceList.ListType.Other: return "##other"; case NamespaceList.ListType.Set: ArrayList ns = new ArrayList(); foreach (string s in list.Enumerate) { ns.Add(s); } ns.Sort(); StringBuilder sb = new StringBuilder(); bool first = true; foreach (string s in ns) { if (first) { first = false; } else { sb.Append(' '); } if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); default: return list.ToString(); } } internal string WriteXmlSchemaObject(XmlSchemaObject? o) { if (o == null) return string.Empty; Write3_XmlSchemaObject((XmlSchemaObject?)o); return GetString(); } private void WriteSortedItems(XmlSchemaObjectCollection? items) { if (items == null) return; ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(items[i]); } list.Sort(new XmlSchemaObjectComparer()); for (int i = 0; i < list.Count; i++) { Write3_XmlSchemaObject((XmlSchemaObject?)list[i]); } } private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) { if (o is null) return; WriteStartElement("attribute"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); WriteAttribute(@"default", @"", ((string?)o.@DefaultValue)); WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } WriteAttribute(@"name", @"", ((string?)o.@Name)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use; WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@SchemaType); WriteEndElement(); } private void Write3_XmlSchemaObject(XmlSchemaObject? o) { if (o is null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaComplexType)) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o); return; } else if (t == typeof(XmlSchemaSimpleType)) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o); return; } else if (t == typeof(XmlSchemaElement)) { Write46_XmlSchemaElement((XmlSchemaElement)o); return; } else if (t == typeof(XmlSchemaAppInfo)) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o); return; } else if (t == typeof(XmlSchemaDocumentation)) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o); return; } else if (t == typeof(XmlSchemaAnnotation)) { Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o); return; } else if (t == typeof(XmlSchemaGroup)) { Write57_XmlSchemaGroup((XmlSchemaGroup)o); return; } else if (t == typeof(XmlSchemaXPath)) { Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o); return; } else if (t == typeof(XmlSchemaIdentityConstraint)) { Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o); return; } else if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } else if (t == typeof(XmlSchemaGroupRef)) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o); return; } else if (t == typeof(XmlSchemaAny)) { Write53_XmlSchemaAny((XmlSchemaAny)o); return; } else if (t == typeof(XmlSchemaSequence)) { Write54_XmlSchemaSequence((XmlSchemaSequence)o); return; } else if (t == typeof(XmlSchemaChoice)) { Write52_XmlSchemaChoice((XmlSchemaChoice)o); return; } else if (t == typeof(XmlSchemaAll)) { Write43_XmlSchemaAll((XmlSchemaAll)o); return; } else if (t == typeof(XmlSchemaComplexContentRestriction)) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o); return; } else if (t == typeof(XmlSchemaComplexContentExtension)) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o); return; } else if (t == typeof(XmlSchemaSimpleContentRestriction)) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleContentExtension)) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o); return; } else if (t == typeof(XmlSchemaComplexContent)) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o); return; } else if (t == typeof(XmlSchemaSimpleContent)) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o); return; } else if (t == typeof(XmlSchemaAnyAttribute)) { Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o); return; } else if (t == typeof(XmlSchemaAttributeGroupRef)) { Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o); return; } else if (t == typeof(XmlSchemaAttributeGroup)) { Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o); return; } else if (t == typeof(XmlSchemaSimpleTypeRestriction)) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleTypeList)) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o); return; } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o); return; } else if (t == typeof(XmlSchemaAttribute)) { Write1_XmlSchemaAttribute((XmlSchemaAttribute)o); return; } } private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o) { if (o is null) return; WriteStartElement("annotation"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAppInfo) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai); } else if (ai is XmlSchemaDocumentation) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai); } } } WriteEndElement(); } private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) { if (o is null) return; WriteStartElement("documentation"); WriteAttribute(@"source", @"", ((string?)o.@Source)); WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string?)o.@Language)); XmlNode?[]? a = (XmlNode?[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]!; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo? o) { if (o is null) return; WriteStartElement("appinfo"); WriteAttribute("source", "", o.Source); XmlNode?[]? a = (XmlNode?[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]!; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) { if (o is null) return; WriteStartElement("simpleType"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleTypeUnion) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeRestriction) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeList) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content); } WriteEndElement(); } private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) { return v.ToString(); } private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion? o) { if (o is null) return; WriteStartElement("union"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (o.MemberTypes != null) { ArrayList list = new ArrayList(); for (int i = 0; i < o.MemberTypes.Length; i++) { list.Add(o.MemberTypes[i]); } list.Sort(new QNameComparer()); _w.Append(','); _w.Append("memberTypes="); for (int i = 0; i < list.Count; i++) { XmlQualifiedName q = (XmlQualifiedName)list[i]!; _w.Append(q.ToString()); _w.Append(','); } } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@BaseTypes); WriteEndElement(); } private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) { if (o is null) return; WriteStartElement("list"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@ItemTypeName.IsEmpty) { WriteAttribute(@"itemType", @"", o.@ItemTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@ItemType); WriteEndElement(); } private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction? o) { if (o is null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteEndElement(); } private void WriteFacets(XmlSchemaObjectCollection? facets) { if (facets == null) return; ArrayList a = new ArrayList(); for (int i = 0; i < facets.Count; i++) { a.Add(facets[i]); } a.Sort(new XmlFacetComparer()); for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject? ai = (XmlSchemaObject?)a[ia]; if (ai is XmlSchemaMinExclusiveFacet) { Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxInclusiveFacet) { Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxExclusiveFacet) { Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinInclusiveFacet) { Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaLengthFacet) { Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaEnumerationFacet) { Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinLengthFacet) { Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaPatternFacet) { Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaTotalDigitsFacet) { Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxLengthFacet) { Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaWhiteSpaceFacet) { Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaFractionDigitsFacet) { Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai); } } } private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o) { if (o is null) return; WriteStartElement(name); WriteAttribute("id", "", o.Id); WriteAttribute("value", "", o.Value); if (o.IsFixed) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private string? Write30_XmlSchemaUse(XmlSchemaUse v) { string? s = null; switch (v) { case XmlSchemaUse.@Optional: s = @"optional"; break; case XmlSchemaUse.@Prohibited: s = @"prohibited"; break; case XmlSchemaUse.@Required: s = @"required"; break; default: break; } return s; } private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup? o) { if (o is null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef? o) { if (o is null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((string?)o.@Id)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o) { if (o is null) return; WriteStartElement("anyAttribute"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { string? s = null; switch (v) { case XmlSchemaContentProcessing.@Skip: s = @"skip"; break; case XmlSchemaContentProcessing.@Lax: s = @"lax"; break; case XmlSchemaContentProcessing.@Strict: s = @"strict"; break; default: break; } return s; } private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { if (o is null) return; WriteStartElement("complexType"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); if (((bool)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); if (((bool)o.@IsMixed) != false) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); } else if (o.@ContentModel is XmlSchemaSimpleContent) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel); } if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o) { if (o is null) return; WriteStartElement("simpleContent"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleContentExtension) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content); } WriteEndElement(); } private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o) { if (o is null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction? o) { if (o is null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o) { if (o is null) return; WriteStartElement("complexContent"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaComplexContentExtension) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content); } WriteEndElement(); } private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension? o) { if (o is null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write43_XmlSchemaAll(XmlSchemaAll o) { if (o is null) return; WriteStartElement("all"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } private void Write46_XmlSchemaElement(XmlSchemaElement? o) { if (o is null) return; WriteStartElement("element"); WriteAttribute(@"id", @"", o.Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (((bool)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); WriteAttribute(@"default", @"", o.DefaultValue); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); WriteAttribute(@"fixed", @"", o.FixedValue); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } if (o.Name != null && o.Name.Length != 0) { WriteAttribute(@"name", @"", o.Name); } if (o.IsNillable) { WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable)); } if (!o.SubstitutionGroup.IsEmpty) { WriteAttribute("substitutionGroup", "", o.SubstitutionGroup); } if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType); } else if (o.SchemaType is XmlSchemaSimpleType) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType); } WriteSortedItems(o.Constraints); WriteEndElement(); } private void Write47_XmlSchemaKey(XmlSchemaKey? o) { if (o is null) return; WriteStartElement("key"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint? o) { if (o is null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } } private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath? o) { if (o is null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private void Write50_XmlSchemaKeyref(XmlSchemaKeyref? o) { if (o is null) return; WriteStartElement("keyref"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); // UNDONE compare reference here WriteAttribute(@"refer", @"", o.@Refer); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } private void Write51_XmlSchemaUnique(XmlSchemaUnique? o) { if (o is null) return; WriteStartElement("unique"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath?)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]); } } WriteEndElement(); } private void Write52_XmlSchemaChoice(XmlSchemaChoice? o) { if (o is null) return; WriteStartElement("choice"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } private void Write53_XmlSchemaAny(XmlSchemaAny? o) { if (o is null) return; WriteStartElement("any"); WriteAttribute(@"id", @"", o.@Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private void Write54_XmlSchemaSequence(XmlSchemaSequence? o) { if (o is null) return; WriteStartElement("sequence"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAny) { Write53_XmlSchemaAny((XmlSchemaAny)ai); } else if (ai is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)ai); } else if (ai is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)ai); } else if (ai is XmlSchemaElement) { Write46_XmlSchemaElement((XmlSchemaElement)ai); } else if (ai is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai); } } } WriteEndElement(); } private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef? o) { if (o is null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction? o) { if (o is null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } private void Write57_XmlSchemaGroup(XmlSchemaGroup? o) { if (o is null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteEndElement(); } } }
37.992974
161
0.518626
[ "MIT" ]
3DCloud/runtime
src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs
48,669
C#
namespace SJResults { public class Competitor { public string Code { get; set; } public string Name { get; set; } public string Birth { get; set; } public string FirstCountry { get; set; } public string SecondCountry { get; set; } public string StartRange { get; set; } } }
27.75
49
0.585586
[ "MIT" ]
Mensix/SJResults
Competitor.cs
333
C#
// <auto-generated> // Code generated by LUISGen .\DeskBooking.json -cs Luis.DeskBooking -o . // Tool github: https://github.com/microsoft/botbuilder-tools // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> using Newtonsoft.Json; using System.Collections.Generic; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.Luis; namespace Microsoft.SallyBot { public partial class AssetsBooking : IRecognizerConvert { public string Text; public string AlteredText; public enum Intent { Bienvenido, CrearReserva, CrearReservaVirtual, Despedida, None, }; public Dictionary<Intent, IntentScore> Intents; public class _Entities { // Built-in entities public DateTimeSpec[] datetime; } public _Entities Entities; [JsonExtensionData(ReadData = true, WriteData = true)] public IDictionary<string, object> Properties { get; set; } public void Convert(dynamic result) { var app = JsonConvert.DeserializeObject<AssetsBooking>(JsonConvert.SerializeObject(result, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); Text = app.Text; AlteredText = app.AlteredText; Intents = app.Intents; Entities = app.Entities; Properties = app.Properties; } public (Intent intent, double score) TopIntent() { Intent maxIntent = Intent.None; var max = 0.0; foreach (var entry in Intents) { if (entry.Value.Score > max) { maxIntent = entry.Key; max = entry.Value.Score.Value; } } return (maxIntent, max); } } }
29.953846
181
0.582948
[ "BSD-3-Clause" ]
LogicalisAr/LogicalisWebex-Sample
CognitiveModels/AssetBooking.cs
1,949
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BizTalkComponents.Utils; using Microsoft.BizTalk.Component.Interop; using Microsoft.BizTalk.Message.Interop; using IComponent = Microsoft.BizTalk.Component.Interop.IComponent; using Microsoft.BizTalk.Component; using System.ComponentModel; using System.Diagnostics; using System.ComponentModel.DataAnnotations; using Microsoft.XLANGs.BaseTypes; using System.IO; using System.Xml; using System.Xml.Xsl; using Microsoft.BizTalk.Streaming; namespace BizTalkComponents.PipelineComponents.EmailCustomizer { [ComponentCategory(CategoryTypes.CATID_PipelineComponent)] [ComponentCategory(CategoryTypes.CATID_Encoder)] [System.Runtime.InteropServices.Guid("9d0e4103-4cce-4536-83fa-4a5040674ad6")] public partial class EmailCustomizer : IBaseComponent, IComponent, IComponentUI, IPersistPropertyBag { private const string FilenamesPropertyName = "FileNames", XSLTFilePathPropertyName = "XSLTFilePath", ApplyXsltOnBodyPartPropertyName = "ApplyXsltOnBodyPart", EmailBodyPropertyName = "EmailBody", EnabledPropertyName = "Enabled"; [DisplayName("Filenames")] [Description("Filenames are separated by veritical pipe (|), parts with empty name will not be attached to your e-mail")] public string FileNames { get; set; } [DisplayName("XSLT File Path")] [Description("Xslt file path you want to apply on the body part of the message.")] public string XSLTFilePath { get; set; } [DisplayName("Apply XSLT On Body Part")] [Description("True to perform the transformation, false to ignore the transformation.")] public bool ApplyXsltOnBodyPart { get; set; } [DisplayName("Email Body")] [Description("Your fixed e-mail plain text or html-formatted.")] public string EmailBody { get; set; } [Description("True to activate the component, false to skip over it.")] public bool Enabled { get; set; } public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { if (!Enabled) { return pInMsg; } string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } IBaseMessageFactory messageFactory = pContext.GetMessageFactory(); IBaseMessage newMsg = messageFactory.CreateMessage(); newMsg.Context = pInMsg.Context; MemoryStream ms = new MemoryStream(); //Create Html body IBaseMessagePart bodyPart = messageFactory.CreateMessagePart(); if (ApplyXsltOnBodyPart) { if (string.IsNullOrEmpty(XSLTFilePath)) throw new ArgumentNullException("XsltFilePath is null"); if (!File.Exists(XSLTFilePath)) throw new FileNotFoundException(string.Format("Cannot find the xslt file '{0}'.", XSLTFilePath)); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(XSLTFilePath); Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream(); if (!originalStream.CanSeek || !originalStream.CanRead) { originalStream = new ReadOnlySeekableStream(originalStream); } XmlReader reader = XmlReader.Create(originalStream); transform.Transform(reader, null, ms); originalStream.Seek(0, SeekOrigin.Begin); pInMsg.BodyPart.Data = originalStream; } else { byte[] buff = Encoding.UTF8.GetBytes(EmailBody); ms.Write(buff, 0, buff.Length); } ms.Seek(0, SeekOrigin.Begin); bodyPart.Data = ms; bodyPart.Charset = "UTF-8"; bodyPart.ContentType = "text/html"; newMsg.AddPart("body", bodyPart, true); //Add all message parts as attachments int i = 0; string[] filenames = FileNames.Split('|'); while (i < pInMsg.PartCount & i < filenames.Length) { if (!string.IsNullOrEmpty(filenames[i])) { string partName = ""; IBaseMessagePart part = pInMsg.GetPartByIndex(i, out partName), newPart = messageFactory.CreateMessagePart(); Stream originalStream = part.GetOriginalDataStream(); newPart.Data = originalStream; newPart.Charset = part.Charset; newPart.ContentType = "text/xml"; newPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", filenames[i]); newMsg.AddPart(filenames[i], newPart, false); } i++; } return newMsg; } } }
42.409836
136
0.612099
[ "MIT" ]
walissa/EmailCustomizer
src/EmailCustomizer/EmailCustomizer.cs
5,176
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.Libraryagent.v1 { /// <summary>The Libraryagent Service.</summary> public class LibraryagentService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public LibraryagentService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public LibraryagentService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Shelves = new ShelvesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "libraryagent"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://libraryagent.googleapis.com/"; #else "https://libraryagent.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://libraryagent.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Library Agent API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Library Agent API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Shelves resource.</summary> public virtual ShelvesResource Shelves { get; } } /// <summary>A base abstract class for Libraryagent requests.</summary> public abstract class LibraryagentBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new LibraryagentBaseServiceRequest instance.</summary> protected LibraryagentBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Libraryagent parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "shelves" collection of methods.</summary> public class ShelvesResource { private const string Resource = "shelves"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ShelvesResource(Google.Apis.Services.IClientService service) { this.service = service; Books = new BooksResource(service); } /// <summary>Gets the Books resource.</summary> public virtual BooksResource Books { get; } /// <summary>The "books" collection of methods.</summary> public class BooksResource { private const string Resource = "books"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BooksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if /// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed /// exceeds allocation quota in any dimensions. /// </summary> /// <param name="name">Required. The name of the book to borrow.</param> public virtual BorrowRequest Borrow(string name) { return new BorrowRequest(service, name); } /// <summary> /// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if /// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed /// exceeds allocation quota in any dimensions. /// </summary> public class BorrowRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Borrow request.</summary> public BorrowRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to borrow.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "borrow"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}:borrow"; /// <summary>Initializes Borrow parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> /// <param name="name">Required. The name of the book to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly created books will not /// necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not exist. /// </summary> /// <param name="parent">Required. The name of the shelf whose books we'd like to list.</param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly created books will not /// necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not exist. /// </summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListBooksResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary>Required. The name of the shelf whose books we'd like to list.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Requested page size. Server may return fewer books than requested. If unspecified, server will pick /// an appropriate default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A token identifying a page of results the server should return. Typically, this is the value of /// ListBooksResponse.next_page_token. returned from the previous call to `ListBooks` method. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+parent}/books"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Return a book to the library. Returns the book if it is returned to the library successfully. Returns /// error if the book does not belong to the library or the users didn't borrow before. /// </summary> /// <param name="name">Required. The name of the book to return.</param> public virtual LibraryagentReturnRequest LibraryagentReturn(string name) { return new LibraryagentReturnRequest(service, name); } /// <summary> /// Return a book to the library. Returns the book if it is returned to the library successfully. Returns /// error if the book does not belong to the library or the users didn't borrow before. /// </summary> public class LibraryagentReturnRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new LibraryagentReturn request.</summary> public LibraryagentReturnRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to return.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "return"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}:return"; /// <summary>Initializes LibraryagentReturn parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> /// <param name="name">Required. The name of the shelf to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Shelf> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the shelf to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); } } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created shelves will not necessarily be /// added to the end of this list. /// </summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created shelves will not necessarily be /// added to the end of this list. /// </summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListShelvesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// Requested page size. Server may return fewer shelves than requested. If unspecified, server will pick an /// appropriate default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A token identifying a page of results the server should return. Typically, this is the value of /// ListShelvesResponse.next_page_token returned from the previous call to `ListShelves` method. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/shelves"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Libraryagent.v1.Data { /// <summary>A single book in the library.</summary> public class GoogleExampleLibraryagentV1Book : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The name of the book author.</summary> [Newtonsoft.Json.JsonPropertyAttribute("author")] public virtual string Author { get; set; } /// <summary> /// The resource name of the book. Book names have the form `shelves/{shelf_id}/books/{book_id}`. The name is /// ignored when creating a book. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Value indicating whether the book has been read.</summary> [Newtonsoft.Json.JsonPropertyAttribute("read")] public virtual System.Nullable<bool> Read { get; set; } /// <summary>The title of the book.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListBooks.</summary> public class GoogleExampleLibraryagentV1ListBooksResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of books.</summary> [Newtonsoft.Json.JsonPropertyAttribute("books")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Book> Books { get; set; } /// <summary> /// A token to retrieve next page of results. Pass this value in the ListBooksRequest.page_token field in the /// subsequent call to `ListBooks` method to retrieve the next page of results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListShelves.</summary> public class GoogleExampleLibraryagentV1ListShelvesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A token to retrieve next page of results. Pass this value in the ListShelvesRequest.page_token field in the /// subsequent call to `ListShelves` method to retrieve the next page of results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of shelves.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shelves")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Shelf> Shelves { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A Shelf contains a collection of books with a theme.</summary> public class GoogleExampleLibraryagentV1Shelf : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Output only. The resource name of the shelf. Shelf names have the form `shelves/{shelf_id}`. The name is /// ignored when creating a shelf. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The theme of the shelf</summary> [Newtonsoft.Json.JsonPropertyAttribute("theme")] public virtual string Theme { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
44.633242
149
0.574955
[ "Apache-2.0" ]
ScriptBox21/google-api-dotnet-client
Src/Generated/Google.Apis.Libraryagent.v1/Google.Apis.Libraryagent.v1.cs
32,493
C#
//using System; //using System.Collections.Generic; //using System.Text; //using System.ComponentModel; //using System.Drawing; //namespace DevAge.Drawing.VisualElements //{ // /// <summary> // /// A background with a border. // /// Use the Background property to set an additional background // /// </summary> // [Serializable] // public class BackgroundBorder : BackgroundBorderBase // { // #region Constructor // /// <summary> // /// Default constructor // /// </summary> // public BackgroundBorder() // { // } // /// <summary> // /// Copy constructor // /// </summary> // /// <param name="other"></param> // public BackgroundBorder(BackgroundBorder other) // : base(other) // { // Border = other.Border; // } // #endregion // #region Properties // private RectangleBorder mBorder = RectangleBorder.NoBorder; // /// <summary> // /// Gets or sets the border to draw around the VisualElement. Default is RectangleBlack1Width. // /// </summary> // public virtual RectangleBorder Border // { // get { return mBorder; } // set { mBorder = value; } // } // protected virtual bool ShouldSerializeBorder() // { // return Border != RectangleBorder.NoBorder; // } // #endregion // /// <summary> // /// Calculate the client area where the content can be drawed, usually removing the area used by the background, for example removing a border. // /// </summary> // /// <param name="graphics"></param> // /// <param name="backGroundArea"></param> // /// <returns></returns> // public override RectangleF GetBackgroundContentRectangle(MeasureHelper measure, RectangleF backGroundArea) // { // backGroundArea = Border.RemoveBorderFromRectangle(backGroundArea); // return base.GetBackgroundContentRectangle(measure, backGroundArea); // } // /// <summary> // /// Calculate the total area used by the backgound and the content, adding the background area to the content area. // /// </summary> // /// <param name="graphics"></param> // /// <param name="contentSize"></param> // /// <returns></returns> // public override SizeF GetBackgroundExtent(MeasureHelper measure, SizeF contentSize) // { // contentSize = base.GetBackgroundExtent(measure, contentSize); // contentSize = Border.AddBorderToSize(contentSize); // return contentSize; // } // protected override void OnDrawBorder(GraphicsCache graphics, RectangleF area) // { // Border.DrawBorder(graphics, Rectangle.Round(area)); // } // /// <summary> // /// Clone // /// </summary> // /// <returns></returns> // public override object Clone() // { // return new BackgroundBorder(this); // } // } //}
31.876289
153
0.563389
[ "Unlicense" ]
GibraltarSoftware/SourceGrid
src/DevAge.Windows.Forms/Drawing/VisualElements/BackgroundBorder.cs
3,092
C#
using System; using UnityEngine; namespace EA4S.Scanner { public class ScannerResultState : IGameState { ScannerGame game; float timer = 2; public ScannerResultState(ScannerGame game) { this.game = game; } public void EnterState() { AudioManager.I.PlayMusic(Music.Relax); } public void ExitState() { } public void Update(float delta) { timer -= delta; if (timer < 0) { game.EndGame(game.CurrentStars, game.CurrentScoreRecord); if (game.CurrentStars == 0) AudioManager.I.PlayDialog("Reward_0Star"); else AudioManager.I.PlayDialog("Reward_" + game.CurrentStars + "Star_" + UnityEngine.Random.Range(1, 4)); } } public void UpdatePhysics(float delta) { } } }
17.866667
120
0.613184
[ "BSD-2-Clause" ]
Megapop/Norad-Eduapp4syria
Antura/EA4S_Antura_U3D/Assets/_games/Scanner/_scripts/ScannerResultState.cs
806
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace VirtuosoQueryData { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new fMain()); } } }
22.434783
65
0.616279
[ "MIT" ]
GeorgiaBr/Virtuoso-Query-Data
DBPediaData/Program.cs
518
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 medialive-2017-10-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MediaLive.Model { /// <summary> /// Mpeg2 Settings /// </summary> public partial class Mpeg2Settings { private Mpeg2AdaptiveQuantization _adaptiveQuantization; private AfdSignaling _afdSignaling; private Mpeg2ColorMetadata _colorMetadata; private Mpeg2ColorSpace _colorSpace; private Mpeg2DisplayRatio _displayAspectRatio; private Mpeg2FilterSettings _filterSettings; private FixedAfd _fixedAfd; private int? _framerateDenominator; private int? _framerateNumerator; private int? _gopClosedCadence; private int? _gopNumBFrames; private double? _gopSize; private Mpeg2GopSizeUnits _gopSizeUnits; private Mpeg2ScanType _scanType; private Mpeg2SubGopLength _subgopLength; private Mpeg2TimecodeInsertionBehavior _timecodeInsertion; /// <summary> /// Gets and sets the property AdaptiveQuantization. Choose Off to disable adaptive quantization. /// Or choose another value to enable the quantizer and set its strength. The strengths /// are: Auto, Off, Low, Medium, High. When you enable this field, MediaLive allows intra-frame /// quantizers to vary, which might improve visual quality. /// </summary> public Mpeg2AdaptiveQuantization AdaptiveQuantization { get { return this._adaptiveQuantization; } set { this._adaptiveQuantization = value; } } // Check to see if AdaptiveQuantization property is set internal bool IsSetAdaptiveQuantization() { return this._adaptiveQuantization != null; } /// <summary> /// Gets and sets the property AfdSignaling. Indicates the AFD values that MediaLive will /// write into the video encode. If you do not know what AFD signaling is, or if your /// downstream system has not given you guidance, choose AUTO.AUTO: MediaLive will try /// to preserve the input AFD value (in cases where multiple AFD values are valid).FIXED: /// MediaLive will use the value you specify in fixedAFD. /// </summary> public AfdSignaling AfdSignaling { get { return this._afdSignaling; } set { this._afdSignaling = value; } } // Check to see if AfdSignaling property is set internal bool IsSetAfdSignaling() { return this._afdSignaling != null; } /// <summary> /// Gets and sets the property ColorMetadata. Specifies whether to include the color space /// metadata. The metadata describes the color space that applies to the video (the colorSpace /// field). We recommend that you insert the metadata. /// </summary> public Mpeg2ColorMetadata ColorMetadata { get { return this._colorMetadata; } set { this._colorMetadata = value; } } // Check to see if ColorMetadata property is set internal bool IsSetColorMetadata() { return this._colorMetadata != null; } /// <summary> /// Gets and sets the property ColorSpace. Choose the type of color space conversion to /// apply to the output. For detailed information on setting up both the input and the /// output to obtain the desired color space in the output, see the section on \"MediaLive /// Features - Video - color space\" in the MediaLive User Guide.PASSTHROUGH: Keep the /// color space of the input content - do not convert it.AUTO:Convert all content that /// is SD to rec 601, and convert all content that is HD to rec 709. /// </summary> public Mpeg2ColorSpace ColorSpace { get { return this._colorSpace; } set { this._colorSpace = value; } } // Check to see if ColorSpace property is set internal bool IsSetColorSpace() { return this._colorSpace != null; } /// <summary> /// Gets and sets the property DisplayAspectRatio. Sets the pixel aspect ratio for the /// encode. /// </summary> public Mpeg2DisplayRatio DisplayAspectRatio { get { return this._displayAspectRatio; } set { this._displayAspectRatio = value; } } // Check to see if DisplayAspectRatio property is set internal bool IsSetDisplayAspectRatio() { return this._displayAspectRatio != null; } /// <summary> /// Gets and sets the property FilterSettings. Optionally specify a noise reduction filter, /// which can improve quality of compressed content. If you do not choose a filter, no /// filter will be applied.TEMPORAL: This filter is useful for both source content that /// is noisy (when it has excessive digital artifacts) and source content that is clean.When /// the content is noisy, the filter cleans up the source content before the encoding /// phase, with these two effects: First, it improves the output video quality because /// the content has been cleaned up. Secondly, it decreases the bandwidth because MediaLive /// does not waste bits on encoding noise.When the content is reasonably clean, the filter /// tends to decrease the bitrate. /// </summary> public Mpeg2FilterSettings FilterSettings { get { return this._filterSettings; } set { this._filterSettings = value; } } // Check to see if FilterSettings property is set internal bool IsSetFilterSettings() { return this._filterSettings != null; } /// <summary> /// Gets and sets the property FixedAfd. Complete this field only when afdSignaling is /// set to FIXED. Enter the AFD value (4 bits) to write on all frames of the video encode. /// </summary> public FixedAfd FixedAfd { get { return this._fixedAfd; } set { this._fixedAfd = value; } } // Check to see if FixedAfd property is set internal bool IsSetFixedAfd() { return this._fixedAfd != null; } /// <summary> /// Gets and sets the property FramerateDenominator. description": "The framerate denominator. /// For example, 1001. The framerate is the numerator divided by the denominator. For /// example, 24000 / 1001 = 23.976 FPS. /// </summary> [AWSProperty(Required=true, Min=1)] public int FramerateDenominator { get { return this._framerateDenominator.GetValueOrDefault(); } set { this._framerateDenominator = value; } } // Check to see if FramerateDenominator property is set internal bool IsSetFramerateDenominator() { return this._framerateDenominator.HasValue; } /// <summary> /// Gets and sets the property FramerateNumerator. The framerate numerator. For example, /// 24000. The framerate is the numerator divided by the denominator. For example, 24000 /// / 1001 = 23.976 FPS. /// </summary> [AWSProperty(Required=true, Min=1)] public int FramerateNumerator { get { return this._framerateNumerator.GetValueOrDefault(); } set { this._framerateNumerator = value; } } // Check to see if FramerateNumerator property is set internal bool IsSetFramerateNumerator() { return this._framerateNumerator.HasValue; } /// <summary> /// Gets and sets the property GopClosedCadence. MPEG2: default is open GOP. /// </summary> [AWSProperty(Min=0)] public int GopClosedCadence { get { return this._gopClosedCadence.GetValueOrDefault(); } set { this._gopClosedCadence = value; } } // Check to see if GopClosedCadence property is set internal bool IsSetGopClosedCadence() { return this._gopClosedCadence.HasValue; } /// <summary> /// Gets and sets the property GopNumBFrames. Relates to the GOP structure. The number /// of B-frames between reference frames. If you do not know what a B-frame is, use the /// default. /// </summary> [AWSProperty(Min=0, Max=7)] public int GopNumBFrames { get { return this._gopNumBFrames.GetValueOrDefault(); } set { this._gopNumBFrames = value; } } // Check to see if GopNumBFrames property is set internal bool IsSetGopNumBFrames() { return this._gopNumBFrames.HasValue; } /// <summary> /// Gets and sets the property GopSize. Relates to the GOP structure. The GOP size (keyframe /// interval) in the units specified in gopSizeUnits. If you do not know what GOP is, /// use the default.If gopSizeUnits is frames, then the gopSize must be an integer and /// must be greater than or equal to 1.If gopSizeUnits is seconds, the gopSize must be /// greater than 0, but does not need to be an integer. /// </summary> public double GopSize { get { return this._gopSize.GetValueOrDefault(); } set { this._gopSize = value; } } // Check to see if GopSize property is set internal bool IsSetGopSize() { return this._gopSize.HasValue; } /// <summary> /// Gets and sets the property GopSizeUnits. Relates to the GOP structure. Specifies whether /// the gopSize is specified in frames or seconds. If you do not plan to change the default /// gopSize, leave the default. If you specify SECONDS, MediaLive will internally convert /// the gop size to a frame count. /// </summary> public Mpeg2GopSizeUnits GopSizeUnits { get { return this._gopSizeUnits; } set { this._gopSizeUnits = value; } } // Check to see if GopSizeUnits property is set internal bool IsSetGopSizeUnits() { return this._gopSizeUnits != null; } /// <summary> /// Gets and sets the property ScanType. Set the scan type of the output to PROGRESSIVE /// or INTERLACED (top field first). /// </summary> public Mpeg2ScanType ScanType { get { return this._scanType; } set { this._scanType = value; } } // Check to see if ScanType property is set internal bool IsSetScanType() { return this._scanType != null; } /// <summary> /// Gets and sets the property SubgopLength. Relates to the GOP structure. If you do not /// know what GOP is, use the default.FIXED: Set the number of B-frames in each sub-GOP /// to the value in gopNumBFrames.DYNAMIC: Let MediaLive optimize the number of B-frames /// in each sub-GOP, to improve visual quality. /// </summary> public Mpeg2SubGopLength SubgopLength { get { return this._subgopLength; } set { this._subgopLength = value; } } // Check to see if SubgopLength property is set internal bool IsSetSubgopLength() { return this._subgopLength != null; } /// <summary> /// Gets and sets the property TimecodeInsertion. Determines how MediaLive inserts timecodes /// in the output video. For detailed information about setting up the input and the output /// for a timecode, see the section on \"MediaLive Features - Timecode configuration\" /// in the MediaLive User Guide.DISABLED: do not include timecodes.GOP_TIMECODE: Include /// timecode metadata in the GOP header. /// </summary> public Mpeg2TimecodeInsertionBehavior TimecodeInsertion { get { return this._timecodeInsertion; } set { this._timecodeInsertion = value; } } // Check to see if TimecodeInsertion property is set internal bool IsSetTimecodeInsertion() { return this._timecodeInsertion != null; } } }
39.991254
108
0.606765
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/Mpeg2Settings.cs
13,717
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xml; using System.Xml.Serialization; namespace WordGame.Storage { /// <summary> /// Словарь слов /// </summary> [XmlRoot(ElementName = "WordList", Namespace = "http://www.orioner.ru/croc")] public class WordList : IEqualityComparer<Word>, IDict { /// <summary> /// Массив словарных слов /// </summary> [XmlElement(ElementName = "Word")] public Word[] Words; /// <summary> /// Загрузить XML-файл /// </summary> /// <param name="name">Имя XML-файла</param> /// <returns></returns> public static WordList Load(string name) { // Сериализатор - десериализатор XmlSerializer ser = new XmlSerializer(typeof(WordList)); // Читатель XML-файла XmlReader rdr = XmlReader.Create(name); // Десериализация object list = ser.Deserialize(rdr); // Приведение типа и возврат результата return (WordList)list; } /// <summary> /// Сохранение словаря в XML-файл /// </summary> /// <param name="name">Имя файла</param> public void Save(string name) { // Сериализатор - десериализатор XmlSerializer ser = new XmlSerializer(typeof(WordList)); // Настройки var settings = new XmlWriterSettings() { Indent = true // Строки по-человечески }; // Писатель using (XmlWriter wrt = XmlWriter.Create(name, settings)) { // Формирование XML-файла ser.Serialize(wrt, this); } } /// <summary> /// Сравнение слов на равенство /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public bool Equals(Word x, Word y) { return x.Name == y.Name; } /// <summary> /// Хэш объекта /// </summary> /// <param name="obj"></param> /// <returns></returns> public int GetHashCode(Word obj) { return obj.Name.GetHashCode(); } /// <summary> /// Проверка на наличие слова в словаре /// </summary> /// <param name="s">Слово</param> /// <returns></returns> public bool Contains(string s) { var w = new Word(s); return Words.Contains(w, this); } /// <summary> /// Добавление слова в словарь /// </summary> /// <param name="s">Новое слово</param> public void Append(string s) { // Перегнать массив в список List<Word> l = Words.ToList(); // Добавление слова l.Add(new Word(s)); // Перегнать список в массив Words = l.ToArray(); // Сохранить в файл Save(@"C:\TEST.XML"); } } }
28.87963
81
0.498237
[ "MIT" ]
sbannikov/csharpcroc
2019-Autumn/WordGame/Storage/WordList.cs
3,541
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // 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 ClearCanvas Inc. 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 OWNER 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. #endregion using System.Collections.Generic; using System.Security.Permissions; using System.Threading; using ClearCanvas.Common; using ClearCanvas.Desktop.Tools; using ClearCanvas.Ris.Application.Common.ReportingWorkflow; namespace ClearCanvas.Ris.Client.Workflow { [ExtensionPoint] public class TranscriptionWorkflowFolderExtensionPoint : ExtensionPoint<IWorklistFolder> { } [ExtensionPoint] public class TranscriptionWorkflowItemToolExtensionPoint : ExtensionPoint<ITool> { } [ExtensionPoint] public class TranscriptionWorkflowFolderToolExtensionPoint : ExtensionPoint<ITool> { } [ExtensionOf(typeof(FolderSystemExtensionPoint))] [PrincipalPermission(SecurityAction.Demand, Role = ClearCanvas.Ris.Application.Common.AuthorityTokens.FolderSystems.Transcription)] public class TranscriptionWorkflowFolderSystem : ReportingWorkflowFolderSystemBase<TranscriptionWorkflowFolderExtensionPoint, TranscriptionWorkflowFolderToolExtensionPoint, TranscriptionWorkflowItemToolExtensionPoint> { public TranscriptionWorkflowFolderSystem() : base(SR.TitleTranscriptionFolderSystem) { } protected override void AddDefaultFolders() { this.Folders.Add(new Folders.Transcription.ToBeReviewedFolder()); this.Folders.Add(new Folders.Transcription.DraftFolder()); if (Thread.CurrentPrincipal.IsInRole(ClearCanvas.Ris.Application.Common.AuthorityTokens.Workflow.Transcription.SubmitForReview)) this.Folders.Add(new Folders.Transcription.AwaitingReviewFolder()); this.Folders.Add(new Folders.Transcription.CompletedFolder()); } protected override string GetPreviewUrl(WorkflowFolder folder, ICollection<ReportingWorklistItem> items) { return WebResourcesSettings.Default.TranscriptionFolderSystemUrl; } protected override SearchResultsFolder CreateSearchResultsFolder() { return new Folders.Transcription.TranscriptionSearchFolder(); } } }
40.988636
133
0.773773
[ "Apache-2.0" ]
econmed/ImageServer20
Ris/Client/Workflow/TranscriptionWorkflowFolderSystem.cs
3,609
C#
namespace android.webkit { [global::MonoJavaBridge.JavaClass()] public sealed partial class WebStorage : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static WebStorage() { InitJNI(); } internal WebStorage(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.webkit.WebStorage.QuotaUpdater_))] public interface QuotaUpdater : global::MonoJavaBridge.IJavaObject { void updateQuota(long arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.webkit.WebStorage.QuotaUpdater))] public sealed partial class QuotaUpdater_ : java.lang.Object, QuotaUpdater { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static QuotaUpdater_() { InitJNI(); } internal QuotaUpdater_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _updateQuota10546; void android.webkit.WebStorage.QuotaUpdater.updateQuota(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.QuotaUpdater_._updateQuota10546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.QuotaUpdater_.staticClass, global::android.webkit.WebStorage.QuotaUpdater_._updateQuota10546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.webkit.WebStorage.QuotaUpdater_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebStorage$QuotaUpdater")); global::android.webkit.WebStorage.QuotaUpdater_._updateQuota10546 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.QuotaUpdater_.staticClass, "updateQuota", "(J)V"); } } internal static global::MonoJavaBridge.MethodId _getInstance10547; public static global::android.webkit.WebStorage getInstance() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._getInstance10547)) as android.webkit.WebStorage; } internal static global::MonoJavaBridge.MethodId _getOrigins10548; public void getOrigins(android.webkit.ValueCallback arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._getOrigins10548, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._getOrigins10548, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getUsageForOrigin10549; public void getUsageForOrigin(java.lang.String arg0, android.webkit.ValueCallback arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._getUsageForOrigin10549, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._getUsageForOrigin10549, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getQuotaForOrigin10550; public void getQuotaForOrigin(java.lang.String arg0, android.webkit.ValueCallback arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._getQuotaForOrigin10550, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._getQuotaForOrigin10550, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setQuotaForOrigin10551; public void setQuotaForOrigin(java.lang.String arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._setQuotaForOrigin10551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._setQuotaForOrigin10551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _deleteOrigin10552; public void deleteOrigin(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._deleteOrigin10552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._deleteOrigin10552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _deleteAllData10553; public void deleteAllData() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.webkit.WebStorage._deleteAllData10553); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._deleteAllData10553); } internal static global::MonoJavaBridge.MethodId _WebStorage10554; public WebStorage() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.webkit.WebStorage.staticClass, global::android.webkit.WebStorage._WebStorage10554); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.webkit.WebStorage.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebStorage")); global::android.webkit.WebStorage._getInstance10547 = @__env.GetStaticMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "getInstance", "()Landroid/webkit/WebStorage;"); global::android.webkit.WebStorage._getOrigins10548 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "getOrigins", "(Landroid/webkit/ValueCallback;)V"); global::android.webkit.WebStorage._getUsageForOrigin10549 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "getUsageForOrigin", "(Ljava/lang/String;Landroid/webkit/ValueCallback;)V"); global::android.webkit.WebStorage._getQuotaForOrigin10550 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "getQuotaForOrigin", "(Ljava/lang/String;Landroid/webkit/ValueCallback;)V"); global::android.webkit.WebStorage._setQuotaForOrigin10551 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "setQuotaForOrigin", "(Ljava/lang/String;J)V"); global::android.webkit.WebStorage._deleteOrigin10552 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "deleteOrigin", "(Ljava/lang/String;)V"); global::android.webkit.WebStorage._deleteAllData10553 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "deleteAllData", "()V"); global::android.webkit.WebStorage._WebStorage10554 = @__env.GetMethodIDNoThrow(global::android.webkit.WebStorage.staticClass, "<init>", "()V"); } } }
66.573643
270
0.799371
[ "MIT" ]
beachmiles/androidmono
jni/MonoJavaBridge/android/generated/android/webkit/WebStorage.cs
8,588
C#
using System; using UnityGameEvents; using UnityGameEventSystemExtensions.Objects; namespace UnityGameEventSystemExtensions { public interface ISystemInt32GameEventListenerController : IGameEventWithParameterListenerController<SystemInt32GameEventListenerObjectScript, Int32> { // ... } }
25.833333
153
0.812903
[ "MIT" ]
BigETI/UnityGameEventSystemExtensions
Runtime/Interfaces/ISystemInt32GameEventListenerController.cs
310
C#
using DarkUI.Renderers; using System.Drawing; using System.Windows.Forms; namespace DarkUI.Controls { public class DarkToolStrip : ToolStrip { #region Constructor Region public DarkToolStrip() { Renderer = new DarkToolStripRenderer(); Padding = new Padding(5, 0, 1, 0); AutoSize = false; Size = new Size(1, 28); } #endregion } }
19.681818
51
0.572748
[ "MIT" ]
ActuallyaDeviloper/DarkUI
DarkUI/Controls/DarkToolStrip.cs
435
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; namespace Dolittle.Runtime.Immutability { /// <summary> /// Holds extension methods for working with immutables. /// </summary> public static class ImmutableExtensions { const BindingFlags PublicInstancePropertyFlag = BindingFlags.Public | BindingFlags.Instance; /// <summary> /// Check if a type is immutable by virtue of it having public properties or fields that can be written to. /// </summary> /// <param name="type"><see cref="Type"/> to check.</param> /// <returns>True if it is immutable, false if not.</returns> /// <remarks> /// Immutability is a difficult concept in C#. Things can be changed via reflection, fields rather than properties, private setters, etc. static /// We are taking a deliberately limited view of immutability. In this case it simply means an object that has no properties with setters (public or private) /// This is not intended to be an indication that the object is truly immutable, instead it's to guide the instantiation strategy when we create and hydrate it /// from a serialized form. /// </remarks> public static bool IsImmutable(this Type type) { var writeableProperties = type.GetWriteableProperties(); var writeableFields = type.GetWriteableFields(); return writeableProperties.Length == 0 && writeableFields.Length == 0; } /// <summary> /// Check if a type is really immutable and if it's not, throw the appropriate exception. /// </summary> /// <param name="type"><see cref="Type"/> to check.</param> public static void ShouldBeImmutable(this Type type) { var writeableProperties = type.GetWriteableProperties(); if (writeableProperties.Length > 0) throw new WriteableImmutablePropertiesFound(type, writeableProperties); var writeableFields = type.GetWriteableFields(); if (writeableFields.Length > 0) throw new WriteableImmutableFieldsFound(type, writeableFields); } /// <summary> /// Get the writeable properties - if any - on a specific type. /// For init-only properties: /// https://www.meziantou.net/csharp9-init-only-properties-are-not-read-only.htm /// </summary> /// <param name="type"><see cref="Type"/> to get from.</param> /// <returns>Writeable <see cref="PropertyInfo">properties</see>.</returns> public static PropertyInfo[] GetWriteableProperties(this Type type) => type.GetProperties(PublicInstancePropertyFlag) .Where(_ => _.CanWrite) .Where(_ => !IsInitSetter(_)) .ToArray(); /// <summary> /// Get the writeable fields - if any - on a specific type. /// </summary> /// <param name="type"><see cref="Type"/> to get from.</param> /// <returns>Writeable <see cref="FieldInfo">fields</see>.</returns> public static FieldInfo[] GetWriteableFields(this Type type) => type .GetFields(PublicInstancePropertyFlag) .Where(_ => (_.Attributes & FieldAttributes.InitOnly) == 0) .ToArray(); static bool IsInitSetter(PropertyInfo property) => property.SetMethod.ReturnParameter .GetRequiredCustomModifiers() .Contains(typeof(System.Runtime.CompilerServices.IsExternalInit)); } }
46.518519
167
0.639331
[ "MIT" ]
dolittle/Runtime
Source/Immutability/ImmutableExtensions.cs
3,768
C#
using System; using System.Linq.Expressions; using System.Text.RegularExpressions; namespace Validatum { public static partial class ValidatorBuilderExtensions { /// <summary> /// Adds a validator to ensure the value is not an empty string. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> NotEmpty(this IValidatorBuilder<string> builder, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } return builder .When( ctx => ctx.Value == string.Empty, ctx => ctx.AddBrokenRule(nameof(NotEmpty), key, message ?? "Value cannot be empty.") ); } /// <summary> /// Adds a validator to ensure the value is not an empty string for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> NotEmpty<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.NotEmpty(key, message)); } /// <summary> /// Adds a validator to ensure the value is an empty string. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Empty(this IValidatorBuilder<string> builder, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } return builder .WhenNot( ctx => ctx.Value == string.Empty, ctx => ctx.AddBrokenRule(nameof(Empty), key, message ?? "Value must be empty.") ); } /// <summary> /// Adds a validator to ensure the value is an empty string for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Empty<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.Empty(key, message)); } /// <summary> /// Adds a validator to ensure the value matches a regular expression pattern. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="pattern">The regular expression pattern.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Regex(this IValidatorBuilder<string> builder, string pattern, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrWhiteSpace(pattern)) { throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); } return builder .WhenNot( ctx => System.Text.RegularExpressions.Regex.IsMatch(ctx.Value ?? string.Empty, pattern), ctx => ctx.AddBrokenRule(nameof(Regex), key, message ?? "Value must match pattern.") ); } /// <summary> /// Adds a validator to ensure the value matches a regular expression pattern using specified regex options. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="pattern">The regular expression pattern.</param> /// <param name="options">The regex options.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Regex(this IValidatorBuilder<string> builder, string pattern, RegexOptions options, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrWhiteSpace(pattern)) { throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); } return builder .WhenNot( ctx => System.Text.RegularExpressions.Regex.IsMatch(ctx.Value ?? string.Empty, pattern, options), ctx => ctx.AddBrokenRule(nameof(Regex), key, message ?? "Value must match pattern.") ); } /// <summary> /// Adds a validator to ensure the value matches a regular expression pattern for the /// target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="pattern">The regular expression pattern.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Regex<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string pattern, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (string.IsNullOrWhiteSpace(pattern)) { throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); } return builder.For(selector, p => p.Regex(pattern, key, message)); } /// <summary> /// Adds a validator to ensure the value matches a regular expression pattern for the /// target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="pattern">The regular expression pattern.</param> /// <param name="options">The regex options.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Regex<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string pattern, RegexOptions options, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (string.IsNullOrWhiteSpace(pattern)) { throw new ArgumentException("Cannot be null or empty or whitespace.", nameof(pattern)); } return builder.For(selector, p => p.Regex(pattern, options, key, message)); } /// <summary> /// Adds a validator to ensure the value starts with the specified value. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="value">The value the string starts with.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> StartsWith(this IValidatorBuilder<string> builder, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } return builder .WhenNot( ctx => ctx.Value?.StartsWith(value) ?? false, ctx => ctx.AddBrokenRule(nameof(StartsWith), key, message ?? $"Value must start with '{value}'.") ); } /// <summary> /// Adds a validator to ensure the value starts with the specified for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="value">The value the string starts with.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> StartsWith<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.StartsWith(value, key, message)); } /// <summary> /// Adds a validator to ensure the value ends with the specified value. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="value">The value the string ends with.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> EndsWith(this IValidatorBuilder<string> builder, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } return builder .WhenNot( ctx => ctx.Value?.EndsWith(value) ?? false, ctx => ctx.AddBrokenRule(nameof(EndsWith), key, message ?? $"Value must end with '{value}'.") ); } /// <summary> /// Adds a validator to ensure the value ends with the specified for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="value">The value the string ends with.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> EndsWith<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.EndsWith(value, key, message)); } /// <summary> /// Adds a validator to ensure the value contains the specified value. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="value">The value the string contains.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Contains(this IValidatorBuilder<string> builder, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } return builder .WhenNot( ctx => ctx.Value?.Contains(value) ?? false, ctx => ctx.AddBrokenRule(nameof(Contains), key, message ?? $"Value must contain '{value}'.") ); } /// <summary> /// Adds a validator to ensure the value contains the specified for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="value">The value the string contains.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Contains<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string value, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Cannot be null or empty.", nameof(value)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.Contains(value, key, message)); } /// <summary> /// Adds a validator to ensure the value length is within a specified range. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="min">The minimum length.</param> /// <param name="max">The maximum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Length(this IValidatorBuilder<string> builder, int min, int max, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (min < 0) { throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); } if (min > max) { throw new ArgumentOutOfRangeException(nameof(min), min, $"Cannot be greater than max parameter (max '{max}')."); } return builder .When( ctx => ctx.Value is null || ctx.Value?.Length < min || ctx.Value?.Length > max, ctx => ctx.AddBrokenRule(nameof(Length), key, message ?? $"Value must be {min} to {max} characters in length.") ); } /// <summary> /// Adds a validator to ensure the value length is within a specified range. /// for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="min">The minimum length.</param> /// <param name="max">The maximum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Length<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, int min, int max, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (min < 0) { throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); } if (min > max) { throw new ArgumentOutOfRangeException(nameof(min), min, $"Cannot be greater than max parameter (max '{max}')."); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.Length(min, max, key, message)); } /// <summary> /// Adds a validator to ensure the value is of a minimum length. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="min">The minimum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> MinLength(this IValidatorBuilder<string> builder, int min, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (min < 0) { throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); } return builder .When( ctx => ctx.Value is null || ctx.Value?.Length < min, ctx => ctx.AddBrokenRule(nameof(MinLength), key, message ?? $"Value must have minimum length of {min}.") ); } /// <summary> /// Adds a validator to ensure the value is of a minimum length for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="min">The minimum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> MinLength<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, int min, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (min < 0) { throw new ArgumentOutOfRangeException(nameof(min), min, "Cannot be less than zero."); } return builder.For<T, string>(selector, p => p.MinLength(min, key, message)); } /// <summary> /// Adds a validator to ensure the value is not longer than maximum length. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="max">The maximum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> MaxLength(this IValidatorBuilder<string> builder, int max, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (max < 0) { throw new ArgumentOutOfRangeException(nameof(max), max, "Cannot be less than zero."); } return builder .When( ctx => ctx.Value?.Length > max, ctx => ctx.AddBrokenRule(nameof(MaxLength), key, message ?? $"Value must have maximum length of {max}.") ); } /// <summary> /// Adds a validator to ensure the value is of a maximum length for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="max">The maximum length.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> MaxLength<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, int max, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } if (max < 0) { throw new ArgumentOutOfRangeException(nameof(max), max, "Cannot be less than zero."); } return builder.For<T, string>(selector, p => p.MaxLength(max, key, message)); } /// <summary> /// Adds a validator to ensure the value is not null or empty or whitespace. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Required(this IValidatorBuilder<string> builder, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } return builder .When( ctx => string.IsNullOrWhiteSpace(ctx.Value), ctx => ctx.AddBrokenRule(nameof(Required), key, message ?? $"Value is required.") ); } /// <summary> /// Adds a validator to ensure the value is not null or empty or whitespace for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Required<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.Required(key, message)); } private static readonly System.Text.RegularExpressions.Regex EmailRegex = new System.Text.RegularExpressions.Regex( @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); /// <summary> /// Adds a validator to ensure the value is an email address. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<string> Email(this IValidatorBuilder<string> builder, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } return builder .WhenNot( ctx => EmailRegex.IsMatch(ctx.Value ?? string.Empty), ctx => ctx.AddBrokenRule(nameof(Email), key, message ?? $"Value must be a valid email.") ); } /// <summary> /// Adds a validator to ensure the value is an email address for the target of the selector expression. /// </summary> /// <param name="builder">The validation builder.</param> /// <param name="selector">The selector expression.</param> /// <param name="key">The key to use in broken rule.</param> /// <param name="message">The message to use in broken rule.</param> public static IValidatorBuilder<T> Email<T>(this IValidatorBuilder<T> builder, Expression<Func<T, string>> selector, string key = null, string message = null) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (selector is null) { throw new ArgumentNullException(nameof(selector)); } key = key ?? selector.GetPropertyPath(); return builder.For<T, string>(selector, p => p.Email(key, message)); } } }
40.794286
154
0.549832
[ "MIT" ]
bsheldrick/validatum
src/Validatum/src/Extensions/ValidatorBuilderExtensions.Strings.cs
28,556
C#
using NBitcoin; using Stratis.SmartContracts.CLR.Local; namespace Stratis.SmartContracts.CLR { public interface ILocalExecutor { ILocalExecutionResult Execute(ulong blockHeight, uint160 sender, Money txOutValue, ContractTxData txData); } }
23.818182
114
0.767176
[ "MIT" ]
0tim0/StratisFullNode
src/Stratis.SmartContracts.CLR/ILocalExecutor.cs
264
C#
using GraphQL; using GraphQL.Client.Tests.Common; using GraphQL.Client.Tests.Common.Chat.Schema; using GraphQL.Server; using GraphQL.Server.Ui.GraphiQL; using GraphQL.Server.Ui.Playground; using GraphQL.StarWars; using GraphQL.Types; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace IntegrationTestServer { public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment environment) { Configuration = configuration; Environment = environment; } public IConfiguration Configuration { get; } public IWebHostEnvironment Environment { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.Configure<KestrelServerOptions>(options => options.AllowSynchronousIO = true); services.AddTransient<IDependencyResolver>(provider => new FuncDependencyResolver(provider.GetService)); services.AddChatSchema(); services.AddStarWarsSchema(); services.AddGraphQL(options => { options.EnableMetrics = true; options.ExposeExceptions = Environment.IsDevelopment(); }) .AddWebSockets(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseWebSockets(); ConfigureGraphQLSchema<ChatSchema>(app, Common.CHAT_ENDPOINT); ConfigureGraphQLSchema<StarWarsSchema>(app, Common.STAR_WARS_ENDPOINT); app.UseGraphiQLServer(new GraphiQLOptions { GraphiQLPath = "/ui/graphiql", GraphQLEndPoint = Common.STAR_WARS_ENDPOINT }); app.UseGraphQLPlayground(new GraphQLPlaygroundOptions { Path = "/ui/playground", GraphQLEndPoint = Common.CHAT_ENDPOINT }); } private void ConfigureGraphQLSchema<TSchema>(IApplicationBuilder app, string endpoint) where TSchema : Schema { app.UseGraphQLWebSockets<TSchema>(endpoint); app.UseGraphQL<TSchema>(endpoint); } } }
35.822785
122
0.657597
[ "MIT" ]
Eilon/graphql-client
tests/IntegrationTestServer/Startup.cs
2,830
C#
using System; namespace RouteOptimizer.Models { public static class Ids { public static string PlaceId(string name, string address) { if (!string.IsNullOrEmpty(name)) { return NameToId(name); } else if (!string.IsNullOrEmpty(address)) { return AddrToId(address); } else { return string.Empty; } } public static string NameToId(string name) => $"[{name}]"; public static string AddrToId(string addr) => $"({addr})"; } }
20
60
0.663043
[ "MIT" ]
Roman-Dementiev/Dwares
Samples/RouteOptimizer/RouteOptimizer/Models/Ids.cs
462
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ESFA.DC.ILR.ValidationService.Interface; namespace ESFA.DC.ILR.ValidationService.RuleSet { public class RuleSetOrchestrationService<T, U> : IRuleSetOrchestrationService<T, U> where T : class { private readonly IRuleSetResolutionService<T> _ruleSetResolutionService; private readonly IValidationItemProviderService<IEnumerable<T>> _validationItemProviderService; private readonly IRuleSetExecutionService<T> _ruleSetExecutionService; private readonly IValidationErrorCache<U> _validationErrorCache; public RuleSetOrchestrationService( IRuleSetResolutionService<T> ruleSetResolutionService, IValidationItemProviderService<IEnumerable<T>> validationItemProviderService, IRuleSetExecutionService<T> ruleSetExecutionService, IValidationErrorCache<U> validationErrorCache) { _ruleSetResolutionService = ruleSetResolutionService; _validationItemProviderService = validationItemProviderService; _ruleSetExecutionService = ruleSetExecutionService; _validationErrorCache = validationErrorCache; } public async Task<IEnumerable<U>> ExecuteAsync(IEnumerable<string> ignoredRules, CancellationToken cancellationToken) { List<IRule<T>> ruleSet = _ruleSetResolutionService.Resolve().Where(x => !ignoredRules.Any(y => string.Equals(x.RuleName, y, StringComparison.OrdinalIgnoreCase))).ToList(); IEnumerable<T> items = await _validationItemProviderService.ProvideAsync(cancellationToken); foreach (T validationItem in items) { cancellationToken.ThrowIfCancellationRequested(); _ruleSetExecutionService.Execute(ruleSet, validationItem); } return _validationErrorCache.ValidationErrors; } } }
43.652174
183
0.728088
[ "MIT" ]
SkillsFundingAgency/DC-ILR-1819-ValidationService
src/ESFA.DC.ILR.ValidationService.RuleSet/RuleSetOrchestrationService.cs
2,010
C#
using System.Reflection; using System; [assembly: AssemblyTitle("SharpArch.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("SharpArch.Data")] [assembly: CLSCompliant(true)]
28.142857
45
0.77665
[ "BSD-3-Clause" ]
DavidChristiansen/Sharp-Architecture
src/SharpArch/SharpArch.Data/Properties/AssemblyInfo.cs
199
C#
using Newtonsoft.Json.Linq; using NUnit.Framework; using CKAN.NetKAN.Model; using CKAN.NetKAN.Validators; namespace Tests.NetKAN.Validators { [TestFixture] public sealed class LicensesValidatorTests { [Test, TestCase("v1.2", @"""WTFPL"""), TestCase("v1.18", @"""Unlicense"""), TestCase("v1.4", @"[ ""GPL-3.0"", ""MIT"" ]"), ] public void Validate_GoodSpecVersionLicense_DoesNotThrow(string spec_version, string license) { Assert.DoesNotThrow(() => TryLicense(spec_version, license)); } [Test, TestCase("1", @"""WTFPL"""), TestCase("v1.17", @"""Unlicense"""), TestCase("v1.4", @"""NotARealLicense"""), TestCase("v1.4", @"[ ""GPL-3.0"", ""Unlicense"" ]"), TestCase("v1.4", @"[ ""GPL-3.0"", ""NotARealLicense"" ]"), ] public void Validate_BadSpecVersionLicense_Throws(string spec_version, string license) { Assert.Throws<CKAN.Kraken>(() => TryLicense(spec_version, license)); } private void TryLicense(string spec_version, string license) { // Arrange var json = new JObject(); json["spec_version"] = spec_version; json["identifier"] = "AwesomeMod"; json["license"] = JToken.Parse(license); // Act var val = new LicensesValidator(); val.Validate(new Metadata(json)); } } }
32.468085
101
0.538008
[ "MIT" ]
050644zf/CKAN
Tests/NetKAN/Validators/LicensesValidatorTests.cs
1,526
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using shradhabookstores.EF; namespace shradhabookstores.Controllers.Backend { public class PaymentsController : Controller { private BookStoreEntities db = new BookStoreEntities(); // GET: Payments public ActionResult Index() { if (Session["LoginUser"] != null) { return View("~/Views/Backend/Payments/Index.cshtml", db.Payments.ToList()); } return RedirectToAction("../Users/Login"); } // GET: Payments/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Payment payment = db.Payments.Find(id); if (payment == null) { return HttpNotFound(); } return View("~/Views/Backend/Payments/Details.cshtml", payment); } // GET: Payments/Create public ActionResult Create() { return View("~/Views/Backend/Payments/Create.cshtml"); } // POST: Payments/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "PaymentId,PaymentName")] Payment payment) { if (ModelState.IsValid) { db.Payments.Add(payment); db.SaveChanges(); return RedirectToAction("Index"); } return View(payment); } // GET: Payments/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Payment payment = db.Payments.Find(id); if (payment == null) { return HttpNotFound(); } return View("~/Views/Backend/Payments/Edit.cshtml", payment); } // POST: Payments/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "PaymentId,PaymentName")] Payment payment) { if (ModelState.IsValid) { db.Entry(payment).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(payment); } // GET: Payments/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Payment payment = db.Payments.Find(id); if (payment == null) { return HttpNotFound(); } return View("~/Views/Backend/Payments/Delete.cshtml", payment); } // POST: Payments/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Payment payment = db.Payments.Find(id); db.Payments.Remove(payment); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
30.393939
111
0.537886
[ "MIT" ]
yuppaoh/BookStore
shradhabookstores/Controllers/Backend/PaymentsController.cs
4,014
C#
namespace BlazorState { using BlazorState.Features.JavaScriptInterop; using BlazorState.Features.Routing; using BlazorState.Pipeline.ReduxDevTools; using BlazorState.Pipeline.State; using BlazorState.Services; using MediatR; using MediatR.Pipeline; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reflection; using static BlazorState.Features.Routing.RouteState; public static class ServiceCollectionExtensions { /// <summary> /// Register BlazorState services based on the aConfigure options /// </summary> /// <param name="aServiceCollection"></param> /// <param name="aConfigureBlazorStateOptionsAction"></param> /// <returns></returns> /// <example></example> /// <remarks>The order of registration matters. /// If the user wants to change they can configure themselves vs using this extension</remarks> public static IServiceCollection AddBlazorState ( this IServiceCollection aServiceCollection, Action<BlazorStateOptions> aConfigureBlazorStateOptionsAction = null ) { ServiceDescriptor flagServiceDescriptor = aServiceCollection.FirstOrDefault ( aServiceDescriptor => aServiceDescriptor.ServiceType == typeof(BlazorHostingLocation) ); if (flagServiceDescriptor == null) { var blazorStateOptions = new BlazorStateOptions(); aConfigureBlazorStateOptionsAction?.Invoke(blazorStateOptions); EnsureLogger(aServiceCollection); EnsureHttpClient(aServiceCollection); EnsureMediator(aServiceCollection, blazorStateOptions); EnusureStates(aServiceCollection, blazorStateOptions); aServiceCollection.AddScoped<BlazorHostingLocation>(); aServiceCollection.AddScoped<JsonRequestHandler>(); aServiceCollection.AddScoped<Subscriptions>(); aServiceCollection.AddScoped(typeof(IRequestPostProcessor<,>), typeof(RenderSubscriptionsPostProcessor<,>)); aServiceCollection.AddScoped<IStore, Store>(); aServiceCollection.AddSingleton(blazorStateOptions); if (blazorStateOptions.UseCloneStateBehavior) { aServiceCollection.AddScoped(typeof(IPipelineBehavior<,>), typeof(CloneStateBehavior<,>)); } if (blazorStateOptions.UseReduxDevToolsBehavior) { aServiceCollection.AddScoped(typeof(IRequestPostProcessor<,>), typeof(ReduxDevToolsPostProcessor<,>)); aServiceCollection.AddScoped<ReduxDevToolsInterop>(); aServiceCollection.AddTransient<IRequestHandler<CommitRequest, Unit>, CommitHandler>(); aServiceCollection.AddTransient<IRequestHandler<JumpToStateRequest, Unit>, JumpToStateHandler>(); aServiceCollection.AddTransient<IRequestHandler<StartRequest, Unit>, StartHandler>(); aServiceCollection.AddScoped(aServiceProvider => (IReduxDevToolsStore)aServiceProvider.GetService<IStore>()); } if (blazorStateOptions.UseRouting) { aServiceCollection.AddScoped<RouteManager>(); aServiceCollection.AddScoped<RouteState>(); aServiceCollection.AddTransient<IRequestHandler<ChangeRouteAction, Unit>, ChangeRouteHandler>(); aServiceCollection.AddTransient<IRequestHandler<InitializeRouteAction, Unit>, InitializeRouteHandler>(); } } return aServiceCollection; } private static void EnsureHttpClient(IServiceCollection aServiceCollection) { var blazorHostingLocation = new BlazorHostingLocation(); // Server Side Blazor doesn't register HttpClient by default if (blazorHostingLocation.IsServerSide) { // Double check that nothing is registered. if (!aServiceCollection.Any(aServiceDescriptor => aServiceDescriptor.ServiceType == typeof(HttpClient))) { // Setup HttpClient for server side in a client side compatible fashion aServiceCollection.AddScoped<HttpClient> ( aServiceProvider => { // Creating the NavigationManager needs to wait until the JS Runtime is initialized, so defer it. NavigationManager navigationManager = aServiceProvider.GetRequiredService<NavigationManager>(); return new HttpClient { BaseAddress = new Uri(navigationManager.BaseUri) }; } ); } } } /// <summary> /// If no ILogger is registered it would throw as we inject it. This provides us with a NullLogger to avoid that /// </summary> /// <param name="aServiceCollection"></param> private static void EnsureLogger(IServiceCollection aServiceCollection) { ServiceDescriptor loggerServiceDescriptor = aServiceCollection.FirstOrDefault ( aServiceDescriptor => aServiceDescriptor.ServiceType == typeof(ILogger<>) ); if (loggerServiceDescriptor == null) { aServiceCollection.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); } } /// <summary> /// Scan Assemblies for Handlers. /// </summary> /// <param name="aServiceCollection"></param> /// <param name="aBlazorStateOptions"></param> private static void EnsureMediator(IServiceCollection aServiceCollection, BlazorStateOptions aBlazorStateOptions) { ServiceDescriptor mediatorServiceDescriptor = aServiceCollection.FirstOrDefault ( aServiceDescriptor => aServiceDescriptor.ServiceType == typeof(IMediator) ); if (mediatorServiceDescriptor == null) { aServiceCollection.AddMediatR(aBlazorStateOptions.Assemblies.ToArray()); } } private static void EnusureStates(IServiceCollection aServiceCollection, BlazorStateOptions aBlazorStateOptions) { foreach (Assembly assembly in aBlazorStateOptions.Assemblies) { IEnumerable<Type> types = assembly.GetTypes().Where ( aType => !aType.IsAbstract && !aType.IsInterface && aType.BaseType != null && aType.BaseType.IsGenericType && aType.BaseType.GetGenericTypeDefinition() == typeof(State<>) ); foreach (Type type in types) { if (!aServiceCollection.Any(aServiceDescriptor => aServiceDescriptor.ServiceType == type)) { aServiceCollection.AddTransient(type); } } } } } }
38.761628
119
0.692965
[ "Unlicense" ]
ShadyNagy/blazor-state
Source/BlazorState/Extensions/ServiceCollectionExtensions.cs
6,667
C#
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use the Utilities SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/utilities-1.31 Unless required by applicable law or agreed to in writing, the Utilities SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System.Collections.Generic; #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN internal class OVRCompositionUtil { public static void SafeDestroy(GameObject obj) { if (Application.isPlaying) { GameObject.Destroy(obj); } else { GameObject.DestroyImmediate(obj); } } public static void SafeDestroy(ref GameObject obj) { SafeDestroy(obj); obj = null; } public static OVRPlugin.CameraDevice ConvertCameraDevice(OVRManager.CameraDevice cameraDevice) { if (cameraDevice == OVRManager.CameraDevice.WebCamera0) { return OVRPlugin.CameraDevice.WebCamera0; } else if (cameraDevice == OVRManager.CameraDevice.WebCamera1) { return OVRPlugin.CameraDevice.WebCamera1; } else if (cameraDevice == OVRManager.CameraDevice.ZEDCamera) { return OVRPlugin.CameraDevice.ZEDCamera; } else { return OVRPlugin.CameraDevice.None; } } public static OVRBoundary.BoundaryType ToBoundaryType(OVRManager.VirtualGreenScreenType type) { if (type == OVRManager.VirtualGreenScreenType.OuterBoundary) { return OVRBoundary.BoundaryType.OuterBoundary; } else if (type == OVRManager.VirtualGreenScreenType.PlayArea) { return OVRBoundary.BoundaryType.PlayArea; } else { Debug.LogWarning("Unmatched VirtualGreenScreenType"); return OVRBoundary.BoundaryType.OuterBoundary; } } public static Vector3 GetWorldPosition(Vector3 trackingSpacePosition) { OVRPose tsPose; tsPose.position = trackingSpacePosition; tsPose.orientation = Quaternion.identity; OVRPose wsPose = OVRExtensions.ToWorldSpacePose(tsPose); Vector3 pos = wsPose.position; return pos; } public static float GetMaximumBoundaryDistance(Camera camera, OVRBoundary.BoundaryType boundaryType) { if (!OVRManager.boundary.GetConfigured()) { return float.MaxValue; } Vector3[] geometry = OVRManager.boundary.GetGeometry(boundaryType); if (geometry.Length == 0) { return float.MaxValue; } float maxDistance = -float.MaxValue; foreach (Vector3 v in geometry) { Vector3 pos = GetWorldPosition(v); float distance = Vector3.Dot(camera.transform.forward, pos); if (maxDistance < distance) { maxDistance = distance; } } return maxDistance; } public static Mesh BuildBoundaryMesh(OVRBoundary.BoundaryType boundaryType, float topY, float bottomY) { if (!OVRManager.boundary.GetConfigured()) { return null; } List<Vector3> geometry = new List<Vector3>(OVRManager.boundary.GetGeometry(boundaryType)); if (geometry.Count == 0) { return null; } geometry.Add(geometry[0]); int numPoints = geometry.Count; Vector3[] vertices = new Vector3[numPoints * 2]; Vector2[] uvs = new Vector2[numPoints * 2]; for (int i = 0; i < numPoints; ++i) { Vector3 v = geometry[i]; vertices[i] = new Vector3(v.x, bottomY, v.z); vertices[i + numPoints] = new Vector3(v.x, topY, v.z); uvs[i] = new Vector2((float)i / (numPoints - 1), 0.0f); uvs[i + numPoints] = new Vector2(uvs[i].x, 1.0f); } int[] triangles = new int[(numPoints - 1) * 2 * 3]; for (int i = 0; i < numPoints - 1; ++i) { // the geometry is built clockwised. only the back faces should be rendered in the camera frame mask triangles[i * 6 + 0] = i; triangles[i * 6 + 1] = i + numPoints; triangles[i * 6 + 2] = i + 1 + numPoints; triangles[i * 6 + 3] = i; triangles[i * 6 + 4] = i + 1 + numPoints; triangles[i * 6 + 5] = i + 1; } Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.uv = uvs; mesh.triangles = triangles; return mesh; } } #endif
28.445783
104
0.666455
[ "MIT" ]
S0leSurvivor/TemboVR
Assets/Oculus/VR/Scripts/Composition/OVRCompositionUtil.cs
4,722
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sandbox.Heaps { /// <summary> /// TODO: reorganize. /// Methods and scenarios related to one test question about running medians. /// Should be split into more relevant files/etc. /// </summary> public class Controller { /// <summary> /// Very basic test-case driver. /// </summary> public static void TestScenario() { int[] TestInput = { 6, 12, 4, 5, 3, 8, 7 }; Console.WriteLine(FindMedian(TestInput)); } /// <summary> /// Use heaps to find a running median in an array of integers. /// </summary> /// <param name="input"></param> /// <returns></returns> public static double FindMedian(int[] input) { MaxHeap lowerHalfHeap = new MaxHeap(input.Length/2); Heap upperHalfHeap = new Heap(input.Length/2); foreach (int item in input) { if (lowerHalfHeap.Size <= upperHalfHeap.Size) lowerHalfHeap.Add(item); else upperHalfHeap.Add(item); Heap.Balance(lowerHalfHeap,upperHalfHeap); } if (input.Length % 2 == 0) return (double)(lowerHalfHeap.Peek() + upperHalfHeap.Peek()) / 2; else return (double)lowerHalfHeap.Peek(); } } }
30.705882
82
0.52682
[ "MIT" ]
juanuberti/Sandbox
Sandbox/Heaps/Controller.cs
1,568
C#
using Competencias.Domain.Aggregates; using Competencias.Domain.Repositories; using SharedKernel.Common; using System.Threading.Tasks; namespace Competencias.Handlers { public class CompetenciaCriadaHandler : IHandler<CompetenciaCriada> { private ICompetenciaRepository _competenciaRepository; public CompetenciaCriadaHandler(ICompetenciaRepository competenciaRepository) { _competenciaRepository = competenciaRepository; } public Task HandleAsync(CompetenciaCriada e) { return Task.CompletedTask; } } }
23.086957
79
0.817326
[ "MIT" ]
erlonfs/gerenciamento-financeiro-pessoal
src/Competencias/Competencias.Handlers/CompetenciaCriadaHandler.cs
533
C#
using System.Collections.Generic; namespace RoslynDom.Common { public interface IProperty : IPropertyOrMethod<IProperty > { IReferencedType PropertyType { get; set; } bool CanGet { get; } bool CanSet { get; } IAccessor GetAccessor { get; set; } IAccessor SetAccessor { get; set; } } }
26.076923
62
0.631268
[ "Apache-2.0" ]
pottereric/RoslynDOM
RoslynDomCommon/Interfaces/IProperty.cs
339
C#