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 /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; namespace Noesis { public class LinearGradientBrush : GradientBrush { internal new static LinearGradientBrush CreateProxy(IntPtr cPtr, bool cMemoryOwn) { return new LinearGradientBrush(cPtr, cMemoryOwn); } internal LinearGradientBrush(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } internal static HandleRef getCPtr(LinearGradientBrush obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } public LinearGradientBrush() { } protected override IntPtr CreateCPtr(Type type, out bool registerExtend) { registerExtend = false; return NoesisGUI_PINVOKE.new_LinearGradientBrush(); } public static DependencyProperty EndPointProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.LinearGradientBrush_EndPointProperty_get(); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public static DependencyProperty StartPointProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.LinearGradientBrush_StartPointProperty_get(); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public Point StartPoint { set { NoesisGUI_PINVOKE.LinearGradientBrush_StartPoint_set(swigCPtr, ref value); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); } get { IntPtr ret = NoesisGUI_PINVOKE.LinearGradientBrush_StartPoint_get(swigCPtr); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); if (ret != IntPtr.Zero) { return Marshal.PtrToStructure<Point>(ret); } else { return new Point(); } } } public Point EndPoint { set { NoesisGUI_PINVOKE.LinearGradientBrush_EndPoint_set(swigCPtr, ref value); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); } get { IntPtr ret = NoesisGUI_PINVOKE.LinearGradientBrush_EndPoint_get(swigCPtr); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); if (ret != IntPtr.Zero) { return Marshal.PtrToStructure<Point>(ret); } else { return new Point(); } } } new internal static IntPtr GetStaticType() { IntPtr ret = NoesisGUI_PINVOKE.LinearGradientBrush_GetStaticType(); if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
31.862745
114
0.699692
[ "MIT" ]
WaveEngine/Extensions
WaveEngine.NoesisGUI/Shared/Proxies/LinearGradientBrush.cs
3,250
C#
using System; using System.Security.Cryptography; using Firebase.Auth; using Firebase.Crashlytics; using UnityEngine; using Random = System.Random; namespace Hamster.States { /// <summary> /// This utility is meant to throw a random type of exception /// to generate a few different types of issues in Crashlytics. /// Return a pseudo random exception type from the choices /// available. The caller of this utility is responsible /// for instantiating/throwing the exception. /// </summary> public static class PseudoRandomExceptionChooser { private static readonly Random RandomGenerator; static PseudoRandomExceptionChooser() { RandomGenerator = new Random(); } /// <summary> /// Throw a random exception from the choices in this directory. Demonstrate /// a different set of functions based on which exception is chosen. /// </summary> /// <param name="message"></param> public static void Throw(String message) { if (FirebaseAuth.DefaultInstance.CurrentUser != null) { Crashlytics.SetUserId(FirebaseAuth.DefaultInstance.CurrentUser.UserId); } int exceptionIndex = RandomGenerator.Next(0, 6); switch (exceptionIndex) { case 0: Crashlytics.Log("Menu meltdown is imminent."); ThrowMenuMeltdown(message); break; case 1: Crashlytics.Log("User triggered another forced exception."); ThrowAnotherForcedException(message); break; case 2: Crashlytics.Log("User triggered an intentionally obscure exception."); ThrowIntentionallyObscureException(); break; case 3: Crashlytics.Log("User triggered a random text exception."); ThrowRandomTextException(message); break; case 4: Crashlytics.Log("User triggered an equally statistically likely exception."); ThrowStatisticallyAsLikelyException(message); break; default: Crashlytics.Log(String.Format("Could not find index {0} - using default meltdown exception", exceptionIndex)); ThrowMenuMeltdown(message); break; } } private static void ThrowMenuMeltdown(String message) { try { throw new MenuMeltdownException(message); } catch (CrashlyticsCaughtException e) { Crashlytics.LogException(e); } } private static void ThrowAnotherForcedException(String message) { try { throw new AnotherForcedException(message); } catch (CrashlyticsCaughtException e) { Crashlytics.LogException(e); } } private static void ThrowIntentionallyObscureException() { try { throw new IntentionallyObscureException("An error occurred."); } catch (CrashlyticsCaughtException e) { Crashlytics.LogException(e); } } private static void ThrowRandomTextException(String message) { Crashlytics.SetCustomKey("guid", Guid.NewGuid().ToString()); try { throw new RandomTextException(message); } catch (CrashlyticsCaughtException e) { Crashlytics.LogException(e); } } private static void ThrowStatisticallyAsLikelyException(String message) { try { throw new StatisticallyAsLikelyException(message); } catch (CrashlyticsCaughtException e) { Crashlytics.LogException(e); } } } }
31.518182
120
0.659071
[ "Apache-2.0" ]
ErnestoGonzalez96/mechahamster
Assets/Hamster/Scripts/States/Exceptions/PseudoRandomExceptionChooser.cs
3,467
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Linq; using Azure.AI.TextAnalytics; namespace Azure.AI.TextAnalytics.Models { /// <summary> The EntitiesResult. </summary> internal partial class EntitiesResult : PreBuiltResult { /// <summary> Initializes a new instance of EntitiesResult. </summary> /// <param name="errors"> Errors by document id. </param> /// <param name="modelVersion"> This field indicates which model is used for scoring. </param> /// <param name="documents"> Response by document. </param> /// <exception cref="ArgumentNullException"> <paramref name="errors"/>, <paramref name="modelVersion"/> or <paramref name="documents"/> is null. </exception> public EntitiesResult(IEnumerable<DocumentError> errors, string modelVersion, IEnumerable<EntitiesResultDocumentsItem> documents) : base(errors, modelVersion) { if (errors == null) { throw new ArgumentNullException(nameof(errors)); } if (modelVersion == null) { throw new ArgumentNullException(nameof(modelVersion)); } if (documents == null) { throw new ArgumentNullException(nameof(documents)); } Documents = documents.ToList(); } /// <summary> Initializes a new instance of EntitiesResult. </summary> /// <param name="errors"> Errors by document id. </param> /// <param name="statistics"> if showStats=true was specified in the request this field will contain information about the request payload. </param> /// <param name="modelVersion"> This field indicates which model is used for scoring. </param> /// <param name="documents"> Response by document. </param> internal EntitiesResult(IList<DocumentError> errors, TextDocumentBatchStatistics statistics, string modelVersion, IList<EntitiesResultDocumentsItem> documents) : base(errors, statistics, modelVersion) { Documents = documents; } /// <summary> Response by document. </summary> public IList<EntitiesResultDocumentsItem> Documents { get; } } }
43.090909
208
0.650211
[ "MIT" ]
ChenTanyi/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/src/Generated/Models/EntitiesResult.cs
2,370
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.eShopOnContainers.Services.Marketing.API.Dto; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Repositories; using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Services; using Microsoft.eShopOnContainers.Services.Marketing.API.Model; using Microsoft.eShopOnContainers.Services.Marketing.API.ViewModel; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.Services.Marketing.API.Controllers { [Route("api/v1/[controller]")] [Authorize] public class CampaignsController : Controller { private readonly MarketingContext _context; private readonly MarketingSettings _settings; private readonly IMarketingDataRepository _marketingDataRepository; private readonly IIdentityService _identityService; private readonly ILogger<CampaignsController> _logger; public CampaignsController(MarketingContext context, IMarketingDataRepository marketingDataRepository, IOptionsSnapshot<MarketingSettings> settings, IIdentityService identityService, ILogger<CampaignsController> logger) { _context = context; _marketingDataRepository = marketingDataRepository; _settings = settings.Value; _identityService = identityService; _logger = logger; } [HttpGet] [ProducesResponseType(typeof(List<CampaignDTO>), (int)HttpStatusCode.OK)] public async Task<IActionResult> GetAllCampaigns() { _logger.LogTrace("Get all campaigns"); var campaignList = await _context.Campaigns .ToListAsync(); if (campaignList is null) { return Ok(); } var campaignDtoList = MapCampaignModelListToDtoList(campaignList); return Ok(campaignDtoList); } [HttpGet("{id:int}")] [ProducesResponseType(typeof(CampaignDTO), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.NotFound)] public async Task<IActionResult> GetCampaignById(int id) { _logger.LogTrace("Get campaign by id {id}", id); var campaign = await _context.Campaigns .SingleOrDefaultAsync(c => c.Id == id); if (campaign is null) { return NotFound(); } var campaignDto = MapCampaignModelToDto(campaign); return Ok(campaignDto); } [HttpPost] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Created)] public async Task<IActionResult> CreateCampaign([FromBody] CampaignDTO campaignDto) { if (campaignDto is null) { return BadRequest(); } var campaign = MapCampaignDtoToModel(campaignDto); await _context.Campaigns.AddAsync(campaign); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetCampaignById), new { id = campaign.Id }, null); } [HttpPut("{id:int}")] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType((int)HttpStatusCode.Created)] public async Task<IActionResult> UpdateCampaign(int id, [FromBody] CampaignDTO campaignDto) { if (id < 1 || campaignDto is null) { return BadRequest(); } var campaignToUpdate = await _context.Campaigns.FindAsync(id); if (campaignToUpdate is null) { return NotFound(); } campaignToUpdate.Name = campaignDto.Name; campaignToUpdate.Description = campaignDto.Description; campaignToUpdate.From = campaignDto.From; campaignToUpdate.To = campaignDto.To; campaignToUpdate.PictureUri = campaignDto.PictureUri; await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetCampaignById), new { id = campaignToUpdate.Id }, null); } [HttpDelete("{id:int}")] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.NotFound)] [ProducesResponseType((int)HttpStatusCode.NoContent)] public async Task<IActionResult> Delete(int id) { if (id < 1) { return BadRequest(); } var campaignToDelete = await _context.Campaigns.FindAsync(id); if (campaignToDelete is null) { return NotFound(); } _context.Campaigns.Remove(campaignToDelete); await _context.SaveChangesAsync(); return NoContent(); } [HttpGet("user")] [ProducesResponseType(typeof(PaginatedItemsViewModel<CampaignDTO>), (int)HttpStatusCode.OK)] public async Task<IActionResult> GetCampaignsByUserId( int pageSize = 10, int pageIndex = 0) { var userId = _identityService.GetUserIdentity(); _logger.LogTrace("Get campaigns by userId {userId}", userId); var marketingData = await _marketingDataRepository.GetAsync(userId.ToString()); var campaignDtoList = new List<CampaignDTO>(); if (marketingData != null) { var locationIdCandidateList = marketingData.Locations.Select(x => x.LocationId); var userCampaignList = await _context.Rules .OfType<UserLocationRule>() .Include(c => c.Campaign) .Where(c => c.Campaign.From <= DateTime.Now && c.Campaign.To >= DateTime.Now && locationIdCandidateList.Contains(c.LocationId)) .Select(c => c.Campaign) .ToListAsync(); if (userCampaignList != null && userCampaignList.Any()) { var userCampaignDtoList = MapCampaignModelListToDtoList(userCampaignList); campaignDtoList.AddRange(userCampaignDtoList); } } var totalItems = campaignDtoList.Count(); campaignDtoList = campaignDtoList .Skip(pageSize * pageIndex) .Take(pageSize).ToList(); var model = new PaginatedItemsViewModel<CampaignDTO>( pageIndex, pageSize, totalItems, campaignDtoList); return Ok(model); } private List<CampaignDTO> MapCampaignModelListToDtoList(List<Campaign> campaignList) { var campaignDtoList = new List<CampaignDTO>(); campaignList.ForEach(campaign => campaignDtoList .Add(MapCampaignModelToDto(campaign))); return campaignDtoList; } private CampaignDTO MapCampaignModelToDto(Campaign campaign) { var userId = _identityService.GetUserIdentity(); var dto = new CampaignDTO { Id = campaign.Id, Name = campaign.Name, Description = campaign.Description, From = campaign.From, To = campaign.To, PictureUri = GetUriPlaceholder(campaign), }; if (!string.IsNullOrEmpty(_settings.CampaignDetailFunctionUri)) { dto.DetailsUri = $"{_settings.CampaignDetailFunctionUri}&campaignId={campaign.Id}&userId={userId}"; } return dto; } private Campaign MapCampaignDtoToModel(CampaignDTO campaignDto) { return new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, From = campaignDto.From, To = campaignDto.To, PictureUri = campaignDto.PictureUri }; } private string GetUriPlaceholder(Campaign campaign) { var baseUri = _settings.PicBaseUrl; return _settings.AzureStorageEnabled ? baseUri + campaign.PictureName : baseUri.Replace("[0]", campaign.Id.ToString()); } } }
36.150407
115
0.600585
[ "MIT" ]
spring-operator/eShopOnContainers
src/Services/Marketing/Marketing.API/Controllers/CampaignsController.cs
8,895
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify(CSharpTestSource src, string? expectedOutput = null) => base.CompileAndVerify(new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, // init-only fails verification verify: Verification.Skipped); [Fact] public void GeneratedConstructor() { var comp = CreateCompilation(@"record C(int x, string y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var y = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, y.Type.SpecialType); Assert.Equal("y", y.Name); } [Fact] public void GeneratedConstructorDefaultValues() { var comp = CreateCompilation(@"record C<T>(int x, T t = default);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.Equal(1, c.Arity); var ctor = (MethodSymbol)c.GetMembers(".ctor")[0]; Assert.Equal(0, ctor.Arity); Assert.Equal(2, ctor.ParameterCount); var x = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.Equal("x", x.Name); var t = ctor.Parameters[1]; Assert.Equal(c.TypeParameters[0], t.Type); Assert.Equal("t", t.Name); } [Fact] public void RecordExistingConstructor1() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, string b) { } }"); comp.VerifyDiagnostics( // (4,12): error CS0111: Type 'C' already defines a member called '.ctor' with the same parameter types // public C(int a, string b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments(".ctor", "C").WithLocation(4, 12), // (4,12): error CS8862: A constructor declared in a record with parameters must have 'this' constructor initializer. // public C(int a, string b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctor = (MethodSymbol)c.GetMembers(".ctor")[2]; Assert.Equal(2, ctor.ParameterCount); var a = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, a.Type.SpecialType); Assert.Equal("a", a.Name); var b = ctor.Parameters[1]; Assert.Equal(SpecialType.System_String, b.Type.SpecialType); Assert.Equal("b", b.Name); } [Fact] public void RecordExistingConstructor01() { var comp = CreateCompilation(@" record C(int x, string y) { public C(int a, int b) // overload { } }"); comp.VerifyDiagnostics( // (4,12): error CS8862: A constructor declared in a record with parameters must have 'this' constructor initializer. // public C(int a, int b) // overload Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(4, 12) ); var c = comp.GlobalNamespace.GetTypeMember("C"); var ctors = c.GetMembers(".ctor"); Assert.Equal(3, ctors.Length); foreach (MethodSymbol ctor in ctors) { if (ctor.ParameterCount == 2) { var p1 = ctor.Parameters[0]; Assert.Equal(SpecialType.System_Int32, p1.Type.SpecialType); var p2 = ctor.Parameters[1]; if (ctor is SynthesizedRecordConstructor) { Assert.Equal("x", p1.Name); Assert.Equal("y", p2.Name); Assert.Equal(SpecialType.System_String, p2.Type.SpecialType); } else { Assert.Equal("a", p1.Name); Assert.Equal("b", p2.Name); Assert.Equal(SpecialType.System_Int32, p2.Type.SpecialType); } } else { Assert.Equal(1, ctor.ParameterCount); Assert.True(c.Equals(ctor.Parameters[0].Type, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void GeneratedProperties() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var x = (SourcePropertySymbolBase)c.GetProperty("x"); Assert.NotNull(x.GetMethod); Assert.Equal(MethodKind.PropertyGet, x.GetMethod.MethodKind); Assert.Equal(SpecialType.System_Int32, x.Type.SpecialType); Assert.False(x.IsReadOnly); Assert.False(x.IsWriteOnly); Assert.False(x.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, x.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, x.ContainingType); Assert.Equal(c, x.ContainingSymbol); var backing = x.BackingField; Assert.Equal(x, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); var getAccessor = x.GetMethod; Assert.Equal(x, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); Assert.Equal(Accessibility.Public, getAccessor.DeclaredAccessibility); var setAccessor = x.SetMethod; Assert.Equal(x, setAccessor.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); var y = (SourcePropertySymbolBase)c.GetProperty("y"); Assert.NotNull(y.GetMethod); Assert.Equal(MethodKind.PropertyGet, y.GetMethod.MethodKind); Assert.Equal(SpecialType.System_Int32, y.Type.SpecialType); Assert.False(y.IsReadOnly); Assert.False(y.IsWriteOnly); Assert.False(y.IsImplicitlyDeclared); Assert.Equal(Accessibility.Public, y.DeclaredAccessibility); Assert.False(x.IsVirtual); Assert.False(x.IsStatic); Assert.Equal(c, y.ContainingType); Assert.Equal(c, y.ContainingSymbol); backing = y.BackingField; Assert.Equal(y, backing.AssociatedSymbol); Assert.Equal(c, backing.ContainingSymbol); Assert.Equal(c, backing.ContainingType); Assert.True(backing.IsImplicitlyDeclared); getAccessor = y.GetMethod; Assert.Equal(y, getAccessor.AssociatedSymbol); Assert.True(getAccessor.IsImplicitlyDeclared); Assert.Equal(c, getAccessor.ContainingSymbol); Assert.Equal(c, getAccessor.ContainingType); setAccessor = y.SetMethod; Assert.Equal(y, setAccessor.AssociatedSymbol); Assert.True(setAccessor.IsImplicitlyDeclared); Assert.Equal(c, setAccessor.ContainingSymbol); Assert.Equal(c, setAccessor.ContainingType); Assert.Equal(Accessibility.Public, setAccessor.DeclaredAccessibility); Assert.True(setAccessor.IsInitOnly); } [Fact] public void RecordEquals_01() { var comp = CreateCompilation(@" record C(int X, int Y) { public bool Equals(C c) => throw null; public override bool Equals(object o) => false; } "); comp.VerifyDiagnostics( // (4,17): error CS8872: 'C.Equals(C)' must allow overriding because the containing record is not sealed. // public bool Equals(C c) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("C.Equals(C)").WithLocation(4, 17), // (5,26): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public override bool Equals(object o) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(5, 26) ); comp = CreateCompilation(@" record C { public int Equals(object o) => throw null; } record D : C { } "); comp.VerifyDiagnostics( // (4,16): warning CS0114: 'C.Equals(object)' hides inherited member 'object.Equals(object)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public int Equals(object o) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Equals").WithArguments("C.Equals(object)", "object.Equals(object)").WithLocation(4, 16), // (4,16): error CS0111: Type 'C' already defines a member called 'Equals' with the same parameter types // public int Equals(object o) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "C").WithLocation(4, 16) ); CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); Console.WriteLine(c.Equals(c)); } public virtual bool Equals(C c) => false; }", expectedOutput: "False").VerifyDiagnostics(); } [Fact] public void RecordEquals_02() { CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(1, 1); var c2 = new C(1, 1); Console.WriteLine(c.Equals(c)); Console.WriteLine(c.Equals(c2)); } }", expectedOutput: @"True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_03() { var verifier = CompileAndVerify(@" using System; sealed record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } public bool Equals(C c) => X == c.X && Y == c.Y; }", expectedOutput: @"True False").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: call ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""int C.X.get"" IL_0006: ldarg.1 IL_0007: callvirt ""int C.X.get"" IL_000c: bne.un.s IL_001d IL_000e: ldarg.0 IL_000f: call ""int C.Y.get"" IL_0014: ldarg.1 IL_0015: callvirt ""int C.Y.get"" IL_001a: ceq IL_001c: ret IL_001d: ldc.i4.0 IL_001e: ret }"); } [Fact] public void RecordEquals_04() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { object c = new C(0, 0); var c2 = new C(0, 0); var c3 = new C(1, 1); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"True False").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_06() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static void Main() { var c = new C(0, 0); object c2 = null; C c3 = null; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False False").VerifyDiagnostics(); } [Fact] public void RecordEquals_07() { var verifier = CompileAndVerify(@" using System; record C(int[] X, string Y) { public static void Main() { var arr = new[] {1, 2}; var c = new C(arr, ""abc""); var c2 = new C(new[] {1, 2}, ""abc""); var c3 = new C(arr, ""abc""); Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals(c3)); } }", expectedOutput: @"False True").VerifyDiagnostics(); } [Fact] public void RecordEquals_08() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z; public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""int C.Z"" IL_0051: ldarg.1 IL_0052: ldfld ""int C.Z"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void RecordEquals_09() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public int Z { get; set; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); } [Fact] public void RecordEquals_10() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { public static int Z; public static void Main() { var c = new C(1, 2); C.Z = 3; var c2 = new C(1, 2); C.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); C.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_11() { var verifier = CompileAndVerify(@" using System; using System.Collections.Generic; record C(int X, int Y) { static Dictionary<C, int> s_dict = new Dictionary<C, int>(); public int Z { get => s_dict[this]; set => s_dict[this] = value; } public static void Main() { var c = new C(1, 2); c.Z = 3; var c2 = new C(1, 2); c2.Z = 4; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.Z = 3; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"True True True True"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 71 (0x47) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0045 IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_0045 IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_0045 IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: ret IL_0045: ldc.i4.0 IL_0046: ret }"); } [Fact] public void RecordEquals_12() { var verifier = CompileAndVerify(@" using System; record C(int X, int Y) { private event Action E; public static void Main() { var c = new C(1, 2); c.E = () => { }; var c2 = new C(1, 2); c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.<X>k__BackingField"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.<X>k__BackingField"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""System.Action C.E"" IL_0051: ldarg.1 IL_0052: ldfld ""System.Action C.E"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void RecordClone1() { var comp = CreateCompilation("record C(int x, int y);"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ret }"); } [Fact] public void RecordClone2_0() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { x = other.x; y = other.y; } }"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); verifier.VerifyIL("C..ctor(C)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: callvirt ""int C.x.get"" IL_000d: call ""void C.x.init"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: callvirt ""int C.y.get"" IL_0019: call ""void C.y.init"" IL_001e: ret } "); } [Fact] public void RecordClone2_0_WithThisInitializer() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : this(other.x, other.y) { } }"); comp.VerifyDiagnostics( // (4,25): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C other) : this(other.x, other.y) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(4, 25) ); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_1() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44781, "https://github.com/dotnet/roslyn/issues/44781")] public void RecordClone2_2() { var comp = CreateCompilation(@" record C(int x, int y) { public C(C other) : base() { } }"); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44782, "https://github.com/dotnet/roslyn/issues/44782")] public void RecordClone3() { var comp = CreateCompilation(@" using System; public record C(int x, int y) { public event Action E; public int Z; public int W = 123; }"); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); var clone = c.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(c, clone.ReturnType); var ctor = (MethodSymbol)c.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(c, TypeCompareKind.ConsiderEverything)); var verifier = CompileAndVerify(comp, verify: Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 67 (0x43) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""int C.<x>k__BackingField"" IL_000d: stfld ""int C.<x>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""int C.<y>k__BackingField"" IL_0019: stfld ""int C.<y>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""System.Action C.E"" IL_0025: stfld ""System.Action C.E"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Z"" IL_0031: stfld ""int C.Z"" IL_0036: ldarg.0 IL_0037: ldarg.1 IL_0038: ldfld ""int C.W"" IL_003d: stfld ""int C.W"" IL_0042: ret } "); } [Fact(Skip = "record struct")] public void RecordClone4_0() { var comp = CreateCompilation(@" using System; public data struct S(int x, int y) { public event Action E; public int Z; }"); comp.VerifyDiagnostics( // (3,21): error CS0171: Field 'S.E' must be fully assigned before control is returned to the caller // public data struct S(int x, int y) Diagnostic(ErrorCode.ERR_UnassignedThis, "(int x, int y)").WithArguments("S.E").WithLocation(3, 21), // (3,21): error CS0171: Field 'S.Z' must be fully assigned before control is returned to the caller // public data struct S(int x, int y) Diagnostic(ErrorCode.ERR_UnassignedThis, "(int x, int y)").WithArguments("S.Z").WithLocation(3, 21), // (5,25): warning CS0067: The event 'S.E' is never used // public event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E").WithLocation(5, 25) ); var s = comp.GlobalNamespace.GetTypeMember("S"); var clone = s.GetMethod(WellKnownMemberNames.CloneMethodName); Assert.Equal(0, clone.Arity); Assert.Equal(0, clone.ParameterCount); Assert.Equal(s, clone.ReturnType); var ctor = (MethodSymbol)s.GetMembers(".ctor")[1]; Assert.Equal(1, ctor.ParameterCount); Assert.True(ctor.Parameters[0].Type.Equals(s, TypeCompareKind.ConsiderEverything)); } [Fact(Skip = "record struct")] public void RecordClone4_1() { var comp = CreateCompilation(@" using System; public data struct S(int x, int y) { public event Action E = null; public int Z = 0; }"); comp.VerifyDiagnostics( // (5,25): error CS0573: 'S': cannot have instance property or field initializers in structs // public event Action E = null; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "E").WithArguments("S").WithLocation(5, 25), // (5,25): warning CS0414: The field 'S.E' is assigned but its value is never used // public event Action E = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "E").WithArguments("S.E").WithLocation(5, 25), // (6,16): error CS0573: 'S': cannot have instance property or field initializers in structs // public int Z = 0; Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "Z").WithArguments("S").WithLocation(6, 16) ); } [Fact] public void NominalRecordEquals() { var verifier = CompileAndVerify(@" using System; record C { private int X; private int Y { get; set; } private event Action E; public static void Main() { var c = new C { X = 1, Y = 2 }; c.E = () => { }; var c2 = new C { X = 1, Y = 2 }; c2.E = () => { }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); c2.E = c.E; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c.Equals((object)c2)); } }", expectedOutput: @"False False True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(object)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.Equals(C)", @" { // Code size 95 (0x5f) .maxstack 3 IL_0000: ldarg.1 IL_0001: brfalse.s IL_005d IL_0003: ldarg.0 IL_0004: callvirt ""System.Type C.EqualityContract.get"" IL_0009: ldarg.1 IL_000a: callvirt ""System.Type C.EqualityContract.get"" IL_000f: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0014: brfalse.s IL_005d IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C.X"" IL_0021: ldarg.1 IL_0022: ldfld ""int C.X"" IL_0027: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_002c: brfalse.s IL_005d IL_002e: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0033: ldarg.0 IL_0034: ldfld ""int C.<Y>k__BackingField"" IL_0039: ldarg.1 IL_003a: ldfld ""int C.<Y>k__BackingField"" IL_003f: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0044: brfalse.s IL_005d IL_0046: call ""System.Collections.Generic.EqualityComparer<System.Action> System.Collections.Generic.EqualityComparer<System.Action>.Default.get"" IL_004b: ldarg.0 IL_004c: ldfld ""System.Action C.E"" IL_0051: ldarg.1 IL_0052: ldfld ""System.Action C.E"" IL_0057: callvirt ""bool System.Collections.Generic.EqualityComparer<System.Action>.Equals(System.Action, System.Action)"" IL_005c: ret IL_005d: ldc.i4.0 IL_005e: ret }"); } [Fact] public void PositionalAndNominalSameEquals() { var v1 = CompileAndVerify(@" using System; record C(int X, string Y) { public event Action E; } ").VerifyDiagnostics(); var v2 = CompileAndVerify(@" using System; record C { public int X { get; } public string Y { get; } public event Action E; }").VerifyDiagnostics(); Assert.Equal(v1.VisualizeIL("C.Equals(C)"), v2.VisualizeIL("C.Equals(C)")); Assert.Equal(v1.VisualizeIL("C.Equals(object)"), v2.VisualizeIL("C.Equals(object)")); } [Fact] public void NominalRecordMembers() { var comp = CreateCompilation(@" #nullable enable record C { public int X { get; init; } public string Y { get; init; } }"); var members = comp.GlobalNamespace.GetTypeMember("C").GetMembers(); AssertEx.Equal(new[] { "System.Type! C.EqualityContract.get", "System.Type! C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X { get; init; }", "System.Int32 C.X.get", "void C.X.init", "System.String! C.<Y>k__BackingField", "System.String! C.Y { get; init; }", "System.String! C.Y.get", "void C.Y.init", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C! C." + WellKnownMemberNames.CloneMethodName + "()", "C.C(C! original)", "C.C()", }, members.Select(m => m.ToTestDisplayString(includeNonNullable: true))); } [Fact] public void PartialTypes_01() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X, int Y) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X, int Y) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X, int Y)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_02() { var src = @" using System; partial record C(int X, int Y) { public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } } partial record C(int X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): error CS8863: Only a single record partial declaration may have a parameter list // partial record C(int X) Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int X)").WithLocation(13, 17) ); Assert.Equal(new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)" }, comp.GetTypeByMetadataName("C")!.Constructors.Select(m => m.ToTestDisplayString())); } [Fact] public void PartialTypes_03() { var src = @" partial record C { public int X = 1; } partial record C(int Y); partial record C { public int Z { get; } = 2; }"; var verifier = CompileAndVerify(src).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stfld ""int C.X"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.2 IL_0010: stfld ""int C.<Z>k__BackingField"" IL_0015: ldarg.0 IL_0016: call ""object..ctor()"" IL_001b: ret }"); } [Fact] public void DataClassAndStruct() { var src = @" data class C1 { } data class C2(int X, int Y); data struct S1 { } data struct S2(int X, int Y);"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // error CS8805: Program using top-level statements must be an executable. Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable).WithLocation(1, 1), // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(2, 1), // (3,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(3, 1), // (3,14): error CS1514: { expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS1513: } expected // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(3, 14), // (3,14): error CS8803: Top-level statements must precede namespace and type declarations. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int X, int Y);").WithLocation(3, 14), // (3,14): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(3, 14), // (3,15): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(3, 15), // (3,15): error CS0165: Use of unassigned local variable 'X' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(3, 15), // (3,22): error CS8185: A declaration is not allowed in this context. // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(3, 22), // (3,22): error CS0165: Use of unassigned local variable 'Y' // data class C2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(3, 22), // (4,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S1 { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(4, 1), // (5,1): error CS0116: A namespace cannot directly contain members such as fields or methods // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "data").WithLocation(5, 1), // (5,15): error CS1514: { expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS1513: } expected // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(5, 15), // (5,15): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int X, int Y)").WithLocation(5, 15), // (5,16): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int X").WithLocation(5, 16), // (5,16): error CS0165: Use of unassigned local variable 'X' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int X").WithArguments("X").WithLocation(5, 16), // (5,20): error CS0128: A local variable or function named 'X' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "X").WithArguments("X").WithLocation(5, 20), // (5,23): error CS8185: A declaration is not allowed in this context. // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int Y").WithLocation(5, 23), // (5,23): error CS0165: Use of unassigned local variable 'Y' // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int Y").WithArguments("Y").WithLocation(5, 23), // (5,27): error CS0128: A local variable or function named 'Y' is already defined in this scope // data struct S2(int X, int Y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "Y").WithArguments("Y").WithLocation(5, 27) ); } [Fact] public void RecordInheritance() { var src = @" class A { } record B : A { } record C : B { } class D : C { } interface E : C { } struct F : C { } enum G : C { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record B : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (5,11): error CS8865: Only records may inherit from records. // class D : C { } Diagnostic(ErrorCode.ERR_BadInheritanceFromRecord, "C").WithLocation(5, 11), // (6,15): error CS0527: Type 'C' in interface list is not an interface // interface E : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(6, 15), // (7,12): error CS0527: Type 'C' in interface list is not an interface // struct F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(7, 12), // (8,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum G : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(8, 10) ); } [Theory] [InlineData(true)] [InlineData(false)] public void RecordInheritance2(bool emitReference) { var src = @" public class A { } public record B { } public record C : B { }"; var comp = CreateCompilation(src); var src2 = @" record D : C { } record E : A { } interface F : C { } struct G : C { } enum H : C { } "; var comp2 = CreateCompilation(src2, parseOptions: TestOptions.RegularPreview, references: new[] { emitReference ? comp.EmitToImageReference() : comp.ToMetadataReference() }); comp2.VerifyDiagnostics( // (3,8): error CS0115: 'E.EqualityContract': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'E.Equals(A?)': no suitable method found to override // record E : A { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "E").WithArguments("E.Equals(A?)").WithLocation(3, 8), // (3,8): error CS8867: No accessible copy constructor found in base type 'A'. // record E : A { } Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("A").WithLocation(3, 8), // (3,12): error CS8864: Records may only inherit from object or another record // record E : A { } Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(3, 12), // (4,15): error CS0527: Type 'C' in interface list is not an interface // interface F : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(4, 15), // (5,12): error CS0527: Type 'C' in interface list is not an interface // struct G : C { } Diagnostic(ErrorCode.ERR_NonInterfaceInInterfaceList, "C").WithArguments("C").WithLocation(5, 12), // (6,10): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum H : C { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "C").WithLocation(6, 10) ); } [Fact] public void GenericRecord() { var src = @" using System; record A<T> { public T Prop { get; init; } } record B : A<int>; record C<T>(T Prop2) : A<T>; class P { public static void Main() { var a = new A<int>() { Prop = 1 }; var a2 = a with { Prop = 2 }; Console.WriteLine(a.Prop + "" "" + a2.Prop); var b = new B() { Prop = 3 }; var b2 = b with { Prop = 4 }; Console.WriteLine(b.Prop + "" "" + b2.Prop); var c = new C<int>(5) { Prop = 6 }; var c2 = c with { Prop = 7, Prop2 = 8 }; Console.WriteLine(c.Prop + "" "" + c.Prop2); Console.WriteLine(c2.Prop2 + "" "" + c2.Prop); } }"; CompileAndVerify(src, expectedOutput: @" 1 2 3 4 6 5 8 7").VerifyDiagnostics(); } [Fact] public void RecordCloneSymbol() { var src = @" record R; record R2 : R"; var comp = CreateCompilation(src); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.False(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); } [Fact] public void AbstractRecordClone() { var src = @" abstract record R; abstract record R2 : R; record R3 : R2; abstract record R4 : R3; record R5 : R4; class C { public static void Main() { R r = new R3(); r = r with { }; R4 r4 = new R5(); r4 = r4 with { }; } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe); var r = comp.GlobalNamespace.GetTypeMember("R"); var clone = (MethodSymbol)r.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.Equal(0, clone.ParameterCount); Assert.Equal(0, clone.Arity); Assert.Equal("R R." + WellKnownMemberNames.CloneMethodName + "()", clone.ToTestDisplayString()); Assert.True(clone.IsImplicitlyDeclared); var r2 = comp.GlobalNamespace.GetTypeMember("R2"); var clone2 = (MethodSymbol)r2.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone2.IsOverride); Assert.False(clone2.IsVirtual); Assert.True(clone2.IsAbstract); Assert.Equal(0, clone2.ParameterCount); Assert.Equal(0, clone2.Arity); Assert.True(clone2.OverriddenMethod.Equals(clone, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R2." + WellKnownMemberNames.CloneMethodName + "()", clone2.ToTestDisplayString()); Assert.True(clone2.IsImplicitlyDeclared); var r3 = comp.GlobalNamespace.GetTypeMember("R3"); var clone3 = (MethodSymbol)r3.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone3.IsOverride); Assert.False(clone3.IsVirtual); Assert.False(clone3.IsAbstract); Assert.Equal(0, clone3.ParameterCount); Assert.Equal(0, clone3.Arity); Assert.True(clone3.OverriddenMethod.Equals(clone2, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R3." + WellKnownMemberNames.CloneMethodName + "()", clone3.ToTestDisplayString()); Assert.True(clone3.IsImplicitlyDeclared); var r4 = comp.GlobalNamespace.GetTypeMember("R4"); var clone4 = (MethodSymbol)r4.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone4.IsOverride); Assert.False(clone4.IsVirtual); Assert.True(clone4.IsAbstract); Assert.Equal(0, clone4.ParameterCount); Assert.Equal(0, clone4.Arity); Assert.True(clone4.OverriddenMethod.Equals(clone3, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R4." + WellKnownMemberNames.CloneMethodName + "()", clone4.ToTestDisplayString()); Assert.True(clone4.IsImplicitlyDeclared); var r5 = comp.GlobalNamespace.GetTypeMember("R5"); var clone5 = (MethodSymbol)r5.GetMembers(WellKnownMemberNames.CloneMethodName).Single(); Assert.True(clone5.IsOverride); Assert.False(clone5.IsVirtual); Assert.False(clone5.IsAbstract); Assert.Equal(0, clone5.ParameterCount); Assert.Equal(0, clone5.Arity); Assert.True(clone5.OverriddenMethod.Equals(clone4, TypeCompareKind.ConsiderEverything)); Assert.Equal("R R5." + WellKnownMemberNames.CloneMethodName + "()", clone5.ToTestDisplayString()); Assert.True(clone5.IsImplicitlyDeclared); var verifier = CompileAndVerify(comp, expectedOutput: "", verify: Verification.Passes).VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 28 (0x1c) .maxstack 1 IL_0000: newobj ""R3..ctor()"" IL_0005: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000a: pop IL_000b: newobj ""R5..ctor()"" IL_0010: callvirt ""R R." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: castclass ""R4"" IL_001a: pop IL_001b: ret }"); } } }
37.570764
223
0.592424
[ "MIT" ]
Jay-Madden/roslyn
src/Compilers/CSharp/Test/Symbol/Symbols/Source/RecordTests.cs
56,546
C#
using SrtVideoPlayer.Shared.Models.Theming; using System.Threading.Tasks; namespace SrtVideoPlayer.Mobile.DependencyServices { public interface IThemingDependencyService { bool DeviceSupportsManualDarkMode(); bool DeviceSupportsAutomaticDarkMode(); bool DeviceRequiresPagesRedraw(); Theme GetDeviceDefaultTheme(); Task<Theme> GetDeviceTheme(); // Implementation for this based on https://codetraveler.io/2019/09/11/check-for-dark-mode-in-xamarin-forms/ } }
34.066667
146
0.74364
[ "MIT" ]
EdgeLatitude/SrtVideoPlayer
SrtVideoPlayer.Mobile/SrtVideoPlayer.Mobile/DependencyServices/IThemingDependencyService.cs
513
C#
using UnityEngine; public class Hoge43 : MonoBehaviour{ void Start(){ Debug.Log(Hoge43.GetIndex()); } void Update(){ } public static int GetIndex(){ return 43; } public int GetIndex0(){ return 0; } public int GetIndex1(){ return 1; } public int GetIndex2(){ return 2; } public int GetIndex3(){ return 3; } public int GetIndex4(){ return 4; } public int GetIndex5(){ return 5; } public int GetIndex6(){ return 6; } public int GetIndex7(){ return 7; } public int GetIndex8(){ return 8; } public int GetIndex9(){ return 9; } public int GetIndex10(){ return 10; } public int GetIndex11(){ return 11; } public int GetIndex12(){ return 12; } public int GetIndex13(){ return 13; } public int GetIndex14(){ return 14; } public int GetIndex15(){ return 15; } public int GetIndex16(){ return 16; } public int GetIndex17(){ return 17; } public int GetIndex18(){ return 18; } public int GetIndex19(){ return 19; } public int GetIndex20(){ return 20; } public int GetIndex21(){ return 21; } public int GetIndex22(){ return 22; } public int GetIndex23(){ return 23; } public int GetIndex24(){ return 24; } public int GetIndex25(){ return 25; } public int GetIndex26(){ return 26; } public int GetIndex27(){ return 27; } public int GetIndex28(){ return 28; } public int GetIndex29(){ return 29; } public int GetIndex30(){ return 30; } public int GetIndex31(){ return 31; } public int GetIndex32(){ return 32; } public int GetIndex33(){ return 33; } public int GetIndex34(){ return 34; } public int GetIndex35(){ return 35; } public int GetIndex36(){ return 36; } public int GetIndex37(){ return 37; } public int GetIndex38(){ return 38; } public int GetIndex39(){ return 39; } public int GetIndex40(){ return 40; } public int GetIndex41(){ return 41; } public int GetIndex42(){ return 42; } public int GetIndex43(){ return 43; } public int GetIndex44(){ return 44; } public int GetIndex45(){ return 45; } public int GetIndex46(){ return 46; } public int GetIndex47(){ return 47; } public int GetIndex48(){ return 48; } public int GetIndex49(){ return 49; } public int GetIndex50(){ return 50; } public int GetIndex51(){ return 51; } public int GetIndex52(){ return 52; } public int GetIndex53(){ return 53; } public int GetIndex54(){ return 54; } public int GetIndex55(){ return 55; } public int GetIndex56(){ return 56; } public int GetIndex57(){ return 57; } public int GetIndex58(){ return 58; } public int GetIndex59(){ return 59; } public int GetIndex60(){ return 60; } public int GetIndex61(){ return 61; } public int GetIndex62(){ return 62; } public int GetIndex63(){ return 63; } public int GetIndex64(){ return 64; } public int GetIndex65(){ return 65; } public int GetIndex66(){ return 66; } public int GetIndex67(){ return 67; } public int GetIndex68(){ return 68; } public int GetIndex69(){ return 69; } public int GetIndex70(){ return 70; } public int GetIndex71(){ return 71; } public int GetIndex72(){ return 72; } public int GetIndex73(){ return 73; } public int GetIndex74(){ return 74; } public int GetIndex75(){ return 75; } public int GetIndex76(){ return 76; } public int GetIndex77(){ return 77; } public int GetIndex78(){ return 78; } public int GetIndex79(){ return 79; } public int GetIndex80(){ return 80; } public int GetIndex81(){ return 81; } public int GetIndex82(){ return 82; } public int GetIndex83(){ return 83; } public int GetIndex84(){ return 84; } public int GetIndex85(){ return 85; } public int GetIndex86(){ return 86; } public int GetIndex87(){ return 87; } public int GetIndex88(){ return 88; } public int GetIndex89(){ return 89; } public int GetIndex90(){ return 90; } public int GetIndex91(){ return 91; } public int GetIndex92(){ return 92; } public int GetIndex93(){ return 93; } public int GetIndex94(){ return 94; } public int GetIndex95(){ return 95; } public int GetIndex96(){ return 96; } public int GetIndex97(){ return 97; } public int GetIndex98(){ return 98; } public int GetIndex99(){ return 99; } public int GetIndex100(){ return 100; } public int GetIndex101(){ return 101; } public int GetIndex102(){ return 102; } public int GetIndex103(){ return 103; } public int GetIndex104(){ return 104; } public int GetIndex105(){ return 105; } public int GetIndex106(){ return 106; } public int GetIndex107(){ return 107; } public int GetIndex108(){ return 108; } public int GetIndex109(){ return 109; } public int GetIndex110(){ return 110; } public int GetIndex111(){ return 111; } public int GetIndex112(){ return 112; } public int GetIndex113(){ return 113; } public int GetIndex114(){ return 114; } public int GetIndex115(){ return 115; } public int GetIndex116(){ return 116; } public int GetIndex117(){ return 117; } public int GetIndex118(){ return 118; } public int GetIndex119(){ return 119; } public int GetIndex120(){ return 120; } public int GetIndex121(){ return 121; } public int GetIndex122(){ return 122; } public int GetIndex123(){ return 123; } public int GetIndex124(){ return 124; } public int GetIndex125(){ return 125; } public int GetIndex126(){ return 126; } public int GetIndex127(){ return 127; } public int GetIndex128(){ return 128; } public int GetIndex129(){ return 129; } public int GetIndex130(){ return 130; } public int GetIndex131(){ return 131; } public int GetIndex132(){ return 132; } public int GetIndex133(){ return 133; } public int GetIndex134(){ return 134; } public int GetIndex135(){ return 135; } public int GetIndex136(){ return 136; } public int GetIndex137(){ return 137; } public int GetIndex138(){ return 138; } public int GetIndex139(){ return 139; } public int GetIndex140(){ return 140; } public int GetIndex141(){ return 141; } public int GetIndex142(){ return 142; } public int GetIndex143(){ return 143; } public int GetIndex144(){ return 144; } public int GetIndex145(){ return 145; } public int GetIndex146(){ return 146; } public int GetIndex147(){ return 147; } public int GetIndex148(){ return 148; } public int GetIndex149(){ return 149; } public int GetIndex150(){ return 150; } public int GetIndex151(){ return 151; } public int GetIndex152(){ return 152; } public int GetIndex153(){ return 153; } public int GetIndex154(){ return 154; } public int GetIndex155(){ return 155; } public int GetIndex156(){ return 156; } public int GetIndex157(){ return 157; } public int GetIndex158(){ return 158; } public int GetIndex159(){ return 159; } public int GetIndex160(){ return 160; } public int GetIndex161(){ return 161; } public int GetIndex162(){ return 162; } public int GetIndex163(){ return 163; } public int GetIndex164(){ return 164; } public int GetIndex165(){ return 165; } public int GetIndex166(){ return 166; } public int GetIndex167(){ return 167; } public int GetIndex168(){ return 168; } public int GetIndex169(){ return 169; } public int GetIndex170(){ return 170; } public int GetIndex171(){ return 171; } public int GetIndex172(){ return 172; } public int GetIndex173(){ return 173; } public int GetIndex174(){ return 174; } public int GetIndex175(){ return 175; } public int GetIndex176(){ return 176; } public int GetIndex177(){ return 177; } public int GetIndex178(){ return 178; } public int GetIndex179(){ return 179; } public int GetIndex180(){ return 180; } public int GetIndex181(){ return 181; } public int GetIndex182(){ return 182; } public int GetIndex183(){ return 183; } public int GetIndex184(){ return 184; } public int GetIndex185(){ return 185; } public int GetIndex186(){ return 186; } public int GetIndex187(){ return 187; } public int GetIndex188(){ return 188; } public int GetIndex189(){ return 189; } public int GetIndex190(){ return 190; } public int GetIndex191(){ return 191; } public int GetIndex192(){ return 192; } public int GetIndex193(){ return 193; } public int GetIndex194(){ return 194; } public int GetIndex195(){ return 195; } public int GetIndex196(){ return 196; } public int GetIndex197(){ return 197; } public int GetIndex198(){ return 198; } public int GetIndex199(){ return 199; } public int GetIndex200(){ return 200; } public int GetIndex201(){ return 201; } public int GetIndex202(){ return 202; } public int GetIndex203(){ return 203; } public int GetIndex204(){ return 204; } public int GetIndex205(){ return 205; } public int GetIndex206(){ return 206; } public int GetIndex207(){ return 207; } public int GetIndex208(){ return 208; } public int GetIndex209(){ return 209; } public int GetIndex210(){ return 210; } public int GetIndex211(){ return 211; } public int GetIndex212(){ return 212; } public int GetIndex213(){ return 213; } public int GetIndex214(){ return 214; } public int GetIndex215(){ return 215; } public int GetIndex216(){ return 216; } public int GetIndex217(){ return 217; } public int GetIndex218(){ return 218; } public int GetIndex219(){ return 219; } public int GetIndex220(){ return 220; } public int GetIndex221(){ return 221; } public int GetIndex222(){ return 222; } public int GetIndex223(){ return 223; } public int GetIndex224(){ return 224; } public int GetIndex225(){ return 225; } public int GetIndex226(){ return 226; } public int GetIndex227(){ return 227; } public int GetIndex228(){ return 228; } public int GetIndex229(){ return 229; } public int GetIndex230(){ return 230; } public int GetIndex231(){ return 231; } public int GetIndex232(){ return 232; } public int GetIndex233(){ return 233; } public int GetIndex234(){ return 234; } public int GetIndex235(){ return 235; } public int GetIndex236(){ return 236; } public int GetIndex237(){ return 237; } public int GetIndex238(){ return 238; } public int GetIndex239(){ return 239; } public int GetIndex240(){ return 240; } public int GetIndex241(){ return 241; } public int GetIndex242(){ return 242; } public int GetIndex243(){ return 243; } public int GetIndex244(){ return 244; } public int GetIndex245(){ return 245; } public int GetIndex246(){ return 246; } public int GetIndex247(){ return 247; } public int GetIndex248(){ return 248; } public int GetIndex249(){ return 249; } public int GetIndex250(){ return 250; } public int GetIndex251(){ return 251; } public int GetIndex252(){ return 252; } public int GetIndex253(){ return 253; } public int GetIndex254(){ return 254; } public int GetIndex255(){ return 255; } public int GetIndex256(){ return 256; } public int GetIndex257(){ return 257; } public int GetIndex258(){ return 258; } public int GetIndex259(){ return 259; } public int GetIndex260(){ return 260; } public int GetIndex261(){ return 261; } public int GetIndex262(){ return 262; } public int GetIndex263(){ return 263; } public int GetIndex264(){ return 264; } public int GetIndex265(){ return 265; } public int GetIndex266(){ return 266; } public int GetIndex267(){ return 267; } public int GetIndex268(){ return 268; } public int GetIndex269(){ return 269; } public int GetIndex270(){ return 270; } public int GetIndex271(){ return 271; } public int GetIndex272(){ return 272; } public int GetIndex273(){ return 273; } public int GetIndex274(){ return 274; } public int GetIndex275(){ return 275; } public int GetIndex276(){ return 276; } public int GetIndex277(){ return 277; } public int GetIndex278(){ return 278; } public int GetIndex279(){ return 279; } public int GetIndex280(){ return 280; } public int GetIndex281(){ return 281; } public int GetIndex282(){ return 282; } public int GetIndex283(){ return 283; } public int GetIndex284(){ return 284; } public int GetIndex285(){ return 285; } public int GetIndex286(){ return 286; } public int GetIndex287(){ return 287; } public int GetIndex288(){ return 288; } public int GetIndex289(){ return 289; } public int GetIndex290(){ return 290; } public int GetIndex291(){ return 291; } public int GetIndex292(){ return 292; } public int GetIndex293(){ return 293; } public int GetIndex294(){ return 294; } public int GetIndex295(){ return 295; } public int GetIndex296(){ return 296; } public int GetIndex297(){ return 297; } public int GetIndex298(){ return 298; } public int GetIndex299(){ return 299; } public int GetIndex300(){ return 300; } public int GetIndex301(){ return 301; } public int GetIndex302(){ return 302; } public int GetIndex303(){ return 303; } public int GetIndex304(){ return 304; } public int GetIndex305(){ return 305; } public int GetIndex306(){ return 306; } public int GetIndex307(){ return 307; } public int GetIndex308(){ return 308; } public int GetIndex309(){ return 309; } public int GetIndex310(){ return 310; } public int GetIndex311(){ return 311; } public int GetIndex312(){ return 312; } public int GetIndex313(){ return 313; } public int GetIndex314(){ return 314; } public int GetIndex315(){ return 315; } public int GetIndex316(){ return 316; } public int GetIndex317(){ return 317; } public int GetIndex318(){ return 318; } public int GetIndex319(){ return 319; } public int GetIndex320(){ return 320; } public int GetIndex321(){ return 321; } public int GetIndex322(){ return 322; } public int GetIndex323(){ return 323; } public int GetIndex324(){ return 324; } public int GetIndex325(){ return 325; } public int GetIndex326(){ return 326; } public int GetIndex327(){ return 327; } public int GetIndex328(){ return 328; } public int GetIndex329(){ return 329; } public int GetIndex330(){ return 330; } public int GetIndex331(){ return 331; } public int GetIndex332(){ return 332; } public int GetIndex333(){ return 333; } public int GetIndex334(){ return 334; } public int GetIndex335(){ return 335; } public int GetIndex336(){ return 336; } public int GetIndex337(){ return 337; } public int GetIndex338(){ return 338; } public int GetIndex339(){ return 339; } public int GetIndex340(){ return 340; } public int GetIndex341(){ return 341; } public int GetIndex342(){ return 342; } public int GetIndex343(){ return 343; } public int GetIndex344(){ return 344; } public int GetIndex345(){ return 345; } public int GetIndex346(){ return 346; } public int GetIndex347(){ return 347; } public int GetIndex348(){ return 348; } public int GetIndex349(){ return 349; } public int GetIndex350(){ return 350; } public int GetIndex351(){ return 351; } public int GetIndex352(){ return 352; } public int GetIndex353(){ return 353; } public int GetIndex354(){ return 354; } public int GetIndex355(){ return 355; } public int GetIndex356(){ return 356; } public int GetIndex357(){ return 357; } public int GetIndex358(){ return 358; } public int GetIndex359(){ return 359; } public int GetIndex360(){ return 360; } public int GetIndex361(){ return 361; } public int GetIndex362(){ return 362; } public int GetIndex363(){ return 363; } public int GetIndex364(){ return 364; } public int GetIndex365(){ return 365; } public int GetIndex366(){ return 366; } public int GetIndex367(){ return 367; } public int GetIndex368(){ return 368; } public int GetIndex369(){ return 369; } public int GetIndex370(){ return 370; } public int GetIndex371(){ return 371; } public int GetIndex372(){ return 372; } public int GetIndex373(){ return 373; } public int GetIndex374(){ return 374; } public int GetIndex375(){ return 375; } public int GetIndex376(){ return 376; } public int GetIndex377(){ return 377; } public int GetIndex378(){ return 378; } public int GetIndex379(){ return 379; } public int GetIndex380(){ return 380; } public int GetIndex381(){ return 381; } public int GetIndex382(){ return 382; } public int GetIndex383(){ return 383; } public int GetIndex384(){ return 384; } public int GetIndex385(){ return 385; } public int GetIndex386(){ return 386; } public int GetIndex387(){ return 387; } public int GetIndex388(){ return 388; } public int GetIndex389(){ return 389; } public int GetIndex390(){ return 390; } public int GetIndex391(){ return 391; } public int GetIndex392(){ return 392; } public int GetIndex393(){ return 393; } public int GetIndex394(){ return 394; } public int GetIndex395(){ return 395; } public int GetIndex396(){ return 396; } public int GetIndex397(){ return 397; } public int GetIndex398(){ return 398; } public int GetIndex399(){ return 399; } public int GetIndex400(){ return 400; } public int GetIndex401(){ return 401; } public int GetIndex402(){ return 402; } public int GetIndex403(){ return 403; } public int GetIndex404(){ return 404; } public int GetIndex405(){ return 405; } public int GetIndex406(){ return 406; } public int GetIndex407(){ return 407; } public int GetIndex408(){ return 408; } public int GetIndex409(){ return 409; } public int GetIndex410(){ return 410; } public int GetIndex411(){ return 411; } public int GetIndex412(){ return 412; } public int GetIndex413(){ return 413; } public int GetIndex414(){ return 414; } public int GetIndex415(){ return 415; } public int GetIndex416(){ return 416; } public int GetIndex417(){ return 417; } public int GetIndex418(){ return 418; } public int GetIndex419(){ return 419; } public int GetIndex420(){ return 420; } public int GetIndex421(){ return 421; } public int GetIndex422(){ return 422; } public int GetIndex423(){ return 423; } public int GetIndex424(){ return 424; } public int GetIndex425(){ return 425; } public int GetIndex426(){ return 426; } public int GetIndex427(){ return 427; } public int GetIndex428(){ return 428; } public int GetIndex429(){ return 429; } public int GetIndex430(){ return 430; } public int GetIndex431(){ return 431; } public int GetIndex432(){ return 432; } public int GetIndex433(){ return 433; } public int GetIndex434(){ return 434; } public int GetIndex435(){ return 435; } public int GetIndex436(){ return 436; } public int GetIndex437(){ return 437; } public int GetIndex438(){ return 438; } public int GetIndex439(){ return 439; } public int GetIndex440(){ return 440; } public int GetIndex441(){ return 441; } public int GetIndex442(){ return 442; } public int GetIndex443(){ return 443; } public int GetIndex444(){ return 444; } public int GetIndex445(){ return 445; } public int GetIndex446(){ return 446; } public int GetIndex447(){ return 447; } public int GetIndex448(){ return 448; } public int GetIndex449(){ return 449; } public int GetIndex450(){ return 450; } public int GetIndex451(){ return 451; } public int GetIndex452(){ return 452; } public int GetIndex453(){ return 453; } public int GetIndex454(){ return 454; } public int GetIndex455(){ return 455; } public int GetIndex456(){ return 456; } public int GetIndex457(){ return 457; } public int GetIndex458(){ return 458; } public int GetIndex459(){ return 459; } public int GetIndex460(){ return 460; } public int GetIndex461(){ return 461; } public int GetIndex462(){ return 462; } public int GetIndex463(){ return 463; } public int GetIndex464(){ return 464; } public int GetIndex465(){ return 465; } public int GetIndex466(){ return 466; } public int GetIndex467(){ return 467; } public int GetIndex468(){ return 468; } public int GetIndex469(){ return 469; } public int GetIndex470(){ return 470; } public int GetIndex471(){ return 471; } public int GetIndex472(){ return 472; } public int GetIndex473(){ return 473; } public int GetIndex474(){ return 474; } public int GetIndex475(){ return 475; } public int GetIndex476(){ return 476; } public int GetIndex477(){ return 477; } public int GetIndex478(){ return 478; } public int GetIndex479(){ return 479; } public int GetIndex480(){ return 480; } public int GetIndex481(){ return 481; } public int GetIndex482(){ return 482; } public int GetIndex483(){ return 483; } public int GetIndex484(){ return 484; } public int GetIndex485(){ return 485; } public int GetIndex486(){ return 486; } public int GetIndex487(){ return 487; } public int GetIndex488(){ return 488; } public int GetIndex489(){ return 489; } public int GetIndex490(){ return 490; } public int GetIndex491(){ return 491; } public int GetIndex492(){ return 492; } public int GetIndex493(){ return 493; } public int GetIndex494(){ return 494; } public int GetIndex495(){ return 495; } public int GetIndex496(){ return 496; } public int GetIndex497(){ return 497; } public int GetIndex498(){ return 498; } public int GetIndex499(){ return 499; } public int GetIndex500(){ return 500; } public int GetIndex501(){ return 501; } public int GetIndex502(){ return 502; } public int GetIndex503(){ return 503; } public int GetIndex504(){ return 504; } public int GetIndex505(){ return 505; } public int GetIndex506(){ return 506; } public int GetIndex507(){ return 507; } public int GetIndex508(){ return 508; } public int GetIndex509(){ return 509; } public int GetIndex510(){ return 510; } public int GetIndex511(){ return 511; } public int GetIndex512(){ return 512; } public int GetIndex513(){ return 513; } public int GetIndex514(){ return 514; } public int GetIndex515(){ return 515; } public int GetIndex516(){ return 516; } public int GetIndex517(){ return 517; } public int GetIndex518(){ return 518; } public int GetIndex519(){ return 519; } public int GetIndex520(){ return 520; } public int GetIndex521(){ return 521; } public int GetIndex522(){ return 522; } public int GetIndex523(){ return 523; } public int GetIndex524(){ return 524; } public int GetIndex525(){ return 525; } public int GetIndex526(){ return 526; } public int GetIndex527(){ return 527; } public int GetIndex528(){ return 528; } public int GetIndex529(){ return 529; } public int GetIndex530(){ return 530; } public int GetIndex531(){ return 531; } public int GetIndex532(){ return 532; } public int GetIndex533(){ return 533; } public int GetIndex534(){ return 534; } public int GetIndex535(){ return 535; } public int GetIndex536(){ return 536; } public int GetIndex537(){ return 537; } public int GetIndex538(){ return 538; } public int GetIndex539(){ return 539; } public int GetIndex540(){ return 540; } public int GetIndex541(){ return 541; } public int GetIndex542(){ return 542; } public int GetIndex543(){ return 543; } public int GetIndex544(){ return 544; } public int GetIndex545(){ return 545; } public int GetIndex546(){ return 546; } public int GetIndex547(){ return 547; } public int GetIndex548(){ return 548; } public int GetIndex549(){ return 549; } public int GetIndex550(){ return 550; } public int GetIndex551(){ return 551; } public int GetIndex552(){ return 552; } public int GetIndex553(){ return 553; } public int GetIndex554(){ return 554; } public int GetIndex555(){ return 555; } public int GetIndex556(){ return 556; } public int GetIndex557(){ return 557; } public int GetIndex558(){ return 558; } public int GetIndex559(){ return 559; } public int GetIndex560(){ return 560; } public int GetIndex561(){ return 561; } public int GetIndex562(){ return 562; } public int GetIndex563(){ return 563; } public int GetIndex564(){ return 564; } public int GetIndex565(){ return 565; } public int GetIndex566(){ return 566; } public int GetIndex567(){ return 567; } public int GetIndex568(){ return 568; } public int GetIndex569(){ return 569; } public int GetIndex570(){ return 570; } public int GetIndex571(){ return 571; } public int GetIndex572(){ return 572; } public int GetIndex573(){ return 573; } public int GetIndex574(){ return 574; } public int GetIndex575(){ return 575; } public int GetIndex576(){ return 576; } public int GetIndex577(){ return 577; } public int GetIndex578(){ return 578; } public int GetIndex579(){ return 579; } public int GetIndex580(){ return 580; } public int GetIndex581(){ return 581; } public int GetIndex582(){ return 582; } public int GetIndex583(){ return 583; } public int GetIndex584(){ return 584; } public int GetIndex585(){ return 585; } public int GetIndex586(){ return 586; } public int GetIndex587(){ return 587; } public int GetIndex588(){ return 588; } public int GetIndex589(){ return 589; } public int GetIndex590(){ return 590; } public int GetIndex591(){ return 591; } public int GetIndex592(){ return 592; } public int GetIndex593(){ return 593; } public int GetIndex594(){ return 594; } public int GetIndex595(){ return 595; } public int GetIndex596(){ return 596; } public int GetIndex597(){ return 597; } public int GetIndex598(){ return 598; } public int GetIndex599(){ return 599; } public int GetIndex600(){ return 600; } public int GetIndex601(){ return 601; } public int GetIndex602(){ return 602; } public int GetIndex603(){ return 603; } public int GetIndex604(){ return 604; } public int GetIndex605(){ return 605; } public int GetIndex606(){ return 606; } public int GetIndex607(){ return 607; } public int GetIndex608(){ return 608; } public int GetIndex609(){ return 609; } public int GetIndex610(){ return 610; } public int GetIndex611(){ return 611; } public int GetIndex612(){ return 612; } public int GetIndex613(){ return 613; } public int GetIndex614(){ return 614; } public int GetIndex615(){ return 615; } public int GetIndex616(){ return 616; } public int GetIndex617(){ return 617; } public int GetIndex618(){ return 618; } public int GetIndex619(){ return 619; } public int GetIndex620(){ return 620; } public int GetIndex621(){ return 621; } public int GetIndex622(){ return 622; } public int GetIndex623(){ return 623; } public int GetIndex624(){ return 624; } public int GetIndex625(){ return 625; } public int GetIndex626(){ return 626; } public int GetIndex627(){ return 627; } public int GetIndex628(){ return 628; } public int GetIndex629(){ return 629; } public int GetIndex630(){ return 630; } public int GetIndex631(){ return 631; } public int GetIndex632(){ return 632; } public int GetIndex633(){ return 633; } public int GetIndex634(){ return 634; } public int GetIndex635(){ return 635; } public int GetIndex636(){ return 636; } public int GetIndex637(){ return 637; } public int GetIndex638(){ return 638; } public int GetIndex639(){ return 639; } public int GetIndex640(){ return 640; } public int GetIndex641(){ return 641; } public int GetIndex642(){ return 642; } public int GetIndex643(){ return 643; } public int GetIndex644(){ return 644; } public int GetIndex645(){ return 645; } public int GetIndex646(){ return 646; } public int GetIndex647(){ return 647; } public int GetIndex648(){ return 648; } public int GetIndex649(){ return 649; } public int GetIndex650(){ return 650; } public int GetIndex651(){ return 651; } public int GetIndex652(){ return 652; } public int GetIndex653(){ return 653; } public int GetIndex654(){ return 654; } public int GetIndex655(){ return 655; } public int GetIndex656(){ return 656; } public int GetIndex657(){ return 657; } public int GetIndex658(){ return 658; } public int GetIndex659(){ return 659; } public int GetIndex660(){ return 660; } public int GetIndex661(){ return 661; } public int GetIndex662(){ return 662; } public int GetIndex663(){ return 663; } public int GetIndex664(){ return 664; } public int GetIndex665(){ return 665; } public int GetIndex666(){ return 666; } public int GetIndex667(){ return 667; } public int GetIndex668(){ return 668; } public int GetIndex669(){ return 669; } public int GetIndex670(){ return 670; } public int GetIndex671(){ return 671; } public int GetIndex672(){ return 672; } public int GetIndex673(){ return 673; } public int GetIndex674(){ return 674; } public int GetIndex675(){ return 675; } public int GetIndex676(){ return 676; } public int GetIndex677(){ return 677; } public int GetIndex678(){ return 678; } public int GetIndex679(){ return 679; } public int GetIndex680(){ return 680; } public int GetIndex681(){ return 681; } public int GetIndex682(){ return 682; } public int GetIndex683(){ return 683; } public int GetIndex684(){ return 684; } public int GetIndex685(){ return 685; } public int GetIndex686(){ return 686; } public int GetIndex687(){ return 687; } public int GetIndex688(){ return 688; } public int GetIndex689(){ return 689; } public int GetIndex690(){ return 690; } public int GetIndex691(){ return 691; } public int GetIndex692(){ return 692; } public int GetIndex693(){ return 693; } public int GetIndex694(){ return 694; } public int GetIndex695(){ return 695; } public int GetIndex696(){ return 696; } public int GetIndex697(){ return 697; } public int GetIndex698(){ return 698; } public int GetIndex699(){ return 699; } public int GetIndex700(){ return 700; } public int GetIndex701(){ return 701; } public int GetIndex702(){ return 702; } public int GetIndex703(){ return 703; } public int GetIndex704(){ return 704; } public int GetIndex705(){ return 705; } public int GetIndex706(){ return 706; } public int GetIndex707(){ return 707; } public int GetIndex708(){ return 708; } public int GetIndex709(){ return 709; } public int GetIndex710(){ return 710; } public int GetIndex711(){ return 711; } public int GetIndex712(){ return 712; } public int GetIndex713(){ return 713; } public int GetIndex714(){ return 714; } public int GetIndex715(){ return 715; } public int GetIndex716(){ return 716; } public int GetIndex717(){ return 717; } public int GetIndex718(){ return 718; } public int GetIndex719(){ return 719; } public int GetIndex720(){ return 720; } public int GetIndex721(){ return 721; } public int GetIndex722(){ return 722; } public int GetIndex723(){ return 723; } public int GetIndex724(){ return 724; } public int GetIndex725(){ return 725; } public int GetIndex726(){ return 726; } public int GetIndex727(){ return 727; } public int GetIndex728(){ return 728; } public int GetIndex729(){ return 729; } public int GetIndex730(){ return 730; } public int GetIndex731(){ return 731; } public int GetIndex732(){ return 732; } public int GetIndex733(){ return 733; } public int GetIndex734(){ return 734; } public int GetIndex735(){ return 735; } public int GetIndex736(){ return 736; } public int GetIndex737(){ return 737; } public int GetIndex738(){ return 738; } public int GetIndex739(){ return 739; } public int GetIndex740(){ return 740; } public int GetIndex741(){ return 741; } public int GetIndex742(){ return 742; } public int GetIndex743(){ return 743; } public int GetIndex744(){ return 744; } public int GetIndex745(){ return 745; } public int GetIndex746(){ return 746; } public int GetIndex747(){ return 747; } public int GetIndex748(){ return 748; } public int GetIndex749(){ return 749; } public int GetIndex750(){ return 750; } public int GetIndex751(){ return 751; } public int GetIndex752(){ return 752; } public int GetIndex753(){ return 753; } public int GetIndex754(){ return 754; } public int GetIndex755(){ return 755; } public int GetIndex756(){ return 756; } public int GetIndex757(){ return 757; } public int GetIndex758(){ return 758; } public int GetIndex759(){ return 759; } public int GetIndex760(){ return 760; } public int GetIndex761(){ return 761; } public int GetIndex762(){ return 762; } public int GetIndex763(){ return 763; } public int GetIndex764(){ return 764; } public int GetIndex765(){ return 765; } public int GetIndex766(){ return 766; } public int GetIndex767(){ return 767; } public int GetIndex768(){ return 768; } public int GetIndex769(){ return 769; } public int GetIndex770(){ return 770; } public int GetIndex771(){ return 771; } public int GetIndex772(){ return 772; } public int GetIndex773(){ return 773; } public int GetIndex774(){ return 774; } public int GetIndex775(){ return 775; } public int GetIndex776(){ return 776; } public int GetIndex777(){ return 777; } public int GetIndex778(){ return 778; } public int GetIndex779(){ return 779; } public int GetIndex780(){ return 780; } public int GetIndex781(){ return 781; } public int GetIndex782(){ return 782; } public int GetIndex783(){ return 783; } public int GetIndex784(){ return 784; } public int GetIndex785(){ return 785; } public int GetIndex786(){ return 786; } public int GetIndex787(){ return 787; } public int GetIndex788(){ return 788; } public int GetIndex789(){ return 789; } public int GetIndex790(){ return 790; } public int GetIndex791(){ return 791; } public int GetIndex792(){ return 792; } public int GetIndex793(){ return 793; } public int GetIndex794(){ return 794; } public int GetIndex795(){ return 795; } public int GetIndex796(){ return 796; } public int GetIndex797(){ return 797; } public int GetIndex798(){ return 798; } public int GetIndex799(){ return 799; } public int GetIndex800(){ return 800; } public int GetIndex801(){ return 801; } public int GetIndex802(){ return 802; } public int GetIndex803(){ return 803; } public int GetIndex804(){ return 804; } public int GetIndex805(){ return 805; } public int GetIndex806(){ return 806; } public int GetIndex807(){ return 807; } public int GetIndex808(){ return 808; } public int GetIndex809(){ return 809; } public int GetIndex810(){ return 810; } public int GetIndex811(){ return 811; } public int GetIndex812(){ return 812; } public int GetIndex813(){ return 813; } public int GetIndex814(){ return 814; } public int GetIndex815(){ return 815; } public int GetIndex816(){ return 816; } public int GetIndex817(){ return 817; } public int GetIndex818(){ return 818; } public int GetIndex819(){ return 819; } public int GetIndex820(){ return 820; } public int GetIndex821(){ return 821; } public int GetIndex822(){ return 822; } public int GetIndex823(){ return 823; } public int GetIndex824(){ return 824; } public int GetIndex825(){ return 825; } public int GetIndex826(){ return 826; } public int GetIndex827(){ return 827; } public int GetIndex828(){ return 828; } public int GetIndex829(){ return 829; } public int GetIndex830(){ return 830; } public int GetIndex831(){ return 831; } public int GetIndex832(){ return 832; } public int GetIndex833(){ return 833; } public int GetIndex834(){ return 834; } public int GetIndex835(){ return 835; } public int GetIndex836(){ return 836; } public int GetIndex837(){ return 837; } public int GetIndex838(){ return 838; } public int GetIndex839(){ return 839; } public int GetIndex840(){ return 840; } public int GetIndex841(){ return 841; } public int GetIndex842(){ return 842; } public int GetIndex843(){ return 843; } public int GetIndex844(){ return 844; } public int GetIndex845(){ return 845; } public int GetIndex846(){ return 846; } public int GetIndex847(){ return 847; } public int GetIndex848(){ return 848; } public int GetIndex849(){ return 849; } public int GetIndex850(){ return 850; } public int GetIndex851(){ return 851; } public int GetIndex852(){ return 852; } public int GetIndex853(){ return 853; } public int GetIndex854(){ return 854; } public int GetIndex855(){ return 855; } public int GetIndex856(){ return 856; } public int GetIndex857(){ return 857; } public int GetIndex858(){ return 858; } public int GetIndex859(){ return 859; } public int GetIndex860(){ return 860; } public int GetIndex861(){ return 861; } public int GetIndex862(){ return 862; } public int GetIndex863(){ return 863; } public int GetIndex864(){ return 864; } public int GetIndex865(){ return 865; } public int GetIndex866(){ return 866; } public int GetIndex867(){ return 867; } public int GetIndex868(){ return 868; } public int GetIndex869(){ return 869; } public int GetIndex870(){ return 870; } public int GetIndex871(){ return 871; } public int GetIndex872(){ return 872; } public int GetIndex873(){ return 873; } public int GetIndex874(){ return 874; } public int GetIndex875(){ return 875; } public int GetIndex876(){ return 876; } public int GetIndex877(){ return 877; } public int GetIndex878(){ return 878; } public int GetIndex879(){ return 879; } public int GetIndex880(){ return 880; } public int GetIndex881(){ return 881; } public int GetIndex882(){ return 882; } public int GetIndex883(){ return 883; } public int GetIndex884(){ return 884; } public int GetIndex885(){ return 885; } public int GetIndex886(){ return 886; } public int GetIndex887(){ return 887; } public int GetIndex888(){ return 888; } public int GetIndex889(){ return 889; } public int GetIndex890(){ return 890; } public int GetIndex891(){ return 891; } public int GetIndex892(){ return 892; } public int GetIndex893(){ return 893; } public int GetIndex894(){ return 894; } public int GetIndex895(){ return 895; } public int GetIndex896(){ return 896; } public int GetIndex897(){ return 897; } public int GetIndex898(){ return 898; } public int GetIndex899(){ return 899; } public int GetIndex900(){ return 900; } public int GetIndex901(){ return 901; } public int GetIndex902(){ return 902; } public int GetIndex903(){ return 903; } public int GetIndex904(){ return 904; } public int GetIndex905(){ return 905; } public int GetIndex906(){ return 906; } public int GetIndex907(){ return 907; } public int GetIndex908(){ return 908; } public int GetIndex909(){ return 909; } public int GetIndex910(){ return 910; } public int GetIndex911(){ return 911; } public int GetIndex912(){ return 912; } public int GetIndex913(){ return 913; } public int GetIndex914(){ return 914; } public int GetIndex915(){ return 915; } public int GetIndex916(){ return 916; } public int GetIndex917(){ return 917; } public int GetIndex918(){ return 918; } public int GetIndex919(){ return 919; } public int GetIndex920(){ return 920; } public int GetIndex921(){ return 921; } public int GetIndex922(){ return 922; } public int GetIndex923(){ return 923; } public int GetIndex924(){ return 924; } public int GetIndex925(){ return 925; } public int GetIndex926(){ return 926; } public int GetIndex927(){ return 927; } public int GetIndex928(){ return 928; } public int GetIndex929(){ return 929; } public int GetIndex930(){ return 930; } public int GetIndex931(){ return 931; } public int GetIndex932(){ return 932; } public int GetIndex933(){ return 933; } public int GetIndex934(){ return 934; } public int GetIndex935(){ return 935; } public int GetIndex936(){ return 936; } public int GetIndex937(){ return 937; } public int GetIndex938(){ return 938; } public int GetIndex939(){ return 939; } public int GetIndex940(){ return 940; } public int GetIndex941(){ return 941; } public int GetIndex942(){ return 942; } public int GetIndex943(){ return 943; } public int GetIndex944(){ return 944; } public int GetIndex945(){ return 945; } public int GetIndex946(){ return 946; } public int GetIndex947(){ return 947; } public int GetIndex948(){ return 948; } public int GetIndex949(){ return 949; } public int GetIndex950(){ return 950; } public int GetIndex951(){ return 951; } public int GetIndex952(){ return 952; } public int GetIndex953(){ return 953; } public int GetIndex954(){ return 954; } public int GetIndex955(){ return 955; } public int GetIndex956(){ return 956; } public int GetIndex957(){ return 957; } public int GetIndex958(){ return 958; } public int GetIndex959(){ return 959; } public int GetIndex960(){ return 960; } public int GetIndex961(){ return 961; } public int GetIndex962(){ return 962; } public int GetIndex963(){ return 963; } public int GetIndex964(){ return 964; } public int GetIndex965(){ return 965; } public int GetIndex966(){ return 966; } public int GetIndex967(){ return 967; } public int GetIndex968(){ return 968; } public int GetIndex969(){ return 969; } public int GetIndex970(){ return 970; } public int GetIndex971(){ return 971; } public int GetIndex972(){ return 972; } public int GetIndex973(){ return 973; } public int GetIndex974(){ return 974; } public int GetIndex975(){ return 975; } public int GetIndex976(){ return 976; } public int GetIndex977(){ return 977; } public int GetIndex978(){ return 978; } public int GetIndex979(){ return 979; } public int GetIndex980(){ return 980; } public int GetIndex981(){ return 981; } public int GetIndex982(){ return 982; } public int GetIndex983(){ return 983; } public int GetIndex984(){ return 984; } public int GetIndex985(){ return 985; } public int GetIndex986(){ return 986; } public int GetIndex987(){ return 987; } public int GetIndex988(){ return 988; } public int GetIndex989(){ return 989; } public int GetIndex990(){ return 990; } public int GetIndex991(){ return 991; } public int GetIndex992(){ return 992; } public int GetIndex993(){ return 993; } public int GetIndex994(){ return 994; } public int GetIndex995(){ return 995; } public int GetIndex996(){ return 996; } public int GetIndex997(){ return 997; } public int GetIndex998(){ return 998; } public int GetIndex999(){ return 999; } }
40.545545
43
0.705673
[ "MIT" ]
mao-test-h/SamplePackage
Runtime/Generated/Hoge43.generated.cs
40,951
C#
using System; public enum Directions { None = 0, Up = 1, Down = 2, Left = 3, Right = 4, } public static class Program { public static void Main (string[] args) { var d = Directions.Up; Console.WriteLine("{0}", ++d); Console.WriteLine("{0}", d); Console.WriteLine("{0}", d++); Console.WriteLine("{0}", d); Console.WriteLine("{0}", --d); Console.WriteLine("{0}", d); Console.WriteLine("{0}", d--); Console.WriteLine("{0}", d); } }
22.125
45
0.506591
[ "MIT" ]
RedpointGames/JSIL
Tests/SimpleTestCases/EnumPrePostIncrement.cs
531
C#
/* Copyright 2021 CrypTool 2 Team <ct2contact@CrypTool.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Windows.Controls; namespace CrypTool.CrypAnalysisViewControl { public class SectionViewLabelsControl : ItemsControl { } }
31.958333
75
0.750978
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
LibSource/CrypAnalysisViewControl/SectionViewLabelsControl.cs
769
C#
using System; using System.Collections.Generic; using System.Linq; using RestSharp; using KeyPayV2.Common; using KeyPayV2.Common.Models; using KeyPayV2.Nz.Enums; using KeyPayV2.Nz.Models.Common; using KeyPayV2.Nz.Models.PayRun; namespace KeyPayV2.Nz.Functions { public class PayRunFunction : BaseFunction { public PayRunFunction(ApiRequestExecutor api) : base(api) {} /// <summary> /// List Pay Run Totals for Employee /// </summary> /// <remarks> /// Lists all the pay run totals for the employee with the specified ID. /// </remarks> public List<PayRunTotalModel> ListPayRunTotalsForEmployee(int businessId, int employeeId) { return ApiRequest<List<PayRunTotalModel>>($"/business/{businessId}/employee/{employeeId}/payruntotals"); } /// <summary> /// Get Journal Details /// </summary> /// <remarks> /// Gets the journal details for this pay run. /// </remarks> public List<NzJournalItemResponse> GetJournalDetails(int businessId, int payRunId) { return ApiRequest<List<NzJournalItemResponse>>($"/business/{businessId}/journal/{payRunId}"); } /// <summary> /// List Pay Runs /// </summary> /// <remarks> /// Get a list of pay runs associated with the business. /// This operation supports OData queries (only $filter, $orderby, $top, $skip). /// </remarks> public List<PayRunModel> ListPayRuns(int businessId, ODataQuery oDataQuery = null) { return ApiRequest<List<PayRunModel>>($"/business/{businessId}/payrun{ODataQuery.ToQueryString(oDataQuery, "?")}"); } /// <summary> /// Create Pay Run /// </summary> /// <remarks> /// Creates a new pay run for this business. /// </remarks> public PayRunModel CreatePayRun(int businessId, PayRunCreateRequest request) { return ApiRequest<PayRunModel,PayRunCreateRequest>($"/business/{businessId}/payrun", request, Method.POST); } /// <summary> /// Get Pay Run /// </summary> /// <remarks> /// Gets the pay run with the specified ID. /// </remarks> public PayRunModel GetPayRun(int businessId, int payRunId) { return ApiRequest<PayRunModel>($"/business/{businessId}/payrun/{payRunId}"); } /// <summary> /// Delete Pay Run /// </summary> /// <remarks> /// Deletes the pay run with the specified ID. /// </remarks> public void DeletePayRun(int businessId, int payRunId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}", Method.DELETE); } /// <summary> /// List Deductions /// </summary> /// <remarks> /// Gets all the deductions for a pay run. /// </remarks> public NzPayRunDeductionResponse ListDeductions(int businessId, int payRunId) { return ApiRequest<NzPayRunDeductionResponse>($"/business/{businessId}/payrun/{payRunId}/deductions"); } /// <summary> /// Create Deductions /// </summary> /// <remarks> /// Add deductions to the specified pay run. /// </remarks> public void CreateDeductions(int businessId, int payRunId, SubmitPayRunDeductionRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/deductions", request, Method.POST); } /// <summary> /// Delete Deduction /// </summary> /// <remarks> /// Deletes the deduction with the specified ID from the pay run. /// </remarks> public void DeleteDeduction(int businessId, int payRunId, DeleteDeductionQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/deductions?id={request.Id}", Method.DELETE); } /// <summary> /// Get Deductions by Employee ID /// </summary> /// <remarks> /// Gets all the deductions for a specific employee in a pay run. /// </remarks> public NzPayRunDeductionResponse GetDeductionsByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<NzPayRunDeductionResponse>($"/business/{businessId}/payrun/{payRunId}/deductions/{employeeId}"); } /// <summary> /// List Earnings Lines /// </summary> /// <remarks> /// Lists all the earnings lines for a pay run. /// </remarks> public NzPayRunEarningsLineResponseModel ListEarningsLines(int businessId, int payRunId) { return ApiRequest<NzPayRunEarningsLineResponseModel>($"/business/{businessId}/payrun/{payRunId}/earningslines"); } /// <summary> /// Create Earnings Lines /// </summary> /// <remarks> /// Adds earnings lines to the specified pay run. /// </remarks> public void CreateEarningsLines(int businessId, int payRunId, NzSubmitPayRunEarningsLineRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/earningslines", request, Method.POST); } /// <summary> /// Delete Earnings Line /// </summary> /// <remarks> /// Deletes the earnings with the specified ID from the pay run. /// </remarks> public void DeleteEarningsLine(int businessId, int payRunId, DeleteEarningsLineQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/earningslines?id={request.Id}", Method.DELETE); } /// <summary> /// Get Earnings Lines by Employee ID /// </summary> /// <remarks> /// Gets all the earnings lines for a specific employee in a pay run. /// </remarks> public NzPayRunEarningsLineResponseModel GetEarningsLinesByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<NzPayRunEarningsLineResponseModel>($"/business/{businessId}/payrun/{payRunId}/earningslines/{employeeId}"); } /// <summary> /// Include Employee /// </summary> /// <remarks> /// Includes an employee in a pay run. /// </remarks> public PayRunTotalModel IncludeEmployee(int businessId, int employeeId, int payRunId) { return ApiRequest<PayRunTotalModel>($"/business/{businessId}/payrun/{payRunId}/employee/{employeeId}", Method.POST); } /// <summary> /// Remove Employee from Pay Run /// </summary> /// <remarks> /// Removes an employee from a pay run. /// </remarks> public void RemoveEmployeeFromPayRun(int businessId, int employeeId, int payRunId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/employee/{employeeId}", Method.DELETE); } /// <summary> /// List Employee Expenses /// </summary> /// <remarks> /// Lists all the employee expenses for a pay run. /// </remarks> public PayRunEmployeeExpenseResponse ListEmployeeExpenses(int businessId, int payRunId) { return ApiRequest<PayRunEmployeeExpenseResponse>($"/business/{businessId}/payrun/{payRunId}/EmployeeExpenses"); } /// <summary> /// Create Employee Expenses /// </summary> /// <remarks> /// Add employee expenses to the specified pay run. /// </remarks> public void CreateEmployeeExpenses(int businessId, int payRunId, SubmitPayRunEmployeeExpenseRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/EmployeeExpenses", request, Method.POST); } /// <summary> /// Delete Employee Expense /// </summary> /// <remarks> /// Deletes the employee expense with the specified ID from the pay run. /// </remarks> public void DeleteEmployeeExpense(int businessId, int payRunId, DeleteEmployeeExpenseQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/EmployeeExpenses?id={request.Id}", Method.DELETE); } /// <summary> /// Get Employee Expenses by Employee ID /// </summary> /// <remarks> /// Gets all the employee expenses for a specific employee in a pay run. /// </remarks> public PayRunEmployeeExpenseResponse GetEmployeeExpensesByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<PayRunEmployeeExpenseResponse>($"/business/{businessId}/payrun/{payRunId}/EmployeeExpenses/{employeeId}"); } /// <summary> /// List Employer Liabilities /// </summary> /// <remarks> /// Lists all the employer liabilities for a pay run. /// </remarks> public PayRunEmployerLiabilityResponse ListEmployerLiabilities(int businessId, int payRunId) { return ApiRequest<PayRunEmployerLiabilityResponse>($"/business/{businessId}/payrun/{payRunId}/employerliabilities"); } /// <summary> /// Create Employer Liabilities /// </summary> /// <remarks> /// Add employer liabilities to the specified pay run. /// </remarks> public void CreateEmployerLiabilities(int businessId, int payRunId, SubmitPayRunEmployerLiabilityRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/employerliabilities", request, Method.POST); } /// <summary> /// Delete Employer Liability /// </summary> /// <remarks> /// Deletes the employer liability with the specified ID from the pay run. /// </remarks> public void DeleteEmployerLiability(int businessId, int payRunId, DeleteEmployerLiabilityQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/employerliabilities?id={request.Id}", Method.DELETE); } /// <summary> /// Get Employer Liabilities by Employee ID /// </summary> /// <remarks> /// Gets all the employer liabilities for a specific employee in a pay run. /// </remarks> public PayRunEmployerLiabilityResponse GetEmployerLiabilitiesByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<PayRunEmployerLiabilityResponse>($"/business/{businessId}/payrun/{payRunId}/employerliabilities/{employeeId}"); } /// <summary> /// Get Bank Payment File /// </summary> /// <remarks> /// Gets a Bank Payment file associated with a pay run. /// </remarks> public void GetBankPaymentFile(int businessId, int payRunId, int paymentFileId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/file/bankpayment/{paymentFileId}"); } /// <summary> /// Get Pay Slip File /// </summary> /// <remarks> /// Gets the pay slip for an employee in a pay run. /// </remarks> public byte[] GetPaySlipFile(int businessId, int employeeId, int payRunId) { return ApiByteArrayRequest($"/business/{businessId}/payrun/{payRunId}/file/payslip/{employeeId}"); } /// <summary> /// Finalise Pay Run /// </summary> /// <remarks> /// Finalises the specified pay run. A pay run can only be finalised if there are no calculations in progress. /// </remarks> public PayRunFinaliseResult FinalisePayRun(int businessId, int payRunId, FinalisePayRunOptions options) { return ApiRequest<PayRunFinaliseResult,FinalisePayRunOptions>($"/business/{businessId}/payrun/{payRunId}/finalise", options, Method.POST); } /// <summary> /// List KiwiSaver Adjustments /// </summary> /// <remarks> /// Lists all the KiwiSaver adjustments for a pay run. /// </remarks> public PayRunKiwiSaverAdjustmentResponse ListKiwisaverAdjustments(int businessId, int payRunId) { return ApiRequest<PayRunKiwiSaverAdjustmentResponse>($"/business/{businessId}/payrun/{payRunId}/kiwisaveradjustments"); } /// <summary> /// Create KiwiSaver Adjustments /// </summary> /// <remarks> /// Adds KiwiSaver adjustments to the specified pay run. /// </remarks> public void CreateKiwisaverAdjustments(int businessId, int payRunId, SubmitPayRunKiwiSaverAdjustmentRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/kiwisaveradjustments", request, Method.POST); } /// <summary> /// Delete KiwiSaver Adjustment /// </summary> /// <remarks> /// Deletes the KiwiSaver adjustment with the specified ID from the pay run. /// </remarks> public void DeleteKiwisaverAdjustment(int businessId, int payRunId, DeleteKiwisaverAdjustmentQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/kiwisaveradjustments?id={request.Id}", Method.DELETE); } /// <summary> /// Get KiwiSaver Adjustments by Employee ID /// </summary> /// <remarks> /// Gets all KiwiSaver adjustments for a specific employee in a pay run. /// </remarks> public PayRunKiwiSaverAdjustmentResponse GetKiwisaverAdjustmentsByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<PayRunKiwiSaverAdjustmentResponse>($"/business/{businessId}/payrun/{payRunId}/kiwisaveradjustments/{employeeId}"); } /// <summary> /// Get Leave Accruals /// </summary> /// <remarks> /// Lists all the leave accruals for the pay run. /// </remarks> public LeaveAccrualResponse GetLeaveAccruals(int businessId, int payRunId, GetLeaveAccrualsQueryModel request) { return ApiRequest<LeaveAccrualResponse>($"/business/{businessId}/payrun/{payRunId}/leaveaccrued?includeLeaveTaken={request.IncludeLeaveTaken}"); } /// <summary> /// Save Leave Accruals /// </summary> /// <remarks> /// Saves a set of leave accruals for the pay run. /// </remarks> public void SaveLeaveAccruals(int businessId, int payRunId, SubmitLeaveAccrualsModel model) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/leaveaccrued", model, Method.POST); } /// <summary> /// Delete Leave Accrual /// </summary> /// <remarks> /// Deletes the manually added leave accrual, leave taken or leave adjustment with the specified ID from the pay run. /// </remarks> public void DeleteLeaveAccrual(int businessId, int payRunId, DeleteLeaveAccrualQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/leaveaccrued?id={request.Id}", Method.DELETE); } /// <summary> /// Get Leave Accruals for Employee /// </summary> /// <remarks> /// Gets the leave accruals for the specified employee in the pay run. /// </remarks> public LeaveAccrualResponse GetLeaveAccrualsForEmployee(int businessId, int employeeId, int payRunId, GetLeaveAccrualsForEmployeeQueryModel request) { return ApiRequest<LeaveAccrualResponse>($"/business/{businessId}/payrun/{payRunId}/leaveaccrued/{employeeId}?includeLeaveTaken={request.IncludeLeaveTaken}"); } /// <summary> /// Net to Gross /// </summary> /// <remarks> /// Calculates net to gross for a given pay run. /// </remarks> public NetToGrossModel NetToGross(int businessId, NetToGrossRequest netToGrossRequest, string payRunId) { return ApiRequest<NetToGrossModel,NetToGrossRequest>($"/business/{businessId}/payrun/{payRunId}/nettogross", netToGrossRequest, Method.POST); } /// <summary> /// Set Pay Run Notation /// </summary> /// <remarks> /// Sets the notation for this pay run. The pay run notation is the message that is shown on all pay slips for this pay run. /// </remarks> public void SetPayRunNotation(int businessId, int payRunId, PayRunNotationModel model) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/notation", model, Method.POST); } /// <summary> /// Delete Pay Run Notation /// </summary> /// <remarks> /// Deletes the notation for this pay run. The pay run notation is the message that is shown on all pay slips for this pay run. /// </remarks> public void DeletePayRunNotation(int businessId, int payRunId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/notation", Method.DELETE); } /// <summary> /// Create Note for Employee /// </summary> /// <remarks> /// Creates a note for an employee record in a pay run. /// </remarks> public PayRunTotalNotationModel CreateNoteForEmployee(int businessId, int employeeId, int payRunId, PayRunTotalNotationModel model) { return ApiRequest<PayRunTotalNotationModel,PayRunTotalNotationModel>($"/business/{businessId}/payrun/{payRunId}/notation/{employeeId}", model, Method.POST); } /// <summary> /// Delete Note for Employee /// </summary> /// <remarks> /// Deletes the note for an employee record in a pay run. /// </remarks> public void DeleteNoteForEmployee(int businessId, int employeeId, int payRunId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/notation/{employeeId}", Method.DELETE); } /// <summary> /// List PAYE Adjustments /// </summary> /// <remarks> /// Lists all the PAYE adjustments for a pay run. /// </remarks> public PayRunPayeAdjustmentResponse ListPayeAdjustments(int businessId, int payRunId) { return ApiRequest<PayRunPayeAdjustmentResponse>($"/business/{businessId}/payrun/{payRunId}/payeadjustments"); } /// <summary> /// Create PAYE Adjustments /// </summary> /// <remarks> /// Adds PAYE adjustments to the specified pay run. /// </remarks> public void CreatePayeAdjustments(int businessId, int payRunId, SubmitPayRunPayeAdjustmentRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/payeadjustments", request, Method.POST); } /// <summary> /// Delete PAYE Adjustment /// </summary> /// <remarks> /// Deletes the PAYE adjustment with the specified ID from the pay run. /// </remarks> public void DeletePayeAdjustment(int businessId, int payRunId, DeletePayeAdjustmentQueryModel request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/payeadjustments?id={request.Id}", Method.DELETE); } /// <summary> /// Get PAYE Adjustments by Employee ID /// </summary> /// <remarks> /// Gets all the PAYE adjustments for a specific employee in a pay run. /// </remarks> public PayRunPayeAdjustmentResponse GetPayeAdjustmentsByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<PayRunPayeAdjustmentResponse>($"/business/{businessId}/payrun/{payRunId}/payeadjustments/{employeeId}"); } /// <summary> /// Get pay run payments /// </summary> /// <remarks> /// Gets the payments associated with a pay run. /// </remarks> public List<NzBankPaymentModel> GetPayRunPayments(int businessId, int payRunId) { return ApiRequest<List<NzBankPaymentModel>>($"/business/{businessId}/payrun/{payRunId}/payments"); } /// <summary> /// List Pay Slip Data /// </summary> /// <remarks> /// Lists all the pay slips for the specified pay run. /// </remarks> public Dictionary<String,NzApiPaySlipModel> ListPaySlipData(int businessId, int payRunId, ListPaySlipDataQueryModel request) { return ApiRequest<Dictionary<String,NzApiPaySlipModel>>($"/business/{businessId}/payrun/{payRunId}/payslips?showAllData={request.ShowAllData}"); } /// <summary> /// Get Pay Slip Data by Employee ID /// </summary> /// <remarks> /// Gets the pay slip data for an employee in a payrun. /// </remarks> public NzApiPaySlipModel GetPaySlipDataByEmployeeId(int businessId, int employeeId, int payRunId, GetPaySlipDataByEmployeeIdQueryModel request) { return ApiRequest<NzApiPaySlipModel>($"/business/{businessId}/payrun/{payRunId}/payslips/{employeeId}?showAllData={request.ShowAllData}"); } /// <summary> /// Recalculate /// </summary> /// <remarks> /// Recalculates a pay run. /// </remarks> public void Recalculate(int businessId, int payRunId) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/recalculate", Method.POST); } /// <summary> /// Set UI Unlock enabled /// </summary> /// <remarks> /// Sets whether a pay run can be unlocked by the UI or not. Only applies to finalized pay runs. /// </remarks> public void SetUiUnlockEnabled(int businessId, int payRunId, SetPayRunUIUnlockStateRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/setuiunlockstate", request, Method.POST); } /// <summary> /// Get Pay Run Summary /// </summary> /// <remarks> /// Gets the pay run summary information with the specified ID. /// </remarks> public PayRunSummaryModel GetPayRunSummary(int businessId, int payRunId) { return ApiRequest<PayRunSummaryModel>($"/business/{businessId}/payrun/{payRunId}/summary"); } /// <summary> /// Terminate Employee in Pay Run /// </summary> /// <remarks> /// Terminates an employee in the specified pay run. /// </remarks> public void TerminateEmployeeInPayRun(int businessId, int payRunId, TerminateEmployeeRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/terminate", request, Method.POST); } /// <summary> /// List Pay Run Totals /// </summary> /// <remarks> /// Lists all of the pay run totals in a pay run. /// </remarks> public NzPayRunTotalResponse ListPayRunTotals(int businessId, int payRunId) { return ApiRequest<NzPayRunTotalResponse>($"/business/{businessId}/payrun/{payRunId}/totals"); } /// <summary> /// Get Pay Run Totals by Employee ID /// </summary> /// <remarks> /// Gets the pay run totals for a specific employee in a pay run. /// </remarks> public NzPayRunTotalResponse GetPayRunTotalsByEmployeeId(int businessId, int employeeId, int payRunId) { return ApiRequest<NzPayRunTotalResponse>($"/business/{businessId}/payrun/{payRunId}/totals/{employeeId}"); } /// <summary> /// Unlock Pay Run /// </summary> /// <remarks> /// Unlocks the specified pay run. /// </remarks> public void UnlockPayRun(int businessId, int payRunId, PayRunUnlockRequest request) { ApiRequest($"/business/{businessId}/payrun/{payRunId}/unlock", request, Method.POST); } /// <summary> /// Create Pay Run (Async) /// </summary> /// <remarks> /// Creates a new pay run for this business asynchronously (the request will return before the pay run is created). /// </remarks> public PayRunJobModel CreatePayRunAsync(int businessId, PayRunCreateRequest request) { return ApiRequest<PayRunJobModel,PayRunCreateRequest>($"/business/{businessId}/payrun/async", request, Method.POST); } /// <summary> /// Get Creation Status /// </summary> /// <remarks> /// Gets the creation status of a pay run that was created asynchronously. /// </remarks> public PayRunJobStatusModel GetCreationStatus(int businessId, Guid jobId) { return ApiRequest<PayRunJobStatusModel>($"/business/{businessId}/payrun/creationstatus/{jobId}"); } /// <summary> /// List Pay Runs Summaries /// </summary> /// <remarks> /// Get a list of pay run summaries associated with the business. /// This operation supports OData queries (only $filter, $orderby, $top, $skip). /// </remarks> public List<PayRunSummaryModel> ListPayRunsSummaries(int businessId, ODataQuery oDataQuery = null) { return ApiRequest<List<PayRunSummaryModel>>($"/business/{businessId}/payrun/summary{ODataQuery.ToQueryString(oDataQuery, "?")}"); } } }
40.820711
170
0.589111
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Nz/Functions/PayRunFunction.cs
26,411
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NecrotomyManager : MonoBehaviour { public enum GameState { TIMEUP, } private GameState state; private Timer timer; // Use this for initialization void Start () { PlayerPrefs.SetInt("Necro", 0); state = GameState.TIMEUP; timer = GameObject.Find("Timer").GetComponent<Timer>(); } public void Necrotomy() { PlayerPrefs.SetInt("Necro", 1); } // Update is called once per frame void Update () { if(PlayerPrefs.GetInt("Necro") == 1) { } } }
18.055556
63
0.6
[ "MIT" ]
milkteabread/Assets
Script/prof/NecrotomyManager.cs
652
C#
using System; namespace AdventOfCode { class Program { static void Main(string[] args) { while (true){ int years = 1; int selectedYear = 0; while (true) { Console.WriteLine("Type in a number corrosponding to a year:"); Console.WriteLine("[1]: 2018"); var val = Console.ReadLine(); try { selectedYear = Convert.ToInt32(val); } catch (Exception){} if (selectedYear < 1 || selectedYear > years) { Console.WriteLine("No valid number entered, try again"); Console.ReadKey(); } else break; Console.Clear(); } int days = 5; int selectedDay = 0; while (true) { Console.WriteLine("Type in a number corrosponding to a day:"); Console.WriteLine($"[1-{days}]"); var val = Console.ReadLine(); try { selectedDay = Convert.ToInt32(val); } catch (Exception) { } if (selectedDay < 1 || selectedDay > days) Console.WriteLine("No valid number entered, try again"); else break; } switch (selectedYear) { case 1: Y2018(selectedDay); break; } Console.WriteLine("Press any key to restart"); Console.ReadKey(); Console.Clear(); } void Y2018(int day) { DateTime start = DateTime.Now; switch (day) { case 1: AOC2018D1.Solve2(); break; case 2: AOC2018D2.Solve2(); break; case 3: AOC2018D3.Solve2(); break; case 4: AOC2018D4.Solve(); break; case 5: AOC2018D5.Solve2(); break; } TimeSpan total = DateTime.Now - start; Console.WriteLine($"Solution took: {total.TotalMilliseconds} ms"); } } } }
31.488636
83
0.348971
[ "MIT" ]
CreatorOfFame/AOC
AdventOfCode/AdventOfCode/Program.cs
2,773
C#
namespace PdfCraft.Contents.Text { internal class BreakPoint { private readonly bool _hasToBreak; private readonly int _lengthInPoints; private readonly string _text; public BreakPoint(bool hasToBreak, int lengthInPoints, string text) { _hasToBreak = hasToBreak; _lengthInPoints = lengthInPoints; _text = text; } public bool HasToBreak { get { return _hasToBreak; } } public string Text { get { return _text; } } public int LengthInPoints { get { return _lengthInPoints; } } } }
22.129032
75
0.54519
[ "Unlicense" ]
W0dan/PdfCraft
PdfCraft/Contents/Text/BreakPoint.cs
686
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class DateTimeFormatInfoFirstDayOfWeek { // PosTest1: Call FirstDayOfWeek getter method should return correct value for InvariantInfo [Fact] public void TestGetter() { VerificationHelper(DateTimeFormatInfo.InvariantInfo, DayOfWeek.Sunday, false); } // PosTest2: Call FirstDayOfWeek setter method should return correct value [Fact] public void TestSetter() { DayOfWeek[] days = new DayOfWeek[] { DayOfWeek.Friday, DayOfWeek.Monday, DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Thursday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, }; for (int i = 0; i < days.Length; ++i) { VerificationHelper(new DateTimeFormatInfo(), days[i], true); } } // NegTest1: ArgumentOutOfRangeException should be thrown when The property is being set to a // value that is not a valid FirstDayOfWeek value [Fact] public void NegTest1() { Assert.Throws<ArgumentOutOfRangeException>(() => { new DateTimeFormatInfo().FirstDayOfWeek = (DayOfWeek)(-1); }); } // NegTest2: InvalidOperationException should be thrown when The property is being set and // the DateTimeFormatInfo is read-only [Fact] public void NegTest2() { Assert.Throws<InvalidOperationException>(() => { DateTimeFormatInfo.InvariantInfo.FirstDayOfWeek = DayOfWeek.Wednesday; }); } private void VerificationHelper(DateTimeFormatInfo info, DayOfWeek expected, bool setter) { if (setter) { info.FirstDayOfWeek = expected; } DayOfWeek actual = info.FirstDayOfWeek; Assert.Equal(expected, actual); } } }
30.766234
102
0.557619
[ "MIT" ]
bpschoch/corefx
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoFirstDayOfWeek.cs
2,369
C#
using ShareFile.Api.Client.Extensions; using ShareFile.Api.Client.Extensions.Tasks; using System; using System.IO; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using ShareFile.Api.Client.Enums; using ShareFile.Api.Client.Exceptions; namespace ShareFile.Api.Client.Transfers.Uploaders { public class ScalingFileUploader : SyncUploaderBase { private readonly ScalingPartUploader partUploader; private ActiveUploadState activeUploadState; public ScalingFileUploader( ShareFileClient client, UploadSpecificationRequest uploadSpecificationRequest, Stream stream, FileUploaderConfig config = null, int? expirationDays = null) : base(client, uploadSpecificationRequest, stream, config, expirationDays) { var partConfig = config != null ? config.PartConfig : new FilePartConfig(); partUploader = new ScalingPartUploader( partConfig, Config.NumberOfThreads, (requestMessage, cancelToken) => Task.Factory.StartNew(() => ExecuteChunkUploadMessage(requestMessage, cancelToken)), progressReporter.ReportProgress, client.Logging); } public ScalingFileUploader( ShareFileClient client, ActiveUploadState activeUploadState, UploadSpecificationRequest uploadSpecificationRequest, Stream stream, FileUploaderConfig config = null) : this(client, uploadSpecificationRequest, stream, config) { this.activeUploadState = activeUploadState; UploadSpecification = activeUploadState.UploadSpecification; } internal ScalingPartUploader PartUploader { get { return partUploader; } } public override long LastConsecutiveByteUploaded { get { return partUploader.LastConsecutiveByteUploaded; } } private bool canRestart = true; protected override UploadResponse InternalUpload(CancellationToken cancellationToken) { try { var offset = activeUploadState == null ? 0 : activeUploadState.BytesUploaded; SetUploadSpecification(); partUploader.NumberOfThreads = Math.Min( partUploader.NumberOfThreads, UploadSpecification.MaxNumberOfThreads.GetValueOrDefault(1)); partUploader.UploadSpecification = UploadSpecification; var uploads = partUploader.Upload( FileStream, UploadSpecificationRequest.FileName, HashProvider, UploadSpecification.ChunkUri.AbsoluteUri, UploadSpecificationRequest.Raw, offset, cancellationToken); uploads.Wait(); return FinishUpload(); } catch (Exception ex) { var agg = ex as AggregateException; if (agg != null) { ex = agg.Unwrap(); } //if (canRestart && ((ex as UploadException)?.IsInvalidUploadId).GetValueOrDefault()) if (canRestart && ((ex is UploadException) && ((UploadException)ex).IsInvalidUploadId)) { activeUploadState = null; UploadSpecification = null; Prepared = false; canRestart = false; return Upload(); } throw; } } private void ExecuteChunkUploadMessage(HttpRequestMessage requestMessage, CancellationToken cancellationToken) { TryPause(); requestMessage.AddDefaultHeaders(Client); var client = GetHttpClient(); using (var responseMessage = RequestExecutor.Send(client, requestMessage, HttpCompletionOption.ResponseContentRead)) { if (Configuration.IsNetCore) { progressReporter.ReportProgress(requestMessage.Content.Headers.ContentLength.GetValueOrDefault()); } string responseContent = responseMessage.Content.ReadAsStringAsync().WaitForTask(); ValidateChunkResponse(responseMessage, responseContent); } } private UploadResponse FinishUpload() { var finishUri = GetFinishUriForThreadedUploads(); var client = GetHttpClient(); var requestMessage = new HttpRequestMessage(HttpMethod.Get, finishUri); requestMessage.Headers.Add("Accept", "application/json"); requestMessage.AddDefaultHeaders(Client); var response = RequestExecutor.Send(client, requestMessage, HttpCompletionOption.ResponseContentRead); return GetUploadResponse(response, HashProvider.GetComputedHashAsString()); } public override void Prepare() { throw new NotImplementedException(); } } }
36.732877
133
0.590528
[ "MIT" ]
Dan-Avel/ShareFile-NET
src/ShareFile.Api.Client/Transfers/Uploaders/ScalingFileUploader.cs
5,365
C#
namespace BotsDotNet.Palringo.SubProfile.Parsing { public interface IParsable { void Process(DataMap data); } }
16.625
49
0.676692
[ "MIT" ]
JTOne123/botsdotnet
BotsDotNet.Palringo/SubProfile/Parsing/IParsable.cs
135
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Framework.Core.Helpers { public static class AsyncHelpers { /// <summary> /// Execute's an async Task<T> method which has a void return value synchronously /// </summary> /// <param name="task">Task<T> method to execute</param> public static void RunSync(Func<Task> task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); } /// <summary> /// Execute's an async Task<T> method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task<T> method to execute</param> /// <returns></returns> public static T RunSync<T>(Func<Task<T>> task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return ret; } private class ExclusiveSynchronizationContext : SynchronizationContext { private bool done; public Exception InnerException { get; set; } readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false); readonly Queue<Tuple<SendOrPostCallback, object>> items = new Queue<Tuple<SendOrPostCallback, object>>(); public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException("We cannot send to our same thread"); } public override void Post(SendOrPostCallback d, object state) { lock (items) { items.Enqueue(Tuple.Create(d, state)); } workItemsWaiting.Set(); } public void EndMessageLoop() { Post(_ => done = true, null); } public void BeginMessageLoop() { while (!done) { Tuple<SendOrPostCallback, object> task = null; lock (items) { if (items.Count > 0) { task = items.Dequeue(); } } if (task != null) { task.Item1(task.Item2); if (InnerException != null) // the method threw an exeption { throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException); } } else { workItemsWaiting.WaitOne(); } } } public override SynchronizationContext CreateCopy() { return this; } } } }
32.37037
120
0.45881
[ "Apache-2.0" ]
lneninger/quickbookdesktop-integrator
src/Framework/Framework.Core/Helpers/AsyncHelpers.cs
4,372
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Windows; namespace AVGUI.Windows.Messages { /// <summary> /// Логика взаимодействия для MessagesWindow.xaml /// </summary> public partial class MessagesWindow : Window { PipeClient Pipe; LogManager LogManager; // Отвечает за логи public MessagesWindow(PipeClient _pipe) { InitializeComponent(); Pipe = _pipe; ContentRendered += Main; } // Парсит json и пишет out сообщения private void parseJSonMessage(string _jSonMessage) { if(_jSonMessage == "") { return; } JObject jSonMessage = JObject.Parse(_jSonMessage); foreach (var item in jSonMessage) { if (item.Key == "alert") { foreach (var item2 in item.Value) { LogManager.OutAlert(item2.ToString()); } } else if(item.Key == "log") { foreach (var item2 in item.Value) { LogManager.OutLog(item2.ToString()); } //LogManager.OutLog(item.Value.ToString()); } else if (item.Key == "debug") { foreach (var item2 in item.Value) { LogManager.OutDebug(item2.ToString()); } //LogManager.OutDebug(item.Value.ToString()); } else if (item.Key == "warning") { foreach (var item2 in item.Value) { LogManager.OutWarning(item2.ToString()); } //LogManager.OutWarning(item.Value.ToString()); } } } public void Main(Object sender, EventArgs e) { ContentRendered -= Main; LogManager = new LogManager(OutputHeader, RichTextBox1, AlertsHeader, RichTextBox2, WarningsHeader, RichTextBox3, DebugHeader, RichTextBox4); string reply = ""; string request = "ready"; Pipe.SendMessage(request); Pipe.ListenMessage(); reply = Pipe.GetMessage(500, 2); parseJSonMessage(reply); } } }
29.134831
153
0.463556
[ "MIT" ]
AVDevTeam/AVCore
AVGUI/Windows/Messages/MessagesWindow.xaml.cs
2,653
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace ListBox.MultiSelectItems { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.777778
42
0.713018
[ "MIT" ]
ChrisDiky/MaterialDesignInXaml.Examples
ListBox/ListBox.MultiSelectItems/App.xaml.cs
340
C#
using JTNE.Protocol.Attributes; using JTNE.Protocol.Formatters; using System; using System.IO; namespace JTNE.Protocol { /// <summary> /// 新能源包 /// 只做简单的头部解析不做复杂的业务逻辑 /// 例如:不同的厂商可能加密方式不同,所以消息数据体不做加解密的判断。 /// </summary> [JTNEFormatter(typeof(JTNEHeaderPackage_PlatformFormatter))] public class JTNEHeaderPackage_Platform { /// <summary> /// 起始符1 /// </summary> public byte BeginFlag1 { get; set; } = JTNEPackage_Device.BeginFlag; /// <summary> /// 起始符2 /// </summary> public byte BeginFlag2 { get; set; } = JTNEPackage_Device.BeginFlag; /// <summary> /// 命令标识 /// <see cref="JTNE.Protocol.Enums.JTNEMsgId_Platform"/> /// </summary> public byte MsgId { get; set; } /// <summary> /// 应答标志 /// <see cref="JTNE.Protocol.Enums.JTNEAskId"/> /// </summary> public byte AskId { get; set; } /// <summary> /// 车辆识别码 /// </summary> public string VIN { get; set; } /// <summary> /// 数据加密方式 (默认不加密) /// 0x01:数据不加密;0x02:数据经过 RSA 算法加密;0x03:数据经过 AES128 位算法加密;“0xFE”表示异常,“0xFF”表示无效 /// <see cref="JTNE.Protocol.Enums.JTNEEncryptMethod"/> /// </summary> public byte EncryptMethod { get; set; } = 0x01; /// <summary> /// 数据单元长度是数据单元的总字节数,有效值范围:0-65531 /// </summary> public ushort DataUnitLength { get; set; } /// <summary> /// 数据体 /// </summary> public byte[] Bodies { get; set; } /// <summary> /// 采用BCC(异或检验)法,校验范围从命令单元的第一个字节开始,同后一个字节异或,直到校验码前一个字节为止, /// 校验码占用一个字节,当数据单元存在加密时,应先加密后检验,先校验后解密 /// </summary> public byte BCCCode { get; set; } } }
30.457627
86
0.543684
[ "MIT" ]
SmallChi/GBNewEnergy
src/JTNE.Protocol/JTNEHeaderPackage_Platform.cs
2,269
C#
// © 2019 Koninklijke Philips N.V. See License.md in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using Philips.CodeAnalysis.Common; using Philips.CodeAnalysis.MaintainabilityAnalyzers.Maintainability; namespace Philips.CodeAnalysis.Test.Maintainability.Maintainability { /// <summary> /// Class for testing AvoidStaticMethodAnalyzer /// </summary> [TestClass] public class AvoidStaticMethodAnalyzerTest : DiagnosticVerifier { #region Non-Public Data Members #endregion #region Non-Public Properties/Methods protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new AvoidStaticMethodAnalyzer(); } protected string CreateFunction(string methodStaticModifier, string classStaticModifier = "", string externKeyword = "", string methodName = "GoodTimes", string returnType = "void", string localMethodModifier = "", string foreignMethodModifier = "", bool factoryMethod = false) { string localMethod = $@"public {localMethodModifier} string BaBaBummmm(string services) {{ return services; }}"; string foreignMethod = $@"public {foreignMethodModifier} string BaBaBa(string services) {{ return services; }}"; string useLocalMethod = (localMethodModifier == "static") ? $@"BaBaBummmm(""testing"")" : string.Empty; string useForeignMethod = (foreignMethodModifier == "static") ? $@"BaBaBa(""testing"")" : string.Empty; string objectDeclaration = factoryMethod ? $@"Caroline caroline = new Caroline();" : string.Empty; return $@" namespace Sweet {{ {classStaticModifier} class Caroline {{ {localMethod} public {methodStaticModifier} {externKeyword} {returnType} {methodName}() {{ {objectDeclaration} {useLocalMethod} {useForeignMethod} return; }} }} {foreignMethodModifier} class ReachingOut {{ {foreignMethod} }} }}"; } #endregion #region Public Interface [TestMethod] public void AllowExternalCode() { string template = CreateFunction("static", externKeyword: "extern"); VerifyCSharpDiagnostic(template); } [TestMethod] public void IgnoreIfInStaticClass() { string template = CreateFunction("static", classStaticModifier: "static"); VerifyCSharpDiagnostic(template); } [TestMethod] public void OnlyCatchStaticMethods() { string template = CreateFunction(""); VerifyCSharpDiagnostic(template); } [TestMethod] public void AllowStaticMainMethod() { string template = CreateFunction("static", methodName: "Main"); VerifyCSharpDiagnostic(template); } [TestMethod] public void IgnoreIfCallsLocalStaticMethod() { string template = CreateFunction("static", localMethodModifier: "static"); // should still catch the local static method being used VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.AvoidStaticMethods)); } [TestMethod] public void CatchIfUsesForeignStaticMethod() { string template = CreateFunction("static", foreignMethodModifier: "static"); VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.AvoidStaticMethods)); } [TestMethod] public void AllowStaticFactoryMethod() { string template = CreateFunction("static", factoryMethod: true); VerifyCSharpDiagnostic(template); } [TestMethod] public void AllowStaticDynamicDataMethod() { string template = CreateFunction("static", returnType: "IEnumerable<object[]>"); VerifyCSharpDiagnostic(template); } [TestMethod] public void CatchPlainStaticMethod() { string template = CreateFunction("static"); VerifyCSharpDiagnostic(template, DiagnosticResultHelper.Create(DiagnosticIds.AvoidStaticMethods)); } #endregion } }
29.444444
280
0.706918
[ "MIT" ]
philips-software/roslyn-analyzers
Philips.CodeAnalysis.Test/Maintainability/Maintainability/AvoidStaticMethodAnalyzerTest.cs
3,978
C#
namespace Logary.CSharpExample { using System; using System.Threading; using System.Threading.Tasks; using Configuration; using CSharp; using Targets; using Adapters.Facade; public static class Program { public static Task<LogManager> StartLiterate() { return LogaryFactory.New("Logary.CSharpExample","laptop", with => with.InternalLogger(ILogger.NewConsole(LogLevel.Debug)) .Target<LiterateConsole.Builder>("console1")); } public static async Task SampleUsage(Logger logger) { // without async logger.LogSimple(MessageModule.Event(LogLevel.Info, "User logged in")); // await placing the Hello World event in the buffer await logger.LogEvent(LogLevel.Debug, "Hello world. Important? {important}", new { important = "yes" }); // await logging the fatal event and getting an ack back from each of the configured // targets await logger.LogEvent(LogLevel.Fatal, "Fatal application error on finaliser thread.", waitForAck: true); await logger.LogEvent(LogLevel.Verbose, "We need to log this with backpressure.", new { tags = new[] { "tag1", "tag2" } }); // alternatively, you can use the ack-explicit functions together with the // data object model that's MessageModule. var message = MessageModule.Event(LogLevel.Warn, "Here be dragons!"); await logger.LogWithAck(message); var val = logger.Time(() => { for (int i = 0; i < 100; i++) Thread.Sleep(1); return 32; }, "sample.config.computeAnswerToEverything") (); await logger.LogEventFormat(LogLevel.Warn, "{horses} is the answer to the universe and everything", val); await logger.Time( () => logger.LogEvent(LogLevel.Debug, "I wonder how long this takes")) (); try { throw new ApplicationException("thing went haywire"); } catch (Exception e) { await logger.LogEventFormat(LogLevel.Fatal, "Unhandled {exception}!", e); } } public static void SampleCibryyUsage(Cibryy.Logging.ILogger logger) { Cibryy.Core.Work(logger); Cibryy.Core.WorkBackpressure(logger); Cibryy.Core.ErrorWithBP(logger); Cibryy.Core.SimpleWork(logger); Cibryy.Core.GenerateAndLogExn(logger); Cibryy.Core.StaticWork(); } public static int Main(string[] args) { // normal console app boilerplate; var mre = new ManualResetEventSlim(false); System.Console.CancelKeyPress += (sender, arg) => mre.Set(); var logary = StartLiterate().Result; // Usage with a library: LogaryFacadeAdapter.Initialise<Cibryy.Logging.ILogger>(logary); var logger = logary.GetLogger("main"); SampleCibryyUsage(LoggerCSharpAdapter.Create<Cibryy.Logging.ILogger>(logger)); // Usage in this program: SampleUsage(logger).Wait(); // Wait for CTRL+C mre.Wait(); return 0; } } }
34.673077
116
0.540488
[ "ECL-2.0", "Apache-2.0" ]
causiq/logary
examples/Logary.CSharpExample/Program.cs
3,608
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GetIssueDetails")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GetIssueDetails")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98e3a8e4-94b1-4bf0-b62c-ed7685cb3838")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.783784
84
0.748927
[ "MIT" ]
StingyJack/DevCommIssueScraper
GetIssueDetails/Properties/AssemblyInfo.cs
1,401
C#
using System; using System.Web.Http; using System.Web.Mvc; using SRMAPI.Areas.HelpPage.ModelDescriptions; using SRMAPI.Areas.HelpPage.Models; namespace SRMAPI.Areas.HelpPage.Controllers { /// <summary> /// The controller that will handle requests for the help page. /// </summary> public class HelpController : Controller { private const string ErrorViewName = "Error"; public HelpController() : this(GlobalConfiguration.Configuration) { } public HelpController(HttpConfiguration config) { Configuration = config; } public HttpConfiguration Configuration { get; private set; } public ActionResult Index() { ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); return View(Configuration.Services.GetApiExplorer().ApiDescriptions); } public ActionResult Api(string apiId) { if (!String.IsNullOrEmpty(apiId)) { HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); if (apiModel != null) { return View(apiModel); } } return View(ErrorViewName); } public ActionResult ResourceModel(string modelName) { if (!String.IsNullOrEmpty(modelName)) { ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); ModelDescription modelDescription; if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) { return View(modelDescription); } } return View(ErrorViewName); } } }
30.777778
116
0.575554
[ "MIT" ]
DrSophistry/SophisRetailManager
SRMAPI/Areas/HelpPage/Controllers/HelpController.cs
1,939
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebApp { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
25.681818
70
0.704425
[ "MIT" ]
1804-Apr-USFdotnet/ram-adhikari-project1
ProjectOne/WebApp/Global.asax.cs
567
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. namespace Microsoft.Telepathy.ServiceBroker.Common { using System; /// <summary> /// Define broker's states /// </summary> [Serializable] public enum BrokerState { /// <summary> /// The broker is not started /// </summary> NotStarted = 0, /// <summary> /// The broker is started /// </summary> Started, /// <summary> /// The broker is running /// </summary> Running, /// <summary> /// The broker is idle /// </summary> Idle, /// <summary> /// The broker is finishing /// </summary> Finishing, /// <summary> /// The broker is finished /// </summary> Finished, /// <summary> /// The broker is suspend /// </summary> Suspend, } }
19.34
50
0.474664
[ "MIT" ]
dubrie/Telepathy
src/soa/CcpWSLB/Common/BrokerState.cs
969
C#
// ----------------------------------------------------------------------------- // 让 .NET 开发更简单,更通用,更流行。 // Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd. // // 框架名称:Furion // 框架作者:百小僧 // 框架版本:2.8.3 // 源码地址:Gitee: https://gitee.com/dotnetchina/Furion // Github:https://github.com/monksoul/Furion // 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE) // ----------------------------------------------------------------------------- using System.ComponentModel; namespace Furion.DependencyInjection { /// <summary> /// 注册范围 /// </summary> [SkipScan] public enum InjectionPatterns { /// <summary> /// 只注册自己 /// </summary> [Description("只注册自己")] Self, /// <summary> /// 第一个接口 /// </summary> [Description("只注册第一个接口")] FirstInterface, /// <summary> /// 自己和第一个接口,默认值 /// </summary> [Description("自己和第一个接口")] SelfWithFirstInterface, /// <summary> /// 所有接口 /// </summary> [Description("所有接口")] ImplementedInterfaces, /// <summary> /// 注册自己包括所有接口 /// </summary> [Description("自己包括所有接口")] All } }
23.735849
81
0.459459
[ "Apache-2.0" ]
dannylincn/Furion
framework/Furion/DependencyInjection/Enums/InjectionPatterns.cs
1,507
C#
using System; using CoreGraphics; using CoreGraphics; using SpriteKit; using UIKit; namespace ButtonTapper3000 { public class BasicScene : SKScene { protected UIColor SelectedColor { get; private set; } protected UIColor UnselectedColor { get; private set; } protected UIColor ButtonColor { get; private set; } protected UIColor InfoColor { get; private set; } protected float FrameMidX { get; private set; } protected float FrameMidY { get; private set; } SKTransition transition; public BasicScene (CGSize size) : base (size) { ScaleMode = SKSceneScaleMode.AspectFill; BackgroundColor = UIColor.FromRGBA (0.15f, 0.15f, 0.3f, 1f); UnselectedColor = UIColor.FromRGBA (0f, 0.5f, 0.5f, 1f); SelectedColor = UIColor.FromRGBA (0.5f, 1f, 0.99f, 1f); ButtonColor = UIColor.FromRGBA (1f, 1f, 0f, 1f); InfoColor = UIColor.FromRGBA (1f, 1f, 1f, 1f); FrameMidX = (float)Frame.GetMidX (); FrameMidY = (float)Frame.GetMidY (); transition = SKTransition.MoveInWithDirection (SKTransitionDirection.Up, 0.5); } public void PresentScene (BasicScene scene) { View.PresentScene (scene, transition); } } }
25.711111
81
0.711322
[ "Apache-2.0" ]
dannycabrera/monotouch-samples
ButtonTapper3000/ButtonTapper3000/Scenes/BasicScene.cs
1,157
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Twitter; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Options for the Twitter authentication middleware. /// </summary> public class TwitterOptions : RemoteAuthenticationOptions { /// <summary> /// Initializes a new instance of the <see cref="TwitterOptions"/> class. /// </summary> public TwitterOptions() { AuthenticationScheme = TwitterDefaults.AuthenticationScheme; DisplayName = AuthenticationScheme; CallbackPath = new PathString("/signin-twitter"); BackchannelTimeout = TimeSpan.FromSeconds(60); Events = new TwitterEvents(); } /// <summary> /// Gets or sets the consumer key used to communicate with Twitter. /// </summary> /// <value>The consumer key used to communicate with Twitter.</value> public string ConsumerKey { get; set; } /// <summary> /// Gets or sets the consumer secret used to sign requests to Twitter. /// </summary> /// <value>The consumer secret used to sign requests to Twitter.</value> public string ConsumerSecret { get; set; } /// <summary> /// Enables the retrieval user details during the authentication process, including /// e-mail addresses. Retrieving e-mail addresses requires special permissions /// from Twitter Support on a per application basis. The default is false. /// See https://dev.twitter.com/rest/reference/get/account/verify_credentials /// </summary> public bool RetrieveUserDetails { get; set; } /// <summary> /// Gets or sets the type used to secure data handled by the middleware. /// </summary> public ISecureDataFormat<RequestToken> StateDataFormat { get; set; } /// <summary> /// Gets or sets the <see cref="ITwitterEvents"/> used to handle authentication events. /// </summary> public new ITwitterEvents Events { get { return (ITwitterEvents)base.Events; } set { base.Events = value; } } } }
38.777778
111
0.636512
[ "Apache-2.0" ]
ghstahl/P7
src/TwitterAuth/TwitterOptions.cs
2,443
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace src { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
23.769231
62
0.631068
[ "MIT" ]
fafg/teamcity-cake-ci-cd-docker-swarm
src/myapi/Program.cs
620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVCFrog { class FrogController { Frog frog = new Frog(); public void growFrog() { frog.grow(); } public void shrinkFrog() { frog.shrink(); } public int getFrogSize() { return frog.getSize(); } } }
15.741935
35
0.487705
[ "MIT" ]
Trev61/MVCFrog
MVCFrog/MVCFrog/FrogController.cs
490
C#
using OsmSharp; using System; namespace OsmDataKit { public class RelationMemberObject { public GeoObject Geo { get; } public string? Role { get; } public OsmGeoType Type => Geo.Type; public long Id => Geo.Id; public string Url => Geo.Url; public RelationMemberObject(GeoObject geo, string? role) { Geo = geo ?? throw new ArgumentNullException(nameof(geo)); Role = role; } public static Func<RelationMemberObject, string> StringFormatter = member => member.Role + " - " + member.Geo.ToString(); public override string ToString() => StringFormatter(this); } }
23.2
74
0.597701
[ "MIT" ]
chubrik/OsmDataKit
OsmDataKit/Models/RelationMemberObject.cs
698
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if ES_BUILD_STANDALONE using System; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Tags are flags that are not interpreted by EventSource but are passed along /// to the EventListener. The EventListener determines the semantics of the flags. /// </summary> [Flags] public enum EventTags { /// <summary> /// No special traits are added to the event. /// </summary> None = 0, /* Bits below 0x10000 are available for any use by the provider. */ /* Bits at or above 0x10000 are reserved for definition by Microsoft. */ } }
28.758621
86
0.677458
[ "MIT" ]
belav/runtime
src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTraits.cs
834
C#
using System; using System.Collections.Generic; using System.Text; namespace Plugin.XamarinExtentions { /// <summary> /// Interface for $safeprojectgroupname$ /// </summary> public class XamarinExtentionsImplementation : IXamarinExtentions { } }
19.428571
69
0.709559
[ "MIT" ]
chachamaru0802/Plugin.XamarinExtentions
src/XamarinExtentions/XamarinExtentions/XamarinExtentionsImplementation.android.cs
274
C#
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2014 SmartsheetClient // %% // 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. // %[license] namespace Smartsheet.Api.OAuth { /// <summary> /// <para>This is the exception thrown by <seealso cref="OAuthFlow"/> To indicate "access_denied" error when obtaining an authorization Code.</para> /// /// <para>Thread safety: Exceptions are not thread safe.</para> /// </summary> public class AccessDeniedException : OAuthAuthorizationCodeException { /// <summary> /// Constructor. /// </summary> /// <param name="message"> the Message </param> public AccessDeniedException(string message) : base(message) { } } }
32.634146
152
0.638266
[ "Apache-2.0" ]
JTP3XP/smartsheet-csharp-sdk
main/Smartsheet/Api/OAuth/AccessDeniedException.cs
1,340
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.Mvc; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Services.Catalog; using Nop.Services.Localization; using Nop.Web.Framework.Mvc; using Nop.Web.Framework.UI.Paging; namespace Nop.Web.Models.Catalog { public partial class CatalogPagingFilteringModel : BasePageableModel { #region Constructors public CatalogPagingFilteringModel() { this.AvailableSortOptions = new List<SelectListItem>(); this.AvailableViewModes = new List<SelectListItem>(); this.PageSizeOptions = new List<SelectListItem>(); this.PriceRangeFilter = new PriceRangeFilterModel(); this.SpecificationFilter = new SpecificationFilterModel(); } #endregion #region Properties /// <summary> /// Price range filter model /// </summary> public PriceRangeFilterModel PriceRangeFilter { get; set; } /// <summary> /// Specification filter model /// </summary> public SpecificationFilterModel SpecificationFilter { get; set; } public bool AllowProductSorting { get; set; } public IList<SelectListItem> AvailableSortOptions { get; set; } public bool AllowProductViewModeChanging { get; set; } public IList<SelectListItem> AvailableViewModes { get; set; } public bool AllowCustomersToSelectPageSize { get; set; } public IList<SelectListItem> PageSizeOptions { get; set; } /// <summary> /// Order by /// </summary> public int OrderBy { get; set; } /// <summary> /// Product sorting /// </summary> public string ViewMode { get; set; } #endregion #region Nested classes public partial class PriceRangeFilterModel : BaseNopModel { #region Const private const string QUERYSTRINGPARAM = "price"; #endregion #region Ctor public PriceRangeFilterModel() { this.Items = new List<PriceRangeFilterItem>(); } #endregion #region Utilities /// <summary> /// Gets parsed price ranges /// </summary> protected virtual IList<PriceRange> GetPriceRangeList(string priceRangesStr) { var priceRanges = new List<PriceRange>(); if (string.IsNullOrWhiteSpace(priceRangesStr)) return priceRanges; string[] rangeArray = priceRangesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str1 in rangeArray) { string[] fromTo = str1.Trim().Split(new [] { '-' }); decimal? from = null; if (!String.IsNullOrEmpty(fromTo[0]) && !String.IsNullOrEmpty(fromTo[0].Trim())) from = decimal.Parse(fromTo[0].Trim(), new CultureInfo("en-US")); decimal? to = null; if (!String.IsNullOrEmpty(fromTo[1]) && !String.IsNullOrEmpty(fromTo[1].Trim())) to = decimal.Parse(fromTo[1].Trim(), new CultureInfo("en-US")); priceRanges.Add(new PriceRange { From = from, To = to }); } return priceRanges; } protected virtual string ExcludeQueryStringParams(string url, IWebHelper webHelper) { var excludedQueryStringParams = "pagenumber"; //remove page filtering if (!String.IsNullOrEmpty(excludedQueryStringParams)) { string[] excludedQueryStringParamsSplitted = excludedQueryStringParams.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string exclude in excludedQueryStringParamsSplitted) url = webHelper.RemoveQueryString(url, exclude); } return url; } #endregion #region Methods public virtual PriceRange GetSelectedPriceRange(IWebHelper webHelper, string priceRangesStr) { var range = webHelper.QueryString<string>(QUERYSTRINGPARAM); if (String.IsNullOrEmpty(range)) return null; string[] fromTo = range.Trim().Split(new [] { '-' }); if (fromTo.Length == 2) { decimal? from = null; if (!String.IsNullOrEmpty(fromTo[0]) && !String.IsNullOrEmpty(fromTo[0].Trim())) from = decimal.Parse(fromTo[0].Trim(), new CultureInfo("en-US")); decimal? to = null; if (!String.IsNullOrEmpty(fromTo[1]) && !String.IsNullOrEmpty(fromTo[1].Trim())) to = decimal.Parse(fromTo[1].Trim(), new CultureInfo("en-US")); var priceRangeList = GetPriceRangeList(priceRangesStr); foreach (var pr in priceRangeList) { if (pr.From == from && pr.To == to) return pr; } } return null; } public virtual void LoadPriceRangeFilters(string priceRangeStr, IWebHelper webHelper, IPriceFormatter priceFormatter) { var priceRangeList = GetPriceRangeList(priceRangeStr); if (priceRangeList.Count > 0) { this.Enabled = true; var selectedPriceRange = GetSelectedPriceRange(webHelper, priceRangeStr); this.Items = priceRangeList.ToList().Select(x => { //from&to var item = new PriceRangeFilterItem(); if (x.From.HasValue) item.From = priceFormatter.FormatPrice(x.From.Value, true, false); if (x.To.HasValue) item.To = priceFormatter.FormatPrice(x.To.Value, true, false); string fromQuery = string.Empty; if (x.From.HasValue) fromQuery = x.From.Value.ToString(new CultureInfo("en-US")); string toQuery = string.Empty; if (x.To.HasValue) toQuery = x.To.Value.ToString(new CultureInfo("en-US")); //is selected? if (selectedPriceRange != null && selectedPriceRange.From == x.From && selectedPriceRange.To == x.To) item.Selected = true; //filter URL string url = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + fromQuery + "-" + toQuery, null); url = ExcludeQueryStringParams(url, webHelper); item.FilterUrl = url; return item; }).ToList(); if (selectedPriceRange != null) { //remove filter URL string url = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM); url = ExcludeQueryStringParams(url, webHelper); this.RemoveFilterUrl = url; } } else { this.Enabled = false; } } #endregion #region Properties public bool Enabled { get; set; } public IList<PriceRangeFilterItem> Items { get; set; } public string RemoveFilterUrl { get; set; } #endregion } public partial class PriceRangeFilterItem : BaseNopModel { public string From { get; set; } public string To { get; set; } public string FilterUrl { get; set; } public bool Selected { get; set; } } public partial class SpecificationFilterModel : BaseNopModel { #region Const private const string QUERYSTRINGPARAM = "specs"; #endregion #region Ctor public SpecificationFilterModel() { this.AlreadyFilteredItems = new List<SpecificationFilterItem>(); this.NotFilteredItems = new List<SpecificationFilterItem>(); } #endregion #region Utilities protected virtual string ExcludeQueryStringParams(string url, IWebHelper webHelper) { var excludedQueryStringParams = "pagenumber"; //remove page filtering if (!String.IsNullOrEmpty(excludedQueryStringParams)) { string[] excludedQueryStringParamsSplitted = excludedQueryStringParams.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string exclude in excludedQueryStringParamsSplitted) { url = webHelper.RemoveQueryString(url, exclude); } } return url; } protected virtual string GenerateFilteredSpecQueryParam(IList<int> optionIds) { string result = ""; if (optionIds == null || optionIds.Count == 0) return result; for (int i = 0; i < optionIds.Count; i++) { result += optionIds[i]; if (i != optionIds.Count - 1) result += ","; } return result; } #endregion #region Methods public virtual List<int> GetAlreadyFilteredSpecOptionIds(IWebHelper webHelper) { var result = new List<int>(); var alreadyFilteredSpecsStr = webHelper.QueryString<string>(QUERYSTRINGPARAM); if (String.IsNullOrWhiteSpace(alreadyFilteredSpecsStr)) return result; foreach (var spec in alreadyFilteredSpecsStr.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { int specId; int.TryParse(spec.Trim(), out specId); if (!result.Contains(specId)) result.Add(specId); } return result; } public virtual void PrepareSpecsFilters(IList<int> alreadyFilteredSpecOptionIds, IList<int> filterableSpecificationAttributeOptionIds, ISpecificationAttributeService specificationAttributeService, IWebHelper webHelper, IWorkContext workContext) { var allFilters = new List<SpecificationAttributeOptionFilter>(); var specificationAttributeOptions = specificationAttributeService .GetSpecificationAttributeOptionsByIds(filterableSpecificationAttributeOptionIds != null ? filterableSpecificationAttributeOptionIds.ToArray() : null); foreach (var sao in specificationAttributeOptions) { var sa = sao.SpecificationAttribute; if (sa != null) { allFilters.Add(new SpecificationAttributeOptionFilter { SpecificationAttributeId = sa.Id, SpecificationAttributeName = sa.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id), SpecificationAttributeDisplayOrder = sa.DisplayOrder, SpecificationAttributeOptionId = sao.Id, SpecificationAttributeOptionName = sao.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id), SpecificationAttributeOptionDisplayOrder = sao.DisplayOrder }); } } //sort loaded options allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder) .ThenBy(saof => saof.SpecificationAttributeName) .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder) .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList(); //get already filtered specification options var alreadyFilteredOptions = allFilters .Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId)) .Select(x => x) .ToList(); //get not filtered specification options var notFilteredOptions = new List<SpecificationAttributeOptionFilter>(); foreach (var saof in allFilters) { //do not add already filtered specification options if (alreadyFilteredOptions.FirstOrDefault(x => x.SpecificationAttributeId == saof.SpecificationAttributeId) != null) continue; //else add it notFilteredOptions.Add(saof); } //prepare the model properties if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0) { this.Enabled = true; this.AlreadyFilteredItems = alreadyFilteredOptions.ToList().Select(x => { var item = new SpecificationFilterItem(); item.SpecificationAttributeName = x.SpecificationAttributeName; item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName; return item; }).ToList(); this.NotFilteredItems = notFilteredOptions.ToList().Select(x => { var item = new SpecificationFilterItem(); item.SpecificationAttributeName = x.SpecificationAttributeName; item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName; //filter URL var alreadyFilteredOptionIds = GetAlreadyFilteredSpecOptionIds(webHelper); if (!alreadyFilteredOptionIds.Contains(x.SpecificationAttributeOptionId)) alreadyFilteredOptionIds.Add(x.SpecificationAttributeOptionId); string newQueryParam = GenerateFilteredSpecQueryParam(alreadyFilteredOptionIds); string filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + newQueryParam, null); filterUrl = ExcludeQueryStringParams(filterUrl, webHelper); item.FilterUrl = filterUrl; return item; }).ToList(); //remove filter URL string removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM); removeFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper); this.RemoveFilterUrl = removeFilterUrl; } else { this.Enabled = false; } } #endregion #region Properties public bool Enabled { get; set; } public IList<SpecificationFilterItem> AlreadyFilteredItems { get; set; } public IList<SpecificationFilterItem> NotFilteredItems { get; set; } public string RemoveFilterUrl { get; set; } #endregion } public partial class SpecificationFilterItem : BaseNopModel { public string SpecificationAttributeName { get; set; } public string SpecificationAttributeOptionName { get; set; } public string FilterUrl { get; set; } } #endregion } }
40.433414
155
0.530271
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Vialinker Source/BaseVialinkerCommerceApps/Presentation/Nop.Web/Models/Catalog/CatalogPagingFilteringModel.cs
16,701
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; namespace Microsoft.Web.Http.Data.Test.Models { /// <summary> /// Sample data class /// </summary> /// <remarks> /// This class exposes several data types (City, County, State and Zip) and some sample /// data for each. /// </remarks> public partial class CityData { private List<State> _states; private List<County> _counties; private List<City> _cities; private List<Zip> _zips; private List<ZipWithInfo> _zipsWithInfo; private List<CityWithInfo> _citiesWithInfo; public CityData() { _states = new List<State>() { new State() { Name="WA", FullName="Washington", TimeZone = TimeZone.Pacific }, new State() { Name="OR", FullName="Oregon", TimeZone = TimeZone.Pacific }, new State() { Name="CA", FullName="California", TimeZone = TimeZone.Pacific }, new State() { Name="OH", FullName="Ohio", TimeZone = TimeZone.Eastern, ShippingZone=ShippingZone.Eastern } }; _counties = new List<County>() { new County() { Name="King", StateName="WA" }, new County() { Name="Pierce", StateName="WA" }, new County() { Name="Snohomish", StateName="WA" }, new County() { Name="Tillamook", StateName="OR" }, new County() { Name="Wallowa", StateName="OR" }, new County() { Name="Jackson", StateName="OR" }, new County() { Name="Orange", StateName="CA" }, new County() { Name="Santa Barbara",StateName="CA" }, new County() { Name="Lucas", StateName="OH" } }; foreach (State state in _states) { foreach (County county in _counties.Where(p => p.StateName == state.Name)) { state.Counties.Add(county); county.State = state; } } _cities = new List<City>() { new CityWithInfo() {Name="Redmond", CountyName="King", StateName="WA", Info="Has Microsoft campus", LastUpdated=DateTime.Now}, new CityWithInfo() {Name="Bellevue", CountyName="King", StateName="WA", Info="Means beautiful view", LastUpdated=DateTime.Now}, new City() {Name="Duvall", CountyName="King", StateName="WA"}, new City() {Name="Carnation", CountyName="King", StateName="WA"}, new City() {Name="Everett", CountyName="King", StateName="WA"}, new City() {Name="Tacoma", CountyName="Pierce", StateName="WA"}, new City() {Name="Ashland", CountyName="Jackson", StateName="OR"}, new City() {Name="Santa Barbara", CountyName="Santa Barbara", StateName="CA"}, new City() {Name="Orange", CountyName="Orange", StateName="CA"}, new City() {Name="Oregon", CountyName="Lucas", StateName="OH"}, new City() {Name="Toledo", CountyName="Lucas", StateName="OH"} }; _citiesWithInfo = new List<CityWithInfo>(this._cities.OfType<CityWithInfo>()); foreach (County county in _counties) { foreach (City city in _cities.Where(p => p.CountyName == county.Name && p.StateName == county.StateName)) { county.Cities.Add(city); city.County = county; } } _zips = new List<Zip>() { new Zip() { Code=98053, FourDigit=8625, CityName="Redmond", CountyName="King", StateName="WA" }, new ZipWithInfo() { Code=98052, FourDigit=8300, CityName="Redmond", CountyName="King", StateName="WA", Info="Microsoft" }, new Zip() { Code=98052, FourDigit=6399, CityName="Redmond", CountyName="King", StateName="WA" }, }; _zipsWithInfo = new List<ZipWithInfo>(this._zips.OfType<ZipWithInfo>()); foreach (City city in _cities) { foreach (Zip zip in _zips.Where(p => p.CityName == city.Name && p.CountyName == city.CountyName && p.StateName == city.StateName)) { city.ZipCodes.Add(zip); zip.City = city; } } foreach (CityWithInfo city in _citiesWithInfo) { foreach (ZipWithInfo zip in _zipsWithInfo.Where(p => p.CityName == city.Name && p.CountyName == city.CountyName && p.StateName == city.StateName)) { city.ZipCodesWithInfo.Add(zip); zip.City = city; } } } public List<State> States { get { return this._states; } } public List<County> Counties { get { return this._counties; } } public List<City> Cities { get { return this._cities; } } public List<CityWithInfo> CitiesWithInfo { get { return this._citiesWithInfo; } } public List<Zip> Zips { get { return this._zips; } } public List<ZipWithInfo> ZipsWithInfo { get { return this._zipsWithInfo; } } } /// <summary> /// These types are simple data types that can be used to build /// mocks and simple data stores. /// </summary> public partial class State { private readonly List<County> _counties = new List<County>(); [Key] public string Name { get; set; } [Key] public string FullName { get; set; } public TimeZone TimeZone { get; set; } public ShippingZone ShippingZone { get; set; } public List<County> Counties { get { return this._counties; } } } [DataContract(Name = "CityName", Namespace = "CityNamespace")] public enum ShippingZone { [EnumMember(Value = "P")] Pacific = 0, // default [EnumMember(Value = "C")] Central, [EnumMember(Value = "E")] Eastern } public enum TimeZone { Central, Mountain, Eastern, Pacific } public partial class County { public County() { Cities = new List<City>(); } [Key] public string Name { get; set; } [Key] public string StateName { get; set; } [IgnoreDataMember] public State State { get; set; } public List<City> Cities { get; set; } } [KnownType(typeof(CityWithEditHistory))] [KnownType(typeof(CityWithInfo))] public partial class City { public City() { ZipCodes = new List<Zip>(); } [Key] public string Name { get; set; } [Key] public string CountyName { get; set; } [Key] public string StateName { get; set; } [IgnoreDataMember] public County County { get; set; } public string ZoneName { get; set; } public string CalculatedCounty { get { return this.CountyName; } set { } } public int ZoneID { get; set; } public List<Zip> ZipCodes { get; set; } public override string ToString() { return this.GetType().Name + " Name=" + this.Name + ", State=" + this.StateName + ", County=" + this.CountyName; } public int this[int index] { get { return index; } set { } } } public abstract partial class CityWithEditHistory : City { private string _editHistory; public CityWithEditHistory() { this.EditHistory = "new"; } // Edit history always appends, never overwrites public string EditHistory { get { return this._editHistory; } set { this._editHistory = this._editHistory == null ? value : (this._editHistory + "," + value); this.LastUpdated = DateTime.Now; } } public DateTime LastUpdated { get; set; } public override string ToString() { return base.ToString() + ", History=" + this.EditHistory + ", Updated=" + this.LastUpdated; } } public partial class CityWithInfo : CityWithEditHistory { public CityWithInfo() { ZipCodesWithInfo = new List<ZipWithInfo>(); } public string Info { get; set; } public List<ZipWithInfo> ZipCodesWithInfo { get; set; } public override string ToString() { return base.ToString() + ", Info=" + this.Info; } } [KnownType(typeof(ZipWithInfo))] public partial class Zip { [Key] public int Code { get; set; } [Key] public int FourDigit { get; set; } public string CityName { get; set; } public string CountyName { get; set; } public string StateName { get; set; } [IgnoreDataMember] public City City { get; set; } } public partial class ZipWithInfo : Zip { public string Info { get; set; } } }
31.859016
162
0.524545
[ "Apache-2.0" ]
Daniel-Svensson/OpenRiaServices
src/archive/OpenRiaServices.DomainControllers.Server/Test/Models/Cities.cs
9,719
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Wyam.Common.Caching; using Wyam.Common.Configuration; using Wyam.Common.Documents; using Wyam.Common.IO; using Wyam.Common.JavaScript; using Wyam.Common.Meta; using Wyam.Common.Modules; using Wyam.Common.Tracing; namespace Wyam.Common.Execution { /// <summary> /// All of the information that represents a given build. Also implements /// <see cref="IMetadata"/> to expose the global metadata. /// </summary> public interface IExecutionContext : IMetadata { /// <summary> /// Uniquly identifies the current execution cycle. This can be used to initialize and/or /// reset static data for a module on new generations (I.e., due to watching). /// For example, cache data could be cleared when this changes between runs. /// </summary> Guid ExecutionId { get; } /// <summary> /// Gets the raw bytes for dynamically compiled assemblies (such as the configuration script). /// </summary> IReadOnlyCollection<byte[]> DynamicAssemblies { get; } /// <summary> /// Gets a set of namespaces that should be brought into scope for modules that perform dynamic compilation. /// </summary> IReadOnlyCollection<string> Namespaces { get; } /// <summary> /// Gets the currently executing pipeline. /// </summary> IReadOnlyPipeline Pipeline { get; } /// <summary> /// Gets the currently executing module. /// </summary> IModule Module { get; } /// <summary> /// Gets the current execution cache. Modules can use the cache to store data between executions. /// </summary> IExecutionCache ExecutionCache { get; } /// <summary> /// Gets the current file system. /// </summary> IReadOnlyFileSystem FileSystem { get; } /// <summary> /// Gets the current settings metadata. /// </summary> IReadOnlySettings Settings { get; } /// <summary> /// Gets the collection of all previously processed documents. /// </summary> IDocumentCollection Documents { get; } /// <summary> /// Gets any input that was passed to the application (for example, on stdin via piping). /// </summary> /// <value> /// The application input. /// </value> string ApplicationInput { get; } /// <summary> /// Gets a <see cref="Stream"/> that can be used for document content. If <paramref name="content"/> /// is not null, the stream is initialized with the specified content. It is prefered to use /// this method to obtain a stream over creating your own if the source of the content does /// not already provide one. The returned streams are optimized for memory usage and performance. /// <remarks>The position is set to the beginning of the stream when returned.</remarks> /// </summary> /// <param name="content">Content to initialize the stream with.</param> /// <returns>A stream for document content.</returns> Stream GetContentStream(string content = null); /// <summary> /// Gets a new document with default initial metadata. /// </summary> /// <returns>The new document.</returns> IDocument GetDocument(); /// <summary> /// Gets a new document with the specified source, content stream, and metadata (in addition to the default initial metadata). /// If <paramref name="disposeStream"/> is true (which it is by default), the provided /// <see cref="Stream"/> will automatically be disposed when the document is disposed (I.e., the /// document takes ownership of the <see cref="Stream"/>). /// </summary> /// <param name="source">The source.</param> /// <param name="stream">The content stream.</param> /// <param name="items">The metadata items.</param> /// <param name="disposeStream">If set to <c>true</c> the provided <see cref="Stream"/> is disposed when the document is.</param> /// <returns>The new document.</returns> IDocument GetDocument(FilePath source, Stream stream, IEnumerable<KeyValuePair<string, object>> items = null, bool disposeStream = true); /// <summary> /// Gets a new document with the specified source and metadata (in addition to the default initial metadata). /// </summary> /// <param name="source">The source.</param> /// <param name="items">The metadata items.</param> /// <returns>The new document.</returns> IDocument GetDocument(FilePath source, IEnumerable<KeyValuePair<string, object>> items = null); /// <summary> /// Gets a new document with the specified content stream and metadata (in addition to the default initial metadata). /// If <paramref name="disposeStream"/> is true (which it is by default), the provided /// <see cref="Stream"/> will automatically be disposed when the document is disposed (I.e., the /// document takes ownership of the <see cref="Stream"/>). /// </summary> /// <param name="stream">The content stream.</param> /// <param name="items">The metadata items.</param> /// <param name="disposeStream">If set to <c>true</c> the provided <see cref="Stream"/> is disposed when the document is.</param> /// <returns>The new document.</returns> IDocument GetDocument(Stream stream, IEnumerable<KeyValuePair<string, object>> items = null, bool disposeStream = true); /// <summary> /// Gets a new document with the specified metadata (in addition to the default initial metadata). /// </summary> /// <param name="items">The metadata items.</param> /// <returns>The new document.</returns> IDocument GetDocument(IEnumerable<KeyValuePair<string, object>> items); /// <summary> /// Clones the specified source document with a new source, new content stream, and additional metadata (all existing metadata is retained) /// or gets a new document if the source document is null or <c>AsNewDocuments()</c> was called on the module. /// If <paramref name="disposeStream"/> is true (which it is by default), the provided /// <see cref="Stream"/> will automatically be disposed when the document is disposed (I.e., the /// document takes ownership of the <see cref="Stream"/>). /// </summary> /// <param name="sourceDocument">The source document.</param> /// <param name="source">The source (if the source document contains a source, then this is ignored and the source document's source is used instead).</param> /// <param name="stream">The content stream.</param> /// <param name="items">The metadata items.</param> /// <param name="disposeStream">If set to <c>true</c> the provided <see cref="Stream"/> is disposed when the document is.</param> /// <returns>The cloned or new document.</returns> IDocument GetDocument(IDocument sourceDocument, FilePath source, Stream stream, IEnumerable<KeyValuePair<string, object>> items = null, bool disposeStream = true); /// <summary> /// Clones the specified source document with a new content stream, and additional metadata (all existing metadata is retained) /// or gets a new document if the source document is null or <c>AsNewDocuments()</c> was called on the module. /// If <paramref name="disposeStream"/> is true (which it is by default), the provided /// <see cref="Stream"/> will automatically be disposed when the document is disposed (I.e., the /// document takes ownership of the <see cref="Stream"/>). /// </summary> /// <param name="sourceDocument">The source document.</param> /// <param name="stream">The content stream.</param> /// <param name="items">The metadata items.</param> /// <param name="disposeStream">If set to <c>true</c> the provided <see cref="Stream"/> is disposed when the document is.</param> /// <returns>The cloned or new document.</returns> IDocument GetDocument(IDocument sourceDocument, Stream stream, IEnumerable<KeyValuePair<string, object>> items = null, bool disposeStream = true); /// <summary> /// Clones the specified source document with a new source and additional metadata (all existing metadata is retained) /// or gets a new document if the source document is null or <c>AsNewDocuments()</c> was called on the module. /// </summary> /// <param name="sourceDocument">The source document.</param> /// <param name="source">The source (if the source document contains a source, then this is ignored and the source document's source is used instead).</param> /// <param name="items">The metadata items.</param> /// <returns>The cloned or new document.</returns> IDocument GetDocument(IDocument sourceDocument, FilePath source, IEnumerable<KeyValuePair<string, object>> items = null); /// <summary> /// Clones the specified source document with identical content and additional metadata (all existing metadata is retained) /// or gets a new document if the source document is null or <c>AsNewDocuments()</c> was called on the module. /// </summary> /// <param name="sourceDocument">The source document.</param> /// <param name="items">The metadata items.</param> /// <returns>The cloned or new document.</returns> IDocument GetDocument(IDocument sourceDocument, IEnumerable<KeyValuePair<string, object>> items); /// <summary> /// Provides access to the same enhanced type conversion used to convert metadata types. /// </summary> /// <typeparam name="T">The destination type.</typeparam> /// <param name="value">The value to convert.</param> /// <param name="result">The result of the conversion.</param> /// <returns><c>true</c> if the conversion could be completed, <c>false</c> otherwise.</returns> bool TryConvert<T>(object value, out T result); /// <summary> /// Executes the specified modules with the specified input documents and returns the result documents. /// </summary> /// <param name="modules">The modules to execute.</param> /// <param name="inputs">The input documents.</param> /// <returns>The result documents from the executed modules.</returns> IReadOnlyList<IDocument> Execute(IEnumerable<IModule> modules, IEnumerable<IDocument> inputs); /// <summary> /// Executes the specified modules with an empty initial input document with optional additional metadata and returns the result documents. /// </summary> /// <param name="modules">The modules to execute.</param> /// <param name="metadata">The metadata to use.</param> /// <returns>The result documents from the executed modules.</returns> IReadOnlyList<IDocument> Execute(IEnumerable<IModule> modules, IEnumerable<KeyValuePair<string, object>> metadata = null); /// <summary> /// Executes the specified modules with an empty initial input document with optional additional metadata and returns the result documents. /// </summary> /// <param name="modules">The modules to execute.</param> /// <param name="metadata">The metadata to use.</param> /// <returns>The result documents from the executed modules.</returns> IReadOnlyList<IDocument> Execute(IEnumerable<IModule> modules, IEnumerable<MetadataItem> metadata); /// <summary> /// Gets a new <see cref="IJsEnginePool"/>. The returned engine pool should be disposed /// when no longer needed. /// </summary> /// <param name="initializer"> /// The code to run when a new engine is created. This should configure /// the environment and set up any required JavaScript libraries. /// </param> /// <param name="startEngines">The number of engines to initially start when a pool is created.</param> /// <param name="maxEngines">The maximum number of engines that will be created in the pool.</param> /// <param name="maxUsagesPerEngine">The maximum number of times an engine can be reused before it is disposed.</param> /// <param name="engineTimeout"> /// The default timeout to use when acquiring an engine from the pool (defaults to 5 seconds). /// If an engine can not be acquired in this timeframe, an exception will be thrown. /// </param> /// <returns>A new JavaScript engine pool.</returns> IJsEnginePool GetJsEnginePool( Action<IJsEngine> initializer = null, int startEngines = 10, int maxEngines = 25, int maxUsagesPerEngine = 100, TimeSpan? engineTimeout = null); } }
55.213389
171
0.64421
[ "MIT" ]
glennawatson/Wyam
src/core/Wyam.Common/Execution/IExecutionContext.cs
13,198
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace CefNet.Internal { public partial class WebViewGlue { public void CreateOrDestroyFocusGlue() { if (AvoidOnTakeFocus() && AvoidOnSetFocus() && AvoidOnGotFocus()) { this.FocusGlue = null; } else if (this.FocusGlue is null) { this.FocusGlue = new CefFocusHandlerGlue(this); } } [MethodImpl(MethodImplOptions.ForwardRef)] internal extern bool AvoidOnTakeFocus(); /// <summary> /// Called when the browser component is about to loose focus. For instance, if focus /// was on the last HTML element and the user pressed the TAB key. /// </summary> /// <param name="browser"></param> /// <param name="next"> /// The |next| will be true if the browser is giving focus to the next component /// and false if the browser is giving focus to the previous component. /// </param> internal protected virtual void OnTakeFocus(CefBrowser browser, bool next) { } [MethodImpl(MethodImplOptions.ForwardRef)] internal extern bool AvoidOnSetFocus(); /// <summary> /// Called when the browser component is requesting focus. Return false to allow /// the focus to be set or true to cancel setting the focus. /// </summary> /// <param name="browser"></param> /// <param name="source"> /// Indicates where the focus request is originating from. /// </param> /// <returns>Return false to allow the focus to be set or true to cancel setting the focus.</returns> internal protected virtual bool OnSetFocus(CefBrowser browser, CefFocusSource source) { return false; } [MethodImpl(MethodImplOptions.ForwardRef)] internal extern bool AvoidOnGotFocus(); /// <summary> /// Called when the browser component has received focus. /// </summary> /// <param name="browser"></param> internal protected virtual void OnGotFocus(CefBrowser browser) { } } }
27.591549
103
0.698315
[ "MIT" ]
CefNet/CefNet
CefNet/Internal/WebViewGlue.CefFocusHandlerGlue.cs
1,961
C#
//////////////////////////////////////////////////////////////////////////////// /// @file SettingWindow.xaml.cs /// @brief SettingWindowクラス /// @author Yuta Yoshinaga /// @date 2017.10.20 /// $Version: $ /// $Revision: $ /// /// Copyright (c) 2017 Yuta Yoshinaga. All Rights reserved. /// /// - 本ソフトウェアの一部又は全てを無断で複写複製(コピー)することは、 /// 著作権侵害にあたりますので、これを禁止します。 /// - 本製品の使用に起因する侵害または特許権その他権利の侵害に関しては /// 当社は一切その責任を負いません。 /// //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace ReversiWpf { //////////////////////////////////////////////////////////////////////////////// /// @class SettingWindow /// @brief SettingWindow.xaml の相互作用ロジッククラス /// //////////////////////////////////////////////////////////////////////////////// public partial class SettingWindow : Window { #region メンバ変数 private ReversiSetting _mSetting; //!< リバーシ設定クラス #endregion #region プロパティ public ReversiSetting mSetting { get { return _mSetting; } set { _mSetting = value; } } #endregion //////////////////////////////////////////////////////////////////////////////// /// @brief コンストラクタ /// @fn SettingWindow(ReversiSetting mSetting) /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// public SettingWindow(ReversiSetting mSetting) { InitializeComponent(); this.mSetting = mSetting; this.reflectSettingForm(); } //////////////////////////////////////////////////////////////////////////////// /// @brief フォームに設定を反映 /// @fn void reflectSettingForm() /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void reflectSettingForm() { // *** 現在のモード *** // if(mSetting.mMode == ReversiConst.DEF_MODE_ONE) { radioButtonMode1.IsChecked = true; radioButtonMode2.IsChecked = false; } else { radioButtonMode1.IsChecked = false; radioButtonMode2.IsChecked = true; } // *** 現在のタイプ *** // if(mSetting.mType == ReversiConst.DEF_TYPE_EASY) { radioButtonType1.IsChecked = true; radioButtonType2.IsChecked = false; radioButtonType3.IsChecked = false; } else if(mSetting.mType == ReversiConst.DEF_TYPE_NOR) { radioButtonType1.IsChecked = false; radioButtonType2.IsChecked = true; radioButtonType3.IsChecked = false; } else { radioButtonType1.IsChecked = false; radioButtonType2.IsChecked = false; radioButtonType3.IsChecked = true; } // *** プレイヤーの色 *** // if(mSetting.mPlayer == ReversiConst.REVERSI_STS_BLACK) { radioButtonPlayer1.IsChecked = true; radioButtonPlayer2.IsChecked = false; } else { radioButtonPlayer1.IsChecked = false; radioButtonPlayer2.IsChecked = true; } // *** アシスト *** // if(mSetting.mAssist == ReversiConst.DEF_ASSIST_OFF) { radioButtonAssist1.IsChecked = true; radioButtonAssist2.IsChecked = false; } else { radioButtonAssist1.IsChecked = false; radioButtonAssist2.IsChecked = true; } // *** ゲームスピード *** // if(mSetting.mGameSpd == ReversiConst.DEF_GAME_SPD_FAST) { radioButtonGameSpd1.IsChecked = true; radioButtonGameSpd2.IsChecked = false; radioButtonGameSpd3.IsChecked = false; } else if(mSetting.mGameSpd == ReversiConst.DEF_GAME_SPD_MID) { radioButtonGameSpd1.IsChecked = false; radioButtonGameSpd2.IsChecked = true; radioButtonGameSpd3.IsChecked = false; } else { radioButtonGameSpd1.IsChecked = false; radioButtonGameSpd2.IsChecked = false; radioButtonGameSpd3.IsChecked = true; } // *** ゲーム終了アニメーション *** // if(mSetting.mEndAnim == ReversiConst.DEF_END_ANIM_OFF) { radioButtonEndAnim1.IsChecked = true; radioButtonEndAnim2.IsChecked = false; } else { radioButtonEndAnim1.IsChecked = false; radioButtonEndAnim2.IsChecked = true; } // *** マスの数 *** // if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_6) { radioButtonMasuCntMenu1.IsChecked = true; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_8) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = true; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_10) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = true; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_12) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = true; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_14) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = true; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_16) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = true; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = false; } else if(mSetting.mMasuCntMenu == ReversiConst.DEF_MASU_CNT_18) { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = true; radioButtonMasuCntMenu8.IsChecked = false; } else { radioButtonMasuCntMenu1.IsChecked = false; radioButtonMasuCntMenu2.IsChecked = false; radioButtonMasuCntMenu3.IsChecked = false; radioButtonMasuCntMenu4.IsChecked = false; radioButtonMasuCntMenu5.IsChecked = false; radioButtonMasuCntMenu6.IsChecked = false; radioButtonMasuCntMenu7.IsChecked = false; radioButtonMasuCntMenu8.IsChecked = true; } pictureBoxPlayerColor1.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(mSetting.mPlayerColor1.A,mSetting.mPlayerColor1.R,mSetting.mPlayerColor1.G,mSetting.mPlayerColor1.B)); pictureBoxPlayerColor2.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(mSetting.mPlayerColor2.A,mSetting.mPlayerColor2.R,mSetting.mPlayerColor2.G,mSetting.mPlayerColor2.B)); pictureBoxBackGroundColor.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(mSetting.mBackGroundColor.A,mSetting.mBackGroundColor.R,mSetting.mBackGroundColor.G,mSetting.mBackGroundColor.B)); pictureBoxBorderColor.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(mSetting.mBorderColor.A,mSetting.mBorderColor.R,mSetting.mBorderColor.G,mSetting.mBorderColor.B)); } //////////////////////////////////////////////////////////////////////////////// /// @brief フォームから設定を読み込み /// @fn void reflectSettingForm() /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void loadSettingForm() { // *** 現在のモード *** // if(radioButtonMode1.IsChecked == true) mSetting.mMode = ReversiConst.DEF_MODE_ONE; else mSetting.mMode = ReversiConst.DEF_MODE_TWO; // *** 現在のタイプ *** // if(radioButtonType1.IsChecked == true) mSetting.mType = ReversiConst.DEF_TYPE_EASY; else if(radioButtonType2.IsChecked == true) mSetting.mType = ReversiConst.DEF_TYPE_NOR; else mSetting.mType = ReversiConst.DEF_TYPE_HARD; // *** プレイヤーの色 *** // if(radioButtonPlayer1.IsChecked == true) mSetting.mPlayer = ReversiConst.REVERSI_STS_BLACK; else mSetting.mPlayer = ReversiConst.REVERSI_STS_WHITE; // *** アシスト *** // if(radioButtonAssist1.IsChecked == true) mSetting.mAssist = ReversiConst.DEF_ASSIST_OFF; else mSetting.mAssist = ReversiConst.DEF_ASSIST_ON; // *** ゲームスピード *** // if(radioButtonGameSpd1.IsChecked == true) mSetting.mGameSpd = ReversiConst.DEF_GAME_SPD_FAST; else if(radioButtonGameSpd2.IsChecked == true) mSetting.mGameSpd = ReversiConst.DEF_GAME_SPD_MID; else mSetting.mGameSpd = ReversiConst.DEF_GAME_SPD_SLOW; // *** ゲーム終了アニメーション *** // if(radioButtonEndAnim1.IsChecked == true) mSetting.mEndAnim = ReversiConst.DEF_END_ANIM_OFF; else mSetting.mEndAnim = ReversiConst.DEF_END_ANIM_ON; // *** マスの数 *** // if(radioButtonMasuCntMenu1.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_6; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_6_VAL; } else if(radioButtonMasuCntMenu2.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_8; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_8_VAL; } else if(radioButtonMasuCntMenu3.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_10; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_10_VAL; } else if(radioButtonMasuCntMenu4.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_12; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_12_VAL; } else if(radioButtonMasuCntMenu5.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_14; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_14_VAL; } else if(radioButtonMasuCntMenu6.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_16; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_16_VAL; } else if(radioButtonMasuCntMenu7.IsChecked == true) { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_18; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_18_VAL; } else { mSetting.mMasuCntMenu = ReversiConst.DEF_MASU_CNT_20; mSetting.mMasuCnt = ReversiConst.DEF_MASU_CNT_20_VAL; } SolidColorBrush work = (SolidColorBrush)pictureBoxPlayerColor1.Background; mSetting.mPlayerColor1 = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); work = (SolidColorBrush)pictureBoxPlayerColor2.Background; mSetting.mPlayerColor2 = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); work = (SolidColorBrush)pictureBoxBackGroundColor.Background; mSetting.mBackGroundColor = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); work = (SolidColorBrush)pictureBoxBorderColor.Background; mSetting.mBorderColor = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); } //////////////////////////////////////////////////////////////////////////////// /// @brief プレイヤー1の色クリック /// @fn void pictureBoxPlayerColor1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) /// @param[in] object sender /// @param[in] MouseButtonEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void pictureBoxPlayerColor1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // ColorDialogクラスのインスタンスを作成 System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog(); // はじめに選択されている色を設定 SolidColorBrush work = (SolidColorBrush)pictureBoxPlayerColor1.Background; cd.Color = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); // ダイアログを表示する if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // 選択された色の取得 pictureBoxPlayerColor1.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(cd.Color.A,cd.Color.R,cd.Color.G,cd.Color.B)); } } //////////////////////////////////////////////////////////////////////////////// /// @brief プレイヤー2の色クリック /// @fn void pictureBoxPlayerColor2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) /// @param[in] object sender /// @param[in] MouseButtonEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void pictureBoxPlayerColor2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // ColorDialogクラスのインスタンスを作成 System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog(); // はじめに選択されている色を設定 SolidColorBrush work = (SolidColorBrush)pictureBoxPlayerColor2.Background; cd.Color = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); // ダイアログを表示する if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // 選択された色の取得 pictureBoxPlayerColor2.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(cd.Color.A,cd.Color.R,cd.Color.G,cd.Color.B)); } } //////////////////////////////////////////////////////////////////////////////// /// @brief 背景の色クリック /// @fn void pictureBoxBackGroundColor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) /// @param[in] object sender /// @param[in] MouseButtonEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void pictureBoxBackGroundColor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // ColorDialogクラスのインスタンスを作成 System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog(); // はじめに選択されている色を設定 SolidColorBrush work = (SolidColorBrush)pictureBoxBackGroundColor.Background; cd.Color = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); // ダイアログを表示する if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // 選択された色の取得 pictureBoxBackGroundColor.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(cd.Color.A,cd.Color.R,cd.Color.G,cd.Color.B)); } } //////////////////////////////////////////////////////////////////////////////// /// @brief 枠線の色クリック /// @fn void pictureBoxBorderColor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) /// @param[in] object sender /// @param[in] MouseButtonEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void pictureBoxBorderColor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // ColorDialogクラスのインスタンスを作成 System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog(); // はじめに選択されている色を設定 SolidColorBrush work = (SolidColorBrush)pictureBoxBorderColor.Background; cd.Color = System.Drawing.Color.FromArgb(work.Color.A,work.Color.R,work.Color.G,work.Color.B); // ダイアログを表示する if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // 選択された色の取得 pictureBoxBorderColor.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(cd.Color.A,cd.Color.R,cd.Color.G,cd.Color.B)); } } //////////////////////////////////////////////////////////////////////////////// /// @brief デフォルト設定に戻すボタンクリック /// @fn void buttonDefault_Click(object sender, RoutedEventArgs e) /// @param[in] object sender /// @param[in] RoutedEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void buttonDefault_Click(object sender, RoutedEventArgs e) { mSetting.reset(); this.reflectSettingForm(); } //////////////////////////////////////////////////////////////////////////////// /// @brief 保存ボタンクリック /// @fn void buttonSave_Click(object sender, RoutedEventArgs e) /// @param[in] object sender /// @param[in] RoutedEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void buttonSave_Click(object sender, RoutedEventArgs e) { this.loadSettingForm(); this.Close(); } //////////////////////////////////////////////////////////////////////////////// /// @brief キャンセルボタンクリック /// @fn void buttonCancel_Click(object sender, RoutedEventArgs e) /// @param[in] object sender /// @param[in] RoutedEventArgs e /// @return ありません /// @author Yuta Yoshinaga /// @date 2017.10.20 /// //////////////////////////////////////////////////////////////////////////////// private void buttonCancel_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
38.568182
212
0.647238
[ "MIT" ]
yuta-yoshinaga/reversiwpf
ReversiWpf/SettingWindow.xaml.cs
19,817
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by avrogen.exe, version 0.9.0.0 // Changes to this file may cause incorrect behavior and will be lost if code // is regenerated // </auto-generated> // ------------------------------------------------------------------------------ namespace eu.driver.model.geojson.photo { using System; using System.Collections.Generic; using System.Text; using Avro; using Avro.Specific; public partial class FeatureCollection : ISpecificRecord { public static Schema _SCHEMA = Avro.Schema.Parse("{\"type\":\"record\",\"name\":\"FeatureCollection\",\"namespace\":\"eu.driver.model.geojson." + "photo\",\"fields\":[{\"name\":\"type\",\"default\":\"FeatureCollection\",\"type\":{\"type\":\"en" + "um\",\"name\":\"FeatureCollectionType\",\"namespace\":\"eu.driver.model.geojson.photo\",\"" + "symbols\":[\"FeatureCollection\"]}},{\"name\":\"bbox\",\"default\":null,\"type\":[\"null\",{\"" + "type\":\"array\",\"items\":\"double\"}]},{\"name\":\"features\",\"type\":[\"null\",{\"type\":\"arr" + "ay\",\"items\":{\"type\":\"record\",\"name\":\"Feature\",\"namespace\":\"eu.driver.model.geojs" + "on.photo\",\"fields\":[{\"name\":\"type\",\"default\":\"Feature\",\"type\":{\"type\":\"enum\",\"na" + "me\":\"FeatureType\",\"namespace\":\"eu.driver.model.geojson.photo\",\"symbols\":[\"Featur" + "e\"]}},{\"name\":\"bbox\",\"default\":null,\"type\":[\"null\",{\"type\":\"array\",\"items\":\"doub" + "le\"}]},{\"name\":\"geometry\",\"type\":[{\"type\":\"record\",\"name\":\"Point\",\"namespace\":\"e" + "u.driver.model.geojson.photo\",\"fields\":[{\"name\":\"type\",\"default\":\"Point\",\"type\":" + "{\"type\":\"enum\",\"name\":\"PointType\",\"namespace\":\"eu.driver.model.geojson.photo\",\"s" + "ymbols\":[\"Point\"]}},{\"name\":\"coordinates\",\"type\":{\"type\":\"array\",\"items\":\"double" + "\"}}]},{\"type\":\"record\",\"name\":\"LineString\",\"namespace\":\"eu.driver.model.geojson." + "photo\",\"fields\":[{\"name\":\"type\",\"default\":\"LineString\",\"type\":{\"type\":\"enum\",\"na" + "me\":\"LineStringType\",\"namespace\":\"eu.driver.model.geojson.photo\",\"symbols\":[\"Lin" + "eString\"]}},{\"name\":\"coordinates\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"array\"" + ",\"items\":\"double\"}}}]},{\"type\":\"record\",\"name\":\"MultiLineString\",\"namespace\":\"eu" + ".driver.model.geojson.photo\",\"fields\":[{\"name\":\"type\",\"default\":\"MultiLineString" + "\",\"type\":{\"type\":\"enum\",\"name\":\"MultiLineStringType\",\"namespace\":\"eu.driver.mode" + "l.geojson.photo\",\"symbols\":[\"MultiLineString\"]}},{\"name\":\"coordinates\",\"type\":{\"" + "type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":\"double\"}}" + "}}]},{\"type\":\"record\",\"name\":\"Polygon\",\"namespace\":\"eu.driver.model.geojson.phot" + "o\",\"fields\":[{\"name\":\"type\",\"default\":\"Polygon\",\"type\":{\"type\":\"enum\",\"name\":\"Po" + "lygonType\",\"namespace\":\"eu.driver.model.geojson.photo\",\"symbols\":[\"Polygon\"]}},{" + "\"name\":\"coordinates\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"ty" + "pe\":\"array\",\"items\":\"double\"}}}}]},{\"type\":\"record\",\"name\":\"MultiPolygon\",\"names" + "pace\":\"eu.driver.model.geojson.photo\",\"fields\":[{\"name\":\"type\",\"default\":\"MultiP" + "olygon\",\"type\":{\"type\":\"enum\",\"name\":\"MultiPolygonType\",\"namespace\":\"eu.driver.m" + "odel.geojson.photo\",\"symbols\":[\"MultiPolygon\"]}},{\"name\":\"coordinates\",\"type\":{\"" + "type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"type\":\"a" + "rray\",\"items\":\"double\"}}}}}]}]},{\"name\":\"properties\",\"type\":{\"type\":\"record\",\"na" + "me\":\"properties\",\"namespace\":\"eu.driver.model.geojson.photo\",\"fields\":[{\"name\":\"" + "id\",\"type\":\"long\"},{\"name\":\"priority\",\"type\":\"long\"},{\"name\":\"viewed\",\"type\":\"bo" + "olean\"},{\"name\":\"signature\",\"type\":\"string\"},{\"name\":\"instant\",\"type\":\"string\"}," + "{\"name\":\"created\",\"type\":[\"null\",\"string\"]},{\"name\":\"updated\",\"type\":\"string\"},{" + "\"name\":\"caption\",\"type\":[\"null\",\"string\"]},{\"name\":\"interpretation\",\"type\":[\"str" + "ing\",\"null\"]},{\"name\":\"meta\",\"type\":{\"type\":\"record\",\"name\":\"meta\",\"namespace\":\"" + "eu.driver.model.geojson.photo\",\"fields\":[{\"name\":\"Source\",\"type\":{\"type\":\"record" + "\",\"name\":\"Source\",\"namespace\":\"eu.driver.model.geojson.photo\",\"fields\":[{\"name\":" + "\"filename\",\"type\":\"string\"},{\"name\":\"camera_make\",\"type\":[\"null\",\"string\"]},{\"na" + "me\":\"width\",\"type\":\"long\"},{\"name\":\"size\",\"type\":\"long\"},{\"name\":\"height\",\"type\"" + ":\"long\"},{\"name\":\"direction\",\"type\":[\"null\",\"double\"]},{\"name\":\"camera_model\",\"t" + "ype\":[\"null\",\"string\"]},{\"name\":\"field_of_view\",\"type\":[\"null\",\"double\"]}]}}]}}," + "{\"name\":\"version\",\"type\":[\"string\",\"null\"]},{\"name\":\"application_id\",\"type\":[\"st" + "ring\",\"null\"]},{\"name\":\"seen\",\"type\":[\"string\",\"null\"]},{\"name\":\"started\",\"type\"" + ":[\"string\",\"null\"]},{\"name\":\"stopped\",\"type\":[\"string\",\"null\"]},{\"name\":\"locatio" + "n_latitude\",\"type\":\"double\"},{\"name\":\"location_longitude\",\"type\":\"double\"},{\"nam" + "e\":\"location_time\",\"type\":\"string\"},{\"name\":\"location_accuracy\",\"type\":[\"double\"" + ",\"null\"]},{\"name\":\"location_altitude\",\"type\":[\"double\",\"null\"]},{\"name\":\"locatio" + "n_provider\",\"type\":[\"string\",\"null\"]},{\"name\":\"location_speed\",\"type\":[\"double\"," + "\"null\"]},{\"name\":\"location_meta\",\"type\":[\"string\",\"null\"]},{\"name\":\"mission_id\"," + "\"type\":[\"long\",\"null\"]},{\"name\":\"mission_name\",\"type\":[\"string\",\"null\"]},{\"name\"" + ":\"thumbnail_hash\",\"type\":\"string\"},{\"name\":\"preview_hash\",\"type\":\"string\"},{\"nam" + "e\":\"category_id\",\"type\":[\"long\",\"null\"]},{\"name\":\"category_name\",\"type\":[\"string" + "\",\"null\"]},{\"name\":\"application_device_type\",\"type\":[\"int\",\"null\"]},{\"name\":\"app" + "lication_last_login\",\"type\":[\"string\",\"null\"]},{\"name\":\"application_phone\",\"type" + "\":[\"string\",\"null\"]},{\"name\":\"application_last_rate\",\"type\":[\"long\",\"null\"]},{\"n" + "ame\":\"application_updated\",\"type\":[\"string\",\"null\"]},{\"name\":\"application_create" + "d\",\"type\":[\"string\",\"null\"]},{\"name\":\"application_application_type\",\"type\":[\"int" + "\",\"null\"]},{\"name\":\"application_connection_type\",\"type\":[\"int\",\"null\"]},{\"name\":" + "\"application_connection_state\",\"type\":[\"int\",\"null\"]},{\"name\":\"user_name\",\"type\"" + ":\"string\"},{\"name\":\"user_id\",\"type\":\"long\"},{\"name\":\"user_username\",\"type\":\"stri" + "ng\"},{\"name\":\"user_color\",\"type\":[\"string\",\"null\"]},{\"name\":\"user_connection_typ" + "e\",\"type\":[\"int\",\"null\"]},{\"name\":\"user_last_login\",\"type\":[\"string\",\"null\"]},{\"" + "name\":\"user_last_rate\",\"type\":[\"long\",\"null\"]},{\"name\":\"observation_url\",\"type\":" + "\"string\"},{\"name\":\"observation_type\",\"type\":\"string\"},{\"name\":\"preview_url\",\"typ" + "e\":\"string\"},{\"name\":\"preview_with_overlay_url\",\"type\":\"string\"},{\"name\":\"thumbn" + "ail_url\",\"type\":\"string\"},{\"name\":\"files\",\"type\":{\"type\":\"array\",\"items\":{\"type\"" + ":\"record\",\"name\":\"files\",\"namespace\":\"eu.driver.model.geojson.photo.files\",\"fiel" + "ds\":[{\"name\":\"id\",\"type\":\"long\"},{\"name\":\"file_type\",\"type\":\"int\"},{\"name\":\"size" + "\",\"type\":[\"long\",\"null\"]},{\"name\":\"state\",\"type\":\"int\"},{\"name\":\"created\",\"type\"" + ":\"string\"},{\"name\":\"request_until\",\"default\":null,\"type\":[\"null\",\"string\"]},{\"na" + "me\":\"meta\",\"type\":[\"null\",\"string\",{\"type\":\"record\",\"name\":\"meta\",\"namespace\":\"e" + "u.driver.model.geojson.photo.files\",\"fields\":[{\"name\":\"Region\",\"type\":{\"type\":\"r" + "ecord\",\"name\":\"Region\",\"namespace\":\"eu.driver.model.geojson.photo.files\",\"fields" + "\":[{\"name\":\"x\",\"type\":\"long\"},{\"name\":\"y\",\"type\":\"long\"},{\"name\":\"width\",\"type\":" + "\"long\"},{\"name\":\"height\",\"type\":\"long\"},{\"name\":\"scale\",\"type\":\"double\"},{\"name\"" + ":\"quality\",\"type\":\"int\"}]}}]}]},{\"name\":\"hash\",\"type\":[\"null\",\"string\"]},{\"name\"" + ":\"url\",\"type\":[\"null\",\"string\"]}]}}}]}}]}}]}]}"); private eu.driver.model.geojson.photo.FeatureCollectionType _type; private IList<System.Double> _bbox; private IList<eu.driver.model.geojson.photo.Feature> _features; public virtual Schema Schema { get { return FeatureCollection._SCHEMA; } } public eu.driver.model.geojson.photo.FeatureCollectionType type { get { return this._type; } set { this._type = value; } } public IList<System.Double> bbox { get { return this._bbox; } set { this._bbox = value; } } public IList<eu.driver.model.geojson.photo.Feature> features { get { return this._features; } set { this._features = value; } } public virtual object Get(int fieldPos) { switch (fieldPos) { case 0: return this.type; case 1: return this.bbox; case 2: return this.features; default: throw new AvroRuntimeException("Bad index " + fieldPos + " in Get()"); }; } public virtual void Put(int fieldPos, object fieldValue) { switch (fieldPos) { case 0: this.type = (eu.driver.model.geojson.photo.FeatureCollectionType)fieldValue; break; case 1: this.bbox = (IList<System.Double>)fieldValue; break; case 2: this.features = (IList<eu.driver.model.geojson.photo.Feature>)fieldValue; break; default: throw new AvroRuntimeException("Bad index " + fieldPos + " in Put()"); }; } } }
63.368098
147
0.513312
[ "MIT" ]
DRIVER-EU/csharp-test-bed-adapter
src/StandardMessages/schemas/eu/driver/model/geojson/photo/FeatureCollection.cs
10,329
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 elasticmapreduce-2009-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ElasticMapReduce.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ElasticMapReduce.Model.Internal.MarshallTransformations { /// <summary> /// DescribeJobFlows Request Marshaller /// </summary> public class DescribeJobFlowsRequestMarshaller : IMarshaller<IRequest, DescribeJobFlowsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeJobFlowsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeJobFlowsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ElasticMapReduce"); string target = "ElasticMapReduce.DescribeJobFlows"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2009-03-31"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCreatedAfter()) { context.Writer.WritePropertyName("CreatedAfter"); context.Writer.Write(publicRequest.CreatedAfter); } if(publicRequest.IsSetCreatedBefore()) { context.Writer.WritePropertyName("CreatedBefore"); context.Writer.Write(publicRequest.CreatedBefore); } if(publicRequest.IsSetJobFlowIds()) { context.Writer.WritePropertyName("JobFlowIds"); context.Writer.WriteArrayStart(); foreach(var publicRequestJobFlowIdsListValue in publicRequest.JobFlowIds) { context.Writer.Write(publicRequestJobFlowIdsListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetJobFlowStates()) { context.Writer.WritePropertyName("JobFlowStates"); context.Writer.WriteArrayStart(); foreach(var publicRequestJobFlowStatesListValue in publicRequest.JobFlowStates) { context.Writer.Write(publicRequestJobFlowStatesListValue); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeJobFlowsRequestMarshaller _instance = new DescribeJobFlowsRequestMarshaller(); internal static DescribeJobFlowsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeJobFlowsRequestMarshaller Instance { get { return _instance; } } } }
37.312977
147
0.605565
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/ElasticMapReduce/Generated/Model/Internal/MarshallTransformations/DescribeJobFlowsRequestMarshaller.cs
4,888
C#
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using FullSerializer; using IBM.Watson.DeveloperCloud.Connection; using IBM.Watson.DeveloperCloud.Logging; using IBM.Watson.DeveloperCloud.Services.LanguageTranslator.v3; using IBM.Watson.DeveloperCloud.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; namespace IBM.Watson.DeveloperCloud.UnitTests { public class TestLanguageTranslatorV3 : UnitTest { private string _pharseToTranslate = "Hello, welcome to IBM Watson!"; private fsSerializer _serializer = new fsSerializer(); private LanguageTranslator _languageTranslator; private bool _autoGetLanguagesTested = false; private bool _getTranslationTested = false; private bool _getModelsTested = false; private bool _getModelTested = false; private bool _identifyTested = false; private bool _getLanguagesTested = false; private string _versionDate = "2018-05-01"; public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); // Test LangaugeTranslator using loaded credentials LanguageTranslator autoLanguageTranslator = new LanguageTranslator(); while (!autoLanguageTranslator.Credentials.HasIamTokenData()) yield return null; autoLanguageTranslator.VersionDate = _versionDate; autoLanguageTranslator.GetLanguages(OnAutoGetLanguages, OnFail); while (!_autoGetLanguagesTested) yield return null; VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) result = File.ReadAllText(credentialsFilepath); else yield break; // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) throw new WatsonException(r.FormattedMessages); // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) throw new WatsonException(r.FormattedMessages); // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("language-translator-sdk")[0].Credentials; _url = credential.Url.ToString(); // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey, IamUrl = credential.IamUrl }; Credentials credentials = new Credentials(tokenOptions, credential.Url); // Wait for tokendata while (!credentials.HasIamTokenData()) yield return null; _languageTranslator = new LanguageTranslator(_versionDate, credentials); if (!_languageTranslator.GetTranslation(OnGetTranslation, OnFail, _pharseToTranslate, "en", "es")) Log.Debug("TestLanguageTranslator.GetTranslation()", "Failed to translate."); while (!_getTranslationTested) yield return null; if (!_languageTranslator.GetModels(OnGetModels, OnFail)) Log.Debug("TestLanguageTranslator.GetModels()", "Failed to get models."); while (!_getModelsTested) yield return null; if (!_languageTranslator.GetModel(OnGetModel, OnFail, "en-es")) Log.Debug("TestLanguageTranslator.GetModel()", "Failed to get model."); while (!_getModelTested) yield return null; if (!_languageTranslator.Identify(OnIdentify, OnFail, _pharseToTranslate)) Log.Debug("TestLanguageTranslator.Identify()", "Failed to identify language."); while (!_identifyTested) yield return null; if (!_languageTranslator.GetLanguages(OnGetLanguages, OnFail)) Log.Debug("TestLanguageTranslator.GetLanguages()", "Failed to get languages."); while (!_getLanguagesTested) yield return null; Log.Debug("TestLanguageTranslator.RunTest()", "Language Translator examples complete."); yield break; } private void OnAutoGetLanguages(Languages response, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnAutoGetLanguages()", "Language Translator - Get languages response: {0}", customData["json"].ToString()); Test(response != null); _autoGetLanguagesTested = true; } private void OnGetModels(TranslationModels models, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnGetModels()", "Language Translator - Get models response: {0}", customData["json"].ToString()); Test(models != null); _getModelsTested = true; } private void OnGetModel(TranslationModel model, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnGetModel()", "Language Translator - Get model response: {0}", customData["json"].ToString()); Test(model != null); _getModelTested = true; } private void OnGetTranslation(Translations translation, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnGetTranslation()", "Langauge Translator - Translate Response: {0}", customData["json"].ToString()); Test(translation != null); _getTranslationTested = true; } private void OnIdentify(IdentifiedLanguages identifiedLanguages, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnIdentify()", "Language Translator - Identify response: {0}", customData["json"].ToString()); Test(identifiedLanguages != null); _identifyTested = true; } private void OnGetLanguages(Languages languages, Dictionary<string, object> customData) { Log.Debug("TestLanguageTranslator.OnGetLanguages()", "Language Translator - Get languages response: {0}", customData["json"].ToString()); Test(languages != null); _getLanguagesTested = true; } private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData) { Log.Error("TestLanguageTranslator.OnFail()", "Error received: {0}", error.ToString()); } } }
42.472527
153
0.650453
[ "MIT" ]
iamdakshak/faceAR
Assets/Watson/Scripts/UnitTests/TestLanguageTranslatorV3.cs
7,732
C#
using ModernWpf.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ModernWpf.SampleApp.ControlPages { /// <summary> /// WebViewPage.xaml 的交互逻辑 /// </summary> public partial class WebViewPage : Page { public WebViewPage() { InitializeComponent(); } } }
21.862069
43
0.716088
[ "MIT" ]
wherewhere/ModernWpf
ModernWpf.SampleApp/ControlPages/WebViewPage.xaml.cs
646
C#
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Runtime.InteropServices; using Tizen; using Tizen.Multimedia.Util; internal static partial class Interop { internal static class ThumbnailExtractor { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void ThumbnailExtractCallback(ThumbnailExtractorError error, string requestId, int thumbWidth, int thumbHeight, IntPtr thumbData, int thumbSize, IntPtr userData); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_create")] internal static extern ThumbnailExtractorError Create(out ThumbnailExtractorHandle handle); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_extract")] internal static extern ThumbnailExtractorError Extract(ThumbnailExtractorHandle handle, ThumbnailExtractCallback callback, IntPtr userData, out IntPtr requestId); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_set_path")] internal static extern ThumbnailExtractorError SetPath(ThumbnailExtractorHandle handle, string path); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_set_size")] internal static extern ThumbnailExtractorError SetSize(ThumbnailExtractorHandle handle, int width, int height); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_cancel")] internal static extern ThumbnailExtractorError Cancel(ThumbnailExtractorHandle handle, string requestId); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_destroy")] internal static extern ThumbnailExtractorError Destroy(IntPtr handle); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_extract_to_buffer")] internal static extern ThumbnailExtractorError ExtractToBuffer(string path, uint width, uint height, out IntPtr thumbData, out int dataSize, out uint thumbWidth, out uint thumbHeight); [DllImport(Libraries.ThumbnailExtractor, EntryPoint = "thumbnail_util_extract_to_file")] internal static extern ThumbnailExtractorError ExtractToFile(string path, uint width, uint height, string thumbPath); } internal class ThumbnailExtractorHandle : CriticalHandle { protected ThumbnailExtractorHandle() : base(IntPtr.Zero) { } public override bool IsInvalid => handle == IntPtr.Zero; protected override bool ReleaseHandle() { var result = ThumbnailExtractor.Destroy(handle); if (result == ThumbnailExtractorError.None) { return true; } Log.Error(GetType().Name, $"Failed to destroy handle : {result}"); return false; } } }
42.9125
130
0.733761
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
src/Tizen.Multimedia.Util/Interop/Interop.ThumbnailExtractor.cs
3,433
C#
#pragma warning disable CS1591 namespace Elements.Geometry.Profiles { public enum SHSProfileType { SHS50xs00x1_6, SHS50xs00x2, SHS50xs00x2_3, SHS50xs00x2_5, SHS50xs00x3, SHS50xs00x3_2, SHS50xs00x4, SHS50xs00x4_5, SHS50xs00x5, SHS50xs00x6, SHS60xs00x1_6, SHS60xs00x2, SHS60xs00x2_3, SHS60xs00x2_5, SHS60xs00x3, SHS60xs00x3_2, SHS60xs00x4, SHS60xs00x4_5, SHS60xs00x5, SHS60xs00x6, SHS75xs00x1_6, SHS75xs00x2, SHS75xs00x2_3, SHS75xs00x2_5, SHS75xs00x3, SHS75xs00x3_2, SHS75xs00x4, SHS75xs00x4_5, SHS75xs00x5, SHS75xs00x6, SHS75xs00x6_3, SHS75xs00x8, SHS80xs00x1_6, SHS80xs00x2, SHS80xs00x2_3, SHS80xs00x2_5, SHS80xs00x3, SHS80xs00x3_2, SHS80xs00x4, SHS80xs00x4_5, SHS80xs00x5, SHS80xs00x6, SHS80xs00x6_3, SHS80xs00x8, SHS90xs00x2_3, SHS90xs00x2_5, SHS90xs00x3, SHS90xs00x3_2, SHS90xs00x4, SHS90xs00x4_5, SHS90xs00x5, SHS90xs00x6, SHS90xs00x6_3, SHS100xs00x1_6, SHS100xs00x2, SHS100xs00x2_3, SHS100xs00x2_5, SHS100xs00x3, SHS100xs00x3_2, SHS100xs00x4, SHS100xs00x4_5, SHS100xs00x5, SHS100xs00x6, SHS100xs00x6_3, SHS100xs00x8, SHS100xs00x9, SHS100xs00x10, SHS100xs00x12, SHS120xs00x6, SHS120xs00x6_3, SHS120xs00x8, SHS120xs00x9, SHS120xs00x10, SHS120xs00x12, SHS125xs00x2_3, SHS125xs00x2_5, SHS125xs00x3, SHS125xs00x3_2, SHS125xs00x4, SHS125xs00x4_5, SHS125xs00x5, SHS125xs00x6, SHS125xs00x6_3, SHS125xs00x8, SHS125xs00x9, SHS125xs00x10, SHS125xs00x12, SHS125xs00x12_5, SHS150xs00x3_2, SHS150xs00x4, SHS150xs00x4_5, SHS150xs00x5, SHS150xs00x6, SHS150xs00x6_3, SHS150xs00x8, SHS150xs00x9, SHS150xs00x10, SHS150xs00x12, SHS150xs00x12_5, SHS175xs00x4_5, SHS175xs00x5, SHS175xs00x6, SHS175xs00x6_3, SHS175xs00x8, SHS175xs00x9, SHS175xs00x10, SHS175xs00x12, SHS175xs00x12_5, SHS200xs00x4_5, SHS200xs00x5, SHS200xs00x6, SHS200xs00x6_3, SHS200xs00x8, SHS200xs00x9, SHS200xs00x10, SHS200xs00x12, SHS200xs00x12_5, SHS200xs00x16, SHS250xs00x6, SHS250xs00x6_3, SHS250xs00x8, SHS250xs00x9, SHS250xs00x10, SHS250xs00x12, SHS250xs00x12_5, SHS250xs00x16, SHS250xs00x19, SHS300xs00x6, SHS300xs00x6_3, SHS300xs00x8, SHS300xs00x9, SHS300xs00x10, SHS300xs00x12, SHS300xs00x12_5, SHS300xs00x16, SHS300xs00x19, SHS350xs00x9, SHS350xs00x10, SHS350xs00x12, SHS350xs00x12_5, SHS350xs00x16, SHS350xs00x19, SHS350xs00x22, SHS400xs00x9, SHS400xs00x10, SHS400xs00x12, SHS400xs00x12_5, SHS400xs00x16, SHS400xs00x19, SHS400xs00x22, SHS450xs00x9, SHS450xs00x10, SHS450xs00x12, SHS450xs00x12_5, SHS450xs00x16, SHS450xs00x19, SHS450xs00x22, SHS500xs00x9, SHS500xs00x10, SHS500xs00x12, SHS500xs00x12_5, SHS500xs00x16, SHS500xs00x19, SHS500xs00x22, SHS550xs00x12, SHS550xs00x12_5, SHS550xs00x16, SHS550xs00x19, SHS550xs00x22 } }
22.454545
36
0.564777
[ "MIT" ]
Autonomation/Elements
Elements/src/Geometry/Profiles/SHSProfileType.cs
3,952
C#
using System; using System.Runtime.InteropServices; using System.Text; namespace Millarow.Win32.User32 { internal static class User32Native { private const string LibraryFileName = "user32.dll"; [DllImport(LibraryFileName, SetLastError = true)] public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport(LibraryFileName, SetLastError = true)] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); [DllImport(LibraryFileName, CharSet = CharSet.Auto)] public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport(LibraryFileName)] public static extern int GetWindowText(IntPtr hWnd, [MarshalAs(UnmanagedType.BStr)] StringBuilder text, int count); [DllImport(LibraryFileName, ExactSpelling = true, SetLastError = true)] public static extern int ScrollWindowEx(IntPtr hWnd, int nXAmount, int nYAmount, IntPtr prcScroll, IntPtr prcRectClip, IntPtr hrgnUpdate, IntPtr prcUpdate, int flags); //add all ExactSpelling = true, [DllImport(LibraryFileName, SetLastError = true)] public static extern IntPtr GetForegroundWindow(); [DllImport(LibraryFileName, SetLastError = true)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport(LibraryFileName, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport(LibraryFileName, SetLastError = true)] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); [DllImport(LibraryFileName, SetLastError = true)] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport(LibraryFileName, SetLastError = true)] public static extern int PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport(LibraryFileName, SetLastError = true)] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); } }
45.1875
176
0.704011
[ "MIT" ]
mcculic/millarowframework
src/Millarow.Win32/User32/User32Native.cs
2,171
C#
using System; using System.Threading.Tasks; namespace Steepshot.Core.Services { public interface ILogService { Task Fatal(Exception ex); Task Error(Exception ex); Task Warning(Exception ex); Task Info(Exception ex); } }
16.75
35
0.645522
[ "MIT" ]
Chainers/steepshot-mobile
Sources/Steepshot/Steepshot.Core/Services/ILogService.cs
270
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using VendingMachine.Core.Models; using VendingMachine.DAL.Data; using VendingMachine.DAL.Entities; using VendingMachine.DAL.Repositories; using Xunit; namespace VendingMachine.Tests.VM.DAL { public class UserDepositRepositoryTests { [Fact] public void AddAmountDepositAsyncTest() { var options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase($"db-{Guid.NewGuid()}") .Options; // Run the test against one instance of the context using (var context = new ApplicationDbContext(options)) { var userId = InitUser(context); var userDepositRepository = new UserDepositRepository(context); userDepositRepository.AddAmountDepositAsync((int)TypeCoin.Price10Rub, userId).GetAwaiter().GetResult(); Assert.Equal(10, userDepositRepository.GetAmountDepositAsync(userId).GetAwaiter().GetResult()); } } [Fact] public void RetrieveDepositAsyncTest() { var options = new DbContextOptionsBuilder<ApplicationDbContext>() .UseInMemoryDatabase($"db-{Guid.NewGuid()}") .Options; // Run the test against one instance of the context using (var context = new ApplicationDbContext(options)) { var userId = InitUser(context); var userDepositRepository = new UserDepositRepository(context); userDepositRepository.AddAmountDepositAsync((int)TypeCoin.Price1Rub, userId).GetAwaiter().GetResult(); userDepositRepository.RetrieveDepositAsync(userId).GetAwaiter().GetResult(); Assert.Equal(0, userDepositRepository.GetAmountDepositAsync(userId).GetAwaiter().GetResult()); } } private Guid InitUser(ApplicationDbContext context) { // new user and purse var user = new User { UserName = "testuser@testuser.com", Email = "testuser@testuser.com", Purse = new Purse { PurseCoins = new List<PurseCoin> { new PurseCoin { TypeCoin = TypeCoin.Price1Rub, Count = 10 }, new PurseCoin { TypeCoin = TypeCoin.Price2Rub, Count = 30 }, new PurseCoin { TypeCoin = TypeCoin.Price5Rub, Count = 20 }, new PurseCoin { TypeCoin = TypeCoin.Price10Rub, Count = 15 } } } }; context.Users.Add(user); context.SaveChanges(); return user.Id; } } }
37.051948
119
0.581143
[ "MIT" ]
alexey-gorshkov/VendingMachineWebAPIAngular
VendingMachine.Tests/VM.DAL/UserDepositRepositoryTests.cs
2,853
C#
using GrEmit.InstructionParameters; namespace GrEmit.StackMutators { internal class SwitchStackMutator : StackMutator { public override void Mutate(GroboIL il, ILInstructionParameter parameter, ref EvaluationStack stack) { var labels = ((LabelsILInstructionParameter)parameter).Labels; CheckNotEmpty(il, stack, () => "A value must be put onto the evaluation stack in order to perform the 'switch' instruction"); CheckNotStruct(il, stack.Pop()); foreach (var label in labels) SaveOrCheck(il, stack, label); } } }
38.25
137
0.661765
[ "MIT" ]
JTOne123/gremit
GrEmit/StackMutators/SwitchStackMutator.cs
612
C#
using Dapper; using System; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.WebSockets; namespace Server.Data { public class DapperDb { public static void Main(string[] args) { using var connection = new SqlConnection("Server=.;Database=DapperDB;Trusted_Connection=True"); connection.Open(); } public static string Login(SqlConnection connection, string username, string password) { var resultAsArray = connection.Query<User>($"select * from Users where UserName = '{username}'").ToArray(); if (resultAsArray.Length==0) { return "User doesn't exist"; } else { if (resultAsArray[0].Password != password) { return "Wrong Password"; } } return "Successfull login"; } public static string Register(SqlConnection connection, string username, string password) { var checkIfUsernameAlreadyExist = connection.Query<User>($"select * from Users where UserName = '{username}'").ToArray(); if (checkIfUsernameAlreadyExist.Length != 0) { return "Username is not available"; } else { var insertQuery = $@"INSERT INTO Users (UserName, Password) VALUES (@username,@password)"; var newUser = new User() { Username = username, Password = password }; var success = connection.Execute(insertQuery, newUser); if (success==1) { return "User successfully created"; } else { return "Unexpected error ocurred - please try again"; } } } } }
29.560606
133
0.519733
[ "MIT" ]
Drakojan/SoftUni_C-_Web_Basics
Exercise_1_simple_web_server/Server.Data/DapperDb.cs
1,953
C#
#nullable disable using System; using System.Collections.Generic; using System.Linq; using VocaDb.Model.Database.Repositories; using VocaDb.Model.Domain; using VocaDb.Model.Domain.Albums; using VocaDb.Model.Domain.Artists; using VocaDb.Model.Domain.ExtLinks; using VocaDb.Model.Domain.Globalization; using VocaDb.Model.Service.Helpers; using VocaDb.Model.Service.Search; namespace VocaDb.Model.Service.QueryableExtensions { public static class AlbumQueryableExtensions { #nullable enable public static IQueryable<Album> OrderByReleaseDate(this IQueryable<Album> query, SortDirection direction) { return query .OrderBy(a => a.OriginalRelease.ReleaseDate.Year, direction) .ThenBy(a => a.OriginalRelease.ReleaseDate.Month, direction) .ThenBy(a => a.OriginalRelease.ReleaseDate.Day, direction); } public static IQueryable<Album> OrderBy(this IQueryable<Album> criteria, AlbumSortRule sortRule, ContentLanguagePreference languagePreference) => sortRule switch { AlbumSortRule.Name => FindHelpers.AddNameOrder(criteria, languagePreference), AlbumSortRule.CollectionCount => criteria.OrderByDescending(a => a.UserCollections.Count), AlbumSortRule.ReleaseDate => criteria.OrderByReleaseDate(SortDirection.Descending), AlbumSortRule.ReleaseDateWithNulls => criteria.OrderByReleaseDate(SortDirection.Descending), AlbumSortRule.AdditionDate => criteria.OrderByDescending(a => a.CreateDate), AlbumSortRule.RatingAverage => criteria.OrderByDescending(a => a.RatingAverageInt).ThenByDescending(a => a.RatingCount), AlbumSortRule.RatingTotal => criteria.OrderByDescending(a => a.RatingTotal).ThenByDescending(a => a.RatingAverageInt), AlbumSortRule.NameThenReleaseDate => FindHelpers.AddNameOrder(criteria, languagePreference).ThenBy(a => a.OriginalRelease.ReleaseDate.Year).ThenBy(a => a.OriginalRelease.ReleaseDate.Month).ThenBy(a => a.OriginalRelease.ReleaseDate.Day), _ => criteria, }; public static IQueryable<Album> OrderBy( this IQueryable<Album> query, EntrySortRule sortRule, ContentLanguagePreference languagePreference, SortDirection? direction) => sortRule switch { EntrySortRule.Name => FindHelpers.AddNameOrder(query, languagePreference), EntrySortRule.AdditionDate => query.OrderByDescending(a => a.CreateDate), EntrySortRule.ActivityDate => query.OrderByReleaseDate(direction ?? SortDirection.Descending), _ => query, }; public static IQueryable<Album> WhereArtistHasType(this IQueryable<Album> query, ArtistType artistType) { return query.WhereArtistHasType<Album, ArtistForAlbum>(artistType); } public static IQueryable<Album> WhereDraftsOnly(this IQueryable<Album> query, bool draftsOnly) { if (!draftsOnly) return query; return query.Where(a => a.Status == EntryStatus.Draft); } public static IQueryable<Album> WhereHasArtist(this IQueryable<Album> query, int artistId) { if (artistId == 0) return query; return query.WhereHasArtist<Album, ArtistForAlbum>(artistId, false, false); } #nullable disable public static IQueryable<Album> WhereHasArtistParticipationStatus( this IQueryable<Album> query, ArtistParticipationQueryParams queryParams, EntryIdsCollection artistIds, IEntityLoader<Artist> artistGetter) { var various = Model.Helpers.ArtistHelper.VariousArtists; var producerRoles = ArtistRoles.Composer | ArtistRoles.Arranger; var artistId = artistIds.Primary; return EntryWithArtistsQueryableExtensions.WhereHasArtistParticipationStatus(new ArtistParticipationQueryParams<Album, ArtistForAlbum>(query, queryParams, artistIds, artistGetter, al => al.AllArtists.Any(a => a.Artist.Id == artistId && !a.IsSupport && ((a.Roles == ArtistRoles.Default) || ((a.Roles & producerRoles) != ArtistRoles.Default)) && a.Album.ArtistString.Default != various), al => al.AllArtists.Any(a => a.Artist.Id == artistId && (a.IsSupport || ((a.Roles != ArtistRoles.Default) && ((a.Roles & producerRoles) == ArtistRoles.Default)) || a.Album.ArtistString.Default == various)) )); } #nullable enable public static IQueryable<Album> WhereHasBarcode(this IQueryable<Album> query, string? barcode) { if (string.IsNullOrEmpty(barcode)) return query; return query.Where(a => a.Identifiers.Any(i => i.Value == barcode)); } public static IQueryable<Album> WhereHasLinkWithCategory(this IQueryable<Album> query, WebLinkCategory category) { return query.Where(m => m.WebLinks.Any(l => l.Category == category)); } /// <summary> /// Filters an artist query by a name query. /// </summary> /// <param name="query">Artist query. Cannot be null.</param> /// <param name="nameFilter">Name filter string. If null or empty, no filtering is done.</param> /// <param name="matchMode">Desired mode for matching names.</param> /// <param name="words"> /// List of words for the words search mode. /// Can be null, in which case the words list will be parsed from <paramref name="nameFilter"/>. /// </param> /// <returns>Filtered query. Cannot be null.</returns> public static IQueryable<Album> WhereHasName(this IQueryable<Album> query, SearchTextQuery textQuery, bool allowCatNum = false) { if (textQuery.IsEmpty) return query; var nameFilter = textQuery.Query; var expression = EntryWithNamesQueryableExtensions.WhereHasNameExpression<Album, AlbumName>(textQuery); if (allowCatNum) { expression = expression.Or(q => q.OriginalRelease.CatNum != null && q.OriginalRelease.CatNum.Contains(nameFilter)); } return query.Where(expression); } public static IQueryable<Album> WhereHasReleaseDate(this IQueryable<Album> criteria) { return criteria.Where(a => a.OriginalRelease.ReleaseDate.Year != null && a.OriginalRelease.ReleaseDate.Month != null && a.OriginalRelease.ReleaseDate.Day != null); } public static IQueryable<Album> WhereHasReleaseYear(this IQueryable<Album> criteria) { return criteria.Where(a => a.OriginalRelease.ReleaseDate.Year != null); } public static IQueryable<Album> WhereHasTag(this IQueryable<Album> query, string? tagName) { return query.WhereHasTag<Album, AlbumTagUsage>(tagName); } public static IQueryable<Album> WhereHasTags(this IQueryable<Album> query, string[]? tagName) { return query.WhereHasTags<Album, AlbumTagUsage>(tagName); } public static IQueryable<Album> WhereHasTags(this IQueryable<Album> query, int[]? tagId, bool childTags = false) { return query.WhereHasTags<Album, AlbumTagUsage>(tagId, childTags); } public static IQueryable<Album> WhereHasType(this IQueryable<Album> query, DiscType albumType) { if (albumType == DiscType.Unknown) return query; return query.Where(m => m.DiscType == albumType); } public static IQueryable<Album> WhereMatchFilter(this IQueryable<Album> query, AdvancedSearchFilter filter) { switch (filter.FilterType) { case AdvancedFilterType.ArtistType: { var param = EnumVal<ArtistType>.Parse(filter.Param); return WhereArtistHasType(query, param); } case AdvancedFilterType.NoCoverPicture: { return query.Where(a => a.CoverPictureMime == null || a.CoverPictureMime == string.Empty); } case AdvancedFilterType.HasStoreLink: { return query.WhereHasLinkWithCategory(WebLinkCategory.Commercial); } case AdvancedFilterType.HasTracks: { return query.Where(a => filter.Negate != a.AllSongs.Any(s => s.Song == null || !s.Song.Deleted)); } case AdvancedFilterType.WebLink: { return query.WhereHasLink<Album, AlbumWebLink>(filter.Param); } } return query; } public static IQueryable<Album> WhereMatchFilters(this IQueryable<Album> query, IEnumerable<AdvancedSearchFilter>? filters) { return filters?.Aggregate(query, WhereMatchFilter) ?? query; } public static IQueryable<Album> WhereReleaseDateIsAfter(this IQueryable<Album> query, DateTime? beginDateNullable) { if (!beginDateNullable.HasValue) return query; var beginDate = beginDateNullable.Value; return query.Where(a => a.OriginalRelease.ReleaseDate.Year > beginDate.Year || (a.OriginalRelease.ReleaseDate.Year == beginDate.Year && a.OriginalRelease.ReleaseDate.Month > beginDate.Month) || (a.OriginalRelease.ReleaseDate.Year == beginDate.Year && a.OriginalRelease.ReleaseDate.Month == beginDate.Month && a.OriginalRelease.ReleaseDate.Day >= beginDate.Day)); } public static IQueryable<Album> WhereReleaseDateIsBefore(this IQueryable<Album> query, DateTime? endDateNullable) { if (!endDateNullable.HasValue) return query; var endDate = endDateNullable.Value; return query.Where(a => a.OriginalRelease.ReleaseDate.Year < endDate.Year || (a.OriginalRelease.ReleaseDate.Year == endDate.Year && a.OriginalRelease.ReleaseDate.Month < endDate.Month) || (a.OriginalRelease.ReleaseDate.Year == endDate.Year && a.OriginalRelease.ReleaseDate.Month == endDate.Month && a.OriginalRelease.ReleaseDate.Day < endDate.Day)); } /// <summary> /// Makes sure that the query is filtered by restrictions of the sort rule. /// This can be used to separate the filtering from the actual sorting, when sorting is not needed (for example, only count is needed). /// </summary> public static IQueryable<Album> WhereSortBy(this IQueryable<Album> query, AlbumSortRule sort) => sort switch { AlbumSortRule.ReleaseDate => query.WhereHasReleaseYear(), _ => query, }; #nullable disable } }
40.778243
240
0.723579
[ "MIT" ]
AgFlore/vocadb
VocaDbModel/Service/QueryableExtensions/AlbumQueryableExtensions.cs
9,746
C#
using System; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using NBitcoin.DataEncoders; using Newtonsoft.Json.Linq; using Xunit; using System.IO; namespace BTCPayServer.Tests { /// <summary> /// This class hold easy to run utilities for dev time /// </summary> public class UtilitiesTests { /// <summary> /// Download transifex transactions and put them in BTCPayServer\wwwroot\locales /// </summary> [Trait("Utilities", "Utilities")] [Fact] public async Task PullTransifexTranslations() { // 1. Generate an API Token on https://www.transifex.com/user/settings/api/ // 2. Run "dotnet user-secrets set TransifexAPIToken <youapitoken>" var client = new TransifexClient(GetTransifexAPIToken()); var json = await client.GetTransifexAsync("https://api.transifex.com/organizations/btcpayserver/projects/btcpayserver/resources/enjson/"); var langs = ((JObject)json["stats"]).Properties().Select(n => n.Name).ToArray(); var langsDir = Path.Combine(Services.LanguageService.TryGetSolutionDirectoryInfo().FullName, "BTCPayServer", "wwwroot", "locales"); Task.WaitAll(langs.Select(async l => { if (l == "no") return; var j = await client.GetTransifexAsync($"https://www.transifex.com/api/2/project/btcpayserver/resource/enjson/translation/{l}/"); var content = j["content"].Value<string>(); if (l == "en_US") l = "en"; if (l == "ne_NP") l = "np_NP"; if (l == "zh_CN") l = "zh-SP"; if (l == "kk") l = "kk-KZ"; var langCode = l.Replace("_", "-"); var langFile = Path.Combine(langsDir, langCode + ".json"); var jobj = JObject.Parse(content); jobj["code"] = langCode; if ((string)jobj["currentLanguage"] == "English") return; jobj.AddFirst(new JProperty("NOTICE_WARN", "THIS CODE HAS BEEN AUTOMATICALLY GENERATED FROM TRANSIFEX, IF YOU WISH TO HELP TRANSLATION COME ON THE SLACK http://slack.btcpayserver.org TO REQUEST PERMISSION TO https://www.transifex.com/btcpayserver/btcpayserver/")); content = jobj.ToString(Newtonsoft.Json.Formatting.Indented); File.WriteAllText(Path.Combine(langsDir, langFile), content); }).ToArray()); } private static string GetTransifexAPIToken() { var builder = new ConfigurationBuilder(); builder.AddUserSecrets("AB0AC1DD-9D26-485B-9416-56A33F268117"); var config = builder.Build(); var token = config["TransifexAPIToken"]; Assert.False(token == null, "TransifexAPIToken is not set.\n 1.Generate an API Token on https://www.transifex.com/user/settings/api/ \n 2.Run \"dotnet user-secrets set TransifexAPIToken <youapitoken>\""); return token; } } public class TransifexClient { public TransifexClient(string apiToken) { Client = new HttpClient(); APIToken = apiToken; } public HttpClient Client { get; } public string APIToken { get; } public async Task<JObject> GetTransifexAsync(string uri) { var message = new HttpRequestMessage(HttpMethod.Get, uri); message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Encoders.Base64.EncodeData(Encoding.ASCII.GetBytes($"api:{APIToken}"))); message.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var response = await Client.SendAsync(message); return await response.Content.ReadAsAsync<JObject>(); } } }
43.606383
280
0.604782
[ "MIT" ]
Deimoscoin/btcpayserver
BTCPayServer.Tests/UtilitiesTests.cs
4,101
C#
namespace Hexure { public interface IAggregateRoot<out TIdentifier> { TIdentifier Id { get; } } }
16.857143
52
0.627119
[ "MIT" ]
sygnowskip/modular-monolith
Source/Hexure/IAggregateRoot.cs
120
C#
using Multichat_Client.API; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Multichat_Client { class Program { static void Main(string[] args) { ClientAPI client = new ClientAPI(); client.Say(); Console.ReadKey(); } } }
18.6
47
0.61828
[ "BSD-3-Clause" ]
OlehMarchenko95/ort_csharp_js
Other solutions/Multichat/Multichat_Client/Program.cs
374
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FalconNet.Sim { public class SimACDefinition : SimMoverDefinition { #if USE_SH_POOLS public: // Overload new/delete to use a SmartHeap pool void *operator new(size_t size) { return MemAllocPtr(gReadInMemPool,size,FALSE); }; void operator delete(void *mem) { if (mem) MemFreePtr(mem); }; #endif // NOTE!!!: This matches the list in digi.h for Maneuver class public enum CombatClass { F4, F5, F14, F15, F16, Mig25, Mig27, A10, Bomber }; public CombatClass combatClass; public SimACDefinition(string fileName) { #if TODO int i; SimlibFileClass* acFile; acFile = SimlibFileClass.Open(fileName, SIMLIB_READ); // What type of combat does it do? combatClass = (CombatClass)atoi(acFile.GetNext()); airframeIndex = atoi(acFile.GetNext()); numPlayerSensors = atoi(acFile.GetNext()); #if USE_SH_POOLS playerSensorData = (int *)MemAllocPtr(gReadInMemPool, sizeof(int)*numPlayerSensors * 2,0); #else playerSensorData = new int[numPlayerSensors * 2]; #endif for (i = 0; i < numPlayerSensors; i++) { playerSensorData[i * 2] = atoi(acFile.GetNext()); playerSensorData[i * 2 + 1] = atoi(acFile.GetNext()); } numSensors = atoi(acFile.GetNext()); #if USE_SH_POOLS sensorData = (int *)MemAllocPtr(gReadInMemPool, sizeof(int)*numSensors * 2,0); #else sensorData = new int[numSensors * 2]; #endif for (i = 0; i < numSensors; i++) { sensorData[i * 2] = atoi(acFile.GetNext()); sensorData[i * 2 + 1] = atoi(acFile.GetNext()); } acFile.Close(); //TODO delete acFile; #endif throw new NotImplementedException(); } // TODO public ~SimACDefinition (void); public int airframeIndex; public int numPlayerSensors; public int[] playerSensorData; } }
29.84507
91
0.598867
[ "MIT" ]
agustinsantos/FalconNet
Sim/AcDef.cs
2,121
C#
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Razor.TagHelpers; using System; using System.Collections.Generic; using LazZiya.TagHelpers.Alerts; using System.Threading.Tasks; using LazZiya.TagHelpers.Utilities; using Microsoft.AspNetCore.Mvc.ViewFeatures; namespace LazZiya.TagHelpers { /// <summary> /// Create alert messages styled with bootstrap 4.x /// Alert contents must be replaced between alert tags e.g. <![CDATA[<alert-success>job done!</alert-success>]]> /// </summary> public class AlertTagHelper : TagHelper { internal AlertStyle AlertStyle { get; set; } = AlertStyle.Primary; /// <summary> /// Header text for the alert /// </summary> public string AlertHeading { get; set; } /// <summary> /// Show closing button, default is true /// </summary> public bool Dismissable { get; set; } = true; /// <summary> /// <para>ViewContext property is not required to be passed as parameter, it will be assigned automatically by the tag helper.</para> /// <para>View context is required to access TempData dictionary that contains the alerts coming from backend</para> /// </summary> [ViewContext] public ViewContext ViewContext { get; set; } = null; /// <summary> /// Create alert messages styled with bootstrap 4.x /// </summary> public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; if (ViewContext != null) { var alerts = ViewContext.TempData.ContainsKey(Alert.TempDataKey) //? JsonConvert.DeserializeObject<List<Alert>>(ViewContext.TempData[Alert.TempDataKey].ToString()) //? (List<Alert>)ViewContext.TempData[Alert.TempDataKey] ? ViewContext.TempData.Get<List<Alert>>(Alert.TempDataKey) : new List<Alert>(); alerts.ForEach(x => output.Content.AppendHtml(AddAlert(x))); ViewContext.TempData.Remove(Alert.TempDataKey); } // read alerts contents from inner html var msg = await output.GetChildContentAsync(); if (!string.IsNullOrWhiteSpace(msg.GetContent())) { var manualAlert = AddAlert(new Alert { AlertHeading = this.AlertHeading, AlertMessage = msg.GetContent(), AlertStyle = this.AlertStyle, Dismissable = this.Dismissable }); output.Content.AppendHtml(manualAlert); } } private TagBuilder AddAlert(Alert alert) { var _alert = new TagBuilder("div"); var alertStyle = Enum.GetName(typeof(AlertStyle), alert.AlertStyle).ToLower(); _alert.AddCssClass($"alert alert-{alertStyle}"); _alert.Attributes.Add("role", "alert"); if (alert.Dismissable) { _alert.InnerHtml.AppendHtml("<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>"); } if (!string.IsNullOrWhiteSpace(alert.AlertHeading)) { _alert.InnerHtml.AppendHtml($"<h4 class='alert-heading'>{alert.AlertHeading}</h4>"); } if (!string.IsNullOrWhiteSpace(alert.AlertMessage)) { _alert.InnerHtml.AppendHtml($"<p class='mb-0'>{alert.AlertMessage}</p>"); } return _alert; } } }
36.861386
172
0.585818
[ "MIT" ]
alimon808/TagHelpers
LazZiya.TagHelpers/AlertTagHelper.cs
3,725
C#
using Codeizi.CQRS.Saga.Context; using Codeizi.CQRS.Saga.Data; using Codeizi.CQRS.Saga.Logs; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Threading.Tasks; namespace Codeizi.CQRS.Saga.DAO { public class SagaLogDAO { private readonly IServiceProvider _serviceProvider; public SagaLogDAO(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task Save(Log log) { var sagaLog = new SagaLog { Created = log.Created, Ended = log.Ended, SagaId = log.SagaId, DataLog = JsonConvert.SerializeObject(log) }; using var context = _serviceProvider.GetRequiredService<SagaContext>(); await context.AddAsync(sagaLog); await context.SaveChangesAsync(); } } }
27.085714
83
0.619198
[ "MIT" ]
JDouglasMendes/codeizi-cqrs-saga
src/Codeizi.CQRS.Saga/DAO/SagaLogDAO.cs
950
C#
// Copyright (c) Lex Li. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.ComponentModel; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Xml; namespace Microsoft.Web.Administration { public sealed class Binding : ConfigurationElement { private IPEndPoint _endPoint; private string _host; private bool _initialized; public Binding(ConfigurationElement element, BindingCollection parent) : base(element, "binding", null, parent, null, null) { Parent = parent; } internal Binding(string protocol, string bindingInformation, byte[] hash, string store, SslFlags flags, BindingCollection parent) : base(null, "binding", null, parent, null, null) { BindingInformation = bindingInformation; Protocol = protocol; CertificateHash = hash; CertificateStoreName = store; if (parent.Parent.Server.SupportsSni) { SslFlags = flags; } Parent = parent; } public override string ToString() { return EndPoint == null ? BindingInformation : $"{EndPoint.Address.AddressToDisplay()}:{EndPoint.Port}:{Host.HostToDisplay()}"; } public string BindingInformation { get { Initialize(); return (string)this["bindingInformation"]; } set { this["bindingInformation"] = value; _initialized = false; } } private void Initialize() { if (_initialized) { return; } _initialized = true; if (!CanBrowse) { _host = string.Empty; _endPoint = null; return; } var value = (string)this["bindingInformation"]; var last = value.LastIndexOf(':'); if (last > 0) { _host = value.Substring(last + 1); var next = value.LastIndexOf(':', last - 1); var port = value.Substring(next + 1, last - next - 1); if (next > -1) { var address = value.Substring(0, next); if (PortIsValid(port, out int number, null, false)) { try { _endPoint = new IPEndPoint(address.DisplayToAddress(), number); } catch (FormatException) { } } } } if (Protocol != "https" || CertificateHash != null) { return; } if (Helper.IsRunningOnMono()) { // TODO: how to do it on Mono? return; } RefreshCertificate(); } public byte[] CertificateHash { get; set; } public string CertificateStoreName { get; set; } public IPEndPoint EndPoint { get { Initialize(); return _endPoint; } } public string Host { get { Initialize(); return _host; } } // ReSharper disable once InconsistentNaming public bool IsIPPortHostBinding { get; internal set; } public string Protocol { get { Initialize(); return (string)this["protocol"]; } set { this["protocol"] = value; _initialized = false; } } public SslFlags SslFlags { get { Initialize(); if (ContainsAttribute("sslFlags")) { if (RawAttributes.ContainsKey("sslFlags")) { try { var input = RawAttributes["sslFlags"]; var result = Enum.Parse(typeof(SslFlags), input); return (SslFlags)result; } catch { throw new COMException($"Filename: \\\\?\\{FileContext.FileName}\r\nLine number: {(Entity as IXmlLineInfo).LineNumber}\r\nError: The 'sslFlags' attribute is invalid. Not a valid unsigned integer\r\n\r\n\r\n"); } } } return SslFlags.None; } set { if (ContainsAttribute("sslFlags")) { this["sslFlags"] = (uint)value; _initialized = false; } } } public bool UseDsMapper { get; set; } internal BindingCollection Parent { get; } internal string ToUri() { var value = BindingInformation; var last = value.LastIndexOf(':'); string host = null; string address = null; string port = null; if (last > 0) { host = value.Substring(last + 1); var next = value.LastIndexOf(':', last - 1); port = value.Substring(next + 1, last - next - 1); if (next > -1) { address = value.Substring(0, next); } } string domain; if (EndPoint == null) { if (string.IsNullOrWhiteSpace(port)) { domain = "localhost"; } else if (PortIsValid(port, out int validPort, null, false)) { domain = $"localhost:{validPort}"; } else { throw new ArgumentException("Value does not fall within the expected range."); } return $"{Protocol}://{domain}"; } domain = address == "*" || address == "0.0.0.0" ? Parent.Parent.Parent.Parent.HostName.ExtractName() : string.IsNullOrWhiteSpace(host) ? address : Host; return IsDefaultPort ? $"{Protocol}://{domain}" : $"{Protocol}://{domain}:{EndPoint.Port}"; } internal string ToIisUrl() { return ToUri() + "/"; } private bool IsDefaultPort { get { if (EndPoint == null) { return true; } if (Protocol == "http") { return EndPoint.Port == 80; } if (Protocol == "https") { return EndPoint.Port == 443; } return false; } } internal bool CanBrowse => Protocol == "http" || Protocol == "https"; internal bool DetectConflicts() { if (SslFlags == SslFlags.Sni) { var sni = NativeMethods.QuerySslSniInfo(new Tuple<string, int>(_host, _endPoint.Port)); return sni != null; // true if detect existing SNI mapping. } var certificate = NativeMethods.QuerySslCertificateInfo(_endPoint); return certificate != null; // true if detect existing IP mapping. } internal bool GetIsSni() { if (!ContainsAttribute("sslFlags")) { return false; } var value = this["sslFlags"]; return ((uint)value & 1U) == 1U; } public void RefreshCertificate() { if (Parent.Parent.Server.SupportsSni) { if (GetIsSni()) { try { var sni = NativeMethods.QuerySslSniInfo(new Tuple<string, int>(_host, _endPoint.Port)); if (sni == null) { CertificateHash = null; CertificateStoreName = string.Empty; SslFlags = SslFlags.Sni; return; } else { CertificateHash = sni.Hash; CertificateStoreName = sni.StoreName; SslFlags = SslFlags.Sni; return; } } catch (Win32Exception) { CertificateHash = null; CertificateStoreName = string.Empty; SslFlags = SslFlags.Sni; return; } } } if (_endPoint == null) { CertificateHash = null; CertificateStoreName = string.Empty; return; } var certificate = NativeMethods.QuerySslCertificateInfo(_endPoint); if (certificate == null) { CertificateHash = null; CertificateStoreName = string.Empty; return; } CertificateHash = certificate.Hash; CertificateStoreName = certificate.StoreName; } internal static bool PortIsValid(string portText, out int port, string text, bool showDialog = true) { const string theServerPortNumberMustBeAPositiveIntegerBetweenAnd = "The server port number must be a positive integer between 1 and 65535"; try { port = int.Parse(portText); } catch (Exception) { if (showDialog) { MessageBox.Show(theServerPortNumberMustBeAPositiveIntegerBetweenAnd, text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } port = 0; return false; } if (port < 1 || port > 65535) { if (showDialog) { MessageBox.Show(theServerPortNumberMustBeAPositiveIntegerBetweenAnd, text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return false; } return true; } } }
29.637566
238
0.429349
[ "MIT" ]
jexuswebserver/JexusManager
Microsoft.Web.Administration/Binding.cs
11,205
C#
using Git.Services; using Git.ViewModels.Users; using SUS.HTTP; using SUS.MvcFramework; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; namespace Git.Controllers { public class UsersController : Controller { private readonly IUsersService usersService; public UsersController(IUsersService userService) { this.usersService = userService; } public HttpResponse Login() { if (this.IsUserSignedIn()) { return this.Redirect("/Repositories/All"); } return this.View(); } [HttpPost] public HttpResponse Login(LoginInputModel input) { if (this.IsUserSignedIn()) { return this.Redirect("/Repositories/All"); } var userId = this.usersService.GetUserId(input.Username, input.Password); if (userId == null) { return this.Error("Invalid username or password."); } this.SignIn(userId); return this.Redirect("/Repositories/All"); } public HttpResponse Register() { if (this.IsUserSignedIn()) { return this.Redirect("/Repositories/All"); } return this.View(); } [HttpPost] public HttpResponse Register(RegisterInputModel input) { if (this.IsUserSignedIn()) { return this.Redirect("/Repositories/All"); } //username validation: if (string.IsNullOrWhiteSpace(input.Username) || input.Username.Length < 5 || input.Username.Length > 20) { return this.Error("Username should be between 5 and 20 characters long."); } if (!this.usersService.IsUsernameAvailable(input.Username)) { return this.Error("Username is already taken."); } if (!Regex.IsMatch(input.Username, @"^[a-zA-Z0-9\._-]+$")) { return this.Error("Invalid username. Only alphanumeric characters, dashes and dots are allowed."); } //password validation: if (string.IsNullOrWhiteSpace(input.Password) || input.Password.Length < 6 || input.Password.Length > 20) { return this.Error("Password should be between 6 and 20 characters long."); } if (input.Password != input.ConfirmPassword) { return this.Error("Passwords do not match."); } //password validation: if (string.IsNullOrWhiteSpace(input.Email) || !new EmailAddressAttribute().IsValid(input.Email)) { return this.Error("Invalid email address."); } if (!this.usersService.IsEmailAvailable(input.Email)) { return this.Error("Email is already taken."); } this.usersService.CreateUser(input.Username, input.Email, input.Password); return this.Redirect("/Users/Login"); } public HttpResponse Logout() { if (!this.IsUserSignedIn()) { return this.Redirect("/Users/Login"); } this.SignOut(); return this.Redirect("/"); } } }
28.430894
117
0.529597
[ "MIT" ]
Paulina-Dyulgerska/CSharp_Web_Lectures
Exam/Apps/Git/Controllers/UsersController.cs
3,499
C#
using System.Collections.Generic; using System.Dynamic; using System.Linq; using TauCode.Data; namespace TauCode.Db.Data { public class DynamicRow : DynamicObject { private readonly IDictionary<string, object> _values; public DynamicRow(object original = null) { IDictionary<string, object> values; if (original is DynamicRow dynamicRow) { values = new ValueDictionary(dynamicRow.ToDictionary()); } else { values = new ValueDictionary(original); } _values = values; } public IDictionary<string, object> ToDictionary() => _values; public override bool TrySetMember(SetMemberBinder binder, object value) { var name = binder.Name; _values[name] = value; return true; } public override bool TryGetMember(GetMemberBinder binder, out object result) { var name = binder.Name; return _values.TryGetValue(name, out result); } public override IEnumerable<string> GetDynamicMemberNames() => _values.Keys; public string[] GetNames() => this.GetDynamicMemberNames().ToArray(); public void SetValue(string name, object value) { _values[name] = value; } public object GetValue(string name) { return _values[name]; } public bool DeleteValue(string name) { return _values.Remove(name); } public bool IsEquivalentTo(object other) { if (other == null) { return false; // no object is equiv. to null } var otherDynamic = new DynamicRow(other); if (_values.Count != otherDynamic._values.Count) { return false; } foreach (var pair in _values) { var key = pair.Key; var value = pair.Value; var otherHas = otherDynamic._values.TryGetValue(key, out var otherValue); if (!otherHas) { return false; } var otherEq = Equals(value, otherValue); if (!otherEq) { return false; } } return true; } } }
25.387755
89
0.509646
[ "Apache-2.0" ]
taucode/taucode.db
src/TauCode.Db/Data/DynamicRow.cs
2,490
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Threading.Tasks; using Microsoft; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.Settings; using Microsoft.VisualStudio.Threading; using Task = System.Threading.Tasks.Task; namespace TameVisualStudioTooltips3 { /// <summary> /// A base class for specifying options /// </summary> internal abstract class TameQuickInfoBaseOptions<T> where T : TameQuickInfoBaseOptions<T>, new() { private static readonly AsyncLazy<T> _liveModel = new AsyncLazy<T>(CreateAsync, ThreadHelper.JoinableTaskFactory); private static readonly AsyncLazy<ShellSettingsManager> _settingsManager = new AsyncLazy<ShellSettingsManager>(GetSettingsManagerAsync, ThreadHelper.JoinableTaskFactory); protected TameQuickInfoBaseOptions() { } /// <summary> /// A singleton instance of the options. MUST be called from UI thread only. /// </summary> /// <remarks> /// Call <see cref="GetLiveInstanceAsync()" /> instead if on a background thread or in an async context on the main thread. /// </remarks> public static T Instance { get { ThreadHelper.ThrowIfNotOnUIThread(); #pragma warning disable VSTHRD102 // Implement internal logic asynchronously return ThreadHelper.JoinableTaskFactory.Run(GetLiveInstanceAsync); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously } } /// <summary> /// Get the singleton instance of the options. Thread safe. /// </summary> public static Task<T> GetLiveInstanceAsync() => _liveModel.GetValueAsync(); /// <summary> /// Creates a new instance of the options class and loads the values from the store. For internal use only /// </summary> /// <returns></returns> public static async Task<T> CreateAsync() { var instance = new T(); await instance.LoadAsync(); return instance; } /// <summary> /// The name of the options collection as stored in the registry. /// </summary> protected virtual string CollectionName { get; } = typeof(T).FullName; /// <summary> /// Hydrates the properties from the registry. /// </summary> public virtual void Load() { #pragma warning disable VSTHRD102 // Implement internal logic asynchronously ThreadHelper.JoinableTaskFactory.Run(LoadAsync); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously } /// <summary> /// Hydrates the properties from the registry asyncronously. /// </summary> public virtual async Task LoadAsync() { ShellSettingsManager manager = await _settingsManager.GetValueAsync(); SettingsStore settingsStore = manager.GetReadOnlySettingsStore(SettingsScope.UserSettings); if (!settingsStore.CollectionExists(CollectionName)) { return; } foreach (PropertyInfo property in GetOptionProperties()) { try { string serializedProp = settingsStore.GetString(CollectionName, property.Name); object value = DeserializeValue(serializedProp, property.PropertyType); property.SetValue(this, value); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); } } } /// <summary> /// Saves the properties to the registry. /// </summary> public virtual void Save() { #pragma warning disable VSTHRD102 // Implement internal logic asynchronously ThreadHelper.JoinableTaskFactory.Run(SaveAsync); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously } /// <summary> /// Saves the properties to the registry asyncronously. /// </summary> public virtual async Task SaveAsync() { ShellSettingsManager manager = await _settingsManager.GetValueAsync(); WritableSettingsStore settingsStore = manager.GetWritableSettingsStore(SettingsScope.UserSettings); if (!settingsStore.CollectionExists(CollectionName)) { settingsStore.CreateCollection(CollectionName); } foreach (PropertyInfo property in GetOptionProperties()) { string output = SerializeValue(property.GetValue(this)); settingsStore.SetString(CollectionName, property.Name, output); } T liveModel = await GetLiveInstanceAsync(); if (this != liveModel) { await liveModel.LoadAsync(); } } /// <summary> /// Serializes an object value to a string using the binary serializer. /// </summary> protected virtual string SerializeValue(object value) { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, value); stream.Flush(); return Convert.ToBase64String(stream.ToArray()); } } /// <summary> /// Deserializes a string to an object using the binary serializer. /// </summary> protected virtual object DeserializeValue(string value, Type type) { byte[] b = Convert.FromBase64String(value); using (var stream = new MemoryStream(b)) { var formatter = new BinaryFormatter(); return formatter.Deserialize(stream); } } private static async Task<ShellSettingsManager> GetSettingsManagerAsync() { #pragma warning disable VSTHRD010 // False-positive in Threading Analyzers. Bug tracked here https://github.com/Microsoft/vs-threading/issues/230 var svc = await AsyncServiceProvider.GlobalProvider.GetServiceAsync(typeof(SVsSettingsManager)) as IVsSettingsManager; #pragma warning restore VSTHRD010 Assumes.Present(svc); return new ShellSettingsManager(svc); } private IEnumerable<PropertyInfo> GetOptionProperties() { return GetType() .GetProperties() .Where(p => p.PropertyType.IsSerializable && p.PropertyType.IsPublic); } } }
30.082902
125
0.732001
[ "Apache-2.0" ]
VictorLoktev/TameVisualStudioTooltips
TameVisualStudioTooltips/TameQuickInfoBaseOptions.cs
5,808
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using StackExchange.Redis; namespace Tests.Issues { [TestFixture] public class SO10825542 { [Test] public void Execute() { using (var muxer = Config.GetUnsecuredConnection()) { var key = "somekey1"; var con = muxer.GetDatabase(1); // set the field value and expiration con.HashSetAsync(key, "field1", Encoding.UTF8.GetBytes("hello world")); con.KeyExpireAsync(key, TimeSpan.FromSeconds(7200)); con.HashSetAsync(key, "field2", "fooobar"); var task = con.HashGetAllAsync(key); con.Wait(task); Assert.AreEqual(2, task.Result.Length); var dict = task.Result.ToStringDictionary(); Assert.AreEqual("hello world", dict["field1"]); Assert.AreEqual("fooobar", dict["field2"]); } } } }
30.4
87
0.554511
[ "Apache-2.0" ]
luberg/StackExchange.Redis
MigratedBookSleeveTestSuite/Issues/SO10825542.cs
1,066
C#
// HO=False using System; // using System; using System.Collections.Generic; // using System.Collections.Generic; using System.Linq; // using System.Linq; using System.Text; // using System.Text; // namespace Charlotte // namespace Charlotte { // { public class ScheduleMinorIodineWrapper // public class GameStatus { // { // HO=True public long InvokeDynamicKallichorePackage = 0; // public long Score = 0; // HO=False public static int ToggleSecureDreamHierarchy; // public static int ADM_a_14026783645662981932_06597970294780149309_z_Count_1; // HO=False public int AddPrivatePassionAuthor() // public int ADM_a_00051742138535018211_06321923970168205092_z_NextCount() { // { return RepresentMatchingTrinculoArray++; // return ADM_a_00051742138535018211_06321923970168205092_z_Count++; } // } // HO=False public void MoveEmptyThuliumSoftware(int CopySuccessfulPlutoniumField, int CompareTemporaryTrinculoSetting) // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_02(int ADM_a_00051742138535018211_06321923970168205092_z_a, int ADM_a_00051742138535018211_06321923970168205092_z_b) { // { this.NormalizeMultipleErinomeCollection(CopySuccessfulPlutoniumField, CompareTemporaryTrinculoSetting, this.AddPrivatePassionAuthor()); // this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_03(ADM_a_00051742138535018211_06321923970168205092_z_a, ADM_a_00051742138535018211_06321923970168205092_z_b, this.ADM_a_00051742138535018211_06321923970168205092_z_NextCount()); } // } // HO=False public int TouchGenericCeresAccount() // public int ADM_a_00051742138535018211_06321923970168205092_z_GetCount() { // { return RepresentMatchingTrinculoArray; // return ADM_a_00051742138535018211_06321923970168205092_z_Count; } // } // HO=False public CompileMissingHafniumDeprecation ExistExpectedKalykeMaster() // public ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo ADM_a_00051742138535018211_06321923970168205092_z_GetValue() { // { return RedirectNextFerdinandObject; // return ADM_a_00051742138535018211_06321923970168205092_z_Value; } // } // HO=False public void ExcludeMinorOsmiumPreference() // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_00() { // { this.ProcessMissingCaliforniumCopyright(this.AddPrivatePassionAuthor()); // this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_01(this.ADM_a_00051742138535018211_06321923970168205092_z_NextCount()); } // } // HO=True public int RestoreCompleteBismuthDescriptor = 0; // public int PlayerPower = 0; // HO=False public int RestartStandaloneSpondeException() { return SetStandaloneSodiumAllocation() == 0 ? 0 : ToggleSecureDreamHierarchy; } // public int ADM_a_14026783645662981932_06597970294780149309_z_GetInt_1() { return ADM_a_14026783645662981932_06597970294780149309_z_GetInt_0() == 0 ? 0 : ADM_a_14026783645662981932_06597970294780149309_z_Count_1; } // HO=True public int OutputAlternativeBerryPost = EmitBlankMetisBranch.DecodeActiveCeriumDisk; // public int PlayerZanki = GameConsts.DEFAULT_ZANKI; // HO=False public void AssociateDedicatedYttriumScreen() // public void ADM_a_00051742138535018211_06321923970168205092_z_ResetCount() { // { this.RefreshUnavailableFontainePool(0); // this.ADM_a_00051742138535018211_06321923970168205092_z_SetCount(0); } // } // HO=False public class CompileMissingHafniumDeprecation // public class ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo { // { public int UninstallAutomaticErbiumAuthor; // public int ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_A; public int SupplyOptionalMatadorUsername; // public int ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_B; public int ReloadGlobalOganessonFile; // public int ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_C; } // } // HO=False public void UploadExpectedJarnsaxaForm(CompileMissingHafniumDeprecation CancelUnknownBerylliumOffset) // public void ADM_a_00051742138535018211_06321923970168205092_z_SetValue(ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo ADM_a_00051742138535018211_06321923970168205092_z_SetValue_Prm) { // { RedirectNextFerdinandObject = CancelUnknownBerylliumOffset; // ADM_a_00051742138535018211_06321923970168205092_z_Value = ADM_a_00051742138535018211_06321923970168205092_z_SetValue_Prm; } // } // HO=False public void NormalizeMultipleErinomeCollection(int CopySuccessfulPlutoniumField, int CompareTemporaryTrinculoSetting, int ClickOptionalChocolatBrace) // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_03(int ADM_a_00051742138535018211_06321923970168205092_z_a, int ADM_a_00051742138535018211_06321923970168205092_z_b, int ADM_a_00051742138535018211_06321923970168205092_z_c) { // { this.FormatCleanHoneyDomain(CopySuccessfulPlutoniumField, CompareTemporaryTrinculoSetting, ClickOptionalChocolatBrace, this.ExistExpectedKalykeMaster().UninstallAutomaticErbiumAuthor, this.ExistExpectedKalykeMaster().SupplyOptionalMatadorUsername, this.ExistExpectedKalykeMaster().ReloadGlobalOganessonFile); // this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_04(ADM_a_00051742138535018211_06321923970168205092_z_a, ADM_a_00051742138535018211_06321923970168205092_z_b, ADM_a_00051742138535018211_06321923970168205092_z_c, this.ADM_a_00051742138535018211_06321923970168205092_z_GetValue().ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_A, this.ADM_a_00051742138535018211_06321923970168205092_z_GetValue().ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_B, this.ADM_a_00051742138535018211_06321923970168205092_z_GetValue().ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_C); } // } // HO=False public static int InvokeSpecificTelestoStatus; // public static int ADM_a_14026783645662981932_06597970294780149309_z_Count_0; // HO=False public static int RepresentMatchingTrinculoArray; // public static int ADM_a_00051742138535018211_06321923970168205092_z_Count; // HO=False public void FormatCleanHoneyDomain(int CopySuccessfulPlutoniumField, int CompareTemporaryTrinculoSetting, int ClickOptionalChocolatBrace, int DefineLatestPortiaIndex, int FailUnusedRhodiumWindow, int UploadCoreMarchArea) // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_04(int ADM_a_00051742138535018211_06321923970168205092_z_a, int ADM_a_00051742138535018211_06321923970168205092_z_b, int ADM_a_00051742138535018211_06321923970168205092_z_c, int ADM_a_00051742138535018211_06321923970168205092_z_a2, int ADM_a_00051742138535018211_06321923970168205092_z_b2, int ADM_a_00051742138535018211_06321923970168205092_z_c2) { // { var SupplyUnauthorizedErriapusTermination = new[] // var ADM_a_00051742138535018211_06321923970168205092_z_infos = new[] { // { new { PreviewAccessiblePeachCertificate = CopySuccessfulPlutoniumField, CleanAvailableNeodymiumModel = DefineLatestPortiaIndex }, // new { ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 = ADM_a_00051742138535018211_06321923970168205092_z_a, ADM_a_00051742138535018211_06321923970168205092_z_Info_P2 = ADM_a_00051742138535018211_06321923970168205092_z_a2 }, new { PreviewAccessiblePeachCertificate = CompareTemporaryTrinculoSetting, CleanAvailableNeodymiumModel = DefineLatestPortiaIndex }, // new { ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 = ADM_a_00051742138535018211_06321923970168205092_z_b, ADM_a_00051742138535018211_06321923970168205092_z_Info_P2 = ADM_a_00051742138535018211_06321923970168205092_z_a2 }, new { PreviewAccessiblePeachCertificate = ClickOptionalChocolatBrace, CleanAvailableNeodymiumModel = DefineLatestPortiaIndex }, // new { ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 = ADM_a_00051742138535018211_06321923970168205092_z_c, ADM_a_00051742138535018211_06321923970168205092_z_Info_P2 = ADM_a_00051742138535018211_06321923970168205092_z_a2 }, }; // }; this.UploadExpectedJarnsaxaForm(new CompileMissingHafniumDeprecation() // this.ADM_a_00051742138535018211_06321923970168205092_z_SetValue(new ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo() { // { UninstallAutomaticErbiumAuthor = CopySuccessfulPlutoniumField, // ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_A = ADM_a_00051742138535018211_06321923970168205092_z_a, SupplyOptionalMatadorUsername = CompareTemporaryTrinculoSetting, // ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_B = ADM_a_00051742138535018211_06321923970168205092_z_b, ReloadGlobalOganessonFile = ClickOptionalChocolatBrace, // ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo_C = ADM_a_00051742138535018211_06321923970168205092_z_c, }); // }); if (SupplyUnauthorizedErriapusTermination[0].PreviewAccessiblePeachCertificate == DefineLatestPortiaIndex) this.ConstructEqualAutonoeExport(SupplyUnauthorizedErriapusTermination[0].CleanAvailableNeodymiumModel); // if (ADM_a_00051742138535018211_06321923970168205092_z_infos[0].ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 == ADM_a_00051742138535018211_06321923970168205092_z_a2) this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_05(ADM_a_00051742138535018211_06321923970168205092_z_infos[0].ADM_a_00051742138535018211_06321923970168205092_z_Info_P2); if (SupplyUnauthorizedErriapusTermination[1].PreviewAccessiblePeachCertificate == FailUnusedRhodiumWindow) this.ConstructEqualAutonoeExport(SupplyUnauthorizedErriapusTermination[1].CleanAvailableNeodymiumModel); // if (ADM_a_00051742138535018211_06321923970168205092_z_infos[1].ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 == ADM_a_00051742138535018211_06321923970168205092_z_b2) this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_05(ADM_a_00051742138535018211_06321923970168205092_z_infos[1].ADM_a_00051742138535018211_06321923970168205092_z_Info_P2); if (SupplyUnauthorizedErriapusTermination[2].PreviewAccessiblePeachCertificate == UploadCoreMarchArea) this.ConstructEqualAutonoeExport(SupplyUnauthorizedErriapusTermination[2].CleanAvailableNeodymiumModel); // if (ADM_a_00051742138535018211_06321923970168205092_z_infos[2].ADM_a_00051742138535018211_06321923970168205092_z_Info_P1 == ADM_a_00051742138535018211_06321923970168205092_z_c2) this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_05(ADM_a_00051742138535018211_06321923970168205092_z_infos[2].ADM_a_00051742138535018211_06321923970168205092_z_Info_P2); } // } // HO=False public static CompileMissingHafniumDeprecation RedirectNextFerdinandObject; // public static ADM_a_00051742138535018211_06321923970168205092_z_ValueInfo ADM_a_00051742138535018211_06321923970168205092_z_Value; // HO=True public int SignInnerUranusMethod = EmitBlankMetisBranch.CopyFalseSunsetControl; // public int PlayerZanBomb = GameConsts.DEFAULT_ZAN_BOMB; // HO=False public void ConstructEqualAutonoeExport(int RenameBooleanPandiaLabel) // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_05(int ADM_a_00051742138535018211_06321923970168205092_z_v) { // { if (RenameBooleanPandiaLabel != this.TouchGenericCeresAccount()) // if (ADM_a_00051742138535018211_06321923970168205092_z_v != this.ADM_a_00051742138535018211_06321923970168205092_z_GetCount()) this.RefreshUnavailableFontainePool(RenameBooleanPandiaLabel); // this.ADM_a_00051742138535018211_06321923970168205092_z_SetCount(ADM_a_00051742138535018211_06321923970168205092_z_v); else // else this.ProcessMissingCaliforniumCopyright(RenameBooleanPandiaLabel); // this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_01(ADM_a_00051742138535018211_06321923970168205092_z_v); } // } // HO=False public int SetStandaloneSodiumAllocation() { return InvokeSpecificTelestoStatus; } // public int ADM_a_14026783645662981932_06597970294780149309_z_GetInt_0() { return ADM_a_14026783645662981932_06597970294780149309_z_Count_0; } // HO=False public void ProcessMissingCaliforniumCopyright(int CopySuccessfulPlutoniumField) // public void ADM_a_00051742138535018211_06321923970168205092_z_Overload_01(int ADM_a_00051742138535018211_06321923970168205092_z_a) { // { this.MoveEmptyThuliumSoftware(CopySuccessfulPlutoniumField, this.AddPrivatePassionAuthor()); // this.ADM_a_00051742138535018211_06321923970168205092_z_Overload_02(ADM_a_00051742138535018211_06321923970168205092_z_a, this.ADM_a_00051742138535018211_06321923970168205092_z_NextCount()); } // } // HO=False public void RefreshUnavailableFontainePool(int TerminateUnavailableRubidiumStack) // public void ADM_a_00051742138535018211_06321923970168205092_z_SetCount(int ADM_a_00051742138535018211_06321923970168205092_z_SetCount_Prm) { // { RepresentMatchingTrinculoArray = TerminateUnavailableRubidiumStack; // ADM_a_00051742138535018211_06321923970168205092_z_Count = ADM_a_00051742138535018211_06321923970168205092_z_SetCount_Prm; } // } // HO=False } // } } // }
62.747619
619
0.859452
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_01/tmpsol_mid/Elsa20200001/Games/GameStatus.cs
13,179
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DotJEM.NUnit.Json")] [assembly: AssemblyDescription("NUnit constraints for JSON data")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("N/A")] [assembly: AssemblyProduct("DotJEM.NUnit.Json")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6f61a83-3e43-46f9-87e2-920b8785fe81")] // 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("0.0.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
38.945946
84
0.746704
[ "MIT" ]
dotJEM/json-nunit
DotJEM.NUnit.Json/Properties/AssemblyInfo.cs
1,444
C#
using System.Collections; using System.Collections.Generic; using Microsoft.Maui.Graphics; namespace Microsoft.Maui.DeviceTests.Stubs { public partial class PickerStub : StubBase, IPicker { public string Title { get; set; } public IList<string> Items { get; set; } = new List<string>(); public IList ItemsSource { get; set; } public int SelectedIndex { get; set; } = -1; public object SelectedItem { get; set; } public double CharacterSpacing { get; set; } public Color TextColor { get; set; } public Font Font { get; set; } } }
22.24
64
0.69964
[ "MIT" ]
JoonghyunCho/maui
src/Core/tests/DeviceTests/Stubs/PickerStub.cs
558
C#
using AutoMapper; using EasyStore.ProductAPI.Models; using EasyStore.ProductAPI.Models.Dto; namespace EasyStore.ProductAPI.Mappers { public class MappingConfig { public static MapperConfiguration RegisterMaps() { var mappingConfig = new MapperConfiguration(c => { c.CreateMap<ProductDto, Product>(); c.CreateMap<Product, ProductDto>(); }); return mappingConfig; } } }
24.3
60
0.600823
[ "Apache-2.0" ]
thiagocruzrj/EasyStore.Microservices
EasyStore/EasyStore.ProductAPI/Mappers/MappingConfig.cs
488
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Web; [assembly: PreApplicationStartMethod (typeof (Test_09.Tests.PreStart), "FormsAuthenticationSetUp")] // 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 ("Test_09")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("Test_09")] [assembly: AssemblyCopyright ("Copyright © 2010")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid ("ef2e428c-6031-4c71-bbe2-97c43ef6ed9d")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion ("1.0.0.0")] [assembly: AssemblyFileVersion ("1.0.0.0")]
37.897436
99
0.746279
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/standalone/EnableFormsAuthentication/Test_09/Properties/AssemblyInfo.cs
1,481
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS.Formula; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.SS; using NPOI.Util; /** * Common superclass for Testing usermodel API for array formulas.<br/> * Formula Evaluation is not Tested here. * * @author Yegor Kozlov * @author Josh Micich */ public abstract class BaseTestSheetUpdateArrayFormulas { protected ITestDataProvider _testDataProvider; //public BaseTestSheetUpdateArrayFormulas() //{ // _testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance; //} protected BaseTestSheetUpdateArrayFormulas(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestAutoCreateOtherCells() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet1"); IRow row1 = sheet.CreateRow(0); ICell cellA1 = row1.CreateCell(0); ICell cellB1 = row1.CreateCell(1); String formula = "42"; sheet.SetArrayFormula(formula, CellRangeAddress.ValueOf("A1:B2")); Assert.AreEqual(formula, cellA1.CellFormula); Assert.AreEqual(formula, cellB1.CellFormula); IRow row2 = sheet.GetRow(1); Assert.IsNotNull(row2); Assert.AreEqual(formula, row2.GetCell(0).CellFormula); Assert.AreEqual(formula, row2.GetCell(1).CellFormula); workbook.Close(); } /** * Set Single-cell array formula */ [Test] public void TestSetArrayFormula_SingleCell() { ICell[] cells; IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ICell cell = sheet.CreateRow(0).CreateCell(0); Assert.IsFalse(cell.IsPartOfArrayFormulaGroup); try { CellRangeAddress c= cell.ArrayFormulaRange; Assert.Fail("expected exception"); } catch (InvalidOperationException e) { Assert.AreEqual("Cell A1 is not part of an array formula.", e.Message); } // row 3 does not yet exist Assert.IsNull(sheet.GetRow(2)); CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2); cells = sheet.SetArrayFormula("SUM(C11:C12*D11:D12)", range).FlattenedCells; Assert.AreEqual(1, cells.Length); // sheet.SetArrayFormula Creates rows and cells for the designated range Assert.IsNotNull(sheet.GetRow(2)); cell = sheet.GetRow(2).GetCell(2); Assert.IsNotNull(cell); Assert.IsTrue(cell.IsPartOfArrayFormulaGroup); //retrieve the range and check it is the same Assert.AreEqual(range.FormatAsString(), cell.ArrayFormulaRange.FormatAsString()); //check the formula Assert.AreEqual("SUM(C11:C12*D11:D12)", cell.CellFormula); workbook.Close(); } /** * Set multi-cell array formula */ [Test] public void TestSetArrayFormula_multiCell() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); // multi-cell formula // rows 3-5 don't exist yet Assert.IsNull(sheet.GetRow(3)); Assert.IsNull(sheet.GetRow(4)); Assert.IsNull(sheet.GetRow(5)); CellRangeAddress range = CellRangeAddress.ValueOf("C4:C6"); ICell[] cells = sheet.SetArrayFormula("SUM(A1:A3*B1:B3)", range).FlattenedCells; Assert.AreEqual(3, cells.Length); // sheet.SetArrayFormula Creates rows and cells for the designated range Assert.AreSame(cells[0], sheet.GetRow(3).GetCell(2)); Assert.AreSame(cells[1], sheet.GetRow(4).GetCell(2)); Assert.AreSame(cells[2], sheet.GetRow(5).GetCell(2)); foreach (ICell acell in cells) { Assert.IsTrue(acell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Formula, acell.CellType); Assert.AreEqual("SUM(A1:A3*B1:B3)", acell.CellFormula); //retrieve the range and check it is the same Assert.AreEqual(range.FormatAsString(), acell.ArrayFormulaRange.FormatAsString()); } workbook.Close(); } /** * Passing an incorrect formula to sheet.SetArrayFormula * should throw FormulaParseException */ [Test] public void TestSetArrayFormula_incorrectFormula() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); try { sheet.SetArrayFormula("incorrect-formula(C11_C12*D11_D12)", new CellRangeAddress(10, 10, 10, 10)); Assert.Fail("expected exception"); } catch (FormulaParseException) { //expected exception } workbook.Close(); } /** * Calls of cell.GetArrayFormulaRange and sheet.RemoveArrayFormula * on a not-array-formula cell throw InvalidOperationException */ [Test] public void TestArrayFormulas_illegalCalls() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ICell cell = sheet.CreateRow(0).CreateCell(0); Assert.IsFalse(cell.IsPartOfArrayFormulaGroup); try { CellRangeAddress c= cell.ArrayFormulaRange; Assert.Fail("expected exception"); } catch (InvalidOperationException e) { Assert.AreEqual("Cell A1 is not part of an array formula.", e.Message); } try { sheet.RemoveArrayFormula(cell); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Cell A1 is not part of an array formula.", e.Message); } workbook.Close(); } /** * create and remove array formulas */ [Test] public void TestRemoveArrayFormula() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); CellRangeAddress range = new CellRangeAddress(3, 5, 2, 2); Assert.AreEqual("C4:C6", range.FormatAsString()); ICellRange<ICell> cr = sheet.SetArrayFormula("SUM(A1:A3*B1:B3)", range); Assert.AreEqual(3, cr.Size); // remove the formula cells in C4:C6 ICellRange<ICell> dcells = sheet.RemoveArrayFormula(cr.TopLeftCell); // RemoveArrayFormula should return the same cells as SetArrayFormula Assert.IsTrue(Arrays.Equals(cr.FlattenedCells, dcells.FlattenedCells)); foreach (ICell acell in cr) { Assert.IsFalse(acell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Blank, acell.CellType); } // cells C4:C6 are not included in array formula, // invocation of sheet.RemoveArrayFormula on any of them throws ArgumentException foreach (ICell acell in cr) { try { sheet.RemoveArrayFormula(acell); Assert.Fail("expected exception"); } catch (ArgumentException e) { String ref1 = new CellReference(acell).FormatAsString(); Assert.AreEqual("Cell " + ref1 + " is not part of an array formula.", e.Message); } } workbook.Close(); } /** * Test that when Reading a workbook from input stream, array formulas are recognized */ [Test] public void TestReadArrayFormula() { ICell[] cells; IWorkbook workbook1 = _testDataProvider.CreateWorkbook(); ISheet sheet1 = workbook1.CreateSheet(); cells = sheet1.SetArrayFormula("SUM(A1:A3*B1:B3)", CellRangeAddress.ValueOf("C4:C6")).FlattenedCells; Assert.AreEqual(3, cells.Length); cells = sheet1.SetArrayFormula("MAX(A1:A3*B1:B3)", CellRangeAddress.ValueOf("A4:A6")).FlattenedCells; Assert.AreEqual(3, cells.Length); ISheet sheet2 = workbook1.CreateSheet(); cells = sheet2.SetArrayFormula("MIN(A1:A3*B1:B3)", CellRangeAddress.ValueOf("D2:D4")).FlattenedCells; Assert.AreEqual(3, cells.Length); IWorkbook workbook2 = _testDataProvider.WriteOutAndReadBack(workbook1); workbook1.Close(); sheet1 = workbook2.GetSheetAt(0); for (int rownum = 3; rownum <= 5; rownum++) { ICell cell1 = sheet1.GetRow(rownum).GetCell(2); Assert.IsTrue(cell1.IsPartOfArrayFormulaGroup); ICell cell2 = sheet1.GetRow(rownum).GetCell(0); Assert.IsTrue(cell2.IsPartOfArrayFormulaGroup); } sheet2 = workbook2.GetSheetAt(1); for (int rownum = 1; rownum <= 3; rownum++) { ICell cell1 = sheet2.GetRow(rownum).GetCell(3); Assert.IsTrue(cell1.IsPartOfArrayFormulaGroup); } workbook2.Close(); } /** * Test that we can Set pre-calculated formula result for array formulas */ [Test] public void TestModifyArrayCells_setFormulaResult() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Single-cell array formula ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.ValueOf("B5")); ICell scell = srange.TopLeftCell; Assert.AreEqual(CellType.Formula, scell.CellType); Assert.AreEqual(0.0, scell.NumericCellValue, 0); scell.SetCellValue(1.1); Assert.AreEqual(1.1, scell.NumericCellValue, 0); //multi-cell array formula ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); foreach (ICell mcell in mrange) { Assert.AreEqual(CellType.Formula, mcell.CellType); Assert.AreEqual(0.0, mcell.NumericCellValue, 0); double fmlaResult = 1.2; mcell.SetCellValue(fmlaResult); Assert.AreEqual(fmlaResult, mcell.NumericCellValue, 0); } workbook.Close(); } [Test] public void TestModifyArrayCells_setCellType() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); // Single-cell array formulas behave just like normal cells - // changing cell type Removes the array formula and associated cached result ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.ValueOf("B5")); ICell scell = srange.TopLeftCell; Assert.AreEqual(CellType.Formula, scell.CellType); Assert.AreEqual(0.0, scell.NumericCellValue, 0); scell.SetCellType(CellType.String); Assert.AreEqual(CellType.String, scell.CellType); scell.SetCellValue("string cell"); Assert.AreEqual("string cell", scell.StringCellValue); //once you create a multi-cell array formula, you cannot change the type of its cells ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); foreach (ICell mcell in mrange) { try { Assert.AreEqual(CellType.Formula, mcell.CellType); mcell.SetCellType(CellType.Numeric); Assert.Fail("expected exception"); } catch (InvalidOperationException e) { CellReference ref1 = new CellReference(mcell); String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; Assert.AreEqual(msg, e.Message); } // a failed invocation of Cell.SetCellType leaves the cell // in the state that it was in prior to the invocation Assert.AreEqual(CellType.Formula, mcell.CellType); Assert.IsTrue(mcell.IsPartOfArrayFormulaGroup); } workbook.Close(); } [Test] public void TestModifyArrayCells_setCellFormula() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.ValueOf("B5")); ICell scell = srange.TopLeftCell; Assert.AreEqual("SUM(A4:A6,B4:B6)", scell.CellFormula); Assert.AreEqual(CellType.Formula, scell.CellType); Assert.IsTrue(scell.IsPartOfArrayFormulaGroup); scell.CellFormula = (/*setter*/"SUM(A4,A6)"); //we are now a normal formula cell Assert.AreEqual("SUM(A4,A6)", scell.CellFormula); Assert.IsFalse(scell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Formula, scell.CellType); //check that Setting formula result works Assert.AreEqual(0.0, scell.NumericCellValue, 0); scell.SetCellValue(33.0); Assert.AreEqual(33.0, scell.NumericCellValue, 0); //multi-cell array formula ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); foreach (ICell mcell in mrange) { //we cannot Set individual formulas for cells included in an array formula try { Assert.AreEqual("A1:A3*B1:B3", mcell.CellFormula); mcell.CellFormula = (/*setter*/"A1+A2"); Assert.Fail("expected exception"); } catch (InvalidOperationException e) { CellReference ref1 = new CellReference(mcell); String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; Assert.AreEqual(msg, e.Message); } // a failed invocation of Cell.SetCellFormula leaves the cell // in the state that it was in prior to the invocation Assert.AreEqual("A1:A3*B1:B3", mcell.CellFormula); Assert.IsTrue(mcell.IsPartOfArrayFormulaGroup); } workbook.Close(); } [Test] public void TestModifyArrayCells_RemoveCell() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Single-cell array formulas behave just like normal cells CellRangeAddress cra = CellRangeAddress.ValueOf("B5"); ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", cra); ICell scell = srange.TopLeftCell; IRow srow = sheet.GetRow(cra.FirstRow); Assert.AreSame(srow, scell.Row); srow.RemoveCell(scell); Assert.IsNull(srow.GetCell(cra.FirstColumn)); //re-create the Removed cell scell = srow.CreateCell(cra.FirstColumn); Assert.AreEqual(CellType.Blank, scell.CellType); Assert.IsFalse(scell.IsPartOfArrayFormulaGroup); //we cannot remove cells included in a multi-cell array formula ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); foreach (ICell mcell in mrange) { int columnIndex = mcell.ColumnIndex; IRow mrow = mcell.Row; try { mrow.RemoveCell(mcell); Assert.Fail("expected exception"); } catch (InvalidOperationException e) { CellReference ref1 = new CellReference(mcell); String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; Assert.AreEqual(msg, e.Message); } // a failed invocation of Row.RemoveCell leaves the row // in the state that it was in prior to the invocation Assert.AreSame(mcell, mrow.GetCell(columnIndex)); Assert.IsTrue(mcell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Formula, mcell.CellType); } workbook.Close(); } [Test] public void TestModifyArrayCells_RemoveRow() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Single-cell array formulas behave just like normal cells CellRangeAddress cra = CellRangeAddress.ValueOf("B5"); ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", cra); ICell scell = srange.TopLeftCell; Assert.AreEqual(CellType.Formula, scell.CellType); IRow srow = scell.Row; Assert.AreSame(srow, sheet.GetRow(cra.FirstRow)); sheet.RemoveRow(srow); Assert.IsNull(sheet.GetRow(cra.FirstRow)); //re-create the Removed row and cell scell = sheet.CreateRow(cra.FirstRow).CreateCell(cra.FirstColumn); Assert.AreEqual(CellType.Blank, scell.CellType); Assert.IsFalse(scell.IsPartOfArrayFormulaGroup); //we cannot remove rows with cells included in a multi-cell array formula ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); foreach (ICell mcell in mrange) { int columnIndex = mcell.ColumnIndex; IRow mrow = mcell.Row; try { sheet.RemoveRow(mrow); Assert.Fail("expected exception"); } catch (InvalidOperationException) { // String msg = "Row[rownum=" + mrow.RowNum + "] Contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; //Assert.AreEqual(msg, e.Message); } // a failed invocation of Row.RemoveCell leaves the row // in the state that it was in prior to the invocation Assert.AreSame(mrow, sheet.GetRow(mrow.RowNum)); Assert.AreSame(mcell, mrow.GetCell(columnIndex)); Assert.IsTrue(mcell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Formula, mcell.CellType); } workbook.Close(); } [Test] public void TestModifyArrayCells_mergeCellsSingle() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.AreEqual(0, sheet.NumMergedRegions); //Single-cell array formulas behave just like normal cells ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.ValueOf("B5")); ICell scell = srange.TopLeftCell; sheet.AddMergedRegion(CellRangeAddress.ValueOf("B5:C6")); //we are still an array formula Assert.AreEqual(CellType.Formula, scell.CellType); Assert.IsTrue(scell.IsPartOfArrayFormulaGroup); Assert.AreEqual(1, sheet.NumMergedRegions); workbook.Close(); } [Test] public void testModifyArrayCells_mergeCellsMulti() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); int expectedNumMergedRegions = 0; Assert.AreEqual(expectedNumMergedRegions, sheet.NumMergedRegions); // we cannot merge cells included in an array formula sheet.SetArrayFormula("A1:A4*B1:B4", CellRangeAddress.ValueOf("C2:F5")); foreach (String ref1 in Arrays.AsList( "C2:F5", // identity "D3:E4", "B1:G6", // contains "B1:C2", "F1:G2", "F5:G6", "B5:C6", // 1x1 corner intersection "B1:C6", "B1:G2", "F1:G6", "B5:G6", // 1-row/1-column intersection "B1:D3", "E1:G3", "E4:G6", "B4:D6", // 2x2 corner intersection "B1:D6", "B1:G3", "E1:G6", "B4:G6" // 2-row/2-column intersection )) { CellRangeAddress cra = CellRangeAddress.ValueOf(ref1); try { sheet.AddMergedRegion(cra); Assert.Fail("expected exception with ref " + ref1); } catch (InvalidOperationException e) { String msg = "The range " + cra.FormatAsString() + " intersects with a multi-cell array formula. You cannot merge cells of an array."; Assert.AreEqual(msg, e.Message); } } //the number of merged regions remains the same Assert.AreEqual(expectedNumMergedRegions, sheet.NumMergedRegions); // we can merge non-intersecting cells foreach (String ref1 in Arrays.AsList( "C1:F1", //above "G2:G5", //right "C6:F6", //bottom "B2:B5", "H7:J9")) { CellRangeAddress cra = CellRangeAddress.ValueOf(ref1); try { sheet.AddMergedRegion(cra); expectedNumMergedRegions++; Assert.AreEqual(expectedNumMergedRegions, sheet.NumMergedRegions); } catch (InvalidOperationException e) { Assert.Fail("did not expect exception with ref: " + ref1 +"\n" + e.Message); } } workbook.Close(); } [Test] public void TestModifyArrayCells_ShiftRows() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Single-cell array formulas behave just like normal cells - we can change the cell type ICellRange<ICell> srange = sheet.SetArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.ValueOf("B5")); ICell scell = srange.TopLeftCell; Assert.AreEqual("SUM(A4:A6,B4:B6)", scell.CellFormula); sheet.ShiftRows(0, 0, 1); sheet.ShiftRows(0, 1, 1); //we cannot Set individual formulas for cells included in an array formula ICellRange<ICell> mrange = sheet.SetArrayFormula("A1:A3*B1:B3", CellRangeAddress.ValueOf("C1:C3")); try { sheet.ShiftRows(0, 0, 1); Assert.Fail("expected exception"); } catch (InvalidOperationException e) { String msg = "Row[rownum=0] contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; Assert.AreEqual(msg, e.Message); } /* TODO: enable Shifting the whole array sheet.ShiftRows(0, 2, 1); //the array C1:C3 is now C2:C4 CellRangeAddress cra = CellRangeAddress.ValueOf("C2:C4"); foreach(Cell mcell in mrange){ //TODO define Equals and hashcode for CellRangeAddress Assert.AreEqual(cra.FormatAsString(), mcell.ArrayFormulaRange.formatAsString()); Assert.AreEqual("A2:A4*B2:B4", mcell.CellFormula); Assert.IsTrue(mcell.IsPartOfArrayFormulaGroup); Assert.AreEqual(CellType.Formula, mcell.CellType); } */ workbook.Close(); } [Ignore("also ignored in poi")] [Test] public void ShouldNotBeAbleToCreateArrayFormulaOnPreexistingMergedRegion() { /* * m = merged region * f = array formula * fm = cell belongs to a merged region and an array formula (illegal, that's what this tests for) * * A B C * 1 f f * 2 fm fm * 3 f f */ IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); CellRangeAddress mergedRegion = CellRangeAddress.ValueOf("B2:C2"); sheet.AddMergedRegion(mergedRegion); CellRangeAddress arrayFormula = CellRangeAddress.ValueOf("C1:C3"); Assume.That(mergedRegion.Intersects(arrayFormula)); Assume.That(arrayFormula.Intersects(mergedRegion)); try { sheet.SetArrayFormula("SUM(A1:A3)", arrayFormula); Assert.Fail("expected exception: should not be able to create an array formula that intersects with a merged region"); } catch (InvalidOperationException e) { // expected } workbook.Close(); } } }
41.853474
163
0.560833
[ "Apache-2.0" ]
68681395/npoi
testcases/main/SS/UserModel/BaseTestSheetUpdateArrayFormulas.cs
27,707
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OpenTelemetry.AutoInstrumentation.ClrProfiler.Managed, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.ClrProfiler.IntegrationTests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.Tests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.TestHelpers, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.IntegrationTests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("OpenTelemetry.AutoInstrumentation.OpenTracing, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.OpenTracing.Tests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.OpenTracing.IntegrationTests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("OpenTelemetry.AutoInstrumentation.AspNet, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] [assembly: InternalsVisibleTo("Datadog.Trace.ClrProfiler.Managed.Tests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("OpenTelemetry.AutoInstrumentation.MSBuild, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.BenchmarkDotNet, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Benchmarks.Trace, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.ServiceFabric, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")] [assembly: InternalsVisibleTo("Datadog.Trace.DuckTyping.Tests, PublicKey=0024000004800000140100000602000000240000525341310008000001000100652bb911930d33a4f67cfd6c712abf77978de155dbdb07b01c08df4f5615af4753b4a5fac5d4d2143ecc8ea6aaab9b3a2fef845a2698139356bf1d1acdd4a4985d493e22b79edbdfc7d1b39de7221669b0b410fa2323a0adc264b953482dea6d913b2c6dcacb3525c3c156f2652df76a3341a39663c9c165ec3cab0f5a80ef72502e49bc5946d23be6c8583ba4a3149f4dbc9a453021e299e5e357846c40514f33db357de4c855dc3225ef96beefe6ee91da24010ea50810f919513756e67e81a363811f8581d5dd0ed4e3e33a725107e70c0e32dcd0e9038885d75f3c0a8c8e0000b98b5ca318827ecc7e5124af2a46c93d6d61c2043c242aafbd33eeb11b87")]
541.315789
675
0.977248
[ "Apache-2.0" ]
anuragvajpayee/opentelemetry-dotnet-instrumentation
src/Datadog.Trace/AssemblyInfo.cs
10,285
C#
using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Diadoc.Api; using Diadoc.Api.Cryptography; using Diadoc.Api.Proto; using Diadoc.Api.Proto.Events; namespace Diadoc.Console { public class ConsoleContext { public ICrypt Crypt { get; set; } public DiadocApi DiadocApi { get; set; } public X509Certificate2 CurrentCert { get; set; } public string CurrentToken { get; set; } public IList<Box> Boxes { get; set; } public BoxEventList Events { get; set; } public IList<Organization> Orgs { get; set; } public string CurrentBoxId { get; set; } public string CurrentOrgId { get; set; } public bool SignByAttorney { get; set; } public bool IsAuthenticated() { return CurrentToken != null; } public void ClearAuthenticationContext() { Events = null; Boxes = null; Orgs = null; } } }
24.083333
52
0.711649
[ "MIT" ]
24twelve/diadocsdk-csharp
Samples/Diadoc.Console/ConsoleContext.cs
869
C#
// // System.ActivationContext class // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace System { [Serializable] [ComVisible (false)] public sealed class ActivationContext : IDisposable, ISerializable { public enum ContextForm { Loose, StoreBounded } private ApplicationIdentity _appid; // FIXME: #pragma warning disable 649 private ContextForm _form; #pragma warning restore 649 private bool _disposed; private ActivationContext (ApplicationIdentity identity) { _appid = identity; } ~ActivationContext () { Dispose (false); } public ContextForm Form { get { return _form; } } public ApplicationIdentity Identity { get { return _appid; } } [MonoTODO ("Missing validation")] static public ActivationContext CreatePartialActivationContext (ApplicationIdentity identity) { if (identity == null) throw new ArgumentNullException ("identity"); // TODO - throw new ArgumentException // - for invalid ApplicationIdentity return new ActivationContext (identity); } [MonoTODO("Missing validation")] static public ActivationContext CreatePartialActivationContext (ApplicationIdentity identity, string[] manifestPaths) { if (identity == null) throw new ArgumentNullException ("identity"); if (manifestPaths == null) throw new ArgumentNullException ("manifestPaths"); // TODO - throw new ArgumentException // - for invalid ApplicationIdentity // - not matching manifests // - number components != # manifest paths return new ActivationContext (identity); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } void Dispose (bool disposing) { if (_disposed) { if (disposing) { } _disposed = true; } } [MonoTODO("Missing serialization support")] void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException ("info"); } } }
26.801653
119
0.721554
[ "Apache-2.0" ]
121468615/mono
mcs/class/corlib/System/ActivationContext.cs
3,243
C#
namespace CollectionsOnline.Tasks { public class AppSettings { public const string APP_SETTINGS = "AppSettings"; public string DatabaseUrl { get; set; } public string DatabaseName { get; set; } public string WebSitePath { get; set; } public string WebSiteUser { get; set; } public string WebSitePassword { get; set; } public string WebSiteComputer { get; set; } public string WebSiteDomain { get; set; } public string CanonicalSiteBase { get; set; } } }
26.478261
57
0.561576
[ "MIT" ]
museumsvictoria/collections-online
src/CollectionsOnline.Tasks/AppSettings.cs
609
C#
using System; using EIP.Common.Entities; using EIP.Common.Entities.CustomAttributes; namespace EIP.System.Models.Entities { /// <summary> /// System_Field表实体类 /// </summary> [Serializable] [Table(Name = "System_Field")] public class SystemField: EntityBase { /// <summary> /// 字段主键 /// </summary> [Id] public Guid FieldId{ get; set; } /// <summary> /// 菜单id /// </summary> public Guid MenuId{ get; set; } /// <summary> /// 字段名称 /// </summary> public string Name{ get; set; } /// <summary> /// 查询sql字段 /// </summary> public string SqlField { get; set; } /// <summary> /// 显示名称 /// </summary> public string Label{ get; set; } /// <summary> /// 排序名称 /// </summary> public string Index{ get; set; } /// <summary> /// 显示列宽 /// </summary> public int? Width{ get; set; } /// <summary> /// 对齐方式 /// </summary> public string Align{ get; set; } /// <summary> /// 是否显示 /// </summary> public bool Hidden{ get; set; } /// <summary> /// 列宽是否重新计算 /// </summary> public bool Fixed{ get; set; } /// <summary> /// 自定义转换 /// </summary> public string Formatter{ get; set; } /// <summary> /// 排序类型 /// </summary> public string Sorttype{ get; set; } /// <summary> /// 排序 /// </summary> public int OrderNo{ get; set; } /// <summary> /// 备注 /// </summary> public string Remark{ get; set; } /// <summary> /// 导出/打印 /// </summary> public bool CanbeDerive{ get; set; } /// <summary> /// 是否冻结 /// </summary> public bool IsFreeze{ get; set; } } }
21.104167
44
0.427937
[ "MIT" ]
woshisunzewei/EIP
Service/System/EIP.System.Models/Entities/SystemField.cs
2,160
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ManejoDeActivos { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Label1_Click(object sender, EventArgs e) { } private void Label3_Click(object sender, EventArgs e) { } private void Button7_Click(object sender, EventArgs e) { } private void button5_Click(object sender, EventArgs e) { } private void assestManagmentBtn_Click(object sender, EventArgs e) { } private void openUserManagment(object childForm) { if (this.homePanel.Controls.Count > 0) this.homePanel.Controls.RemoveAt(0); Form fh = childForm as Form; fh.TopLevel = false; fh.Dock = DockStyle.Fill; this.homePanel.Controls.Add(fh); this.homePanel.Tag = fh; fh.Show(); } private void userManagmentBtn_Click(object sender, EventArgs e) { openUserManagment(new UserManagment()); } private void transferAssestBtn_Click(object sender, EventArgs e) { openUserManagment(new TransferAssest()); } } }
22.101449
73
0.577705
[ "MIT" ]
KarlaRjc/DisAppsSoft
AssetsManagement/AssetsManagement/GUI/ManejoDeActivos/ManejoDeActivos/Form1.cs
1,527
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Xunit; using Xunit.Extensions; namespace Mosa.UnitTest.Collection.xUnit { public class DoubleFixture : TestFixture { //private static double Tolerance = 0.000001d; //private static IComparer<double> target = new ApproximateComparer(Tolerance); [Theory] [MemberData("R8R8", DisableDiscoveryEnumeration = true)] public void AddR8R8(double a, double b) { Assert.Equal(DoubleTests.AddR8R8(a, b), Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "AddR8R8", a, b)); } [Theory] [MemberData("R8R8", DisableDiscoveryEnumeration = true)] public void SubR8R8(double a, double b) { Assert.Equal(DoubleTests.SubR8R8(a, b), Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "SubR8R8", a, b)); } [Theory] [MemberData("R8R8", DisableDiscoveryEnumeration = true)] public void MulR8R8(double a, double b) { Assert.Equal(DoubleTests.MulR8R8(a, b), Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "MulR8R8", a, b)); } [Theory] [MemberData("R8R8", DisableDiscoveryEnumeration = true)] public void DivR8R8(double a, double b) { if (a == int.MinValue && b == -1) { // Assert.Inconclusive("TODO: Overflow exception not implemented"); return; } if (b == 0) { return; } Assert.Equal(DoubleTests.DivR8R8(a, b), Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "DivR8R8", a, b)); } //[Theory] //[ExpectedException(typeof(DivideByZeroException))] public void DivR8R8DivideByZeroException(double a) { Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "DivR8R8", (double)0, a, (double)0); } [Theory] [MemberData("R8R8", DisableDiscoveryEnumeration = true)] public void RemR8R8(double a, double b) { if (a == int.MinValue && b == -1) { //Assert.Inconclusive("TODO: Overflow exception not implemented"); return; } if (b == 0) { return; } Assert.Equal(DoubleTests.RemR8R8(a, b), Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "RemR8R8", a, b)); } //[Theory] //[ExpectedException(typeof(DivideByZeroException))] public void RemI4I4DivideByZeroException(int a) { Run<double>("Mosa.UnitTest.Collection", "DoubleTests", "RemR8R8", (double)0, a, (double)0); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CeqR8R8(double a, double b) { Assert.Equal(DoubleTests.CeqR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CeqR8R8", a, b)); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CneqR8R8(double a, double b) { Assert.Equal(DoubleTests.CneqR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CneqR8R8", a, b)); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CltR8R8(double a, double b) { Assert.Equal(DoubleTests.CltR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CltR8R8", a, b)); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CgtR8R8(double a, double b) { Assert.Equal(DoubleTests.CgtR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CgtR8R8", a, b)); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CleR8R8(double a, double b) { Assert.Equal(DoubleTests.CleR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CleR8R8", a, b)); } [Theory] [MemberData("R8SimpleR8Simple", DisableDiscoveryEnumeration = true)] public void CgeR8R8(double a, double b) { Assert.Equal(DoubleTests.CgeR8R8(a, b), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "CgeR8R8", a, b)); } [Fact] public void Newarr() { Assert.True(Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "Newarr")); } [Theory] [MemberData("I4Small", DisableDiscoveryEnumeration = true)] public void Ldlen(int length) { Assert.True(Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "Ldlen", length)); } [Theory] [MemberData("I4SmallR8Simple", DisableDiscoveryEnumeration = true)] public void StelemR8(int index, double value) { Assert.True(Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "Stelem", index, value)); } [Theory] [MemberData("I4SmallR8Simple", DisableDiscoveryEnumeration = true)] public void LdelemR8(int index, double value) { Assert.True(Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "Ldelem", index, value)); } [Theory] [MemberData("I4SmallR8Simple", DisableDiscoveryEnumeration = true)] public void LdelemaR8(int index, double value) { Assert.True(Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "Ldelema", index, value)); } [Theory] [MemberData("R8", DisableDiscoveryEnumeration = true)] public void IsNaN(double value) { Assert.Equal(DoubleTests.IsNaN(value), Run<bool>("Mosa.UnitTest.Collection", "DoubleTests", "IsNaN", value)); } } }
30.011905
116
0.688814
[ "BSD-3-Clause" ]
carverh/ShiftOS
Source/Mosa.UnitTest.Collection.xUnit/DoubleFixture.cs
5,044
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace FluffySpoon.Automation.Web.Fluent.Context { public interface IMethodChainContext : IAwaitable { Task RunAllAsync(); Task RunNextAsync(); int NodeCount { get; } IEnumerable<IWebAutomationFrameworkInstance> Frameworks { get; } IWebAutomationEngine AutomationEngine { get; } TMethodChainNode Enqueue<TMethodChainNode>(TMethodChainNode node) where TMethodChainNode : IBaseMethodChainNode; } }
28.294118
114
0.798337
[ "MIT" ]
ffMathy/FluffySpoon.Automation
src/FluffySpoon.Automation.Web/Fluent/Context/IMethodChainContext.cs
483
C#
// <auto-generated /> namespace BIMStore.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class v1 : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(v1)); string IMigrationMetadata.Id { get { return "201810050955480_v1"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
26.2
85
0.605598
[ "MIT" ]
x3n0r/BIMStore
BIMStore/Migrations/201810050955480_v1.Designer.cs
786
C#
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.AccessControl; using System.Security.Permissions; using System.Security.Principal; using Microsoft.WindowsAzure.Management.CloudService; using Microsoft.WindowsAzure.Management.CloudService.AzureTools; using Microsoft.WindowsAzure.Management.CloudService.Properties; using Microsoft.WindowsAzure.Management.CloudService.Scaffolding; using Microsoft.WindowsAzure.Management.CloudService.ServiceDefinitionSchema; using Microsoft.WindowsAzure.Management.CloudService.Utilities; namespace Microsoft.WindowsAzure.Management.CloudService.Model { /// <summary> /// Class that encapsulates all of the info about a service, to which we can add roles. This is all in memory, so no disk operations occur. /// </summary> public class AzureService { public ServicePathInfo Paths { get; private set; } public ServiceComponents Components { get; private set; } private string scaffoldingFolderPath; public string ServiceName { get { return this.Components.Definition.name; } } public AzureService(string serviceParentDirectory, string name, string scaffoldingPath) : this() { Validate.ValidateDirectoryFull(serviceParentDirectory, Resources.ServiceParentDirectory); Validate.ValidateStringIsNullOrEmpty(name, "Name"); Validate.ValidateFileName(name, string.Format(Resources.InvalidFileName, "Name")); Validate.ValidateDnsName(name, "Name"); string newServicePath = Path.Combine(serviceParentDirectory, name); if (Directory.Exists(newServicePath)) { throw new ArgumentException(string.Format(Resources.ServiceAlreadyExistsOnDisk, name, newServicePath)); } SetScaffolding(scaffoldingPath); Paths = new ServicePathInfo(newServicePath); CreateNewService(Paths.RootPath, name); Components = new ServiceComponents(Paths); ConfigureNewService(Components, Paths, name); } //for stopping the emulator none of the path info is required public AzureService() { } public AzureService(string rootPath, string scaffoldingPath) { SetScaffolding(scaffoldingPath); Paths = new ServicePathInfo(rootPath); Components = new ServiceComponents(Paths); } private void SetScaffolding(string scaffoldingFolderDirectory) { if (string.IsNullOrEmpty(scaffoldingFolderDirectory)) { scaffoldingFolderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } else { Validate.ValidateDirectoryExists(scaffoldingFolderDirectory); scaffoldingFolderPath = scaffoldingFolderDirectory; } } private void ConfigureNewService(ServiceComponents components, ServicePathInfo paths, string serviceName) { Components.Definition.name = serviceName; Components.CloudConfig.serviceName = serviceName; Components.LocalConfig.serviceName = serviceName; Components.Save(paths); } private void CreateNewService(string serviceRootPath, string serviceName) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters[ScaffoldParams.Slot] = string.Empty; parameters[ScaffoldParams.Subscription] = string.Empty; parameters[ScaffoldParams.Location] = string.Empty; parameters[ScaffoldParams.StorageAccountName] = string.Empty; parameters[ScaffoldParams.ServiceName] = serviceName; Scaffold.GenerateScaffolding(Path.Combine(scaffoldingFolderPath, Resources.GeneralScaffolding), serviceRootPath, parameters); } /// <summary> /// Creates a role name, ensuring it doesn't already exist. If null is passed in, a number will be appended to the defaultRoleName. /// </summary> /// <param name="name"></param> /// <param name="defaultName"></param> /// <param name="existingNames"></param> /// <returns></returns> private string GetRoleName(string name, string defaultName, IEnumerable<string> existingNames) { if (!string.IsNullOrEmpty(name)) { if (existingNames.Contains(name.ToLower())) { // Role does exist, user should pick a unique name // throw new ArgumentException(string.Format(Resources.AddRoleMessageRoleExists, name)); } if (!ServiceComponents.ValidRoleName(name)) { // The provided name is invalid role name // throw new ArgumentException(string.Format(Resources.InvalidRoleNameMessage, name)); } } if (name == null) { name = defaultName; } else { return name; } int index = 1; string curName = name + index.ToString(); while (existingNames.Contains(curName.ToLower())) { curName = name + (++index).ToString(); } return curName; } /// <summary> /// Adds the given role to both config files and the service def. /// </summary> /// <param name="role"></param> private void AddRoleCore(String Scaffolding, RoleInfo role, RoleType type) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters[ScaffoldParams.Role] = role; parameters[ScaffoldParams.Components] = Components; parameters[ScaffoldParams.RoleName] = role.Name; parameters[ScaffoldParams.InstancesCount] = role.InstanceCount; parameters[ScaffoldParams.Port] = Components.GetNextPort(); parameters[ScaffoldParams.Paths] = Paths; parameters[ScaffoldParams.NodeModules] = General.GetNodeModulesPath(); parameters[ScaffoldParams.NodeJsProgramFilesX86] = General.GetWithProgramFilesPath(Resources.NodeProgramFilesFolderName, false); string scaffoldPath = Path.Combine(Path.Combine(scaffoldingFolderPath, Scaffolding), type.ToString()); Scaffold.GenerateScaffolding(scaffoldPath, Path.Combine(Paths.RootPath, role.Name), parameters); } public RoleInfo AddWebRole(string scaffolding, string name = null, int instanceCount = 1) { name = GetRoleName(name, Resources.WebRole, Components.Definition.WebRole == null ? new String[0] : Components.Definition.WebRole.Select(wr => wr.name.ToLower())); WebRoleInfo role = new WebRoleInfo(name, instanceCount); AddRoleCore(scaffolding, role, RoleType.WebRole); return role; } public RoleInfo AddWorkerRole(string Scaffolding, string name = null, int instanceCount = 1) { name = GetRoleName(name, Resources.WorkerRole, Components.Definition.WorkerRole == null ? new String[0] : Components.Definition.WorkerRole.Select(wr => wr.name.ToLower())); WorkerRoleInfo role = new WorkerRoleInfo(name, instanceCount); AddRoleCore(Scaffolding, role, RoleType.WorkerRole); return role; } public void ChangeRolePermissions(RoleInfo role) { string rolePath = Path.Combine(Paths.RootPath, role.Name); DirectoryInfo directoryInfo = new DirectoryInfo(rolePath); DirectorySecurity directoryAccess = directoryInfo.GetAccessControl(AccessControlSections.All); directoryAccess.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null), FileSystemRights.ReadAndExecute | FileSystemRights.Write, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); directoryInfo.SetAccessControl(directoryAccess); } [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void CreatePackage(DevEnv type, out string standardOutput, out string standardError) { var packageTool = new CsPack(); packageTool.CreatePackage(Components.Definition, Paths.RootPath, type, out standardOutput, out standardError); } /// <summary> /// Starts azure emulator for this service. /// </summary> /// <remarks>This methods removes all deployments already in the emulator.</remarks> /// <param name="launch">Switch to control opening a browser for web roles.</param> /// <param name="standardOutput">Output result from csrun.exe</param> /// <param name="standardError">Error result from csrun.exe</param> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void StartEmulator(bool launch, out string standardOutput, out string standardError) { var runTool = new CsRun(); runTool.StartEmulator(Paths.LocalPackage, Paths.LocalConfiguration, launch, out standardOutput, out standardError); } [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void StopEmulator(out string standardOutput, out string standardError) { var runTool = new CsRun(); runTool.StopEmulator(out standardOutput, out standardError); } public void ChangeServiceName(string newName, ServicePathInfo paths) { Validate.ValidateDnsName(newName, "service name"); Components.Definition.name = newName; Components.CloudConfig.serviceName = newName; Components.LocalConfig.serviceName = newName; Components.Save(paths); } public void SetRoleInstances(ServicePathInfo paths, string roleName, int instances) { Components.SetRoleInstances(roleName, instances); Components.Save(paths); } } }
45.369919
191
0.645731
[ "Apache-2.0" ]
dineshkummarc/azure-sdk-tools
WindowsAzurePowershell/src/Management.CloudService/Model/AzureService.cs
11,163
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Friends { /* This module handles adding/removing friends, and the the presence notification process for login/logoff of friends. The presence notification works as follows: - After the user initially connects to a region (so we now have a UDP connection to work with), this module fetches the friends of user (those are cached), their on-/offline status, and info about the region they are in from the MessageServer. - (*) It then informs the user about the on-/offline status of her friends. - It then informs all online friends currently on this region-server about user's new online status (this will save some network traffic, as local messages don't have to be transferred inter-region, and it will be all that has to be done in Standalone Mode). - For the rest of the online friends (those not on this region-server), this module uses the provided region-information to map users to regions, and sends one notification to every region containing the friends to inform on that server. - The region-server will handle that in the following way: - If it finds the friend, it informs her about the user being online. - If it doesn't find the friend (maybe she TPed away in the meantime), it stores that information. - After it processed all friends, it returns the list of friends it couldn't find. - If this list isn't empty, the FriendsModule re-requests information about those online friends that have been missed and starts at (*) again until all friends have been found, or until it tried 3 times (to prevent endless loops due to some uncaught error). NOTE: Online/Offline notifications don't need to be sent on region change. We implement two XMLRpc handlers here, handling all the inter-region things we have to handle: - On-/Offline-Notifications (bulk) - Terminate Friendship messages (single) */ public class FriendsModule : IRegionModule, IFriendsModule { private class Transaction { public UUID agentID; public string agentName; public uint count; public Transaction(UUID agentID, string agentName) { this.agentID = agentID; this.agentName = agentName; this.count = 1; } } private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate); private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>(); private Dictionary<UUID, UUID> m_pendingCallingcardRequests = new Dictionary<UUID,UUID>(); private Scene m_initialScene; // saves a lookup if we don't have a specific scene private Dictionary<ulong, Scene> m_scenes = new Dictionary<ulong,Scene>(); private IMessageTransferModule m_TransferModule = null; private IGridServices m_gridServices = null; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { lock (m_scenes) { if (m_scenes.Count == 0) { MainServer.Instance.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk); MainServer.Instance.AddXmlRPCHandler("terminate_friend", processTerminateFriend); m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max m_initialScene = scene; } if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle)) m_scenes[scene.RegionInfo.RegionHandle] = scene; } scene.RegisterModuleInterface<IFriendsModule>(this); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientClosed; } public void PostInitialise() { if (m_scenes.Count > 0) { m_TransferModule = m_initialScene.RequestModuleInterface<IMessageTransferModule>(); m_gridServices = m_initialScene.CommsManager.GridService; } if (m_TransferModule == null) m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work"); } public void Close() { } public string Name { get { return "FriendsModule"; } } public bool IsSharedModule { get { return true; } } #endregion #region IInterregionFriendsComms public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online) { List<UUID> tpdAway = new List<UUID>(); // destRegionHandle is a region on another server RegionInfo info = m_gridServices.RequestNeighbourInfo(destRegionHandle); if (info != null) { string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; Hashtable reqParams = new Hashtable(); reqParams["agentID"] = agentId.ToString(); reqParams["agentOnline"] = online; int count = 0; foreach (UUID uuid in friends) { reqParams["friendID_" + count++] = uuid.ToString(); } reqParams["friendCount"] = count; IList parameters = new ArrayList(); parameters.Add(reqParams); try { XmlRpcRequest request = new XmlRpcRequest("presence_update_bulk", parameters); XmlRpcResponse response = request.Send(httpServer, 5000); Hashtable respData = (Hashtable)response.Value; count = (int)respData["friendCount"]; for (int i = 0; i < count; ++i) { UUID uuid; if (UUID.TryParse((string)respData["friendID_" + i], out uuid)) tpdAway.Add(uuid); } } catch (WebException e) { // Ignore connect failures, simulators come and go // if (!e.Message.Contains("ConnectFailure")) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); } } catch (Exception e) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); } } else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}???", destRegionHandle); return tpdAway; } public bool TriggerTerminateFriend(ulong destRegionHandle, UUID agentID, UUID exFriendID) { // destRegionHandle is a region on another server RegionInfo info = m_gridServices.RequestNeighbourInfo(destRegionHandle); if (info == null) { m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region {0}", destRegionHandle); return false; // region not found??? } string httpServer = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/presence_update_bulk"; Hashtable reqParams = new Hashtable(); reqParams["agentID"] = agentID.ToString(); reqParams["friendID"] = exFriendID.ToString(); IList parameters = new ArrayList(); parameters.Add(reqParams); try { XmlRpcRequest request = new XmlRpcRequest("terminate_friend", parameters); XmlRpcResponse response = request.Send(httpServer, 5000); Hashtable respData = (Hashtable)response.Value; return (bool)respData["success"]; } catch (Exception e) { m_log.Error("[OGS1 GRID SERVICES]: InformFriendsInOtherRegion XMLRPC failure: ", e); return false; } } #endregion #region Incoming XMLRPC messages /// <summary> /// Receive presence information changes about clients in other regions. /// </summary> /// <param name="req"></param> /// <returns></returns> public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)req.Params[0]; List<UUID> friendsNotHere = new List<UUID>(); // this is called with the expectation that all the friends in the request are on this region-server. // But as some time passed since we checked (on the other region-server, via the MessagingServer), // some of the friends might have teleported away. // Actually, even now, between this line and the sending below, some people could TP away. So, // we'll have to lock the m_rootAgents list for the duration to prevent/delay that. lock (m_rootAgents) { List<ScenePresence> friendsHere = new List<ScenePresence>(); try { UUID agentID = new UUID((string)requestData["agentID"]); bool agentOnline = (bool)requestData["agentOnline"]; int count = (int)requestData["friendCount"]; for (int i = 0; i < count; ++i) { UUID uuid; if (UUID.TryParse((string)requestData["friendID_" + i], out uuid)) { if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid)); else friendsNotHere.Add(uuid); } } // now send, as long as they are still here... UUID[] agentUUID = new UUID[] { agentID }; if (agentOnline) { foreach (ScenePresence agent in friendsHere) { agent.ControllingClient.SendAgentOnline(agentUUID); } } else { foreach (ScenePresence agent in friendsHere) { agent.ControllingClient.SendAgentOffline(agentUUID); } } } catch(Exception e) { m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e); } } // no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region, // which should be caught on the next iteration... Hashtable result = new Hashtable(); int idx = 0; foreach (UUID uuid in friendsNotHere) { result["friendID_" + idx++] = uuid.ToString(); } result["friendCount"] = idx; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } public XmlRpcResponse processTerminateFriend(XmlRpcRequest req, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable)req.Params[0]; bool success = false; UUID agentID; UUID friendID; if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) && requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID)) { // try to find it and if it is there, prevent it to vanish before we sent the message lock (m_rootAgents) { if (m_rootAgents.ContainsKey(agentID)) { m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID); GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID); success = true; } } } // return whether we were successful Hashtable result = new Hashtable(); result["success"] = success; XmlRpcResponse response = new XmlRpcResponse(); response.Value = result; return response; } #endregion #region Scene events private void OnNewClient(IClientAPI client) { // All friends establishment protocol goes over instant message // There's no way to send a message from the sim // to a user to 'add a friend' without causing dialog box spam // Subscribe to instant messages client.OnInstantMessage += OnInstantMessage; // Friend list management client.OnApproveFriendRequest += OnApproveFriendRequest; client.OnDenyFriendRequest += OnDenyFriendRequest; client.OnTerminateFriendship += OnTerminateFriendship; // ... calling card handling... client.OnOfferCallingCard += OnOfferCallingCard; client.OnAcceptCallingCard += OnAcceptCallingCard; client.OnDeclineCallingCard += OnDeclineCallingCard; // we need this one exactly once per agent session (see comments in the handler below) client.OnEconomyDataRequest += OnEconomyDataRequest; // if it leaves, we want to know, too client.OnLogout += OnLogout; } private void ClientClosed(UUID AgentId, Scene scene) { // agent's client was closed. As we handle logout in OnLogout, this here has only to handle // TPing away (root agent is closed) or TPing/crossing in a region far enough away (client // agent is closed). // NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around // in one of the regions here anymore. lock (m_rootAgents) { if (m_rootAgents.ContainsKey(AgentId)) { m_rootAgents.Remove(AgentId); } } } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { lock (m_rootAgents) { m_rootAgents[avatar.UUID] = avatar.RegionHandle; // Claim User! my user! Mine mine mine! } } private void MakeChildAgent(ScenePresence avatar) { lock (m_rootAgents) { if (m_rootAgents.ContainsKey(avatar.UUID)) { // only delete if the region matches. As this is a shared module, the avatar could be // root agent in another region on this server. if (m_rootAgents[avatar.UUID] == avatar.RegionHandle) { m_rootAgents.Remove(avatar.UUID); // m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent"); } } } } #endregion private ScenePresence GetRootPresenceFromAgentID(UUID AgentID) { ScenePresence returnAgent = null; lock (m_scenes) { ScenePresence queryagent = null; foreach (Scene scene in m_scenes.Values) { queryagent = scene.GetScenePresence(AgentID); if (queryagent != null) { if (!queryagent.IsChildAgent) { returnAgent = queryagent; break; } } } } return returnAgent; } private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID) { ScenePresence returnAgent = null; lock (m_scenes) { ScenePresence queryagent = null; foreach (Scene scene in m_scenes.Values) { queryagent = scene.GetScenePresence(AgentID); if (queryagent != null) { returnAgent = queryagent; break; } } } return returnAgent; } public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage) { CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId); if (userInfo != null) { GridInstantMessage msg = new GridInstantMessage( toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId, (byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero); FriendshipOffered(msg); } else { m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId); } } #region FriendRequestHandling private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { // Friend Requests go by Instant Message.. using the dialog param // https://wiki.secondlife.com/wiki/ImprovedInstantMessage if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38 { // fromAgentName is the *destination* name (the friend we offer friendship to) ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID)); im.fromAgentName = initiator != null ? initiator.Name : "(hippo)"; FriendshipOffered(im); } else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39 { FriendshipAccepted(client, im); } else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40 { FriendshipDeclined(client, im); } } /// <summary> /// Invoked when a user offers a friendship. /// </summary> /// /// <param name="im"></param> /// <param name="client"></param> private void FriendshipOffered(GridInstantMessage im) { // this is triggered by the initiating agent: // A local agent offers friendship to some possibly remote friend. // A IM is triggered, processed here and sent to the friend (possibly in a remote region). m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}", im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline); // 1.20 protocol sends an UUID in the message field, instead of the friendship offer text. // For interoperability, we have to clear that if (Util.isUUID(im.message)) im.message = ""; // be sneeky and use the initiator-UUID as transactionID. This means we can be stateless. // we have to look up the agent name on friendship-approval, though. im.imSessionID = im.fromAgentID; if (m_TransferModule != null) { // Send it to whoever is the destination. // If new friend is local, it will send an IM to the viewer. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server m_TransferModule.SendInstantMessage( im, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } /// <summary> /// Invoked when a user accepts a friendship offer. /// </summary> /// <param name="im"></param> /// <param name="client"></param> private void FriendshipAccepted(IClientAPI client, GridInstantMessage im) { m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})", client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); } /// <summary> /// Invoked when a user declines a friendship offer. /// </summary> /// May not currently be used - see OnDenyFriendRequest() instead /// <param name="im"></param> /// <param name="client"></param> private void FriendshipDeclined(IClientAPI client, GridInstantMessage im) { UUID fromAgentID = new UUID(im.fromAgentID); UUID toAgentID = new UUID(im.toAgentID); // declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator // toAgentID is initiator, fromAgentID declined friendship m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})", client != null ? client.AgentId.ToString() : "<null>", fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog); // Send the decline to whoever is the destination. GridInstantMessage msg = new GridInstantMessage( client.Scene, fromAgentID, client.Name, toAgentID, im.dialog, im.message, im.offline != 0, im.Position); // If new friend is local, it will send an IM to the viewer. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } private void OnGridInstantMessage(GridInstantMessage msg) { // This event won't be raised unless we have that agent, // so we can depend on the above not trying to send // via grid again //m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}", // msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog); if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered || msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted || msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined) { // this should succeed as we *know* the root agent is here. m_TransferModule.SendInstantMessage(msg, delegate(bool success) { //m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted) { // for accept friendship, we have to do a bit more ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName); } } private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName) { m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}", fromAgentID, fromName, toAgentID); // a new friend was added in the initiator's and friend's data, so the cache entries are wrong now. lock (m_friendLists) { m_friendLists.Invalidate(fromAgentID.ToString()); m_friendLists.Invalidate(toAgentID.ToString()); } // now send presence update and add a calling card for the new friend ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID); if (initiator == null) { // quite wrong. Shouldn't happen. m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID); return; } m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online", initiator.Name, fromName); // tell initiator that friend is online initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID }); // find the folder for the friend... //InventoryFolderImpl folder = // initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard); IInventoryService invService = initiator.Scene.InventoryService; InventoryFolderBase folder = invService.GetFolderForType(toAgentID, AssetType.CallingCard); if (folder != null) { // ... and add the calling card CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName); } } private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}", client.Name, client.AgentId, agentID, friendID); // store the new friend persistently for both avatars m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline); // The cache entries aren't valid anymore either, as we just added a friend to both sides. lock (m_friendLists) { m_friendLists.Invalidate(agentID.ToString()); m_friendLists.Invalidate(friendID.ToString()); } // if it's a local friend, we don't have to do the lookup ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID); if (friendPresence != null) { m_log.Debug("[FRIEND]: Local agent detected."); // create calling card CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name); // local message means OnGridInstantMessage won't be triggered, so do the work here. friendPresence.ControllingClient.SendInstantMessage( new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipAccepted, agentID.ToString(), false, Vector3.Zero)); ApproveFriendship(agentID, friendID, client.Name); } else { m_log.Debug("[FRIEND]: Remote agent detected."); // fetch the friend's name for the calling card. CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID); // create calling card CreateCallingCard(client, friendID, callingCardFolders[0], info.UserProfile.FirstName + " " + info.UserProfile.SurName); // Compose (remote) response to friend. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipAccepted, agentID.ToString(), false, Vector3.Zero); if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } // tell client that new friend is online client.SendAgentOnline(new UUID[] { friendID }); } private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) { m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}", client.Name, client.AgentId, agentID, friendID); // Compose response to other agent. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID, (byte)InstantMessageDialog.FriendshipDeclined, agentID.ToString(), false, Vector3.Zero); // send decline to initiator if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) { m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success); } ); } } private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID) { // client.AgentId == agentID! // this removes the friends from the stored friendlists. After the next login, they will be gone... m_initialScene.StoreRemoveFriendship(agentID, exfriendID); // ... now tell the two involved clients that they aren't friends anymore. // I don't know why we have to tell <agent>, as this was caused by her, but that's how it works in SL... client.SendTerminateFriend(exfriendID); // now send the friend, if online ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID); if (presence != null) { m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID); presence.ControllingClient.SendTerminateFriend(agentID); } else { // retry 3 times, in case the agent TPed from the last known region... for (int retry = 0; retry < 3; ++retry) { // wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID); if (null == data) break; if (!data.AgentOnline) { m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID); break; // if ex-friend isn't online, we don't need to send } m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}", agentID, exfriendID, data.Handle); // try to send to foreign region, retry if it fails (friend TPed away, for example) if (TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break; } } // clean up cache: FriendList is wrong now... lock (m_friendLists) { m_friendLists.Invalidate(agentID.ToString()); m_friendLists.Invalidate(exfriendID.ToString()); } } #endregion #region CallingCards private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID) { m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}", client.AgentId, destID, transactionID); // This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent // (or the root instead of the child) ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); if (destAgent == null) { client.SendAlertMessage("The person you have offered a card to can't be found anymore."); return; } lock (m_pendingCallingcardRequests) { m_pendingCallingcardRequests[transactionID] = client.AgentId; } // inform the destination agent about the offer destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID); } private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name) { InventoryItemBase item = new InventoryItemBase(); item.AssetID = UUID.Zero; item.AssetType = (int)AssetType.CallingCard; item.BasePermissions = (uint)PermissionMask.Copy; item.CreationDate = Util.UnixTimeSinceEpoch(); item.CreatorId = creator.ToString(); item.CurrentPermissions = item.BasePermissions; item.Description = ""; item.EveryOnePermissions = (uint)PermissionMask.None; item.Flags = 0; item.Folder = folder; item.GroupID = UUID.Zero; item.GroupOwned = false; item.ID = UUID.Random(); item.InvType = (int)InventoryType.CallingCard; item.Name = name; item.NextPermissions = item.EveryOnePermissions; item.Owner = client.AgentId; item.SalePrice = 10; item.SaleType = (byte)SaleType.Not; ((Scene)client.Scene).AddInventoryItem(client, item); } private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID) { m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}", client.AgentId, client.FirstName, client.LastName, transactionID, folderID); UUID destID; lock (m_pendingCallingcardRequests) { if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) { m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", client.Name); return; } // else found pending calling card request with that transaction. m_pendingCallingcardRequests.Remove(transactionID); } ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); // inform sender of the card that destination declined the offer if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID); // put a calling card into the inventory of receiver CreateCallingCard(client, destID, folderID, destAgent.Name); } private void OnDeclineCallingCard(IClientAPI client, UUID transactionID) { m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}", client.Name, client.AgentId, transactionID); UUID destID; lock (m_pendingCallingcardRequests) { if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID)) { m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.", client.Name); return; } // else found pending calling card request with that transaction. m_pendingCallingcardRequests.Remove(transactionID); } ScenePresence destAgent = GetAnyPresenceFromAgentID(destID); // inform sender of the card that destination declined the offer if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID); } /// <summary> /// Send presence information about a client to other clients in both this region and others. /// </summary> /// <param name="client"></param> /// <param name="friendList"></param> /// <param name="iAmOnline"></param> private void SendPresenceState(IClientAPI client, List<FriendListItem> friendList, bool iAmOnline) { //m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out"); if (friendList == null || friendList.Count == 0) { //m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name); return; // nothing we can do if she doesn't have friends... } // collect sets of friendIDs; to send to (online and offline), and to receive from // TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets. // I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago... List<UUID> friendIDsToSendTo = new List<UUID>(); List<UUID> candidateFriendIDsToReceive = new List<UUID>(); foreach (FriendListItem item in friendList) { if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0) { // friend is allowed to see my presence => add if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0) friendIDsToSendTo.Add(item.Friend); if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) candidateFriendIDsToReceive.Add(item.Friend); } } // we now have a list of "interesting" friends (which we have to find out on-/offline state for), // friends we want to send our online state to (if *they* are online, too), and // friends we want to receive online state for (currently unknown whether online or not) // as this processing might take some time and friends might TP away, we try up to three times to // reach them. Most of the time, we *will* reach them, and this loop won't loop int retry = 0; do { // build a list of friends to look up region-information and on-/offline-state for List<UUID> friendIDsToLookup = new List<UUID>(friendIDsToSendTo); foreach (UUID uuid in candidateFriendIDsToReceive) { if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid); } m_log.DebugFormat( "[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}", friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name); // we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't // necessarily contain the correct online state... Dictionary<UUID, FriendRegionInfo> friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup); m_log.DebugFormat( "[FRIEND]: Found {0} regionInfos for {1} friends of {2}", friendRegions.Count, friendIDsToLookup.Count, client.Name); // argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops. UUID[] agentArr = new UUID[] { client.AgentId }; // first, send to friend presence state to me, if I'm online... if (iAmOnline) { List<UUID> friendIDsToReceive = new List<UUID>(); for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i) { UUID uuid = candidateFriendIDsToReceive[i]; FriendRegionInfo info; if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) { friendIDsToReceive.Add(uuid); } } m_log.DebugFormat( "[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name); if (friendIDsToReceive.Count > 0) client.SendAgentOnline(friendIDsToReceive.ToArray()); // clear them for a possible second iteration; we don't have to repeat this candidateFriendIDsToReceive.Clear(); } // now, send my presence state to my friends for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i) { UUID uuid = friendIDsToSendTo[i]; FriendRegionInfo info; if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline) { // any client is good enough, root or child... ScenePresence agent = GetAnyPresenceFromAgentID(uuid); if (agent != null) { //m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name); // friend is online and on this server... if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr); else agent.ControllingClient.SendAgentOffline(agentArr); // done, remove it friendIDsToSendTo.RemoveAt(i); } } else { //m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i); // friend is offline => no need to try sending friendIDsToSendTo.RemoveAt(i); } } m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count); // we now have all the friends left that are online (we think), but not on this region-server if (friendIDsToSendTo.Count > 0) { // sort them into regions Dictionary<ulong, List<UUID>> friendsInRegion = new Dictionary<ulong,List<UUID>>(); foreach (UUID uuid in friendIDsToSendTo) { ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already List<UUID> friends; if (!friendsInRegion.TryGetValue(handle, out friends)) { friends = new List<UUID>(); friendsInRegion[handle] = friends; } friends.Add(uuid); } m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count); // clear uuids list and collect missed friends in it for the next retry friendIDsToSendTo.Clear(); // send bulk updates to the region foreach (KeyValuePair<ulong, List<UUID>> pair in friendsInRegion) { //m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line", // pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off"); friendIDsToSendTo.AddRange(InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline)); } } // now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them. // In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again... } while (++retry < 3 && friendIDsToSendTo.Count > 0); } private void OnEconomyDataRequest(UUID agentID) { // KLUDGE: This is the only way I found to get a message (only) after login was completed and the // client is connected enough to receive UDP packets). // This packet seems to be sent only once, just after connection was established to the first // region after login. // We use it here to trigger a presence update; the old update-on-login was never be heard by // the freshly logged in viewer, as it wasn't connected to the region at that time. // TODO: Feel free to replace this by a better solution if you find one. // get the agent. This should work every time, as we just got a packet from it //ScenePresence agent = GetRootPresenceFromAgentID(agentID); // KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit ScenePresence agent = GetAnyPresenceFromAgentID(agentID); // just to be paranoid... if (agent == null) { m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID); return; } List<FriendListItem> fl; lock (m_friendLists) { fl = (List<FriendListItem>)m_friendLists.Get(agent.ControllingClient.AgentId.ToString(), m_initialScene.GetFriendList); } // tell everyone that we are online SendPresenceState(agent.ControllingClient, fl, true); } private void OnLogout(IClientAPI remoteClient) { List<FriendListItem> fl; lock (m_friendLists) { fl = (List<FriendListItem>)m_friendLists.Get(remoteClient.AgentId.ToString(), m_initialScene.GetFriendList); } // tell everyone that we are offline SendPresenceState(remoteClient, fl, false); } } #endregion }
45.568468
147
0.554556
[ "BSD-3-Clause" ]
Ideia-Boa/diva-distribution
OpenSim/Region/CoreModules/Avatar/Friends/FriendsModule.cs
50,581
C#
using System; using System.IO; public class NgFile { public static string PathSeparatorNormalize(string path) { char[] array = path.ToCharArray(); for (int i = 0; i < path.get_Length(); i++) { if (path.get_Chars(i) == '/' || path.get_Chars(i) == '\\') { array[i] = '/'; } } path = new string(array); return path; } public static string CombinePath(string path1, string path2) { return NgFile.PathSeparatorNormalize(Path.Combine(path1, path2)); } public static string CombinePath(string path1, string path2, string path3) { return NgFile.PathSeparatorNormalize(Path.Combine(Path.Combine(path1, path2), path3)); } public static string GetSplit(string path, int nIndex) { if (nIndex < 0) { return path; } string[] array = path.Split(new char[] { '/', '\\' }); if (nIndex < array.Length) { return array[nIndex]; } return string.Empty; } public static string GetFilename(string path) { int num = path.get_Length() - 1; while (0 <= num) { if (path.get_Chars(num) == '/' || path.get_Chars(num) == '\\') { if (num == path.get_Length() - 1) { return string.Empty; } return NgFile.TrimFileExt(path.Substring(num + 1)); } else { num--; } } return NgFile.TrimFileExt(path); } public static string GetFilenameExt(string path) { int num = path.get_Length() - 1; while (0 <= num) { if (path.get_Chars(num) == '/' || path.get_Chars(num) == '\\') { if (num == path.get_Length() - 1) { return string.Empty; } return path.Substring(num + 1); } else { num--; } } return path; } public static string GetFileExt(string path) { int num = path.get_Length() - 1; while (0 <= num) { if (path.get_Chars(num) == '.') { return path.Substring(num + 1); } num--; } return string.Empty; } public static string TrimFilenameExt(string path) { int num = path.get_Length() - 1; while (0 <= num) { if (path.get_Chars(num) == '/' || path.get_Chars(num) == '\\') { return path.Substring(0, num); } num--; } return string.Empty; } public static string TrimFileExt(string filename) { int num = filename.get_Length() - 1; while (0 <= num) { if (filename.get_Chars(num) == '.') { return filename.Substring(0, num); } num--; } return filename; } public static string TrimLastFolder(string path) { int num = path.get_Length() - 1; while (0 <= num) { if ((path.get_Chars(num) == '/' || path.get_Chars(num) == '\\') && num != path.get_Length() - 1) { return path.Substring(0, num); } num--; } return string.Empty; } public static string GetLastFolder(string path) { int num = path.get_Length() - 1; while (0 <= num) { if ((path.get_Chars(num) == '/' || path.get_Chars(num) == '\\') && num != path.get_Length() - 1) { if (path.get_Chars(path.get_Length() - 1) == '/' || path.get_Chars(path.get_Length() - 1) == '\\') { return path.Substring(num + 1, path.get_Length() - num - 2); } return path.Substring(num + 1, path.get_Length() - num - 1); } else { num--; } } return path; } public static bool CompareExtName(string srcPath, string tarLowerExt, bool bCheckCase) { if (bCheckCase) { return NgFile.GetFilenameExt(srcPath).ToLower() == tarLowerExt; } return NgFile.GetFilenameExt(srcPath) == tarLowerExt; } }
19.568182
102
0.590302
[ "MIT" ]
corefan/tianqi_src
src/NgFile.cs
3,444
C#
namespace Demo.Reviews { public record Author(int Id, string Name); }
18.25
46
0.726027
[ "MIT" ]
glucaci/elastic-apm-poc
src/reviews/Author.cs
73
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Net.HttpEndPointManager // // Author: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Collections.Generic; using System.Net.Sockets; namespace System.Net { internal sealed class HttpEndPointManager { private static Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>> s_ipEndPoints = new Dictionary<IPAddress, Dictionary<int, HttpEndPointListener>>(); private HttpEndPointManager() { } public static void AddListener(HttpListener listener) { List<string> added = new List<string>(); try { lock ((s_ipEndPoints as ICollection).SyncRoot) { foreach (string prefix in listener.Prefixes) { AddPrefixInternal(prefix, listener); added.Add(prefix); } } } catch { foreach (string prefix in added) { RemovePrefix(prefix, listener); } throw; } } public static void AddPrefix(string prefix, HttpListener listener) { lock ((s_ipEndPoints as ICollection).SyncRoot) { AddPrefixInternal(prefix, listener); } } private static void AddPrefixInternal(string p, HttpListener listener) { int start = p.IndexOf(':') + 3; int colon = p.IndexOf(':', start); if (colon != -1) { // root can't be -1 here, since we've already checked for ending '/' in ListenerPrefix. int root = p.IndexOf('/', colon, p.Length - colon); string portString = p.Substring(colon + 1, root - colon - 1); int port; if (!int.TryParse(portString, out port) || port <= 0 || port >= 65536) { throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_port); } } ListenerPrefix lp = new ListenerPrefix(p); if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_listener_host); if (lp.Path!.Contains('%')) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); // listens on all the interfaces if host name cannot be parsed by IPAddress. HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.AddPrefix(lp, listener); } private static HttpEndPointListener GetEPListener(string host, int port, HttpListener listener, bool secure) { IPAddress addr; if (host == "*" || host == "+") { addr = IPAddress.Any; } else { const int NotSupportedErrorCode = 50; try { addr = Dns.GetHostAddresses(host)[0]; } catch { // Throw same error code as windows, request is not supported. throw new HttpListenerException(NotSupportedErrorCode, SR.net_listener_not_supported); } if (IPAddress.Any.Equals(addr)) { // Don't support listening to 0.0.0.0, match windows behavior. throw new HttpListenerException(NotSupportedErrorCode, SR.net_listener_not_supported); } } Dictionary<int, HttpEndPointListener>? p; if (s_ipEndPoints.ContainsKey(addr)) { p = s_ipEndPoints[addr]; } else { p = new Dictionary<int, HttpEndPointListener>(); s_ipEndPoints[addr] = p; } HttpEndPointListener? epl; if (p.ContainsKey(port)) { epl = p[port]; } else { try { epl = new HttpEndPointListener(listener, addr, port, secure); } catch (SocketException ex) { throw new HttpListenerException(ex.ErrorCode, ex.Message); } p[port] = epl; } return epl; } public static void RemoveEndPoint(HttpEndPointListener epl, IPEndPoint ep) { lock ((s_ipEndPoints as ICollection).SyncRoot) { Dictionary<int, HttpEndPointListener>? p = null; p = s_ipEndPoints[ep.Address]; p.Remove(ep.Port); if (p.Count == 0) { s_ipEndPoints.Remove(ep.Address); } epl.Close(); } } public static void RemoveListener(HttpListener listener) { lock ((s_ipEndPoints as ICollection).SyncRoot) { foreach (string prefix in listener.Prefixes) { RemovePrefixInternal(prefix, listener); } } } public static void RemovePrefix(string prefix, HttpListener listener) { lock ((s_ipEndPoints as ICollection).SyncRoot) { RemovePrefixInternal(prefix, listener); } } private static void RemovePrefixInternal(string prefix, HttpListener listener) { ListenerPrefix lp = new ListenerPrefix(prefix); if (lp.Path!.Contains('%')) return; if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) return; HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.RemovePrefix(lp, listener); } } }
35.364055
167
0.545478
[ "MIT" ]
333fred/runtime
src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs
7,674
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PartsUnlimited.Models { public class ConfigSettings { public ConnectionStringsSettings ConnectionStrings { get; set; } } public class ConnectionStringsSettings { public string DefaultConnectionString { get; set; } } }
20.444444
72
0.720109
[ "MIT" ]
ganeshtodkar20/GDBC-PartsUnlimited
src/PartsUnlimited.Models/ConfigSettings.cs
370
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.Applications.Events; using Microsoft.Quantum.Telemetry.Commands; namespace Microsoft.Quantum.Telemetry.OutOfProcess { public interface IExternalProcessConnector : IDisposable { TextWriter? InputTextWriter { get; } TextReader? OutputTextReader { get; } bool IsRunning { get; } void WaitForExit(); void Start(); void Kill(); } internal class DefaultExternalProcessConnector : IExternalProcessConnector { private TelemetryManagerConfig configuration; private Process? process; private bool disposedValue; private object instanceLock = new object(); public TextWriter? InputTextWriter => this.process?.StandardInput; public TextReader? OutputTextReader => this.process?.StandardOutput; public bool IsRunning => (this.process != null) && !this.process.HasExited; public void WaitForExit() => this.process?.WaitForExit(); public DefaultExternalProcessConnector(TelemetryManagerConfig configuration) { this.configuration = configuration; } private Process StartProcess() { List<string> arguments = new List<string>(); var outOfProcessExecutablePath = this.configuration.OutOfProcessExecutablePath; if (string.IsNullOrEmpty(outOfProcessExecutablePath)) { outOfProcessExecutablePath = Process.GetCurrentProcess().MainModule!.FileName!; // if this is not a self-contained application, we need to run it via the dotnet cli if (string.Equals( Path.GetFileNameWithoutExtension(outOfProcessExecutablePath), "dotnet", StringComparison.InvariantCultureIgnoreCase)) { if (TelemetryManager.IsTestHostProcess) { throw new InvalidOperationException($"'testhost' cannot be used as an external process. Please set the config option 'OutOfProcessExecutablePath'."); } else { arguments.Add($"{Assembly.GetEntryAssembly()!.Location} "); } } } else if (string.Equals( ".dll", Path.GetExtension(outOfProcessExecutablePath), StringComparison.InvariantCultureIgnoreCase)) { // if this is not a self-contained application, we need to run it via the dotnet cli arguments.Add(outOfProcessExecutablePath); outOfProcessExecutablePath = "dotnet"; } arguments.Add(TelemetryManagerConstants.OUTOFPROCESSUPLOADARG); if (this.configuration.TestMode) { arguments.Add(TelemetryManagerConstants.TESTMODE); } var process = new Process() { StartInfo = new ProcessStartInfo() { FileName = outOfProcessExecutablePath, Arguments = string.Join(' ', arguments), RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, }, EnableRaisingEvents = true, }; process.Exited += (sender, e) => { this.process = null; }; process.Start(); return process; } public void Start() { if (this.process == null) { lock (this.instanceLock) { if (this.process == null) { this.process = this.StartProcess(); } } } } public void Kill() { try { this.process?.Kill(); } catch { } this.process = null; } protected virtual void Dispose(bool disposing) { if (!this.disposedValue) { if (disposing) { this.process?.Dispose(); } this.disposedValue = true; } } public void Dispose() { this.Dispose(disposing: true); GC.SuppressFinalize(this); } } public class OutOfProcessLogger : ILogger, IDisposable { private IExternalProcessConnector externalProcess; private ConcurrentDictionary<Thread, object?>? debugThreads; private ICommandSerializer serializer; private TelemetryManagerConfig configuration; private object instanceLock = new object(); private bool disposedValue; public OutOfProcessLogger(TelemetryManagerConfig configuration, IExternalProcessConnector? externalProcessConnector = null) { this.configuration = configuration; this.serializer = (ICommandSerializer)Activator.CreateInstance(configuration.OutOfProcessSerializerType)!; this.externalProcess = externalProcessConnector ?? new DefaultExternalProcessConnector(configuration); if (TelemetryManagerConstants.IsDebugBuild || configuration.TestMode) { this.debugThreads = new ConcurrentDictionary<Thread, object?>(); } } public void AwaitForExternalProcessExit() => this.externalProcess.WaitForExit(); private void CreateExternalProcessIfNeeded() { if (!this.externalProcess.IsRunning) { lock (this.instanceLock) { if (!this.externalProcess.IsRunning) { this.externalProcess.Start(); if (TelemetryManagerConstants.IsDebugBuild || TelemetryManager.TestMode) { this.debugThreads!.TryAdd(this.StartDebugThread(), null); } } } } } private EVTStatus SendCommand(CommandBase command) { // let's not start a new process just to ask it to quit if (!(command is QuitCommand)) { this.CreateExternalProcessIfNeeded(); if (!this.externalProcess.IsRunning) { throw new InvalidOperationException("OutOfProcessUpload external process is not running"); } } var success = this.TrySendCommand(command); // try one more time if this is not a Quit command if (!success && !(command is QuitCommand)) { this.CreateExternalProcessIfNeeded(); success = this.TrySendCommand(command); } return success ? EVTStatus.OK : EVTStatus.Fail; } private bool TrySendCommand(CommandBase command) { try { var messages = this.serializer.Write(command); lock (this.instanceLock) { foreach (var message in messages) { this.externalProcess.InputTextWriter?.WriteLine(message); } } return true; } catch (IOException) { // If we get an IOException it means we are unable to communicate // with the external process anymore and we need to kill it. this.externalProcess.Kill(); } return false; } public void Quit() => this.SendCommand(new QuitCommand()); public EVTStatus LogEvent(EventProperties eventProperties) => this.SendCommand(new LogEventCommand(eventProperties)); public EVTStatus SetContext(string name, object value, TelemetryPropertyType type, PiiKind piiKind = PiiKind.None) => this.SendCommand(new SetContextCommand(new SetContextArgs(name, value, type, piiKind != PiiKind.None))); public EVTStatus SetContext(string name, string value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.String, piiKind); public EVTStatus SetContext(string name, double value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.Double, piiKind); public EVTStatus SetContext(string name, long value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.Long, piiKind); public EVTStatus SetContext(string name, bool value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.Boolean, piiKind); public EVTStatus SetContext(string name, DateTime value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.DateTime, piiKind); public EVTStatus SetContext(string name, Guid value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, value, TelemetryPropertyType.Guid, piiKind); public EVTStatus SetContext(string name, sbyte value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); public EVTStatus SetContext(string name, short value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); public EVTStatus SetContext(string name, int value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); public EVTStatus SetContext(string name, byte value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); public EVTStatus SetContext(string name, ushort value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); public EVTStatus SetContext(string name, uint value, PiiKind piiKind = PiiKind.None) => this.SetContext(name, (long)value, piiKind); private Thread StartDebugThread() { Thread thread = new Thread(this.DebugThreadMethod); thread.Start(); return thread; } private void DebugThreadMethod() { while (!this.disposedValue && this.externalProcess.OutputTextReader != null) { try { var message = this.externalProcess.OutputTextReader.ReadLine(); if (message != null) { TelemetryManager.LogToDebug($"OutOfProcessUploader sent: {message}"); } else { Thread.Sleep(TimeSpan.FromSeconds(1)); if (!this.externalProcess.IsRunning) { break; } } } catch (ThreadInterruptedException) { break; } catch (Exception exception) { TelemetryManager.LogToDebug($"OutOfProcessLogger failed to read uploader:{Environment.NewLine}{exception}"); break; } } TelemetryManager.LogToDebug($"OutOfProcessUploader has exited."); this.debugThreads?.TryRemove(Thread.CurrentThread, out var _); } protected virtual void Dispose(bool disposing) { if (!this.disposedValue) { if (disposing) { this.externalProcess.Dispose(); } this.disposedValue = true; this.debugThreads?.Keys.ToList().ForEach((debugThread) => debugThread.Interrupt()); } } public void Dispose() { this.Dispose(disposing: true); GC.SuppressFinalize(this); } } }
34.715818
173
0.547301
[ "MIT" ]
ScriptBox99/qsharp-compiler
src/Telemetry/Library/OutOfProcess/OutOfProcessLogger.cs
12,949
C#
using System; namespace FontAwesome { /// <summary> /// The unicode values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Unicode { /// <summary> /// fa-files-medical unicode value ("\uf7fd"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/files-medical /// </summary> public const string FilesMedical = "\uf7fd"; } /// <summary> /// The Css values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Css { /// <summary> /// FilesMedical unicode value ("fa-files-medical"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/files-medical /// </summary> public const string FilesMedical = "fa-files-medical"; } /// <summary> /// The Icon names for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Icon { /// <summary> /// fa-files-medical unicode value ("\uf7fd"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/files-medical /// </summary> public const string FilesMedical = "FilesMedical"; } }
37.098361
154
0.597879
[ "MIT" ]
michaelswells/FontAwesomeAttribute
FontAwesome/FontAwesome.FilesMedical.cs
2,263
C#
/* * Copyright (c) Contributors, http://vision-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Vision-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.IO; using Nini.Config; using Vision.Framework.ConsoleFramework; using Vision.Framework.DatabaseInterfaces; using Vision.Framework.Modules; using Vision.Framework.Servers; using Vision.Framework.Services; using Vision.Framework.Services.ClassHelpers.Profile; using Vision.Framework.Utilities; namespace Vision.Services { public class BannedUserLoginModule : ILoginModule { protected IAuthenticationService m_AuthenticationService; protected ILoginService m_LoginService; protected bool m_UseTOS = false; protected string m_TOSLocation = ""; public string Name { get { return GetType ().Name; } } public void Initialize (ILoginService service, IConfigSource config, IRegistryCore registry) { IConfig loginServerConfig = config.Configs ["LoginService"]; if (loginServerConfig != null) { m_UseTOS = loginServerConfig.GetBoolean ("UseTermsOfServiceOnFirstLogin", false); m_TOSLocation = loginServerConfig.GetString ("FileNameOfTOS", ""); if (m_TOSLocation.Length > 0) { if (m_TOSLocation.ToLower ().StartsWith ("http://", StringComparison.Ordinal)) m_TOSLocation = m_TOSLocation.Replace ("ServersHostname", MainServer.Instance.HostName); else { var simBase = registry.RequestModuleInterface<ISimulationBase> (); var TOSFileName = PathHelpers.VerifyReadFile (m_TOSLocation, ".txt", simBase.DefaultDataPath + "/html"); if (TOSFileName == "") { m_UseTOS = false; MainConsole.Instance.ErrorFormat ("Unable to locate the Terms of Service file : '{0}'", m_TOSLocation); MainConsole.Instance.Error ("Displaying 'Terms of Service' for a new user login is disabled!"); } else m_TOSLocation = TOSFileName; } } else m_UseTOS = false; } m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService> (); m_LoginService = service; } public LoginResponse Login (Hashtable request, UserAccount account, IAgentInfo agentInfo, string authType, string password, out object data) { IAgentConnector agentData = Framework.Utilities.DataManager.RequestPlugin<IAgentConnector> (); data = null; if (request == null) return null; //If its null, its just a verification request, allow them to see things even if they are banned bool tosExists = false; string tosAccepted = ""; if (request.ContainsKey ("agree_to_tos")) { tosExists = true; tosAccepted = request ["agree_to_tos"].ToString (); } //MAC BANNING START var mac = (string)request ["mac"]; if (mac == "") { data = "Bad Viewer Connection"; return new LLFailedLoginResponse (LoginResponseEnum.Indeterminant, data.ToString (), false); } // TODO: Some TPV's now send their version in the Channel /* string channel = "Unknown"; if (request.Contains("channel") && request["channel"] != null) channel = request["channel"].ToString(); */ bool AcceptedNewTOS = false; //This gets if the viewer has accepted the new TOS if (!agentInfo.AcceptTOS && tosExists) { if (tosAccepted == "0") AcceptedNewTOS = false; else if (tosAccepted == "1") AcceptedNewTOS = true; else AcceptedNewTOS = bool.Parse (tosAccepted); if (agentInfo.AcceptTOS != AcceptedNewTOS) { agentInfo.AcceptTOS = AcceptedNewTOS; agentData.UpdateAgent (agentInfo); } } if (!AcceptedNewTOS && !agentInfo.AcceptTOS && m_UseTOS) { data = "TOS not accepted"; if (m_TOSLocation.ToLower ().StartsWith ("http://", StringComparison.Ordinal)) return new LLFailedLoginResponse (LoginResponseEnum.ToSNeedsSent, m_TOSLocation, false); // text file var ToSText = File.ReadAllText (Path.Combine (Environment.CurrentDirectory, m_TOSLocation)); return new LLFailedLoginResponse (LoginResponseEnum.ToSNeedsSent, ToSText, false); } if ((agentInfo.Flags & IAgentFlags.PermBan) == IAgentFlags.PermBan) { MainConsole.Instance.InfoFormat ( "[Login service]: Login failed for user {0}, reason: user is permanently banned.", account.Name); data = "Permanently banned"; return LLFailedLoginResponse.PermanentBannedProblem; } if ((agentInfo.Flags & IAgentFlags.TempBan) == IAgentFlags.TempBan) { bool IsBanned = true; string until = ""; if (agentInfo.OtherAgentInformation.ContainsKey ("TemporaryBanInfo")) { DateTime bannedTime = agentInfo.OtherAgentInformation ["TemporaryBanInfo"].AsDate (); until = string.Format (" until {0} {1}", bannedTime.ToLocalTime ().ToShortDateString (), bannedTime.ToLocalTime ().ToLongTimeString ()); //Check to make sure the time hasn't expired if (bannedTime.Ticks < DateTime.Now.ToUniversalTime ().Ticks) { //The banned time is less than now, let the user in. IsBanned = false; } } if (IsBanned) { MainConsole.Instance.InfoFormat ( "[Login service]: Login failed for user {0}, reason: user is temporarily banned {1}.", account.Name, until); data = string.Format ("You are blocked from connecting to this service{0}.", until); return new LLFailedLoginResponse (LoginResponseEnum.Indeterminant, data.ToString (), false); } } return null; } } }
48.788571
132
0.586671
[ "MIT" ]
VisionSim/Vision-Sim
Vision/Services/GenericServices/LLLoginService/LoginModules/BannedUserLoginModule.cs
8,540
C#
namespace Definux.Emeraude.Resources { /// <summary> /// Default system formats in the Emeraude. /// </summary> public static class SystemFormats { /// <summary> /// Default date format used by Emeraude. /// </summary> public const string DateFormat = "dddd, dd/MM/yyyy"; /// <summary> /// Default time format used by Emeraude. /// </summary> public const string TimeFormat = @"hh\:mm"; /// <summary> /// Default date time format used by Emeraude. /// </summary> public const string DateTimeFormat = "dddd, dd/MM/yyyy HH:mm"; /// <summary> /// Default short date format used by Emeraude. /// </summary> public const string ShortDateFormat = "dd/MM/yyyy"; /// <summary> /// Default date separator used by Emeraude. /// </summary> public const string DateSeparator = "/"; } }
28.323529
70
0.554517
[ "Apache-2.0" ]
Definux/Emeraude
src/Core/Definux.Emeraude.Resources/SystemFormats.cs
965
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.DependencyInjection; using WorkflowCore.IntegrationTests.Scenarios; using Xunit; namespace WorkflowCore.Tests.PostgreSQL.Scenarios { [Collection("Postgres collection")] public class PostgresForeachScenario : ForeachScenario { protected override void ConfigureServices(IServiceCollection services) { services.AddWorkflow(x => x.UsePostgreSQL(PostgresDockerSetup.ScenarioConnectionString, true, true)); } } }
29.631579
113
0.74778
[ "MIT" ]
201512130144/demo
test/WorkflowCore.Tests.PostgreSQL/Scenarios/PostgresForeachScenario.cs
565
C#
using System; using System.ComponentModel; using System.Threading.Tasks; using Xamarin.Forms; using Connectivity.Plugin; using Microsoft.WindowsAzure.MobileServices; namespace Moments { public class App : Application { public App () { Styles.RegisterGlobalStyles (); if (AccountService.Instance.ReadyToSignIn) { MainPage = FetchMainUI (); } else { MainPage = new WelcomePage (); } } public static NavigationPage FetchMainUI () { var momentsPage = new MomentsPage (); var cameraPage = new CameraPage (); var friendsPage = new FriendsPage (); var profilePage = new ProfilePage (); var carouselPage = new CarouselPage { Children = { momentsPage, cameraPage, friendsPage, profilePage }, CurrentPage = momentsPage }; var navigationPage = new NavigationPage (carouselPage) { BarBackgroundColor = Colors.NavigationBarColor, BarTextColor = Colors.NavigationBarTextColor }; if (Device.OS != TargetPlatform.Android) { NavigationPage.SetHasNavigationBar (carouselPage, false); carouselPage.CurrentPage = cameraPage; } else { carouselPage.Title = "Friends"; carouselPage.CurrentPage = friendsPage; } carouselPage.PropertyChanged += (object sender, PropertyChangedEventArgs e) => { if (e.PropertyName == "CurrentPage") { var currentPageType = carouselPage.CurrentPage.GetType (); if (currentPageType == typeof (MomentsPage)) { NavigationPage.SetHasNavigationBar (carouselPage, true); carouselPage.Title = "Moments"; } else if (currentPageType == typeof (CameraPage)) { NavigationPage.SetHasNavigationBar (carouselPage, false); carouselPage.Title = "Camera"; } else if (currentPageType == typeof (ProfilePage)) { NavigationPage.SetHasNavigationBar (carouselPage, true); carouselPage.Title = "Profile"; } else { NavigationPage.SetHasNavigationBar (carouselPage, true); carouselPage.Title = "Friends"; } } }; carouselPage.CurrentPageChanged += (object sender, EventArgs e) => { var currentPage = carouselPage.CurrentPage as BasePage; if (carouselPage.CurrentPage.GetType () == typeof (FriendsPage) && Device.OS == TargetPlatform.iOS) { currentPage.LeftToolbarItems.Add (new ToolbarItem { Icon = "FriendRequestsButton.png", Command = new Command (() => currentPage.Navigation.PushModalAsync (new NavigationPage (new FriendRequestsPage ()) { BarBackgroundColor = Colors.NavigationBarColor, BarTextColor = Colors.NavigationBarTextColor }, true)), Priority = 1 }); } else { currentPage.LeftToolbarItems.Clear (); } }; return navigationPage; } } }
29.12766
122
0.686998
[ "MIT" ]
BrotherBrett/moments
Moments - CSharp/Moments.Shared/Moments.cs
2,738
C#
using System; using System.IO; using System.Text; using System.Threading.Tasks; namespace Parse.Internal.Utilities { /// <summary> /// A collection of utility methods and properties for writing to the app-specific persistent storage folder. /// </summary> internal static class StorageManager { static StorageManager() => AppDomain.CurrentDomain.ProcessExit += (_, __) => { if (new FileInfo(FallbackPersistentStorageFilePath) is FileInfo file && file.Exists) file.Delete(); }; /// <summary> /// The path to a persistent user-specific storage location specific to the final client assembly of the Parse library. /// </summary> public static string PersistentStorageFilePath => Path.GetFullPath(Path.Combine(ParseClient.CurrentConfiguration.StorageConfiguration.RelativeStorageFilePath, ParseClient.CurrentConfiguration.StorageConfiguration?.RelativeStorageFilePath ?? FallbackPersistentStorageFilePath)); /// <summary> /// Gets the calculated persistent storage file fallback path for this app execution. /// </summary> public static string FallbackPersistentStorageFilePath { get; } = ParseClient.Configuration.IdentifierBasedStorageConfiguration.Fallback.RelativeStorageFilePath; /// <summary> /// Asynchronously writes the provided little-endian 16-bit character string <paramref name="content"/> to the file wrapped by the provided <see cref="FileInfo"/> instance. /// </summary> /// <param name="file">The <see cref="FileInfo"/> instance wrapping the target file that is to be written to</param> /// <param name="content">The little-endian 16-bit Unicode character string (UTF-16) that is to be written to the <paramref name="file"/></param> /// <returns>A task that completes once the write operation to the <paramref name="file"/> completes</returns> public static async Task WriteToAsync(this FileInfo file, string content) { using (FileStream stream = new FileStream(Path.GetFullPath(file.FullName), FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan | FileOptions.Asynchronous)) { byte[] data = Encoding.Unicode.GetBytes(content); await stream.WriteAsync(data, 0, data.Length); } } /// <summary> /// Asynchronously read all of the little-endian 16-bit character units (UTF-16) contained within the file wrapped by the provided <see cref="FileInfo"/> instance. /// </summary> /// <param name="file">The <see cref="FileInfo"/> instance wrapping the target file that string content is to be read from</param> /// <returns>A task that should contain the little-endian 16-bit character string (UTF-16) extracted from the <paramref name="file"/> if the read completes successfully</returns> public static async Task<string> ReadAllTextAsync(this FileInfo file) { using (StreamReader reader = new StreamReader(file.OpenRead(), Encoding.Unicode)) return await reader.ReadToEndAsync(); } /// <summary> /// Gets or creates the file pointed to by <see cref="PersistentStorageFilePath"/> and returns it's wrapper as a <see cref="FileInfo"/> instance. /// </summary> public static FileInfo PersistentStorageFileWrapper { get { Directory.CreateDirectory(PersistentStorageFilePath.Substring(0, PersistentStorageFilePath.LastIndexOf(Path.DirectorySeparatorChar))); FileInfo file = new FileInfo(PersistentStorageFilePath); if (!file.Exists) using (file.Create()) ; // Hopefully the JIT doesn't no-op this. The behaviour of the "using" clause should dictate how the stream is closed, to make sure it happens properly. return file; } } /// <summary> /// Gets the file wrapper for the specified <paramref name="path"/>. /// </summary> /// <param name="path">The relative path to the target file</param> /// <returns>An instance of <see cref="FileInfo"/> wrapping the the <paramref name="path"/> value</returns> public static FileInfo GetWrapperForRelativePersistentStorageFilePath(string path) { path = Path.GetFullPath(Path.Combine(ParseClient.CurrentConfiguration.StorageConfiguration.RelativeStorageFilePath, path)); return new FileInfo(path); } public static async Task TransferAsync(string originFilePath, string targetFilePath) { if (!String.IsNullOrWhiteSpace(originFilePath) && !String.IsNullOrWhiteSpace(targetFilePath) && new FileInfo(originFilePath) is FileInfo originFile && originFile.Exists && new FileInfo(targetFilePath) is FileInfo targetFile) using (StreamWriter writer = new StreamWriter(targetFile.OpenWrite(), Encoding.Unicode)) using (StreamReader reader = new StreamReader(originFile.OpenRead(), Encoding.Unicode)) await writer.WriteAsync(await reader.ReadToEndAsync()); } } }
58.741573
285
0.675593
[ "BSD-3-Clause" ]
alexnaldo/Parse-SDK-dotNET
Parse/Internal/Utilities/StorageManager.cs
5,228
C#
// Copyright Epic Games, Inc. All Rights Reserved. using EOSCSharpSample.Helpers; using EOSCSharpSample.Services; using EOSCSharpSample.ViewModels; namespace EOSCSharpSample.Commands { public class FriendsSubscribeUpdatesCommand : CommandBase { public override bool CanExecute(object parameter) { return !string.IsNullOrWhiteSpace(ViewModelLocator.Main.AccountId) && (ViewModelLocator.Friends.Friends.Count != 0) && (ViewModelLocator.Friends.NotificationId == 0); } public override void Execute(object parameter) { FriendsService.SubscribeUpdates(); } } }
29.272727
178
0.703416
[ "MIT" ]
EpicGames/EOS-Getting-Started
CSharp/EOSCSharpSample_10/EOSCSharpSample/EOSCSharpSample/Commands/FriendsSubscribeUpdatesCommand.cs
646
C#
using Xamarin.Forms; using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; namespace PlatformSpecifics { public class iOSModalPagePresentationStyleCS : ContentPage { public iOSModalPagePresentationStyleCS() { On<iOS>().SetModalPresentationStyle(UIModalPresentationStyle.OverFullScreen); var button = new Button { Text = "Return to Platform-Specifics List" }; button.Clicked += async (sender, e) => { await Navigation.PopModalAsync(); }; Content = new StackLayout { Margin = new Thickness(20,35,20,20), Children = { new Label { Text = "Modal popup as a form sheet.", HorizontalOptions = LayoutOptions.Center }, button } }; } } }
30.4
114
0.573465
[ "Apache-2.0" ]
15217711253/xamarin-forms-samples
UserInterface/PlatformSpecifics/PlatformSpecifics/iOS/CS/iOSModalPagePresentationStyleCS.cs
914
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Asn1Editor")] [assembly: AssemblyDescription("ASN.1 .NET-based WPF data viewer and editor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sysadmins LV")] [assembly: AssemblyProduct("Asn1Editor")] [assembly: AssemblyCopyright("Copyright © Sysadmins LV 2014 - 2018")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.10.1")] [assembly: AssemblyFileVersion("1.3.10.1")] [assembly: GuidAttribute("2b21970c-0f72-4a53-909e-23148c2f7540")]
41.245614
93
0.76308
[ "MIT" ]
KohrAhr/Asn1Editor.WPF
Asn1Editor/Properties/AssemblyInfo.cs
2,354
C#
using BaGet.Core.Entities; namespace BaGet.Core.Legacy.OData { public class PackageWithUrls { private readonly string resourceIdUrl; private readonly string packageContentUrl; private readonly ODataPackage pkg; public PackageWithUrls(ODataPackage pkg, string resourceIdUrl, string packageContentUrl) { this.pkg = pkg; this.resourceIdUrl = resourceIdUrl; this.packageContentUrl = packageContentUrl; } public PackageWithUrls(Package pkg, string resourceIdUrl, string packageContentUrl) { this.pkg = new ODataPackage(pkg); this.resourceIdUrl = resourceIdUrl; this.packageContentUrl = packageContentUrl; } public string ResourceIdUrl => resourceIdUrl; public string PackageContentUrl => packageContentUrl; public ODataPackage Pkg => pkg; } }
28.875
96
0.659091
[ "MIT" ]
ai-traders/BaGet
src/BaGet.Core/Legacy/OData/PackageUrls.cs
924
C#
using System; using System.Linq.Expressions; namespace QiBuBlog.Util { internal static class PredicateBuilder { private static Expression<Func<T, bool>> BaseAnd<T>() { return f => true; } private static Expression<Func<T, bool>> BaseOr<T>() { return f => false; } public static Expression<Func<T, bool>> Or<T>( this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var secondBody = expr2.Body.Replace(expr2.Parameters[0], expr1.Parameters[0]); return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, secondBody), expr1.Parameters); } public static Expression<Func<T, bool>> And<T>( this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var secondBody = expr2.Body.Replace(expr2.Parameters[0], expr1.Parameters[0]); return Expression.Lambda<Func<T, bool>> (Expression.AndAlso(expr1.Body, secondBody), expr1.Parameters); } private static Expression Replace(this Expression expression, Expression searchEx, Expression replaceEx) { return new ReplaceVisitor(searchEx, replaceEx).Visit(expression); } public static Expression<Func<T, bool>> CombineOrPreicatesWithAndPredicates<T>(this Expression<Func<T, bool>> combinedPredicate, Expression<Func<T, bool>> andPredicate, Expression<Func<T, bool>> orPredicate) { combinedPredicate = combinedPredicate ?? BaseAnd<T>(); if (andPredicate != null && orPredicate != null) { andPredicate = andPredicate.And(orPredicate); combinedPredicate = combinedPredicate.And(andPredicate); } else if (orPredicate != null) { combinedPredicate = combinedPredicate.And(orPredicate); } else { combinedPredicate = combinedPredicate.And(andPredicate); } return combinedPredicate; } public static void AddToPredicateTypeBasedOnIfAndOrOr<T>(ref Expression<Func<T, bool>> andPredicate, ref Expression<Func<T, bool>> orPredicate, Expression<Func<T, bool>> newExpression, bool isAnd) { if (isAnd) { andPredicate = andPredicate ?? BaseAnd<T>(); andPredicate = andPredicate.And(newExpression); } else { orPredicate = orPredicate ?? BaseOr<T>(); orPredicate = orPredicate.Or(newExpression); } } } internal class ReplaceVisitor : ExpressionVisitor { private readonly Expression _from, _to; public ReplaceVisitor(Expression from, Expression to) { this._from = from; this._to = to; } public override Expression Visit(Expression node) { return node == _from ? _to : base.Visit(node); } } public class PredicatePack<T> { private Expression<Func<T, bool>> _expression; public PredicatePack(bool initVal = true) { _expression = p => initVal; } public PredicatePack<T> PushAnd(Expression<Func<T, bool>> exp) { _expression = _expression.And(exp); return this; } public PredicatePack<T> PushOr(Expression<Func<T, bool>> exp) { _expression = _expression.Or(exp); return this; } private Expression<Func<T, bool>> GetExpression() { return (Expression<Func<T, bool>>)_expression.Reduce(); } public static implicit operator Expression<Func<T, bool>>(PredicatePack<T> obj) { return obj.GetExpression(); } } }
32.048
136
0.562906
[ "Apache-2.0" ]
icodemaker/qibublog
Code/QiBuBlog.Util/PredicatePack.cs
4,008
C#
using GSD.Common; using GSD.Tests.Should; using Moq; using Moq.Protected; using NUnit.Framework; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace GSD.UnitTests.Common { [TestFixture] public class OrgInfoServerTests { public static List<OrgInfo> TestOrgInfo = new List<OrgInfo>() { new OrgInfo() { OrgName = "org1", Platform = "windows", Ring = "fast", Version = "1.2.3.1" }, new OrgInfo() { OrgName = "org1", Platform = "windows", Ring = "slow", Version = "1.2.3.2" }, new OrgInfo() { OrgName = "org1", Platform = "macOS", Ring = "fast", Version = "1.2.3.3" }, new OrgInfo() { OrgName = "org1", Platform = "macOS", Ring = "slow", Version = "1.2.3.4" }, new OrgInfo() { OrgName = "org2", Platform = "windows", Ring = "fast", Version = "1.2.3.5" }, new OrgInfo() { OrgName = "org2", Platform = "windows", Ring = "slow", Version = "1.2.3.6" }, new OrgInfo() { OrgName = "org2", Platform = "macOS", Ring = "fast", Version = "1.2.3.7" }, new OrgInfo() { OrgName = "org2", Platform = "macOS", Ring = "slow", Version = "1.2.3.8" }, }; private string baseUrl = "https://www.contoso.com"; private interface IHttpMessageHandlerProtectedMembers { Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken token); } [TestCaseSource("TestOrgInfo")] public void QueryNewestVersionWithParams(OrgInfo orgInfo) { Mock<HttpMessageHandler> handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict); handlerMock.Protected().As<IHttpMessageHandlerProtectedMembers>() .Setup(m => m.SendAsync(It.Is<HttpRequestMessage>(request => this.UriMatches(request.RequestUri, this.baseUrl, orgInfo.OrgName, orgInfo.Platform, orgInfo.Ring)), It.IsAny<CancellationToken>())) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(this.ConstructResponseContent(orgInfo.Version)) }); HttpClient httpClient = new HttpClient(handlerMock.Object); OrgInfoApiClient upgradeChecker = new OrgInfoApiClient(httpClient, this.baseUrl); Version version = upgradeChecker.QueryNewestVersion(orgInfo.OrgName, orgInfo.Platform, orgInfo.Ring); version.ShouldEqual(new Version(orgInfo.Version)); handlerMock.VerifyAll(); } private bool UriMatches(Uri uri, string baseUrl, string expectedOrgName, string expectedPlatform, string expectedRing) { bool hostMatches = uri.Host.Equals(baseUrl); Dictionary<string, string> queryParams = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string param in uri.Query.Substring(1).Split('&')) { string[] fields = param.Split('='); string key = fields[0]; string value = fields[1]; queryParams.Add(key, value); } if (queryParams.Count != 3) { return false; } if (!queryParams.TryGetValue("Organization", out string orgName) || !string.Equals(orgName, expectedOrgName, StringComparison.OrdinalIgnoreCase)) { return false; } if (!queryParams.TryGetValue("platform", out string platform) || !string.Equals(platform, expectedPlatform, StringComparison.OrdinalIgnoreCase)) { return false; } if (!queryParams.TryGetValue("ring", out string ring) || !string.Equals(ring, expectedRing, StringComparison.OrdinalIgnoreCase)) { return false; } return true; } private string ConstructResponseContent(string version) { return $"{{\"version\" : \"{version}\"}} "; } public class OrgInfo { public string OrgName { get; set; } public string Ring { get; set; } public string Platform { get; set; } public string Version { get; set; } } } }
39.711712
209
0.591425
[ "MIT" ]
derrickstolee/VFSForG
GSD/GSD.UnitTests/Common/OrgInfoApiClientTests.cs
4,408
C#
using System; using System.Collections.Generic; using System.Linq; namespace Launchpad { public partial class DeviceInfo { public static DeviceInfo LaunchpadMini { get; } = new DeviceInfo( DeviceType.LaunchpadMini, "Launchpad Mini", "MIDI 1", new byte[,] { { 204, 205, 206, 207, 208, 209, 210, 211, 255 }, { 00, 01, 02, 03, 04, 05, 06, 07, 08 }, { 16, 17, 18, 19, 20, 21, 22, 23, 24 }, { 32, 33, 34, 35, 36, 37, 38, 39, 40 }, { 48, 49, 50, 51, 52, 53, 54, 55, 56 }, { 64, 65, 66, 67, 68, 69, 70, 71, 72 }, { 80, 81, 82, 83, 84, 85, 86, 87, 88 }, { 96, 97, 98, 99, 100, 101, 102, 103, 104 }, { 112, 113, 114, 115, 116, 117, 118, 119, 120 }, }, new byte[,] { { 72, 73, 74, 75, 76, 77, 78, 79, 255 }, { 00, 01, 02, 03, 04, 05, 06, 07, 64 }, { 08, 09, 10, 11, 12, 13, 14, 15, 65 }, { 16, 17, 18, 19, 20, 21, 22, 23, 66 }, { 24, 25, 26, 27, 28, 29, 30, 31, 67 }, { 32, 33, 34, 35, 36, 37, 38, 39, 68 }, { 40, 41, 42, 43, 44, 45, 46, 47, 69 }, { 48, 49, 50, 51, 52, 53, 54, 55, 70 }, { 56, 57, 58, 59, 60, 61, 62, 63, 71 }, }, 0, 0, new Dictionary<byte, SystemButton> { [08] = SystemButton.Track1, [24] = SystemButton.Track2, [40] = SystemButton.Track3, [56] = SystemButton.Track4, [72] = SystemButton.Track5, [88] = SystemButton.Track6, [104] = SystemButton.Track7, [120] = SystemButton.Track8, [204] = SystemButton.Up, [205] = SystemButton.Down, [206] = SystemButton.Left, [207] = SystemButton.Right, [208] = SystemButton.Mode1, [209] = SystemButton.Mode2, [210] = SystemButton.Mode3, [211] = SystemButton.Mode4 }, new Dictionary<byte, Color> { // TODO: Impl }, d => new LaunchpadSRenderer(d)); } }
38.193548
73
0.403716
[ "MIT" ]
DKingAlpha/Launchpad.Net
src/Launchpad.Net/Devices/LaunchpadMini.cs
2,368
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Sql.V20201101Preview.Outputs { [OutputType] public sealed class ManagedInstancePrivateEndpointPropertyResponse { /// <summary> /// Resource id of the private endpoint. /// </summary> public readonly string? Id; [OutputConstructor] private ManagedInstancePrivateEndpointPropertyResponse(string? id) { Id = id; } } }
26.321429
81
0.675712
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Sql/V20201101Preview/Outputs/ManagedInstancePrivateEndpointPropertyResponse.cs
737
C#
using System.Windows; namespace PunkOrgan { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private PunkHammond synth = new PunkHammond(); public MainWindow() { synth.LoadState(); synth.LoadPresets(); DataContext = synth; Closing += synth.Window_Closed; KeyDown += synth.Window_KeyDown; KeyUp += synth.Window_KeyUp; InitializeComponent(); } private void slider_Bending_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) { slider_Bending.Value = 0; } } }
25.482759
125
0.585927
[ "MIT" ]
MiklosPathy/zplusnth
PunkOrgan/MainWindow.xaml.cs
741
C#