content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClaySharp.Behaviors; using Microsoft.CSharp.RuntimeBinder; using NUnit.Framework; namespace ClaySharp.Tests { [TestFixture] public class BinderFallbackTests { class TestMemberBehavior : ClayBehavior { public override object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args) { return name == "Sample" ? "Data" : proceed(); } public override object GetMember(Func<object> proceed, object self, string name) { return name == "Sample" ? "Data" : proceed(); } public override object SetMember(Func<object> proceed, object self, string name, object value) { return name == "Sample" ? "Data" : proceed(); } } class TestIndexBehavior : ClayBehavior { public override object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys) { return IsIndexZero(keys) ? "Data" : proceed(); } public override object SetIndex(Func<object> proceed, object self, IEnumerable<object> keys, object value) { return IsIndexZero(keys) ? "Data" : proceed(); } private static bool IsIndexZero(IEnumerable<object> keys) { return keys.Count() == 1 && keys.Single().GetType() == typeof(int) && keys.Cast<int>().Single() == 0; } } [Test] public void InvokeMemberThrowsFallbackException() { dynamic alpha = new Object(); dynamic beta = new Clay(new TestMemberBehavior()); var ex1 = Assert.Throws<RuntimeBinderException>(() => alpha.Hello1()); Assert.That(ex1.Message, Is.StringEnding("does not contain a definition for 'Hello1'")); var ex2 = Assert.Throws<RuntimeBinderException>(() => beta.Hello2()); Assert.That(ex2.Message, Is.StringEnding("does not contain a definition for 'Hello2'")); Assert.That(beta.Sample(), Is.EqualTo("Data")); } [Test] public void GetMemberThrowsFallbackException() { dynamic alpha = new Object(); dynamic beta = new Clay(new TestMemberBehavior()); var ex1 = Assert.Throws<RuntimeBinderException>(() => { var hi = alpha.Hello1; }); Assert.That(ex1.Message, Is.StringEnding("does not contain a definition for 'Hello1'")); var ex2 = Assert.Throws<RuntimeBinderException>(() => { var hi = beta.Hello2; }); Assert.That(ex2.Message, Is.StringEnding("does not contain a definition for 'Hello2'")); Assert.That(beta.Sample, Is.EqualTo("Data")); } [Test] public void SetMemberThrowsFallbackException() { dynamic alpha = new Object(); dynamic beta = new Clay(new TestMemberBehavior()); var ex1 = Assert.Throws<RuntimeBinderException>(() => { alpha.Hello1 = 1; }); Assert.That(ex1.Message, Is.StringEnding("does not contain a definition for 'Hello1'")); var ex2 = Assert.Throws<RuntimeBinderException>(() => { beta.Hello2 = 2; }); Assert.That(ex2.Message, Is.StringEnding("does not contain a definition for 'Hello2'")); var x = (beta.Sample = 3); Assert.That(x, Is.EqualTo("Data")); } [Test] public void GetIndexThrowsFallbackException() { dynamic alpha = new Object(); dynamic beta = new Clay(new TestMemberBehavior()); var ex1 = Assert.Throws<RuntimeBinderException>(() => { var hi = alpha[0]; }); Assert.That(ex1.Message, Is.StringMatching(@"Cannot apply indexing with \[\] to an expression of type .*")); var ex2 = Assert.Throws<RuntimeBinderException>(() => { var hi = beta[0]; }); Assert.That(ex2.Message, Is.StringMatching(@"Cannot apply indexing with \[\] to an expression of type .*")); } [Test] public void SetIndexThrowsFallbackException() { dynamic alpha = new Object(); dynamic beta = new Clay(new TestMemberBehavior()); var ex1 = Assert.Throws<RuntimeBinderException>(() => { alpha[0] = 1; }); Assert.That(ex1.Message, Is.StringMatching(@"Cannot apply indexing with \[\] to an expression of type .*")); var ex2 = Assert.Throws<RuntimeBinderException>(() => { beta[0] = 2; }); Assert.That(ex2.Message, Is.StringMatching(@"Cannot apply indexing with \[\] to an expression of type .*")); } public interface IAlpha { string Hello(); string Foo(); } public class Alpha { public virtual string Hello() { return "World"; } } public class AlphaBehavior : ClayBehavior { public override object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args) { return proceed() + "-"; } public override object InvokeMemberMissing(Func<object> proceed, object self, string name, INamedEnumerable<object> args) { if (name == "Foo") return "Bar"; return proceed(); } } [Test] public void TestInvokePaths() { var dynamically = ClayActivator.CreateInstance<Alpha>(new IClayBehavior[] { new InterfaceProxyBehavior(), new AlphaBehavior() }); Alpha statically = dynamically; IAlpha interfacially = dynamically; Assert.That(dynamically.Hello(), Is.EqualTo("World-")); Assert.That(statically.Hello(), Is.EqualTo("World-")); Assert.That(interfacially.Hello(), Is.EqualTo("World-")); Assert.That(dynamically.Foo(), Is.EqualTo("Bar-")); Assert.That(interfacially.Foo(), Is.EqualTo("Bar-")); Assert.Throws<RuntimeBinderException>(() => dynamically.MissingNotHandled()); } public class Beta { public virtual string Hello { get { return "World"; } } } public class BetaBehavior : ClayBehavior { public override object GetMember(Func<object> proceed, object self, string name) { return proceed() + "-"; } public override object GetMemberMissing(Func<object> proceed, object self, string name) { if (name == "Foo") return "Bar"; return proceed(); } } [Test] public void TestGetPaths() { var dynamically = ClayActivator.CreateInstance<Beta>(new[] { new BetaBehavior() }); Beta statically = dynamically; Assert.That(dynamically.Hello, Is.EqualTo("World-")); Assert.That(statically.Hello, Is.EqualTo("World-")); Assert.That(dynamically.Foo, Is.EqualTo("Bar-")); Assert.Throws<RuntimeBinderException>(() => { var x = dynamically.MissingPropNotHandled; }); } } }
38.613402
136
0.558804
[ "MIT" ]
bleroy/clay
src/ClaySharp.Tests/BinderFallbackTests.cs
7,493
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("OtpLibrary")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("OtpLibrary")] [assembly: System.Reflection.AssemblyTitleAttribute("OtpLibrary")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.916667
80
0.647658
[ "MIT" ]
OliverMBathurst/Security-Tools
Libraries/OTPLibrary/obj/Release/netstandard2.0/OTPLibrary.AssemblyInfo.cs
982
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Desk.Gist.Security.Areas.Identity.Data; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Desk.Gist.Security.Areas.Identity.Pages.Account { [AllowAnonymous] public class LoginModel : PageModel { private readonly UserManager<AppUser> _userManager; private readonly SignInManager<AppUser> _signInManager; private readonly ILogger<LoginModel> _logger; public LoginModel(SignInManager<AppUser> signInManager, ILogger<LoginModel> logger, UserManager<AppUser> userManager) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public async Task OnGetAsync(string returnUrl = null) { if (!string.IsNullOrEmpty(ErrorMessage)) { ModelState.AddModelError(string.Empty, ErrorMessage); } returnUrl ??= Url.Content("~/"); // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation("User logged in."); return LocalRedirect(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToPage("./Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return Page(); } } // If we got this far, something failed, redisplay form return Page(); } } }
34.044643
142
0.596643
[ "MIT" ]
zhaobingwang/Desk
Gist/src/Desk.Gist.Security/Areas/Identity/Pages/Account/Login.cshtml.cs
3,815
C#
namespace ExplosivesDude { using System; using System.Windows.Threading; public class Explosive : MapObject { private readonly int range, power; private readonly DispatcherTimer tim; private int seconds; private bool triggered; public Explosive(Player p) : this(p.X, p.Y, p.BombRange, p.BombPower, p) { } public Explosive(int x, int y, int range, int power, Player owner) : base(x, y) { this.range = range; this.power = power; this.Owner = owner; this.Owner.BombAmount--; this.SetImageSource(Properties.Resources.Bomb3); this.seconds = 3; this.triggered = false; owner.TriggerActivated += this.Owner_TriggerActivated; this.tim = new DispatcherTimer(); this.StartCountdown(1000); this.tim.Tick += this.Tim_Tick; } public event EventHandler<OnBombExplodedEventArgs> BombExploded; private Player Owner { get; } public override int GetLookupId() { return ((int)Game.ClassType.Explosive * 1000000) + base.GetLookupId(); } public void Trigger() { if (!this.triggered) { this.triggered = true; this.StartCountdown(100); } } public void ActivateRemote() { this.tim.Stop(); this.SetImageSource(Properties.Resources.C4); } public void StartCountdown(int interval) { if (this.seconds > 0) { this.seconds--; } this.tim.Interval = TimeSpan.FromMilliseconds(interval); this.tim.Start(); } private void Explode() { this.Owner.BombAmount++; this.BombExploded?.Invoke(this, new OnBombExplodedEventArgs(this.Owner, this.X, this.Y, this.range, this.power)); } private void Owner_TriggerActivated(object sender, EventArgs e) { Player owner = (Player)sender; owner.TriggerActivated -= this.Owner_TriggerActivated; this.Explode(); } private void Tim_Tick(object sender, EventArgs e) { switch (this.seconds) { case 0: this.tim.Stop(); this.Owner.TriggerActivated -= this.Owner_TriggerActivated; this.Explode(); break; case 1: this.SetImageSource(Properties.Resources.Bomb1); this.seconds--; break; case 2: this.SetImageSource(Properties.Resources.Bomb2); this.seconds--; break; } } } }
28.153846
125
0.51127
[ "MIT" ]
rumkugel13/ExplosivesDude_WPF
ExplosivesDude/MapObjects/Explosive.cs
2,930
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace LocalizableStringExtractor { /// <summary> /// Interaction logic</summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void StartBtn_Click(object sender, RoutedEventArgs e) { m_extractor.ExtractAll(); Close(); } private void CancelBtn_Click(object sender, RoutedEventArgs e) { Close(); } private void AssembliesBtn_Click(object sender, RoutedEventArgs e) { m_extractor.OpenSettingsFile(); } private Extractor m_extractor = new Extractor(); } }
24.23913
75
0.630493
[ "Apache-2.0" ]
StirfireStudios/ATF
DevTools/Localization/LocalizableStringExtractor/Window1.xaml.cs
1,072
C#
namespace Vecc.AutoDocker.Client.Docker.Swarms { public enum RestartPolicyCondition { None, OnFailure, Any } }
15.7
48
0.566879
[ "MIT" ]
veccsolutions/Vecc.AutoDocker
src/Vecc.AutoDocker.Client/Docker/Swarms/RestartPolicyCondition.cs
159
C#
using System; using HotChocolate.Execution; using HotChocolate.Types; using Snapshooter.Xunit; using Xunit; namespace HotChocolate.Integration.EmbeddedResolvers { public class EmbeddedResolverTests { [Fact] public void ResolverResultIsObject() { // arrange ISchema schema = SchemaBuilder.New() .AddQueryType<QueryType>() .Create(); IQueryExecutor executor = schema.MakeExecutable(); // act IExecutionResult result = executor.Execute( QueryRequestBuilder.New() .SetQuery("{ foo { bar { baz }}}") .Create()); // assert result.MatchSnapshot(); } public class QueryType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Query"); descriptor.Field<QueryType>(t => t.GetFoo()).Type<FooType>(); } public object GetFoo() { return new object(); } } public class FooType : ObjectType { protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Foo"); descriptor.Field<FooType>(t => t.Bar()).Type<BarType>(); } public Bar Bar() { return new Bar(); } } public class BarType : ObjectType<Bar> { protected override void Configure(IObjectTypeDescriptor<Bar> descriptor) { } } public class Bar { public string Baz { get; } = "Bar"; } } }
24.328947
84
0.489995
[ "MIT" ]
Coldplayer1995/GraphQLTest
src/Core/Core.Tests/Integration/EmbeddedResolvers/EmbeddedResolverTests.cs
1,849
C#
using System; using System.Collections.Generic; using System.Text; namespace MxNet.GluonTS.Dataset.Split { class TimeSeriesSlice { } }
13.545455
37
0.724832
[ "Apache-2.0" ]
AnshMittal1811/MxNet.Sharp
src/MxNet.GluonTS/Dataset/Split/TimeSeriesSlice.cs
151
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Schema { using System; using System.ComponentModel; using System.Xml.Serialization; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Globalization; internal abstract class FacetsChecker { private struct FacetsCompiler { private readonly DatatypeImplementation _datatype; private readonly RestrictionFacets _derivedRestriction; private readonly RestrictionFlags _baseFlags; private readonly RestrictionFlags _baseFixedFlags; private readonly RestrictionFlags _validRestrictionFlags; //Helpers private readonly XmlSchemaDatatype _nonNegativeInt; private readonly XmlSchemaDatatype _builtInType; private readonly XmlTypeCode _builtInEnum; private bool _firstPattern; private StringBuilder? _regStr; private XmlSchemaPatternFacet? _pattern_facet; public FacetsCompiler(DatatypeImplementation baseDatatype, RestrictionFacets restriction) { _firstPattern = true; _regStr = null; _pattern_facet = null; _datatype = baseDatatype; _derivedRestriction = restriction; _baseFlags = _datatype.Restriction != null ? _datatype.Restriction.Flags : 0; _baseFixedFlags = _datatype.Restriction != null ? _datatype.Restriction.FixedFlags : 0; _validRestrictionFlags = _datatype.ValidRestrictionFlags; _nonNegativeInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.NonNegativeInteger).Datatype!; _builtInEnum = !(_datatype is Datatype_union || _datatype is Datatype_List) ? _datatype.TypeCode : 0; _builtInType = (int)_builtInEnum > 0 ? DatatypeImplementation.GetSimpleTypeFromTypeCode(_builtInEnum).Datatype! : _datatype; } internal void CompileLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Length, SR.Sch_LengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.Length, SR.Sch_DupLengthFacet); _derivedRestriction.Length = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_LengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.Length) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.Length, _derivedRestriction.Length)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_LengthGtBaseLength, facet); } } // If the base has the MinLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } // If the base has the MaxLength facet, check that our derived length is not violating it if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.Length) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.Length); } internal void CompileMinLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinLength, SR.Sch_MinLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinLength, SR.Sch_DupMinLengthFacet); _derivedRestriction.MinLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MinLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MinLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinLength, _derivedRestriction.MinLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MinLength) != 0) { if (_datatype.Restriction!.MinLength > _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtBaseMinLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length < _derivedRestriction.MinLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MinLength); } internal void CompileMaxLengthFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxLength, SR.Sch_MaxLengthFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxLength, SR.Sch_DupMaxLengthFacet); _derivedRestriction.MaxLength = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_MaxLengthFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.MaxLength) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxLength, _derivedRestriction.MaxLength)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.MaxLength) != 0) { if (_datatype.Restriction!.MaxLength < _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxLengthGtBaseMaxLength, facet); } } if ((_baseFlags & RestrictionFlags.Length) != 0) { if (_datatype.Restriction!.Length > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MaxMinLengthBaseLength, facet); } } SetFlag(facet, RestrictionFlags.MaxLength); } internal void CompilePatternFacet(XmlSchemaPatternFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.Pattern, SR.Sch_PatternFacetProhibited); if (_firstPattern == true) { _regStr = new StringBuilder(); _regStr.Append('('); _regStr.Append(facet.Value); _pattern_facet = facet; _firstPattern = false; } else { _regStr!.Append(")|("); _regStr.Append(facet.Value); } SetFlag(facet, RestrictionFlags.Pattern); } internal void CompileEnumerationFacet(XmlSchemaFacet facet, IXmlNamespaceResolver nsmgr, XmlNameTable nameTable) { CheckProhibitedFlag(facet, RestrictionFlags.Enumeration, SR.Sch_EnumerationFacetProhibited); if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = new ArrayList(); } _derivedRestriction.Enumeration.Add(ParseFacetValue(_datatype, facet, SR.Sch_EnumerationFacetInvalid, nsmgr, nameTable)); SetFlag(facet, RestrictionFlags.Enumeration); } internal void CompileWhitespaceFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_WhiteSpaceFacetProhibited); CheckDupFlag(facet, RestrictionFlags.WhiteSpace, SR.Sch_DupWhiteSpaceFacet); if (facet.Value == "preserve") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Preserve; } else if (facet.Value == "replace") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Replace; } else if (facet.Value == "collapse") { _derivedRestriction.WhiteSpace = XmlSchemaWhiteSpace.Collapse; } else { throw new XmlSchemaException(SR.Sch_InvalidWhiteSpace, facet.Value, facet); } if ((_baseFixedFlags & RestrictionFlags.WhiteSpace) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.WhiteSpace, _derivedRestriction.WhiteSpace)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } //Check base and derived whitespace facets XmlSchemaWhiteSpace baseWhitespace; if ((_baseFlags & RestrictionFlags.WhiteSpace) != 0) { baseWhitespace = _datatype.Restriction!.WhiteSpace; } else { baseWhitespace = _datatype.BuiltInWhitespaceFacet; } if (baseWhitespace == XmlSchemaWhiteSpace.Collapse && (_derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Replace || _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve) ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction1, facet); } if (baseWhitespace == XmlSchemaWhiteSpace.Replace && _derivedRestriction.WhiteSpace == XmlSchemaWhiteSpace.Preserve ) { throw new XmlSchemaException(SR.Sch_WhiteSpaceRestriction2, facet); } SetFlag(facet, RestrictionFlags.WhiteSpace); } internal void CompileMaxInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_MaxInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxInclusive, SR.Sch_DupMaxInclusiveFacet); _derivedRestriction.MaxInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxInclusive!, _derivedRestriction.MaxInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxInclusive, facet); SetFlag(facet, RestrictionFlags.MaxInclusive); } internal void CompileMaxExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_MaxExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MaxExclusive, SR.Sch_DupMaxExclusiveFacet); _derivedRestriction.MaxExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MaxExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MaxExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MaxExclusive!, _derivedRestriction.MaxExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MaxExclusive, facet); SetFlag(facet, RestrictionFlags.MaxExclusive); } internal void CompileMinInclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_MinInclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinInclusive, SR.Sch_DupMinInclusiveFacet); _derivedRestriction.MinInclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinInclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinInclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinInclusive!, _derivedRestriction.MinInclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinInclusive, facet); SetFlag(facet, RestrictionFlags.MinInclusive); } internal void CompileMinExclusiveFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_MinExclusiveFacetProhibited); CheckDupFlag(facet, RestrictionFlags.MinExclusive, SR.Sch_DupMinExclusiveFacet); _derivedRestriction.MinExclusive = ParseFacetValue(_builtInType, facet, SR.Sch_MinExclusiveFacetInvalid, null, null); if ((_baseFixedFlags & RestrictionFlags.MinExclusive) != 0) { if (!_datatype.IsEqual(_datatype.Restriction!.MinExclusive!, _derivedRestriction.MinExclusive)) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } CheckValue(_derivedRestriction.MinExclusive, facet); SetFlag(facet, RestrictionFlags.MinExclusive); } internal void CompileTotalDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_TotalDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.TotalDigits, SR.Sch_DupTotalDigitsFacet); XmlSchemaDatatype positiveInt = DatatypeImplementation.GetSimpleTypeFromTypeCode(XmlTypeCode.PositiveInteger).Datatype!; _derivedRestriction.TotalDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(positiveInt, facet, SR.Sch_TotalDigitsFacetInvalid, null, null)); if ((_baseFixedFlags & RestrictionFlags.TotalDigits) != 0) { if (_datatype.Restriction!.TotalDigits != _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.TotalDigits) != 0) { if (_derivedRestriction.TotalDigits > _datatype.Restriction!.TotalDigits) { throw new XmlSchemaException(SR.Sch_TotalDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.TotalDigits); } internal void CompileFractionDigitsFacet(XmlSchemaFacet facet) { CheckProhibitedFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_FractionDigitsFacetProhibited); CheckDupFlag(facet, RestrictionFlags.FractionDigits, SR.Sch_DupFractionDigitsFacet); _derivedRestriction.FractionDigits = XmlBaseConverter.DecimalToInt32((decimal)ParseFacetValue(_nonNegativeInt, facet, SR.Sch_FractionDigitsFacetInvalid, null, null)); if ((_derivedRestriction.FractionDigits != 0) && (_datatype.TypeCode != XmlTypeCode.Decimal)) { throw new XmlSchemaException(SR.Sch_FractionDigitsFacetInvalid, SR.Sch_FractionDigitsNotOnDecimal, facet); } if ((_baseFixedFlags & RestrictionFlags.FractionDigits) != 0) { if (_datatype.Restriction!.FractionDigits != _derivedRestriction.FractionDigits) { throw new XmlSchemaException(SR.Sch_FacetBaseFixed, facet); } } if ((_baseFlags & RestrictionFlags.FractionDigits) != 0) { if (_derivedRestriction.FractionDigits > _datatype.Restriction!.FractionDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsMismatch, string.Empty); } } SetFlag(facet, RestrictionFlags.FractionDigits); } internal void FinishFacetCompile() { //Additional check for pattern facet //If facet is XMLSchemaPattern, then the String built inside the loop //needs to be converted to a RegEx if (_firstPattern == false) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = new ArrayList(); } try { _regStr!.Append(')'); string tempStr = _regStr.ToString(); if (tempStr.Contains('|')) { // ordinal compare _regStr.Insert(0, '('); _regStr.Append(')'); } _derivedRestriction.Patterns.Add(new Regex(Preprocess(_regStr.ToString()))); } catch (Exception e) { throw new XmlSchemaException(SR.Sch_PatternFacetInvalid, new string[] { e.Message }, e, _pattern_facet!.SourceUri, _pattern_facet.LineNumber, _pattern_facet.LinePosition, _pattern_facet); } } } private void CheckValue(object value, XmlSchemaFacet facet) { RestrictionFacets? restriction = _datatype.Restriction; switch (facet.FacetType) { case FacetType.MaxInclusive: if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MaxIncExlMismatch, string.Empty); } } break; case FacetType.MaxExclusive: if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxInclusive) != 0) { //Base facet has maxInclusive if (_datatype.Compare(value, restriction!.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MaxExlIncMismatch, string.Empty); } } break; case FacetType.MinInclusive: if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinIncExlMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinIncMaxExlMismatch, string.Empty); } } break; case FacetType.MinExclusive: if ((_baseFlags & RestrictionFlags.MinExclusive) != 0) { //Base facet has minExclusive if (_datatype.Compare(value, restriction!.MinExclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MinInclusive) != 0) { //Base facet has minInclusive if (_datatype.Compare(value, restriction!.MinInclusive!) < 0) { throw new XmlSchemaException(SR.Sch_MinExlIncMismatch, string.Empty); } } if ((_baseFlags & RestrictionFlags.MaxExclusive) != 0) { //Base facet has maxExclusive if (_datatype.Compare(value, restriction!.MaxExclusive!) >= 0) { throw new XmlSchemaException(SR.Sch_MinExlMaxExlMismatch, string.Empty); } } break; default: Debug.Fail($"Unexpected facet type {facet.FacetType}"); break; } } internal void CompileFacetCombinations() { //They are not allowed on the same type but allowed on derived types. if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MaxInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 ) { throw new XmlSchemaException(SR.Sch_MinInclusiveExclusive, string.Empty); } if ( (_derivedRestriction.Flags & RestrictionFlags.Length) != 0 && (_derivedRestriction.Flags & (RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0 ) { throw new XmlSchemaException(SR.Sch_LengthAndMinMax, string.Empty); } CopyFacetsFromBaseType(); // Check combinations if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxLength) != 0 ) { if (_derivedRestriction.MinLength > _derivedRestriction.MaxLength) { throw new XmlSchemaException(SR.Sch_MinLengthGtMaxLength, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxInclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinInclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinInclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxExclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxExclusive, string.Empty); } } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) != 0 && (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) != 0 ) { if (_datatype.Compare(_derivedRestriction.MinExclusive!, _derivedRestriction.MaxInclusive!) > 0) { throw new XmlSchemaException(SR.Sch_MinExclusiveGtMaxInclusive, string.Empty); } } if ((_derivedRestriction.Flags & (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) == (RestrictionFlags.TotalDigits | RestrictionFlags.FractionDigits)) { if (_derivedRestriction.FractionDigits > _derivedRestriction.TotalDigits) { throw new XmlSchemaException(SR.Sch_FractionDigitsGtTotalDigits, string.Empty); } } } private void CopyFacetsFromBaseType() { RestrictionFacets baseRestriction = _datatype.Restriction!; // Copy additional facets from the base type if ( (_derivedRestriction.Flags & RestrictionFlags.Length) == 0 && (_baseFlags & RestrictionFlags.Length) != 0 ) { _derivedRestriction.Length = baseRestriction.Length; SetFlag(RestrictionFlags.Length); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinLength) == 0 && (_baseFlags & RestrictionFlags.MinLength) != 0 ) { _derivedRestriction.MinLength = baseRestriction.MinLength; SetFlag(RestrictionFlags.MinLength); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxLength) == 0 && (_baseFlags & RestrictionFlags.MaxLength) != 0 ) { _derivedRestriction.MaxLength = baseRestriction.MaxLength; SetFlag(RestrictionFlags.MaxLength); } if ((_baseFlags & RestrictionFlags.Pattern) != 0) { if (_derivedRestriction.Patterns == null) { _derivedRestriction.Patterns = baseRestriction.Patterns; } else { _derivedRestriction.Patterns.AddRange(baseRestriction.Patterns!); } SetFlag(RestrictionFlags.Pattern); } if ((_baseFlags & RestrictionFlags.Enumeration) != 0) { if (_derivedRestriction.Enumeration == null) { _derivedRestriction.Enumeration = baseRestriction.Enumeration; } SetFlag(RestrictionFlags.Enumeration); } if ( (_derivedRestriction.Flags & RestrictionFlags.WhiteSpace) == 0 && (_baseFlags & RestrictionFlags.WhiteSpace) != 0 ) { _derivedRestriction.WhiteSpace = baseRestriction.WhiteSpace; SetFlag(RestrictionFlags.WhiteSpace); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxInclusive) == 0 && (_baseFlags & RestrictionFlags.MaxInclusive) != 0 ) { _derivedRestriction.MaxInclusive = baseRestriction.MaxInclusive; SetFlag(RestrictionFlags.MaxInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MaxExclusive) == 0 && (_baseFlags & RestrictionFlags.MaxExclusive) != 0 ) { _derivedRestriction.MaxExclusive = baseRestriction.MaxExclusive; SetFlag(RestrictionFlags.MaxExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinInclusive) == 0 && (_baseFlags & RestrictionFlags.MinInclusive) != 0 ) { _derivedRestriction.MinInclusive = baseRestriction.MinInclusive; SetFlag(RestrictionFlags.MinInclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.MinExclusive) == 0 && (_baseFlags & RestrictionFlags.MinExclusive) != 0 ) { _derivedRestriction.MinExclusive = baseRestriction.MinExclusive; SetFlag(RestrictionFlags.MinExclusive); } if ( (_derivedRestriction.Flags & RestrictionFlags.TotalDigits) == 0 && (_baseFlags & RestrictionFlags.TotalDigits) != 0 ) { _derivedRestriction.TotalDigits = baseRestriction.TotalDigits; SetFlag(RestrictionFlags.TotalDigits); } if ( (_derivedRestriction.Flags & RestrictionFlags.FractionDigits) == 0 && (_baseFlags & RestrictionFlags.FractionDigits) != 0 ) { _derivedRestriction.FractionDigits = baseRestriction.FractionDigits; SetFlag(RestrictionFlags.FractionDigits); } } private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver? nsmgr, XmlNameTable? nameTable) { object? typedValue; Exception? ex = datatype.TryParseValue(facet.Value!, nameTable, nsmgr, out typedValue); if (ex == null) { return typedValue!; } else { throw new XmlSchemaException(code, new string[] { ex.Message }, ex, facet.SourceUri, facet.LineNumber, facet.LinePosition, facet); } } private struct Map { internal Map(char m, string r) { match = m; replacement = r; } internal char match; internal string replacement; }; private static readonly Map[] s_map = { new Map('c', "\\p{_xmlC}"), new Map('C', "\\P{_xmlC}"), new Map('d', "\\p{_xmlD}"), new Map('D', "\\P{_xmlD}"), new Map('i', "\\p{_xmlI}"), new Map('I', "\\P{_xmlI}"), new Map('w', "\\p{_xmlW}"), new Map('W', "\\P{_xmlW}"), }; private static string Preprocess(string pattern) { StringBuilder bufBld = new StringBuilder(); bufBld.Append('^'); char[] source = pattern.ToCharArray(); int length = pattern.Length; int copyPosition = 0; for (int position = 0; position < length - 2; position++) { if (source[position] == '\\') { if (source[position + 1] == '\\') { position++; // skip it } else { char ch = source[position + 1]; for (int i = 0; i < s_map.Length; i++) { if (s_map[i].match == ch) { if (copyPosition < position) { bufBld.Append(source, copyPosition, position - copyPosition); } bufBld.Append(s_map[i].replacement); position++; copyPosition = position + 1; break; } } } } } if (copyPosition < length) { bufBld.Append(source, copyPosition, length - copyPosition); } bufBld.Append('$'); return bufBld.ToString(); } private void CheckProhibitedFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_validRestrictionFlags & flag) == 0) { throw new XmlSchemaException(errorCode, _datatype.TypeCodeString, facet); } } private void CheckDupFlag(XmlSchemaFacet facet, RestrictionFlags flag, string errorCode) { if ((_derivedRestriction.Flags & flag) != 0) { throw new XmlSchemaException(errorCode, facet); } } private void SetFlag(XmlSchemaFacet facet, RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if (facet.IsFixed) { _derivedRestriction.FixedFlags |= flag; } } private void SetFlag(RestrictionFlags flag) { _derivedRestriction.Flags |= flag; if ((_baseFixedFlags & flag) != 0) { _derivedRestriction.FixedFlags |= flag; } } } internal virtual Exception? CheckLexicalFacets(ref string parseString, XmlSchemaDatatype datatype) { CheckWhitespaceFacets(ref parseString, datatype); return CheckPatternFacets(datatype.Restriction, parseString); } internal virtual Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { return null; } internal virtual Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { return null; } internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { // before parsing, check whitespace facet RestrictionFacets? restriction = datatype.Restriction; switch (datatype.Variety) { case XmlSchemaDatatypeVariety.List: s = s.Trim(); break; case XmlSchemaDatatypeVariety.Atomic: if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } else if (datatype.BuiltInWhitespaceFacet == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction != null && (restriction.Flags & RestrictionFlags.WhiteSpace) != 0) { //Restriction has whitespace facet specified if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Replace) { s = XmlComplianceUtil.CDataNormalize(s); } else if (restriction.WhiteSpace == XmlSchemaWhiteSpace.Collapse) { s = XmlComplianceUtil.NonCDataNormalize(s); } } break; default: break; } } internal Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) { if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { for (int i = 0; i < restriction.Patterns!.Count; ++i) { Regex regex = (Regex)restriction.Patterns[i]!; if (!regex.IsMatch(value)) { return new XmlSchemaException(SR.Sch_PatternConstraintFailed, string.Empty); } } } return null; } internal virtual bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return false; } //Compile-time Facet Checking internal virtual RestrictionFacets ConstructRestriction(DatatypeImplementation datatype, XmlSchemaObjectCollection facets, XmlNameTable nameTable) { //Datatype is the type on which this method is called RestrictionFacets derivedRestriction = new RestrictionFacets(); FacetsCompiler facetCompiler = new FacetsCompiler(datatype, derivedRestriction); for (int i = 0; i < facets.Count; ++i) { XmlSchemaFacet facet = (XmlSchemaFacet)facets[i]; if (facet.Value == null) { throw new XmlSchemaException(SR.Sch_InvalidFacet, facet); } IXmlNamespaceResolver nsmgr = new SchemaNamespaceManager(facet); switch (facet.FacetType) { case FacetType.Length: facetCompiler.CompileLengthFacet(facet); break; case FacetType.MinLength: facetCompiler.CompileMinLengthFacet(facet); break; case FacetType.MaxLength: facetCompiler.CompileMaxLengthFacet(facet); break; case FacetType.Pattern: facetCompiler.CompilePatternFacet((facet as XmlSchemaPatternFacet)!); break; case FacetType.Enumeration: facetCompiler.CompileEnumerationFacet(facet, nsmgr, nameTable); break; case FacetType.Whitespace: facetCompiler.CompileWhitespaceFacet(facet); break; case FacetType.MinInclusive: facetCompiler.CompileMinInclusiveFacet(facet); break; case FacetType.MinExclusive: facetCompiler.CompileMinExclusiveFacet(facet); break; case FacetType.MaxInclusive: facetCompiler.CompileMaxInclusiveFacet(facet); break; case FacetType.MaxExclusive: facetCompiler.CompileMaxExclusiveFacet(facet); break; case FacetType.TotalDigits: facetCompiler.CompileTotalDigitsFacet(facet); break; case FacetType.FractionDigits: facetCompiler.CompileFractionDigitsFacet(facet); break; default: throw new XmlSchemaException(SR.Sch_UnknownFacet, facet); } } facetCompiler.FinishFacetCompile(); facetCompiler.CompileFacetCombinations(); return derivedRestriction; } internal static decimal Power(int x, int y) { //Returns X raised to the power Y decimal returnValue = 1m; decimal decimalValue = (decimal)x; if (y > 28) { //CLR decimal cannot handle more than 29 digits (10 power 28.) return decimal.MaxValue; } for (int i = 0; i < y; i++) { returnValue = returnValue * decimalValue; } return returnValue; } } internal class Numeric10FacetsChecker : FacetsChecker { private readonly decimal _maxValue; private readonly decimal _minValue; internal Numeric10FacetsChecker(decimal minVal, decimal maxVal) { _minValue = minVal; _maxValue = maxVal; } internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { decimal decimalValue = datatype.ValueConverter.ToDecimal(value); return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(decimal value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; //Check built-in facets if (value > _maxValue || value < _minValue) { return new OverflowException(SR.Format(SR.XmlConvert_Overflow, value.ToString(CultureInfo.InvariantCulture), datatype.TypeCodeString)); } //Check user-defined facets if (flags != 0) { Debug.Assert(restriction != null); if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDecimal(restriction.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDecimal(restriction.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < valueConverter.ToDecimal(restriction.MinInclusive!)) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDecimal(restriction.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return CheckTotalAndFractionDigits(value, restriction.TotalDigits, restriction.FractionDigits, ((flags & RestrictionFlags.TotalDigits) != 0), ((flags & RestrictionFlags.FractionDigits) != 0)); } return null; } internal override Exception? CheckValueFacets(long value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(int value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override Exception? CheckValueFacets(short value, XmlSchemaDatatype datatype) { decimal decimalValue = (decimal)value; return CheckValueFacets(decimalValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter); } internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDecimal(enumeration[i]!)) { return true; } } return false; } internal Exception? CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) { decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ; int powerCnt = 0; if (value < 0) { value = decimal.Negate(value); //Need to compare maxValue allowed against the absolute value } while (decimal.Truncate(value) != value) { //Till it has a fraction value = value * 10; powerCnt++; } if (checkTotal && (value > maxValue || powerCnt > totalDigits)) { return new XmlSchemaException(SR.Sch_TotalDigitsConstraintFailed, string.Empty); } if (checkFraction && powerCnt > fractionDigits) { return new XmlSchemaException(SR.Sch_FractionDigitsConstraintFailed, string.Empty); } return null; } } internal class Numeric2FacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { double doubleValue = datatype.ValueConverter.ToDouble(value); return CheckValueFacets(doubleValue, datatype); } internal override Exception? CheckValueFacets(double value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; XmlValueConverter valueConverter = datatype.ValueConverter; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (value > valueConverter.ToDouble(restriction!.MaxInclusive!)) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (value >= valueConverter.ToDouble(restriction!.MaxExclusive!)) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (value < (valueConverter.ToDouble(restriction!.MinInclusive!))) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (value <= valueConverter.ToDouble(restriction!.MinExclusive!)) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, valueConverter)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override Exception? CheckValueFacets(float value, XmlSchemaDatatype datatype) { double doubleValue = (double)value; return CheckValueFacets(doubleValue, datatype); } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter); } private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { if (value == valueConverter.ToDouble(enumeration[i]!)) { return true; } } return false; } } internal class DurationFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { TimeSpan timeSpanValue = (TimeSpan)datatype.ValueConverter.ChangeType(value, typeof(TimeSpan)); return CheckValueFacets(timeSpanValue, datatype); } internal override Exception? CheckValueFacets(TimeSpan value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (TimeSpan.Compare(value, (TimeSpan)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((TimeSpan)value, enumeration); } private bool MatchEnumeration(TimeSpan value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (TimeSpan.Compare(value, (TimeSpan)enumeration[i]!) == 0) { return true; } } return false; } } internal class DateTimeFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { DateTime dateTimeValue = datatype.ValueConverter.ToDateTime(value); return CheckValueFacets(dateTimeValue, datatype); } internal override Exception? CheckValueFacets(DateTime value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.MaxInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxInclusive!) > 0) { return new XmlSchemaException(SR.Sch_MaxInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MaxExclusive!) >= 0) { return new XmlSchemaException(SR.Sch_MaxExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinInclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinInclusive!) < 0) { return new XmlSchemaException(SR.Sch_MinInclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinExclusive) != 0) { if (datatype.Compare(value, (DateTime)restriction!.MinExclusive!) <= 0) { return new XmlSchemaException(SR.Sch_MinExclusiveConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype); } private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (DateTime)enumeration[i]!) == 0) { return true; } } return false; } } internal class StringFacetsChecker : FacetsChecker { //All types derived from string & anyURI private static Regex? s_languagePattern; private static Regex LanguagePattern { get { if (s_languagePattern == null) { Regex langRegex = new Regex("^([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*$"); Interlocked.CompareExchange(ref s_languagePattern, langRegex, null); } return s_languagePattern; } } internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { string stringValue = datatype.ValueConverter.ToString(value); return CheckValueFacets(stringValue, datatype, true); } internal override Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype) { return CheckValueFacets(value, datatype, true); } internal Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) { //Length, MinLength, MaxLength int length = value.Length; RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; Exception? exception; exception = CheckBuiltInFacets(value, datatype.TypeCode, verifyUri); if (exception != null) return exception; if (flags != 0) { if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype); } private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) { if (datatype.TypeCode == XmlTypeCode.AnyUri) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals(((Uri)enumeration[i]!).OriginalString)) { return true; } } } else { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((string)enumeration[i]!)) { return true; } } } return false; } private Exception? CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) { Exception? exception = null; switch (typeCode) { case XmlTypeCode.AnyUri: if (verifyUri) { Uri? uri; exception = XmlConvert.TryToUri(s, out uri); } break; case XmlTypeCode.NormalizedString: exception = XmlConvert.TryVerifyNormalizedString(s); break; case XmlTypeCode.Token: exception = XmlConvert.TryVerifyTOKEN(s); break; case XmlTypeCode.Language: if (s == null || s.Length == 0) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } if (!LanguagePattern.IsMatch(s)) { return new XmlSchemaException(SR.Sch_InvalidLanguageId, string.Empty); } break; case XmlTypeCode.NmToken: exception = XmlConvert.TryVerifyNMTOKEN(s); break; case XmlTypeCode.Name: exception = XmlConvert.TryVerifyName(s); break; case XmlTypeCode.NCName: case XmlTypeCode.Id: case XmlTypeCode.Idref: case XmlTypeCode.Entity: exception = XmlConvert.TryVerifyNCName(s); break; default: break; } return exception; } } internal class QNameFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { XmlQualifiedName qualifiedNameValue = (XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)); return CheckValueFacets(qualifiedNameValue, datatype); } internal override Exception? CheckValueFacets(XmlQualifiedName value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { Debug.Assert(restriction != null); // If there are facets defined string strValue = value.ToString(); int length = strValue.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction.Enumeration!)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration); } private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { if (value.Equals((XmlQualifiedName)enumeration[i]!)) { return true; } } return false; } } internal class MiscFacetsChecker : FacetsChecker { //For bool, anySimpleType } internal class BinaryFacetsChecker : FacetsChecker { //hexBinary & Base64Binary internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { byte[] byteArrayValue = (byte[])value; return CheckValueFacets(byteArrayValue, datatype); } internal override Exception? CheckValueFacets(byte[] value, XmlSchemaDatatype datatype) { //Length, MinLength, MaxLength RestrictionFacets? restriction = datatype.Restriction; int length = value.Length; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if (flags != 0) { //if it has facets defined if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { return MatchEnumeration((byte[])value, enumeration, datatype); } private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, (byte[])enumeration[i]!) == 0) { return true; } } return false; } } internal class ListFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { // Check for facets allowed on lists - Length, MinLength, MaxLength Array values = (value as Array)!; Debug.Assert(values != null); RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & (RestrictionFlags.Length | RestrictionFlags.MinLength | RestrictionFlags.MaxLength)) != 0) { int length = values.Length; if ((flags & RestrictionFlags.Length) != 0) { if (restriction!.Length != length) { return new XmlSchemaException(SR.Sch_LengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MinLength) != 0) { if (length < restriction!.MinLength) { return new XmlSchemaException(SR.Sch_MinLengthConstraintFailed, string.Empty); } } if ((flags & RestrictionFlags.MaxLength) != 0) { if (restriction!.MaxLength < length) { return new XmlSchemaException(SR.Sch_MaxLengthConstraintFailed, string.Empty); } } } if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]!) == 0) { return true; } } return false; } } internal class UnionFacetsChecker : FacetsChecker { internal override Exception? CheckValueFacets(object value, XmlSchemaDatatype datatype) { RestrictionFacets? restriction = datatype.Restriction; RestrictionFlags flags = restriction != null ? restriction.Flags : 0; if ((flags & RestrictionFlags.Enumeration) != 0) { if (!MatchEnumeration(value, restriction!.Enumeration!, datatype)) { return new XmlSchemaException(SR.Sch_EnumerationConstraintFailed, string.Empty); } } return null; } internal override bool MatchEnumeration(object value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { if (datatype.Compare(value, enumeration[i]!) == 0) { // Compare on Datatype_union will compare two XsdSimpleValue return true; } } return false; } } }
42.597238
211
0.521693
[ "MIT" ]
ANISSARIZKY/runtime
src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs
74,034
C#
using Juniper.Input; using UnityEngine; namespace Juniper.Animation { [DisallowMultipleComponent] public class PresentationTransition : MonoBehaviour { [ReadOnly] public Vector3 startPosition; [ReadOnly] public Quaternion startRotation; public Material startMaterial; [ReadOnly] public Material endMaterial; private MasterSceneController master; /// <summary> /// The method to use to pre-compute the transition value. /// </summary> public TweenType tween; /// <summary> /// The constant value to provide to the tweening function. Currently, only the Bump tween /// function uses this value. /// </summary> [Tooltip("The constant value to provide to the tweening function. Currently, only the Bump tween function uses this value.")] public float tweenK; private float value = 0; /// <summary> /// The amount of time it takes to complete the transition. /// </summary> public float length = 0.25f; private Direction state = Direction.Stopped; private MeshRenderer startRend; private MeshRenderer endRend; private MaterialPropertyBlock startProps; private MaterialPropertyBlock endProps; private Vector3 EndPosition { get { return master.systemUserInterface.position; } } private Quaternion EndRotation { get { return master.systemUserInterface.rotation; } } #if UNITY_EDITOR public void OnValidate() { var renderer = GetComponent<MeshRenderer>(); if (renderer != null) { endMaterial = renderer.GetMaterial(); } } #endif private MeshRenderer CreateChild(Material mat, out MaterialPropertyBlock props) { var obj = GameObject.CreatePrimitive(PrimitiveType.Quad); obj.Remove<MeshCollider>(); var rend = obj.GetComponent<MeshRenderer>(); rend.SetMaterial(mat); obj.transform.SetParent(transform, false); props = new MaterialPropertyBlock(); rend.SetPropertyBlock(props); return rend; } public void Awake() { Find.Any(out master); startMaterial = Instantiate(startMaterial); startRend = CreateChild(startMaterial, out startProps); startRend.transform.localRotation = Quaternion.Euler(0, 180, 0); endRend = CreateChild(endMaterial, out endProps); SetAlpha(0); this.Remove<MeshRenderer>(); } public void Toggle() { if (state == Direction.Forward) { state = Direction.Reverse; } else { if (value == 0) { startPosition = transform.position; startRotation = transform.rotation; } state = Direction.Forward; } } public void Update() { var nextState = state; if (state == Direction.Forward && value < 1) { value += Time.smoothDeltaTime / length; if (value > 1) { value = 1; } } else if (state == Direction.Reverse && value > 0) { value -= Time.smoothDeltaTime / length; if (value < 0) { value = 0; nextState = Direction.Stopped; } } var tweenFunc = Tween.Functions[tween]; var tweenValue = tweenFunc(value, tweenK, state); RenderValue(tweenValue); state = nextState; } private void RenderValue(float value) { if (state != Direction.Stopped) { transform.rotation = Quaternion.SlerpUnclamped(startRotation, EndRotation, value); transform.position = Vector3.LerpUnclamped(startPosition, EndPosition, value); SetAlpha(value); } } private void SetAlpha(float value) { endProps.SetFloat("_Alpha", value); endRend.SetPropertyBlock(endProps); startProps.SetFloat("_Alpha", 1 - value); startRend.SetPropertyBlock(startProps); } } }
27.596491
133
0.521085
[ "MIT" ]
capnmidnight/Juniper
etc/Old Unity Code/Scripts/Animation/PresentationTransition.cs
4,719
C#
using StreamCompress.Domain.GZip; using StreamCompress.Domain.Huffman; using StreamCompress.Domain.Image; using StreamCompress.Domain.LZ; using StreamCompress.DomainExtensions.Huffman; using StreamCompress.DomainExtensions.Image; using StreamCompress.DomainExtensions.LZ; using StreamCompress.DomainExtensions.GZip; using StreamCompress.Utils; using System; using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; using System.IO; namespace StreamCompress { /// <summary> /// Main program /// </summary> public class Program { /// <summary> /// Supported methods /// </summary> public enum Method { /// <summary> /// Converts image as gray scale /// </summary> AsGrayScale, /// <summary> /// Converts image as gray scale and encode it using Huffman coding /// </summary> AsGrayScaleAsHuffmanEncoded, /// <summary> /// Decodes huffman encoded gray scale image /// </summary> AsGrayScaleAsHuffmanDecoded, /// <summary> /// Encodes image using LZ78 compression /// </summary> AsLZ78Encoded, /// <summary> /// Decodes image using LZ78 compression /// </summary> AsLZ78Decoded, /// <summary> /// Converts image as gray scale and encodes image using LZ78 compression /// </summary> AsGrayScaleAsLZ78Encoded, /// <summary> /// Decodes gray scale image using LZ78 compression /// </summary> AsGrayScaleAsLZ78Decoded, /// <summary> /// Encodes image using GZip compression /// </summary> AsGZipEncoded, /// <summary> /// Decodes image using GZip compression /// </summary> AsGZipDecoded, /// <summary> /// Converts image as gray scale and encodes image using GZip compression /// </summary> AsGrayScaleAsGZipEncoded, /// <summary> /// Decodes gray scale image using GZip compression /// </summary> AsGrayScaleAsGZipDecoded } /// <summary> /// Gray scale image color counts /// </summary> public enum GrayScaleColors { /// <summary> /// 256 colors /// </summary> Full = 256, /// <summary> /// 128 colors /// </summary> Half = 128, /// <summary> /// 64 colors /// </summary> Quarter = 64, /// <summary> /// 32 colors /// </summary> HalfOfQuarter = 32 } /// <summary> /// LZ compression dictionary types /// </summary> public enum LZCompressionDictionary { /// <summary> /// Hash table implementation /// </summary> HashTable, /// <summary> /// Trie dynamic size node table implementation /// </summary> Trie, /// <summary> /// Trie fixed size node table implementation /// </summary> Trie256 } /// <summary> /// Command line arguments /// </summary> public class CommandLineArgs { /// <summary> /// Source data path /// </summary> public string SourcePath { get; set; } /// <summary> /// Sourcefiles filename suffix with extension /// </summary> public string SourceFileSuffix { get; set; } /// <summary> /// Source files start index /// </summary> public int StartIndex { get; set; } /// <summary> /// How many source files are proceed /// </summary> public int Count { get; set; } /// <summary> /// Output folder /// </summary> public string DestinationPath { get; set; } /// <summary> /// Output file suffix /// </summary> public string DestinationFileSuffix { get; set; } /// <summary> /// Compression method /// </summary> public Method? Method { get; set; } /// <summary> /// Image crop left /// </summary> public int CropLeftPx { get; set; } /// <summary> /// Image crop right /// </summary> public int CropRightPx { get; set; } /// <summary> /// Image crop top /// </summary> public int CropTopPx { get; set; } /// <summary> /// Image crop bottom /// </summary> public int CropBottomPx { get; set; } /// <summary> /// How many colors are used in gray scale image /// </summary> public GrayScaleColors? GrayScaleColors { get; set; } /// <summary> /// Dictionary implementation used in LZ78 compression /// </summary> public LZCompressionDictionary LZCompressionDictionary { get; set; } /// <summary> /// Hash table dictionary prime number /// </summary> public int LZCompressionHashTablePrime { get; set; } /// <summary> /// Dynamic trie implementation node tables initial size /// </summary> public int LZCompressionTrieInitialCapacity { get; set; } } /// <summary> /// Program start method /// </summary> /// <param name="args">Command line arguments</param> /// <returns>0 when OK</returns> public static int Main(string[] args) { var command = new RootCommand(){ new Option<string>( "--source-path", description: "Stream images source folder"), new Option<string>( "--source-file-suffix", description: "Source filename suffix"), new Option<string>( "--destination-path", description: "Destination folder"), new Option<string>( "--destination-file-suffix", description: "Destination filename suffix"), new Option<int?>( "--start-index", getDefaultValue: () => 0, description: "Image stream first image index"), new Option<int?>( "--count", getDefaultValue: () => 1, description: "Count of images to handle"), new Option<Method?>( "--method", description: "Image handling method"), new Option<GrayScaleColors?>( "--gray-scale-colors", getDefaultValue: () => GrayScaleColors.Full, description: "Gray scale image color count"), new Option<int?>( "--crop-left-px", getDefaultValue: () => 0, description:"Image crop px left"), new Option<int?>( "--crop-right-px", getDefaultValue: () => 0, description:"Image crop px right"), new Option<int?>( "--crop-top-px", getDefaultValue: () => 0, description:"Image crop px top"), new Option<int?>( "--crop-bottom-px", getDefaultValue: () => 0, description:"Image crop px bottom"), new Option<LZCompressionDictionary?>( "--lz-compression-dictionary", getDefaultValue: () => LZCompressionDictionary.HashTable, description: "LZ compression dictionary type"), new Option<int?>( "--lz-compression-hash-table-prime", getDefaultValue: () => 12289, description: "LZ compression hash table prime"), new Option<int?>( "--lz-compression-trie-initial-capacity", getDefaultValue: () => 1, description: "LZ compression trie node container initial capacity")}; command.Description = "Stream Compress App"; var commandResults = new List<CommandResult>(); command.Handler = CommandHandler.Create( (CommandLineArgs cmdArgs) => { if (!cmdArgs.Method.HasValue) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.Method)} '{cmdArgs.Method}'!"); } if (!Directory.Exists(cmdArgs.SourcePath)) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.SourcePath)} '{cmdArgs.SourcePath}'!"); } if (!Directory.Exists(cmdArgs.DestinationPath)) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.DestinationPath)} '{cmdArgs.DestinationPath}'!"); } if (cmdArgs.StartIndex < 0) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.StartIndex)} '{cmdArgs.StartIndex}'!"); } if (cmdArgs.Count < 1) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.Count)} '{cmdArgs.Count}'!"); } if (cmdArgs.CropLeftPx < 0) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.CropLeftPx)} '{cmdArgs.CropLeftPx}'!"); } if (cmdArgs.CropRightPx < 0) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.CropRightPx)} '{cmdArgs.CropRightPx}'!"); } if (cmdArgs.CropTopPx < 0) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.CropTopPx)} '{cmdArgs.CropTopPx}'!"); } if (cmdArgs.CropBottomPx < 0) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.CropBottomPx)} '{cmdArgs.CropBottomPx}'!"); } if (cmdArgs.LZCompressionHashTablePrime < 1) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.LZCompressionHashTablePrime)} '{cmdArgs.LZCompressionHashTablePrime}'!"); } if (cmdArgs.LZCompressionTrieInitialCapacity < 1) { throw new ArgumentException($"Invalid argument {nameof(cmdArgs.LZCompressionTrieInitialCapacity)} '{cmdArgs.LZCompressionTrieInitialCapacity}'!"); } for (int i = cmdArgs.StartIndex; i < cmdArgs.StartIndex + cmdArgs.Count; i++) { var sourceFile = _filePath(i, cmdArgs.SourcePath, cmdArgs.SourceFileSuffix); if (!File.Exists(sourceFile)) { throw new ArgumentException($"Source file '{sourceFile}' not exist!"); } } var method = cmdArgs.Method.Value; switch (method) { case Method.AsGrayScale: commandResults = SourceLooper<ImageFrame, ImageFrameGrayScale>(cmdArgs, (index, a, image) => { return image .AsCroppedImage(a.AsCropSetup()) .AsGrayScale((int)a.GrayScaleColors.GetValueOrDefault()); }); break; case Method.AsGrayScaleAsHuffmanEncoded: commandResults = SourceLooper<ImageFrame, HuffmanImageFrame>(cmdArgs, (index, a, image) => { return image .AsCroppedImage(a.AsCropSetup()) .AsGrayScale((int)a.GrayScaleColors.GetValueOrDefault(GrayScaleColors.Full)) .AsHuffmanEncoded(); }); break; case Method.AsGrayScaleAsHuffmanDecoded: commandResults = SourceLooper<HuffmanImageFrame, ImageFrameGrayScale>(cmdArgs, (index, a, image) => { return image.AsImageGrayScaleFrame(); }); break; case Method.AsLZ78Encoded: commandResults = SourceLooper<ImageFrame, LZImageFrame>(cmdArgs, (index, a, image) => { var retData = image .AsCroppedImage(a.AsCropSetup()); switch (a.LZCompressionDictionary) { case LZCompressionDictionary.HashTable: return retData.AsLZEncodedUsingHashTable(a.LZCompressionHashTablePrime); case LZCompressionDictionary.Trie: return retData.AsLZEncodedUsingTrie(a.LZCompressionTrieInitialCapacity); case LZCompressionDictionary.Trie256: return retData.AsLZEncodedUsingTrie256(); default: throw new NotSupportedException(); } }); break; case Method.AsLZ78Decoded: commandResults = SourceLooper<LZImageFrame, ImageFrame>(cmdArgs, (index, a, image) => { switch (a.LZCompressionDictionary) { case LZCompressionDictionary.HashTable: return image.AsImageFrameUsingHashTable<ImageFrame>(a.LZCompressionHashTablePrime); case LZCompressionDictionary.Trie: return image.AsImageFrameUsingTrie<ImageFrame>(a.LZCompressionTrieInitialCapacity); case LZCompressionDictionary.Trie256: return image.AsImageFrameUsingTrie256<ImageFrame>(); default: throw new NotSupportedException(); } }); break; case Method.AsGrayScaleAsLZ78Encoded: commandResults = SourceLooper<ImageFrame, LZImageFrame>(cmdArgs, (index, a, image) => { var retData = image .AsCroppedImage(a.AsCropSetup()) .AsGrayScale((int)a.GrayScaleColors.GetValueOrDefault(GrayScaleColors.Full)); switch (a.LZCompressionDictionary) { case LZCompressionDictionary.HashTable: return retData.AsLZEncodedUsingHashTable(a.LZCompressionHashTablePrime); case LZCompressionDictionary.Trie: return retData.AsLZEncodedUsingTrie(a.LZCompressionTrieInitialCapacity); case LZCompressionDictionary.Trie256: return retData.AsLZEncodedUsingTrie256(); default: throw new NotSupportedException(); } }); break; case Method.AsGrayScaleAsLZ78Decoded: commandResults = SourceLooper<LZImageFrame, ImageFrameGrayScale>(cmdArgs, (index, a, image) => { switch (a.LZCompressionDictionary) { case LZCompressionDictionary.HashTable: return image.AsImageFrameUsingHashTable<ImageFrameGrayScale>(a.LZCompressionHashTablePrime); case LZCompressionDictionary.Trie: return image.AsImageFrameUsingTrie<ImageFrameGrayScale>(a.LZCompressionTrieInitialCapacity); case LZCompressionDictionary.Trie256: return image.AsImageFrameUsingTrie256<ImageFrameGrayScale>(); default: throw new NotSupportedException(); } }); break; case Method.AsGZipEncoded: commandResults = SourceLooper<ImageFrame, GZipImageFrame>(cmdArgs, (index, a, image) => { return image .AsCroppedImage(a.AsCropSetup()) .AsGZipEncoded(); }); break; case Method.AsGZipDecoded: commandResults = SourceLooper<GZipImageFrame, ImageFrame>(cmdArgs, (index, a, image) => { return image.AsImageFrame<ImageFrame>(); }); break; case Method.AsGrayScaleAsGZipEncoded: commandResults = SourceLooper<ImageFrame, GZipImageFrame>(cmdArgs, (index, a, image) => { return image .AsCroppedImage(a.AsCropSetup()) .AsGrayScale((int)a.GrayScaleColors.GetValueOrDefault(GrayScaleColors.Full)) .AsGZipEncoded(); }); break; case Method.AsGrayScaleAsGZipDecoded: commandResults = SourceLooper<GZipImageFrame, ImageFrameGrayScale>(cmdArgs, (index, a, image) => { return image.AsImageFrame<ImageFrameGrayScale>(); }); break; } }); var commandRet = command.Invoke(args); if (commandRet == 0) { commandResults.ForEach(cr => { Console.WriteLine($"{cr.SourceBytesLenght};{cr.DestinationBytesLenght};{Math.Round(cr.CalculatePercent().GetValueOrDefault(), 2)} %"); }); } return commandRet; } /// <summary> /// Builds full path to file /// </summary> /// <param name="i">File index</param> /// <param name="path">File path</param> /// <param name="suffix">File suffix</param> /// <returns>Full path</returns> private static string _filePath(int i, string path, string suffix) { return FileExtensions.PathCombine(path, $"{i.ToString("00000")}-{suffix}"); } /// <summary> /// Iterates over source folder and reads file using index. /// Executes given function and then saves return value to file. /// </summary> /// <typeparam name="T">Type of domain object</typeparam> /// <typeparam name="R">Type of domain object</typeparam> /// <param name="cmdArgs">Command line arguments</param> /// <param name="func">Executing function</param> private static List<CommandResult> SourceLooper<T, R>( CommandLineArgs cmdArgs, Func<int, CommandLineArgs, T, ISaveable<R>> func) where T : ISaveable<T>, new() { var commandRet = new List<CommandResult>(); for (int i = cmdArgs.StartIndex; i < cmdArgs.Count + cmdArgs.StartIndex; i++) { var sourceFile = _filePath(i, cmdArgs.SourcePath, cmdArgs.SourceFileSuffix); var image = new T(); //open file and creates domain object ((ISaveable<T>)image).Open(sourceFile); //executes given function var ret = func(i, cmdArgs, image); var destFile = _filePath(i, cmdArgs.DestinationPath, cmdArgs.DestinationFileSuffix); //saves file ret.Save(destFile); switch (cmdArgs.Method.Value) { case Method.AsGrayScale: case Method.AsLZ78Encoded: case Method.AsGrayScaleAsLZ78Encoded: case Method.AsGrayScaleAsHuffmanEncoded: case Method.AsGZipEncoded: case Method.AsGrayScaleAsGZipEncoded: var sfInfo = new FileInfo(sourceFile); var dfInfo = new FileInfo(destFile); var commandResult = new CommandResult { SourceFileName = sfInfo.Name, SourceBytesLenght = sfInfo.Length, DestinationFileName = dfInfo.Name, DestinationBytesLenght = dfInfo.Length }; commandRet.Add(commandResult); break; case Method.AsGrayScaleAsHuffmanDecoded: case Method.AsLZ78Decoded: case Method.AsGrayScaleAsLZ78Decoded: case Method.AsGZipDecoded: case Method.AsGrayScaleAsGZipDecoded: default: break; } } return commandRet; } private class CommandResult { public string SourceFileName { get; set; } public string DestinationFileName { get; set; } public long SourceBytesLenght { get; set; } public long DestinationBytesLenght { get; set; } public long BytesLenghtDiff => Math.Abs(SourceBytesLenght - DestinationBytesLenght); public decimal? CalculatePercent() { var min = Math.Min(SourceBytesLenght, DestinationBytesLenght); var max = Math.Max(SourceBytesLenght, DestinationBytesLenght); if (max > 0) { return Math.Round(((min / (decimal)max) * 100.00m), 2); } return null; } } } }
33.361165
153
0.651999
[ "MIT" ]
kallepaa/high-speed-image-stream-compress
StreamCompress/Program.cs
17,183
C#
using Octokit.Tests.Integration.fixtures; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Octokit.Tests.Integration.Clients { public class RepositoryHooksClientTests { [Collection(RepositoriesHooksCollection.Name)] public class TheGetAllMethod { readonly RepositoriesHooksFixture _fixture; public TheGetAllMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task ReturnsAllHooksFromRepository() { var github = Helper.GetAuthenticatedClient(); var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); var actualHook = hooks[0]; AssertHook(_fixture.ExpectedHook, actualHook); } [IntegrationTest] public async Task ReturnsAllHooksFromRepositoryWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryId); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); var actualHook = hooks[0]; AssertHook(_fixture.ExpectedHook, actualHook); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithoutStart() { var github = Helper.GetAuthenticatedClient(); var options = new ApiOptions { PageSize = 5, PageCount = 1 }; var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, options); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithoutStartWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var options = new ApiOptions { PageSize = 5, PageCount = 1 }; var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryId, options); Assert.Equal(_fixture.ExpectedHooks.Count, hooks.Count); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithStart() { var github = Helper.GetAuthenticatedClient(); var options = new ApiOptions { PageSize = 3, PageCount = 1, StartPage = 2 }; var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, options); Assert.Equal(1, hooks.Count); } [IntegrationTest] public async Task ReturnsCorrectCountOfHooksWithStartWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var options = new ApiOptions { PageSize = 3, PageCount = 1, StartPage = 2 }; var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryId, options); Assert.Equal(1, hooks.Count); } [IntegrationTest] public async Task ReturnsDistinctResultsBasedOnStartPage() { var github = Helper.GetAuthenticatedClient(); var startOptions = new ApiOptions { PageSize = 2, PageCount = 1 }; var firstPage = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, startOptions); var skipStartOptions = new ApiOptions { PageSize = 2, PageCount = 1, StartPage = 2 }; var secondPage = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName, skipStartOptions); Assert.NotEqual(firstPage[0].Id, secondPage[0].Id); Assert.NotEqual(firstPage[1].Id, secondPage[1].Id); } [IntegrationTest] public async Task ReturnsDistinctResultsBasedOnStartPageWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var startOptions = new ApiOptions { PageSize = 2, PageCount = 1 }; var firstPage = await github.Repository.Hooks.GetAll(_fixture.RepositoryId, startOptions); var skipStartOptions = new ApiOptions { PageSize = 2, PageCount = 1, StartPage = 2 }; var secondPage = await github.Repository.Hooks.GetAll(_fixture.RepositoryId, skipStartOptions); Assert.NotEqual(firstPage[0].Id, secondPage[0].Id); Assert.NotEqual(firstPage[1].Id, secondPage[1].Id); } } [Collection(RepositoriesHooksCollection.Name)] public class TheGetMethod { readonly RepositoriesHooksFixture _fixture; public TheGetMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task GetHookByCreatedId() { var github = Helper.GetAuthenticatedClient(); var actualHook = await github.Repository.Hooks.Get(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHook.Id); AssertHook(_fixture.ExpectedHook, actualHook); } [IntegrationTest] public async Task GetHookByCreatedIdWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var actualHook = await github.Repository.Hooks.Get(_fixture.RepositoryId, _fixture.ExpectedHook.Id); AssertHook(_fixture.ExpectedHook, actualHook); } } public class TheCreateMethod { [IntegrationTest] public async Task CreateAWebHookForTestRepository() { var github = Helper.GetAuthenticatedClient(); var repoName = Helper.MakeNameWithTimestamp("create-hooks-test"); var repository = await github.Repository.Create(new NewRepository(repoName) { AutoInit = true }); var url = "http://test.com/example"; var contentType = WebHookContentType.Json; var secret = "53cr37"; var config = new Dictionary<string, string> { { "hostname", "http://hostname.url" }, { "username", "username" }, { "password", "password" } }; var parameters = new NewRepositoryWebHook("windowsazure", config, url) { Events = new[] { "push" }, Active = false, ContentType = contentType, Secret = secret }; var hook = await github.Repository.Hooks.Create(Helper.UserName, repository.Name, parameters.ToRequest()); var baseHookUrl = CreateExpectedBaseHookUrl(repository.Url, hook.Id); var webHookConfig = CreateExpectedConfigDictionary(config, url, contentType, secret); Assert.Equal("windowsazure", hook.Name); Assert.Equal(new[] { "push" }.ToList(), hook.Events.ToList()); Assert.Equal(baseHookUrl, hook.Url); Assert.Equal(baseHookUrl + "/test", hook.TestUrl); Assert.Equal(baseHookUrl + "/pings", hook.PingUrl); Assert.NotNull(hook.CreatedAt); Assert.NotNull(hook.UpdatedAt); Assert.Equal(webHookConfig.Keys.OrderBy(x => x), hook.Config.Keys.OrderBy(x => x)); Assert.Equal(webHookConfig.Values.OrderBy(x => x), hook.Config.Values.OrderBy(x => x)); Assert.Equal(false, hook.Active); } [IntegrationTest] public async Task CreateAWebHookForTestRepositoryWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var repoName = Helper.MakeNameWithTimestamp("create-hooks-test"); var repository = await github.Repository.Create(new NewRepository(repoName) { AutoInit = true }); var url = "http://test.com/example"; var contentType = WebHookContentType.Json; var secret = "53cr37"; var config = new Dictionary<string, string> { { "hostname", "http://hostname.url" }, { "username", "username" }, { "password", "password" } }; var parameters = new NewRepositoryWebHook("windowsazure", config, url) { Events = new[] { "push" }, Active = false, ContentType = contentType, Secret = secret }; var hook = await github.Repository.Hooks.Create(repository.Id, parameters.ToRequest()); var baseHookUrl = CreateExpectedBaseHookUrl(repository.Url, hook.Id); var webHookConfig = CreateExpectedConfigDictionary(config, url, contentType, secret); Assert.Equal("windowsazure", hook.Name); Assert.Equal(new[] { "push" }.ToList(), hook.Events.ToList()); Assert.Equal(baseHookUrl, hook.Url); Assert.Equal(baseHookUrl + "/test", hook.TestUrl); Assert.Equal(baseHookUrl + "/pings", hook.PingUrl); Assert.NotNull(hook.CreatedAt); Assert.NotNull(hook.UpdatedAt); Assert.Equal(webHookConfig.Keys.OrderBy(x => x), hook.Config.Keys.OrderBy(x => x)); Assert.Equal(webHookConfig.Values.OrderBy(x => x), hook.Config.Values.OrderBy(x => x)); Assert.Equal(false, hook.Active); } Dictionary<string, string> CreateExpectedConfigDictionary(Dictionary<string, string> config, string url, WebHookContentType contentType, string secret) { return new Dictionary<string, string> { { "url", url }, { "content_type", contentType.ToString().ToLowerInvariant() }, { "secret", secret }, { "insecure_ssl", "False" } }.Union(config).ToDictionary(k => k.Key, v => v.Value); } string CreateExpectedBaseHookUrl(string url, int id) { return url + "/hooks/" + id; } } [Collection(RepositoriesHooksCollection.Name)] public class TheEditMethod { readonly RepositoriesHooksFixture _fixture; public TheEditMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task EditHookWithNoNewConfigRetainsTheOldConfig() { var github = Helper.GetAuthenticatedClient(); var editRepositoryHook = new EditRepositoryHook { AddEvents = new[] { "pull_request" } }; var actualHook = await github.Repository.Hooks.Edit(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHooks[0].Id, editRepositoryHook); var expectedConfig = new Dictionary<string, string> { { "content_type", "json" }, { "url", "http://test.com/example" } }; Assert.Equal(new[] { "deployment", "pull_request" }.ToList(), actualHook.Events.ToList()); Assert.Equal(expectedConfig.Keys, actualHook.Config.Keys); Assert.Equal(expectedConfig.Values, actualHook.Config.Values); } [IntegrationTest] public async Task EditHookWithNoNewConfigRetainsTheOldConfigWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var editRepositoryHook = new EditRepositoryHook { AddEvents = new[] { "pull_request" } }; var actualHook = await github.Repository.Hooks.Edit(_fixture.RepositoryId, _fixture.ExpectedHooks[1].Id, editRepositoryHook); var expectedConfig = new Dictionary<string, string> { { "content_type", "json" }, { "url", "http://test.com/example" } }; Assert.Equal(new[] { "push", "pull_request" }.ToList(), actualHook.Events.ToList()); Assert.Equal(expectedConfig.Keys, actualHook.Config.Keys); Assert.Equal(expectedConfig.Values, actualHook.Config.Values); } [IntegrationTest] public async Task EditHookWithNewInformation() { var github = Helper.GetAuthenticatedClient(); var editRepositoryHook = new EditRepositoryHook(new Dictionary<string, string> { { "project", "GEZDGORQFY2TCNZRGY2TSMBVGUYDK" } }) { AddEvents = new[] { "pull_request" } }; var actualHook = await github.Repository.Hooks.Edit(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHooks[2].Id, editRepositoryHook); var expectedConfig = new Dictionary<string, string> { { "project", "GEZDGORQFY2TCNZRGY2TSMBVGUYDK" } }; Assert.Equal(new[] { "push", "pull_request" }.ToList(), actualHook.Events.ToList()); Assert.Equal(expectedConfig.Keys, actualHook.Config.Keys); Assert.Equal(expectedConfig.Values, actualHook.Config.Values); } [IntegrationTest] public async Task EditHookWithNewInformationWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); var editRepositoryHook = new EditRepositoryHook(new Dictionary<string, string> { { "project", "GEZDGORQFY2TCNZRGY2TSMBVGUYDK" } }) { AddEvents = new[] { "pull_request" } }; var actualHook = await github.Repository.Hooks.Edit(_fixture.RepositoryId, _fixture.ExpectedHooks[3].Id, editRepositoryHook); var expectedConfig = new Dictionary<string, string> { { "project", "GEZDGORQFY2TCNZRGY2TSMBVGUYDK" } }; Assert.Equal(new[] { "push", "pull_request" }.ToList(), actualHook.Events.ToList()); Assert.Equal(expectedConfig.Keys, actualHook.Config.Keys); Assert.Equal(expectedConfig.Values, actualHook.Config.Values); } } [Collection(RepositoriesHooksCollection.Name)] public class TheTestMethod { readonly RepositoriesHooksFixture _fixture; public TheTestMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task TestACreatedHook() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Test(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHook.Id); } [IntegrationTest] public async Task TestACreatedHookWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Test(_fixture.RepositoryId, _fixture.ExpectedHook.Id); } } [Collection(RepositoriesHooksCollection.Name)] public class ThePingMethod { readonly RepositoriesHooksFixture _fixture; public ThePingMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task PingACreatedHook() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Ping(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHook.Id); } [IntegrationTest] public async Task PingACreatedHookWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Ping(_fixture.RepositoryId, _fixture.ExpectedHook.Id); } } [Collection(RepositoriesHooksCollection.Name)] public class TheDeleteMethod { readonly RepositoriesHooksFixture _fixture; public TheDeleteMethod(RepositoriesHooksFixture fixture) { _fixture = fixture; } [IntegrationTest] public async Task DeleteCreatedWebHook() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Delete(_fixture.RepositoryOwner, _fixture.RepositoryName, _fixture.ExpectedHook.Id); var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryOwner, _fixture.RepositoryName); Assert.Empty(hooks.Where(hook => hook.Id == _fixture.ExpectedHook.Id)); } [IntegrationTest] public async Task DeleteCreatedWebHookWithRepositoryId() { var github = Helper.GetAuthenticatedClient(); await github.Repository.Hooks.Delete(_fixture.RepositoryId, _fixture.ExpectedHooks[1].Id); var hooks = await github.Repository.Hooks.GetAll(_fixture.RepositoryId); Assert.Empty(hooks.Where(hook => hook.Id == _fixture.ExpectedHooks[1].Id)); } } static void AssertHook(RepositoryHook expectedHook, RepositoryHook actualHook) { Assert.Equal(expectedHook.Id, actualHook.Id); Assert.Equal(expectedHook.Active, actualHook.Active); Assert.Equal(expectedHook.Config, actualHook.Config); Assert.Equal(expectedHook.CreatedAt, actualHook.CreatedAt); Assert.Equal(expectedHook.Name, actualHook.Name); Assert.Equal(expectedHook.PingUrl, actualHook.PingUrl); Assert.Equal(expectedHook.TestUrl, actualHook.TestUrl); Assert.Equal(expectedHook.UpdatedAt, actualHook.UpdatedAt); Assert.Equal(expectedHook.Url, actualHook.Url); } } }
39.508197
169
0.565405
[ "MIT" ]
7enderhead/octokit.net
Octokit.Tests.Integration/Clients/RepositoryHooksClientTests.cs
19,282
C#
using Newtonsoft.Json; using System.IO; using System.Reflection; using System.Text; namespace LuKaSo.Zonky.Tests.IntegrationProduction.Common { public class SecretsJsonReader { private readonly string _path; public SecretsJsonReader() { _path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(SecretsJsonReader)).Location) + "/secrets.json"; } public Secrets Read() { using (var stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new StreamReader(stream, Encoding.UTF8)) using (var jsonReader = new JsonTextReader(reader)) { var serializer = new JsonSerializer(); return serializer.Deserialize<Secrets>(jsonReader); } } } }
29.344828
118
0.626322
[ "MIT" ]
lkavale/LuKaSo.Zonky
tests/LuKaSo.Zonky.Tests.IntegrationProduction/Common/SecretsJsonReader.cs
853
C#
using FizzWare.NBuilder; using Owlvey.Falcon.Core.Entities; using Owlvey.Falcon.Core.Exceptions; using System; using Xunit; namespace Owlvey.Falcon.UnitTests.Entities { public class CustomerEntityUnitTest { [Fact] public void CreateCustomerEntitySuccess() { var createdBy = Guid.NewGuid().ToString("n"); var name = Faker.Company.Name(); var customerEntity = CustomerEntity.Factory.Create(createdBy, DateTime.UtcNow, name); Assert.Equal(name, customerEntity.Name); Assert.Equal(createdBy, customerEntity.CreatedBy); } [Fact] public void CreateCustomerEntityFail() { var createdBy = Guid.NewGuid().ToString("n"); var name = string.Empty; Assert.Throws<InvalidStateException>(() => { CustomerEntity.Factory.Create(name, DateTime.UtcNow, createdBy); }); } [Fact] public void CreateCustomerSuccess() { var entity = CustomerEntity.Factory.Create("test", DateTime.Now, "test"); Assert.NotNull(entity.CreatedBy); Assert.NotNull(entity.CreatedOn); Assert.NotNull(entity.ModifiedBy); Assert.NotNull(entity.ModifiedOn); Assert.NotNull(entity.Name); } } }
28.326531
97
0.589337
[ "Apache-2.0" ]
owlvey/owlvey_falcon
tests/Owlvey.Falcon.UnitTests/Entities/CustomerEntityUnitTest.cs
1,388
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2016-11-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// A complex type that controls whether access logs are written for this streaming distribution. /// </summary> public partial class StreamingLoggingConfig { private string _bucket; private bool? _enabled; private string _prefix; /// <summary> /// Gets and sets the property Bucket. /// <para> /// The Amazon S3 bucket to store the access logs in, for example, <code>myawslogbucket.s3.amazonaws.com</code>. /// </para> /// </summary> public string Bucket { get { return this._bucket; } set { this._bucket = value; } } // Check to see if Bucket property is set internal bool IsSetBucket() { return this._bucket != null; } /// <summary> /// Gets and sets the property Enabled. /// <para> /// Specifies whether you want CloudFront to save access logs to an Amazon S3 bucket. /// If you do not want to enable logging when you create a streaming distribution or if /// you want to disable logging for an existing streaming distribution, specify <code>false</code> /// for <code>Enabled</code>, and specify <code>empty Bucket</code> and <code>Prefix</code> /// elements. If you specify <code>false</code> for <code>Enabled</code> but you specify /// values for <code>Bucket</code> and <code>Prefix</code>, the values are automatically /// deleted. /// </para> /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property Prefix. /// <para> /// An optional string that you want CloudFront to prefix to the access log <code>filenames</code> /// for this streaming distribution, for example, <code>myprefix/</code>. If you want /// to enable logging, but you do not want to specify a prefix, you still must include /// an empty <code>Prefix</code> element in the <code>Logging</code> element. /// </para> /// </summary> public string Prefix { get { return this._prefix; } set { this._prefix = value; } } // Check to see if Prefix property is set internal bool IsSetPrefix() { return this._prefix != null; } } }
34.864078
120
0.613478
[ "Apache-2.0" ]
miltador-forks/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/StreamingLoggingConfig.cs
3,591
C#
using StyletCoreIoC.Creation; using System; using System.Collections.Generic; using System.Linq.Expressions; namespace StyletCoreIoC.Internal.Creators { /// <summary> /// Base class for all ICreators (which want to use it). Provides convenience /// </summary> internal abstract class CreatorBase : ICreator { public virtual RuntimeTypeHandle TypeHandle { get; protected set; } protected IRegistrationContext ParentContext { get; set; } protected CreatorBase(IRegistrationContext parentContext) { this.ParentContext = parentContext; } // Common utility method protected Expression CompleteExpressionFromCreator(Expression creator, ParameterExpression registrationContext) { var type = Type.GetTypeFromHandle(this.TypeHandle); var instanceVar = Expression.Variable(type, "instance"); var assignment = Expression.Assign(instanceVar, creator); var buildUpExpression = this.ParentContext.GetBuilderUpper(type).GetExpression(instanceVar, registrationContext); // We always start with: // var instance = new Class(.....) // instance.Property1 = new .... // instance.Property2 = new .... var blockItems = new List<Expression>() { assignment, buildUpExpression }; // If it implements IInjectionAware, follow that up with: // instance.ParametersInjected() if (typeof(IInjectionAware).IsAssignableFrom(type)) blockItems.Add(Expression.Call(instanceVar, typeof(IInjectionAware).GetMethod("ParametersInjected"))); // Final appearance of instanceVar, as this sets the return value of the block blockItems.Add(instanceVar); var completeExpression = Expression.Block(new[] { instanceVar }, blockItems); return completeExpression; } public abstract Expression GetInstanceExpression(ParameterExpression registrationContext); } }
42.673469
126
0.654711
[ "MIT" ]
ZhangchiBao/Stylet
StyletCore/StyletIoC/Internal/Creators/CreatorBase.cs
2,045
C#
using System.Diagnostics.CodeAnalysis; using FluentDbTools.Common.Abstractions; using FluentDbTools.SqlBuilder; using FluentDbTools.SqlBuilder.Abstractions; using FluentDbTools.SqlBuilder.Abstractions.Parameters; // FluentDbTools.Extensions.SqlBuilder namespace FluentDbTools.Extensions.SqlBuilder { /// <summary> /// Static Factory class for FluentDbTools.SqlBuilder project<br/> /// -> THIS static constructor, Will call <see cref="RegisterDapperTypeHandlers"/> to register Dapper TypeHandlers<br/> /// <br/> /// </summary> [SuppressMessage("ReSharper", "UnusedMember.Global")] public static class SqlBuilderFactory { static SqlBuilderFactory() { RegisterDapperTypeHandlers(); } /// <summary> /// Will register Dapper TypeHandlers /// </summary> public static void RegisterDapperTypeHandlers() { TypeHandlerRegistration.RegisterTypeHandlers(); } /// <summary> /// Create a <see cref="ISqlBuilder"/> instance.<br/> /// See <see cref="IDbConfigSchemaTargets"/> for parameter details<br/> /// <inheritdoc cref="IDbConfigSchemaTargets"/> /// </summary> /// <param name="dbConfigConfig">See <see cref="IDbConfigSchemaTargets.Schema"/></param> /// <returns></returns> public static ISqlBuilder CreateSqlBuilder(this IDbConfigSchemaTargets dbConfigConfig) { return dbConfigConfig.SqlBuilder(); } /// <summary> /// Create a <see cref="ISqlBuilder"/> instance by parameters /// </summary> /// <param name="schema"><inheritdoc cref="IDbConfigSchemaTargets.Schema"/></param> /// <param name="schemaPrefixId"><inheritdoc cref="IDbConfigSchemaTargets.GetSchemaPrefixId"/></param> /// <param name="dbType"><inheritdoc cref="IDbConfigSchemaTargets.DbType"/></param> /// <returns></returns> public static ISqlBuilder CreateSqlBuilder( string schema, string schemaPrefixId, SupportedDatabaseTypes dbType = SupportedDatabaseTypes.Oracle) { return FluentDbTools.SqlBuilder.SqlBuilderFactory.SqlBuilder(schema, schemaPrefixId, dbType); } /// <summary> /// Create a <see cref="IDatabaseParameterResolver"/> instance. <br/> /// See <see cref="IDbConfigSchemaTargets"/> for parameter details<br/> /// <inheritdoc cref="IDbConfigSchemaTargets"/> /// </summary> /// <param name="dbConfigConfig"></param> /// <returns></returns> public static IDatabaseParameterResolver CreateDatabaseParameterResolver(this IDbConfigSchemaTargets dbConfigConfig) { return dbConfigConfig.DatabaseParameterResolver(); } /// <summary> /// Create a <see cref="IDatabaseParameterResolver"/> instance by parameters /// </summary> /// <param name="schema"><inheritdoc cref="IDbConfigSchemaTargets.Schema"/></param> /// <param name="schemaPrefixId"><inheritdoc cref="IDbConfigSchemaTargets.GetSchemaPrefixId"/></param> /// <param name="dbType"><inheritdoc cref="IDbConfigSchemaTargets.DbType"/></param> /// <returns></returns> public static IDatabaseParameterResolver CreateDatabaseParameterResolver( string schema, string schemaPrefixId, SupportedDatabaseTypes dbType = SupportedDatabaseTypes.Oracle) { return FluentDbTools.SqlBuilder.SqlBuilderFactory.DatabaseParameterResolver(schema, schemaPrefixId, dbType); } } } namespace FluentDbTools.Extensions.SqlBuilder { internal class _ { static _() { SqlBuilderFactory.RegisterDapperTypeHandlers(); } } }
39.112245
124
0.650665
[ "MIT" ]
DIPSAS/FluentDbTools
src/FluentDbTools/Extensions/FluentDbTools.Extensions.SqlBuilder/SqlBuilderFactory.cs
3,833
C#
using Core.Entities; using System; using System.Collections.Generic; using System.Text; namespace Entities.Concrete { public class Comment : IEntity { public int CommentId { get; set; } public int GameId { get; set; } public int UserId { get; set; } //This user ıd may be both parent or child development expert. public int Score { get; set; } public string Description { get; set; } public DateTimeOffset Date { get; set; } } }
21.608696
102
0.635815
[ "MIT" ]
fatihkaralar/SeniorDesignProject
SeniorProject/Entities/Concrete/Comment.cs
500
C#
using System.Threading.Tasks; using Surging.Core.CPlatform.Ioc; using Surging.Hero.Organization.IApplication.Corporation.Dtos; namespace Surging.Hero.Organization.Domain.Organizations { public interface ICorporationDomainService : ITransientDependency { Task CreateCorporation(CreateCorporationInput input); Task UpdateCorporation(UpdateCorporationInput input); Task DeleteCorporation(long id); Task<Corporation> GetCorporation(long id); } }
32.533333
69
0.772541
[ "MIT" ]
DotNetExample/Surging.Hero
src/Services/Organization/Surging.Hero.Organization.Domain/Organizations/Corporations/ICorporationDomainService.cs
490
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.Concurrent; using System.Collections.Generic; using System.Linq; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Option; namespace QuantConnect.Brokerages.Backtesting { /// <summary> /// Represents a brokerage to be used during backtesting. This is intended to be only be used with the BacktestingTransactionHandler /// </summary> public class BacktestingBrokerage : Brokerage { // flag used to indicate whether or not we need to scan for // fills, this is purely a performance concern is ConcurrentDictionary.IsEmpty // is not exactly the fastest operation and Scan gets called at least twice per // time loop private bool _needsScan; private readonly ConcurrentDictionary<int, Order> _pending; private readonly object _needsScanLock = new object(); private readonly HashSet<Symbol> _pendingOptionAssignments = new HashSet<Symbol>(); /// <summary> /// This is the algorithm under test /// </summary> protected readonly IAlgorithm Algorithm; /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm /// </summary> /// <param name="algorithm">The algorithm instance</param> public BacktestingBrokerage(IAlgorithm algorithm) : base("Backtesting Brokerage") { Algorithm = algorithm; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="name">The name of the brokerage</param> protected BacktestingBrokerage(IAlgorithm algorithm, string name) : base(name) { Algorithm = algorithm; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Creates a new BacktestingBrokerage for the specified algorithm. Adds market simulation to BacktestingBrokerage; /// </summary> /// <param name="algorithm">The algorithm instance</param> /// <param name="marketSimulation">The backtesting market simulation instance</param> public BacktestingBrokerage(IAlgorithm algorithm, IBacktestingMarketSimulation marketSimulation) : base("Backtesting Brokerage") { Algorithm = algorithm; MarketSimulation = marketSimulation; _pending = new ConcurrentDictionary<int, Order>(); } /// <summary> /// Gets the connection status /// </summary> /// <remarks> /// The BacktestingBrokerage is always connected /// </remarks> public override bool IsConnected => true; /// <summary> /// Gets all open orders on the account /// </summary> /// <returns>The open orders returned from IB</returns> public override List<Order> GetOpenOrders() { return Algorithm.Transactions.GetOpenOrders().ToList(); } /// <summary> /// Gets all holdings for the account /// </summary> /// <returns>The current holdings from the account</returns> public override List<Holding> GetAccountHoldings() { // grab everything from the portfolio with a non-zero absolute quantity return (from kvp in Algorithm.Portfolio.Securities.OrderBy(x => x.Value.Symbol) where kvp.Value.Holdings.AbsoluteQuantity > 0 select new Holding(kvp.Value)).ToList(); } /// <summary> /// Gets the current cash balance for each currency held in the brokerage account /// </summary> /// <returns>The current cash balance for each currency available for trading</returns> public override List<CashAmount> GetCashBalance() { return Algorithm.Portfolio.CashBook.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList(); } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.PlaceOrder(): Type: " + order.Type + " Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity); } if (order.Status == OrderStatus.New) { lock (_needsScanLock) { _needsScan = true; SetPendingOrder(order); } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId); // fire off the event that says this order has been submitted var submitted = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Submitted }; OnOrderEvent(submitted); return true; } return false; } /// <summary> /// Updates the order with the same ID /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public override bool UpdateOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.UpdateOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity + " Status: " + order.Status); } lock (_needsScanLock) { Order pending; if (!_pending.TryGetValue(order.Id, out pending)) { // can't update something that isn't there return false; } _needsScan = true; SetPendingOrder(order); } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId); // fire off the event that says this order has been updated var updated = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.UpdateSubmitted }; OnOrderEvent(updated); return true; } /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was made for the order to be canceled, false otherwise</returns> public override bool CancelOrder(Order order) { if (Algorithm.LiveMode) { Log.Trace("BacktestingBrokerage.CancelOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity); } lock (_needsScanLock) { Order pending; if (!_pending.TryRemove(order.Id, out pending)) { // can't cancel something that isn't there return false; } } var orderId = order.Id.ToStringInvariant(); if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(order.Id.ToStringInvariant()); // fire off the event that says this order has been canceled var canceled = new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Canceled }; OnOrderEvent(canceled); return true; } /// <summary> /// Market Simulation - simulates various market conditions in backtest /// </summary> public IBacktestingMarketSimulation MarketSimulation { get; set; } /// <summary> /// Scans all the outstanding orders and applies the algorithm model fills to generate the order events /// </summary> public virtual void Scan() { lock (_needsScanLock) { // there's usually nothing in here if (!_needsScan) { return; } var stillNeedsScan = false; // process each pending order to produce fills/fire events foreach (var kvp in _pending.OrderBy(x => x.Key)) { var order = kvp.Value; if (order == null) { Log.Error("BacktestingBrokerage.Scan(): Null pending order found: " + kvp.Key); _pending.TryRemove(kvp.Key, out order); continue; } if (order.Status.IsClosed()) { // this should never actually happen as we always remove closed orders as they happen _pending.TryRemove(order.Id, out order); continue; } // all order fills are processed on the next bar (except for market orders) if (order.Time == Algorithm.UtcTime && order.Type != OrderType.Market) { stillNeedsScan = true; continue; } var fills = new OrderEvent[0]; Security security; if (!Algorithm.Securities.TryGetValue(order.Symbol, out security)) { Log.Error("BacktestingBrokerage.Scan(): Unable to process order: " + order.Id + ". The security no longer exists."); // invalidate the order in the algorithm before removing OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) {Status = OrderStatus.Invalid}); _pending.TryRemove(order.Id, out order); continue; } if (order.Type == OrderType.MarketOnOpen) { // This is a performance improvement: // Since MOO should never fill on the same bar or on stale data (see FillModel) // the order can remain unfilled for multiple 'scans', so we want to avoid // margin and portfolio calculations since they are expensive var currentBar = security.GetLastData(); var localOrderTime = order.Time.ConvertFromUtc(security.Exchange.TimeZone); if (currentBar == null || localOrderTime >= currentBar.EndTime) { stillNeedsScan = true; continue; } } // check if the time in force handler allows fills if (order.TimeInForce.IsOrderExpired(security, order)) { OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero) { Status = OrderStatus.Canceled, Message = "The order has expired." }); _pending.TryRemove(order.Id, out order); continue; } // check if we would actually be able to fill this if (!Algorithm.BrokerageModel.CanExecuteOrder(security, order)) { continue; } // verify sure we have enough cash to perform the fill HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult; try { hasSufficientBuyingPowerResult = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder(Algorithm.Portfolio, security, order); } catch (Exception err) { // if we threw an error just mark it as invalid and remove the order from our pending list OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero, err.Message) { Status = OrderStatus.Invalid }); Order pending; _pending.TryRemove(order.Id, out pending); Log.Error(err); Algorithm.Error($"Order Error: id: {order.Id}, Error executing margin models: {err.Message}"); continue; } //Before we check this queued order make sure we have buying power: if (hasSufficientBuyingPowerResult.IsSufficient) { //Model: var model = security.FillModel; //Based on the order type: refresh its model to get fill price and quantity try { if (order.Type == OrderType.OptionExercise) { var option = (Option)security; fills = option.OptionExerciseModel.OptionExercise(option, order as OptionExerciseOrder).ToArray(); } else { var context = new FillModelParameters( security, order, Algorithm.SubscriptionManager.SubscriptionDataConfigService, Algorithm.Settings.StalePriceTimeSpan); fills = new[] { model.Fill(context).OrderEvent }; } // invoke fee models for completely filled order events foreach (var fill in fills) { if (fill.Status == OrderStatus.Filled) { // this check is provided for backwards compatibility of older user-defined fill models // that may be performing fee computation inside the fill model w/out invoking the fee model // TODO : This check can be removed in April, 2019 -- a 6-month window to upgrade (also, suspect small % of users, if any are impacted) if (fill.OrderFee.Value.Amount == 0m) { fill.OrderFee = security.FeeModel.GetOrderFee( new OrderFeeParameters(security, order)); } } } } catch (Exception err) { Log.Error(err); Algorithm.Error($"Order Error: id: {order.Id}, Transaction model failed to fill for order type: {order.Type} with error: {err.Message}"); } } else { // invalidate the order in the algorithm before removing var message = $"Insufficient buying power to complete order (Value:{order.GetValue(security).SmartRounding()}), Reason: {hasSufficientBuyingPowerResult.Reason}."; OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, OrderFee.Zero, message) { Status = OrderStatus.Invalid }); Order pending; _pending.TryRemove(order.Id, out pending); Algorithm.Error($"Order Error: id: {order.Id}, {message}"); continue; } foreach (var fill in fills) { // check if the fill should be emitted if (!order.TimeInForce.IsFillValid(security, order, fill)) { break; } // change in status or a new fill if (order.Status != fill.Status || fill.FillQuantity != 0) { // we update the order status so we do not re process it if we re enter // because of the call to OnOrderEvent. // Note: this is done by the transaction handler but we have a clone of the order order.Status = fill.Status; //If the fill models come back suggesting filled, process the affects on portfolio OnOrderEvent(fill); } if (order.Type == OrderType.OptionExercise) { fill.Message = order.Tag; OnOptionPositionAssigned(fill); } } if (fills.All(x => x.Status.IsClosed())) { _pending.TryRemove(order.Id, out order); } else { stillNeedsScan = true; } } // if we didn't fill then we need to continue to scan or // if there are still pending orders _needsScan = stillNeedsScan || !_pending.IsEmpty; } } /// <summary> /// Runs market simulation /// </summary> public void SimulateMarket() { // if simulator is installed, we run it MarketSimulation?.SimulateMarketConditions(this, Algorithm); } /// <summary> /// This method is called by market simulator in order to launch an assignment event /// </summary> /// <param name="option">Option security to assign</param> /// <param name="quantity">Quantity to assign</param> public virtual void ActivateOptionAssignment(Option option, int quantity) { // do not process the same assignment more than once if (_pendingOptionAssignments.Contains(option.Symbol)) return; _pendingOptionAssignments.Add(option.Symbol); var request = new SubmitOrderRequest(OrderType.OptionExercise, option.Type, option.Symbol, -quantity, 0m, 0m, Algorithm.UtcTime, "Simulated option assignment before expiration"); var ticket = Algorithm.Transactions.ProcessRequest(request); Log.Trace($"BacktestingBrokerage.ActivateOptionAssignment(): OrderId: {ticket.OrderId}"); } /// <summary> /// Event invocator for the OrderFilled event /// </summary> /// <param name="e">The OrderEvent</param> protected override void OnOrderEvent(OrderEvent e) { if (e.Status.IsClosed() && _pendingOptionAssignments.Contains(e.Symbol)) { _pendingOptionAssignments.Remove(e.Symbol); } base.OnOrderEvent(e); } /// <summary> /// The BacktestingBrokerage is always connected. This is a no-op. /// </summary> public override void Connect() { //NOP } /// <summary> /// The BacktestingBrokerage is always connected. This is a no-op. /// </summary> public override void Disconnect() { //NOP } /// <summary> /// Sets the pending order as a clone to prevent object reference nastiness /// </summary> /// <param name="order">The order to be added to the pending orders dictionary</param> /// <returns></returns> private void SetPendingOrder(Order order) { _pending[order.Id] = order; } } }
42.319312
190
0.508155
[ "Apache-2.0" ]
ezaruba/Lean
Brokerages/Backtesting/BacktestingBrokerage.cs
22,135
C#
using System; using System.IO; namespace Microsoft.EntityFrameworkCore.DataEncryption { /// <summary> /// Provides a mechanism for implementing a custom encryption provider. /// </summary> public interface IEncryptionProvider { /// <summary> /// Encrypts a value. /// </summary> /// <typeparam name="TStore"> /// The type of data stored in the database. /// </typeparam> /// <typeparam name="TModel"> /// The type of value stored in the model. /// </typeparam> /// <param name="dataToEncrypt"> /// Input data to encrypt. /// </param> /// <param name="converter"> /// Function which converts the model value to a byte array. /// </param> /// <param name="encoder"> /// Function which encodes the value for storing the the database. /// </param> /// <returns> /// Encrypted data. /// </returns> /// <exception cref="ArgumentNullException"> /// <para><paramref name="converter"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para><paramref name="encoder"/> is <see langword="null"/>.</para> /// </exception> TStore Encrypt<TStore, TModel>(TModel dataToEncrypt, Func<TModel, byte[]> converter, Func<Stream, TStore> encoder); /// <summary> /// Decrypts a value. /// </summary> /// <typeparam name="TStore"> /// The type of data stored in the database. /// </typeparam> /// <typeparam name="TModel"> /// The type of value stored in the model. /// </typeparam> /// <param name="dataToDecrypt"> /// Encrypted data to decrypt. /// </param> /// <param name="decoder"> /// Function which converts the stored data to a byte array. /// </param> /// <param name="converter"> /// Function which converts the decrypted <see cref="Stream"/> to the return value. /// </param> /// <returns> /// Decrypted data. /// </returns> /// <exception cref="ArgumentNullException"> /// <para><paramref name="decoder"/> is <see langword="null"/>.</para> /// <para>-or-</para> /// <para><paramref name="converter"/> is <see langword="null"/>.</para> /// </exception> TModel Decrypt<TStore, TModel>(TStore dataToDecrypt, Func<TStore, byte[]> decoder, Func<Stream, TModel> converter); } }
37.205882
123
0.54585
[ "MIT" ]
AIKICo/EntityFrameworkCore.DataEncryption
src/EntityFrameworkCore.DataEncryption/IEncryptionProvider.cs
2,532
C#
using System; using System.Collections.Generic; using System.Linq; namespace Chatter.MessageBrokers.Routing.Slips { public class RoutingSlip { private readonly IList<RoutingStep> _visited; internal RoutingSlip() { _visited = new List<RoutingStep>(); Route = new List<RoutingStep>(); Attachments = new Dictionary<string, object>(); } public Guid Id { get; set; } public IList<RoutingStep> Route { get; internal set; } public IDictionary<string, object> Attachments { get; internal set; } public IReadOnlyList<RoutingStep> Visited => (IReadOnlyList<RoutingStep>)_visited; public string RouteToNextStep() { var currentStep = Route.FirstOrDefault(); if (currentStep == null) { return null; } _visited.Add(currentStep); Route.RemoveAt(0); return currentStep.DestinationPath; } } }
25.525
90
0.58668
[ "MIT" ]
brenpike/Chatter
src/Chatter.MessageBrokers/src/Chatter.MessageBrokers/Routing/Slips/RoutingSlip.cs
1,023
C#
public class CharacterPanel : BlackDiceMonoBehaviour { public CharacterTile[] CharacterTiles { get; private set; } public void Awake() { CharacterTiles = GetComponentsInChildren<CharacterTile>(); } }
25
66
0.702222
[ "MIT" ]
ModestosV/BlackDice
Online Grid Arena/Assets/Scripts/HUD/CharacterPanel.cs
227
C#
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using System.Collections.Generic; using SimpleScene.Util3d; using OpenTK; namespace SimpleScene { // this class is the binder between the WavefrontObjLoader types and the // OpenTK SimpleScene vertex formats public static class VertexSoup_VertexFormatBinder { // convert wavefrontobjloader vector formats, to our OpenTK Vector3 format // generateDrawIndexBuffer(..) // // Walks the wavefront faces, feeds pre-configured verticies to the VertexSoup, // and returns a new index-buffer pointing to the new VertexSoup.verticies indicies. public static void generateDrawIndexBuffer( WavefrontObjLoader wff, WavefrontObjLoader.MaterialInfoWithFaces objMatSubset, out UInt16[] indicies_return, out SSVertex_PosNormTex[] verticies_return) { const bool shouldDedup = true; // this lets us turn on/of vertex-soup deduping var soup = new VertexSoup<SSVertex_PosNormTex>(deDup:shouldDedup); List<UInt16> draw_indicies = new List<UInt16>(); // (0) go throu`gh the materials and faces, DENORMALIZE from WF-OBJ into fully-configured verticies // load indexes var m = objMatSubset; // wavefrontOBJ stores color in CIE-XYZ color space. Convert this to Alpha-RGB var materialDiffuseColor = WavefrontObjLoader.CIEXYZtoColor(m.mtl.vDiffuse).ToArgb(); foreach (var face in m.faces) { // iterate over the vericies of a wave-front FACE... // DEREFERENCE each .obj vertex paramater (position, normal, texture coordinate) SSVertex_PosNormTex[] vertex_list = new SSVertex_PosNormTex[face.v_idx.Length]; for (int facevertex = 0; facevertex < face.v_idx.Length; facevertex++) { // position vertex_list[facevertex].Position = wff.positions[face.v_idx[facevertex]].Xyz; // normal int normal_idx = face.n_idx[facevertex]; if (normal_idx != -1) { vertex_list[facevertex].Normal = wff.normals[normal_idx]; } // texture coordinate int tex_index = face.tex_idx[facevertex]; if (tex_index != -1 ) { vertex_list[facevertex].Tu = wff.texCoords[tex_index].X; vertex_list[facevertex].Tv = 1- wff.texCoords[tex_index].Y; } } // turn them into indicies in the vertex soup.. // .. we hand the soup a set of fully configured verticies. It // .. dedups and accumulates them, and hands us back indicies // .. relative to it's growing list of deduped verticies. UInt16[] soup_indicies = soup.digestVerticies(vertex_list); // now we add these indicies to the draw-list. Right now we assume // draw is using GL_TRIANGLE, so we convert NGONS into triange lists if (soup_indicies.Length == 3) { // triangle draw_indicies.Add(soup_indicies[0]); draw_indicies.Add(soup_indicies[1]); draw_indicies.Add(soup_indicies[2]); } else if (soup_indicies.Length == 4) { // quad draw_indicies.Add(soup_indicies[0]); draw_indicies.Add(soup_indicies[1]); draw_indicies.Add(soup_indicies[2]); draw_indicies.Add(soup_indicies[0]); draw_indicies.Add(soup_indicies[2]); draw_indicies.Add(soup_indicies[3]); } else { // This n-gon algorithm only works if the n-gon is coplanar and convex, // which Wavefront OBJ says they must be. // .. to tesselate concave ngons, one must tesselate using a more complex method, see // http://en.wikipedia.org/wiki/Polygon_triangulation#Ear_clipping_method // manually generate a triangle-fan for (int x = 1; x < (soup_indicies.Length-1); x++) { draw_indicies.Add(soup_indicies[0]); draw_indicies.Add(soup_indicies[x]); draw_indicies.Add(soup_indicies[x+1]); } // throw new NotImplementedException("unhandled face size: " + newindicies.Length); } } // convert the linked-lists into arrays and return indicies_return = draw_indicies.ToArray(); verticies_return = soup.verticies.ToArray(); Console.WriteLine ("VertexSoup_VertexFormatBinder:generateDrawIndexBuffer : \r\n {0} verticies, {1} indicies. Dedup = {2}", verticies_return.Length, indicies_return.Length, shouldDedup ? "YES" : "NO"); } } }
36.216667
129
0.68937
[ "Apache-2.0" ]
8Observer8/SimpleScene
SimpleScene/Meshes/wfOBJ/VertexSoup_VertexFormatBinder.cs
4,346
C#
using System.ComponentModel.DataAnnotations; namespace NewWebApplicationSample.Models { public class WeChatPayMicroPayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "auth_code")] public string AuthCode { get; set; } } public class WeChatPayPubPayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "notify_url")] public string NotifyUrl { get; set; } [Required] [Display(Name = "trade_type")] public string TradeType { get; set; } [Required] [Display(Name = "openid")] public string OpenId { get; set; } } public class WeChatPayQRPayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "notify_url")] public string NotifyUrl { get; set; } [Required] [Display(Name = "trade_type")] public string TradeType { get; set; } } public class WeChatPayAppPayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "notify_url")] public string NotifyUrl { get; set; } [Required] [Display(Name = "trade_type")] public string TradeType { get; set; } } public class WeChatPayH5PayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "notify_url")] public string NotifyUrl { get; set; } [Required] [Display(Name = "trade_type")] public string TradeType { get; set; } } public class WeChatPayLiteAppPayViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "body")] public string Body { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } [Required] [Display(Name = "notify_url")] public string NotifyUrl { get; set; } [Required] [Display(Name = "trade_type")] public string TradeType { get; set; } [Required] [Display(Name = "openid")] public string OpenId { get; set; } } public class WeChatPayOrderQueryViewModel { [Display(Name = "transaction_id")] public string TransactionId { get; set; } [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } } public class WeChatPayReverseViewModel { [Display(Name = "transaction_id")] public string TransactionId { get; set; } [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } } public class WeChatPayCloseOrderViewModel { [Required] [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } } public class WeChatPayRefundViewModel { [Required] [Display(Name = "out_refund_no")] public string OutRefundNo { get; set; } [Display(Name = "transaction_id")] public string TransactionId { get; set; } [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } [Required] [Display(Name = "total_fee")] public int TotalFee { get; set; } [Required] [Display(Name = "refund_fee")] public int RefundFee { get; set; } [Display(Name = "refund_desc")] public string RefundDesc { get; set; } [Display(Name = "notify_url")] public string NotifyUrl { get; set; } } public class WeChatPayRefundQueryViewModel { [Display(Name = "refund_id")] public string RefundId { get; set; } [Display(Name = "out_refund_no")] public string OutRefundNo { get; set; } [Display(Name = "transaction_id")] public string TransactionId { get; set; } [Display(Name = "out_trade_no")] public string OutTradeNo { get; set; } } public class WeChatPayDownloadBillViewModel { [Required] [Display(Name = "bill_date")] public string BillDate { get; set; } [Required] [Display(Name = "bill_type")] public string BillType { get; set; } [Display(Name = "tar_type")] public string TarType { get; set; } } public class WeChatPayDownloadFundFlowViewModel { [Required] [Display(Name = "bill_date")] public string BillDate { get; set; } [Required] [Display(Name = "account_type")] public string AccountType { get; set; } [Display(Name = "tar_type")] public string TarType { get; set; } } public class WeChatPayTransfersViewModel { [Required] [Display(Name = "partner_trade_no")] public string PartnerTradeNo { get; set; } [Required] [Display(Name = "openid")] public string OpenId { get; set; } [Required] [Display(Name = "check_name")] public string CheckName { get; set; } [Display(Name = "re_user_name")] public string ReUserName { get; set; } [Required] [Display(Name = "amount")] public int Amount { get; set; } [Required] [Display(Name = "desc")] public string Desc { get; set; } [Required] [Display(Name = "spbill_create_ip")] public string SpbillCreateIp { get; set; } } public class WeChatPayGetTransferInfoViewModel { [Required] [Display(Name = "partner_trade_no")] public string PartnerTradeNo { get; set; } } public class WeChatPayPayBankViewModel { [Required] [Display(Name = "partner_trade_no")] public string PartnerTradeNo { get; set; } [Required] [Display(Name = "enc_bank_no")] public string EncBankNo { get; set; } [Required] [Display(Name = "enc_true_name")] public string EncTrueName { get; set; } [Required] [Display(Name = "bank_code")] public string BankCode { get; set; } [Required] [Display(Name = "amount")] public int Amount { get; set; } [Display(Name = "desc")] public string Desc { get; set; } } public class WeChatPayQueryBankViewModel { [Required] [Display(Name = "partner_trade_no")] public string PartnerTradeNo { get; set; } } }
25.455357
51
0.556881
[ "MIT" ]
Aosir/Payment
samples/NewWebApplicationSample/Models/WeChatPayViewModel.cs
8,555
C#
using System; using System.Collections.Generic; namespace PAXSchedule.Models.Gudebook { public partial class GuidebookVenue { public long Id { get; set; } public long? GuideId { get; set; } public string? Name { get; set; } public string? Description { get; set; } public string? Image { get; set; } public string? Street { get; set; } public string? City { get; set; } public string? State { get; set; } public string? Zipcode { get; set; } public double? Longitude { get; set; } public double? Latitude { get; set; } public double? Zoom { get; set; } public DateTime? LastUpdated { get; set; } public virtual GuidebookGuide? Guide { get; set; } } }
31.08
58
0.590734
[ "MIT" ]
remyjette/PAXSchedule
Models/Guidebook/GuidebookVenue.cs
777
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Hl7.Fhir.ElementModel; using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Health.Core.Extensions; using Microsoft.Health.Core.Features.Context; using Microsoft.Health.Extensions.DependencyInjection; using Microsoft.Health.Fhir.Core.Configs; using Microsoft.Health.Fhir.Core.Exceptions; using Microsoft.Health.Fhir.Core.Extensions; using Microsoft.Health.Fhir.Core.Features.Context; using Microsoft.Health.Fhir.Core.Features.Definition; using Microsoft.Health.Fhir.Core.Features.Operations; using Microsoft.Health.Fhir.Core.Features.Operations.Reindex; using Microsoft.Health.Fhir.Core.Features.Operations.Reindex.Models; using Microsoft.Health.Fhir.Core.Features.Persistence; using Microsoft.Health.Fhir.Core.Features.Search; using Microsoft.Health.Fhir.Core.Features.Search.Parameters; using Microsoft.Health.Fhir.Core.Features.Search.Registry; using Microsoft.Health.Fhir.Core.Features.Search.SearchValues; using Microsoft.Health.Fhir.Core.Features.Security.Authorization; using Microsoft.Health.Fhir.Core.Messages.Reindex; using Microsoft.Health.Fhir.Core.Messages.Search; using Microsoft.Health.Fhir.Core.Models; using Microsoft.Health.Fhir.Core.UnitTests.Extensions; using Microsoft.Health.Fhir.Tests.Common; using Microsoft.Health.Fhir.Tests.Common.FixtureParameters; using Microsoft.Health.Fhir.Tests.Integration.Persistence; using Microsoft.Health.Test.Utilities; using NSubstitute; using Xunit; using Task = System.Threading.Tasks.Task; namespace Microsoft.Health.Fhir.Tests.Integration.Features.Operations.Reindex { [FhirStorageTestsFixtureArgumentSets(DataStore.All)] public class ReindexJobTests : IClassFixture<FhirStorageTestsFixture>, IAsyncLifetime { private readonly FhirStorageTestsFixture _fixture; private readonly IFhirStorageTestHelper _testHelper; private IFhirOperationDataStore _fhirOperationDataStore; private IScoped<IFhirOperationDataStore> _scopedOperationDataStore; private IScoped<IFhirDataStore> _scopedDataStore; private IFhirStorageTestHelper _fhirStorageTestHelper; private SearchParameterDefinitionManager _searchParameterDefinitionManager; private ReindexJobConfiguration _jobConfiguration; private CreateReindexRequestHandler _createReindexRequestHandler; private ReindexUtilities _reindexUtilities; private readonly ISearchIndexer _searchIndexer = Substitute.For<ISearchIndexer>(); private ISupportedSearchParameterDefinitionManager _supportedSearchParameterDefinitionManager; private SearchParameterStatusManager _searchParameterStatusManager; private readonly ISearchParameterSupportResolver _searchParameterSupportResolver = Substitute.For<ISearchParameterSupportResolver>(); private ReindexJobWorker _reindexJobWorker; private IScoped<ISearchService> _searchService; private readonly IReindexJobThrottleController _throttleController = Substitute.For<IReindexJobThrottleController>(); private readonly RequestContextAccessor<IFhirRequestContext> _contextAccessor = Substitute.For<RequestContextAccessor<IFhirRequestContext>>(); private readonly ISearchParameterOperations _searchParameterOperations = Substitute.For<ISearchParameterOperations>(); public ReindexJobTests(FhirStorageTestsFixture fixture) { _fixture = fixture; _testHelper = _fixture.TestHelper; } public async Task InitializeAsync() { _fhirOperationDataStore = _fixture.OperationDataStore; _fhirStorageTestHelper = _fixture.TestHelper; _scopedOperationDataStore = _fhirOperationDataStore.CreateMockScope(); _scopedDataStore = _fixture.DataStore.CreateMockScope(); _jobConfiguration = new ReindexJobConfiguration(); IOptions<ReindexJobConfiguration> optionsReindexConfig = Substitute.For<IOptions<ReindexJobConfiguration>>(); optionsReindexConfig.Value.Returns(_jobConfiguration); _searchParameterDefinitionManager = _fixture.SearchParameterDefinitionManager; _supportedSearchParameterDefinitionManager = _fixture.SupportedSearchParameterDefinitionManager; ResourceWrapperFactory wrapperFactory = Mock.TypeWithArguments<ResourceWrapperFactory>( new RawResourceFactory(new FhirJsonSerializer()), new FhirRequestContextAccessor(), _searchIndexer, _searchParameterDefinitionManager, Deserializers.ResourceDeserializer); _searchParameterStatusManager = _fixture.SearchParameterStatusManager; _createReindexRequestHandler = new CreateReindexRequestHandler( _fhirOperationDataStore, DisabledFhirAuthorizationService.Instance, optionsReindexConfig, _searchParameterDefinitionManager, _searchParameterOperations); _reindexUtilities = new ReindexUtilities( () => _scopedDataStore, _searchIndexer, Deserializers.ResourceDeserializer, _supportedSearchParameterDefinitionManager, _searchParameterStatusManager, wrapperFactory); _searchService = _fixture.SearchService.CreateMockScope(); await _fhirStorageTestHelper.DeleteAllReindexJobRecordsAsync(CancellationToken.None); _throttleController.GetThrottleBasedDelay().Returns(0); _throttleController.GetThrottleBatchSize().Returns(100U); } public Task DisposeAsync() { return Task.CompletedTask; } [Fact] public async Task GivenLessThanMaximumRunningJobs_WhenCreatingAReindexJob_ThenNewJobShouldBeCreated() { var request = new CreateReindexRequest(); CreateReindexResponse response = await _createReindexRequestHandler.Handle(request, CancellationToken.None); Assert.NotNull(response); Assert.False(string.IsNullOrWhiteSpace(response.Job.JobRecord.Id)); } [Fact] public async Task GivenAlreadyRunningJob_WhenCreatingAReindexJob_ThenJobConflictExceptionThrown() { var request = new CreateReindexRequest(); CreateReindexResponse response = await _createReindexRequestHandler.Handle(request, CancellationToken.None); Assert.NotNull(response); Assert.False(string.IsNullOrWhiteSpace(response.Job.JobRecord.Id)); await Assert.ThrowsAsync<JobConflictException>(() => _createReindexRequestHandler.Handle(request, CancellationToken.None)); } [Fact] public async Task GivenNoSupportedSearchParameters_WhenRunningReindexJob_ThenJobIsCanceled() { var request = new CreateReindexRequest(); CreateReindexResponse response = await _createReindexRequestHandler.Handle(request, CancellationToken.None); Assert.NotNull(response); Assert.False(string.IsNullOrWhiteSpace(response.Job.JobRecord.Id)); _reindexJobWorker = new ReindexJobWorker( () => _scopedOperationDataStore, Options.Create(_jobConfiguration), InitializeReindexJobTask, _searchParameterOperations, NullLogger<ReindexJobWorker>.Instance); await _reindexJobWorker.Handle(new SearchParametersInitializedNotification(), CancellationToken.None); var cancellationTokenSource = new CancellationTokenSource(); try { await PerformReindexingOperation(response, OperationStatus.Canceled, cancellationTokenSource); } finally { cancellationTokenSource.Cancel(); } } [Fact] public async Task GivenNoMatchingResources_WhenRunningReindexJob_ThenJobIsCompleted() { var searchParam = _supportedSearchParameterDefinitionManager.GetSearchParameter(new Uri("http://hl7.org/fhir/SearchParameter/Measure-name")); searchParam.IsSearchable = false; var request = new CreateReindexRequest(); CreateReindexResponse response = await _createReindexRequestHandler.Handle(request, CancellationToken.None); Assert.NotNull(response); Assert.False(string.IsNullOrWhiteSpace(response.Job.JobRecord.Id)); _reindexJobWorker = new ReindexJobWorker( () => _scopedOperationDataStore, Options.Create(_jobConfiguration), InitializeReindexJobTask, _searchParameterOperations, NullLogger<ReindexJobWorker>.Instance); await _reindexJobWorker.Handle(new SearchParametersInitializedNotification(), CancellationToken.None); var cancellationTokenSource = new CancellationTokenSource(); try { await PerformReindexingOperation(response, OperationStatus.Completed, cancellationTokenSource); Assert.True(searchParam.IsSearchable); } finally { cancellationTokenSource.Cancel(); searchParam.IsSearchable = true; } } [Fact] public async Task GivenNewSearchParamCreatedBeforeResourcesToBeIndexed_WhenReindexJobCompleted_ThenResourcesAreIndexedAndParamIsSearchable() { var randomName = Guid.NewGuid().ToString().ComputeHash().Substring(0, 14).ToLower(); string searchParamName = randomName; string searchParamCode = randomName + "Code"; SearchParameter searchParam = await CreateSearchParam(searchParamName, SearchParamType.String, ResourceType.Patient, "Patient.name", searchParamCode); string sampleName1 = randomName + "searchIndicesPatient1"; string sampleName2 = randomName + "searchIndicesPatient2"; string sampleId1 = Guid.NewGuid().ToString(); string sampleId2 = Guid.NewGuid().ToString(); // Set up the values that the search index extraction should return during reindexing var searchValues = new List<(string, ISearchValue)> { (sampleId1, new StringSearchValue(sampleName1)), (sampleId2, new StringSearchValue(sampleName2)) }; MockSearchIndexExtraction(searchValues, searchParam); UpsertOutcome sample1 = await CreatePatientResource(sampleName1, sampleId1); UpsertOutcome sample2 = await CreatePatientResource(sampleName2, sampleId2); // Create the query <fhirserver>/Patient?foo=searchIndicesPatient1 var queryParams = new List<Tuple<string, string>> { new(searchParamCode, sampleName1) }; SearchResult searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // Confirm that the search parameter "foo" is marked as unsupported Assert.Equal(searchParamCode, searchResults.UnsupportedSearchParameters.FirstOrDefault()?.Item1); // When search parameters aren't recognized, they are ignored // Confirm that "foo" is dropped from the query string and all patients are returned Assert.Equal(2, searchResults.Results.Count()); CreateReindexResponse response = await SetUpForReindexing(); var cancellationTokenSource = new CancellationTokenSource(); try { await PerformReindexingOperation(response, OperationStatus.Completed, cancellationTokenSource); // Rerun the same search as above searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // This time, foo should not be dropped from the query string Assert.Single(searchResults.Results); // The foo search parameter can be used to filter for the first test patient ResourceWrapper patient = searchResults.Results.FirstOrDefault().Resource; Assert.Contains(sampleName1, patient.RawResource.Data); // Confirm that the reindexing operation did not create a new version of the resource Assert.Equal("1", searchResults.Results.FirstOrDefault().Resource.Version); } finally { cancellationTokenSource.Cancel(); _searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement()); await _testHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample1.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample2.Wrapper.ToResourceKey(), CancellationToken.None); } } [Fact] public async Task GivenReindexJobRunning_WhenReindexJobCancelRequest_ThenReindexJobStopsAndMarkedCanceled() { var randomName = Guid.NewGuid().ToString().ComputeHash().Substring(0, 14).ToLower(); string searchParamName = randomName; string searchParamCode = randomName + "Code"; SearchParameter searchParam = await CreateSearchParam(searchParamName, SearchParamType.String, ResourceType.Patient, "Patient.name", searchParamCode); const string sampleName1 = "searchIndicesPatient1"; const string sampleName2 = "searchIndicesPatient2"; const string sampleName3 = "searchIndicesPatient3"; const string sampleName4 = "searchIndicesPatient4"; string sampleId1 = Guid.NewGuid().ToString(); string sampleId2 = Guid.NewGuid().ToString(); string sampleId3 = Guid.NewGuid().ToString(); string sampleId4 = Guid.NewGuid().ToString(); // Set up the values that the search index extraction should return during reindexing var searchValues = new List<(string, ISearchValue)> { (sampleId1, new StringSearchValue(sampleName1)), (sampleId2, new StringSearchValue(sampleName2)), (sampleId3, new StringSearchValue(sampleName3)), (sampleId4, new StringSearchValue(sampleName4)), }; MockSearchIndexExtraction(searchValues, searchParam); UpsertOutcome sample1 = await CreatePatientResource(sampleName1, sampleId1); UpsertOutcome sample2 = await CreatePatientResource(sampleName2, sampleId2); UpsertOutcome sample3 = await CreatePatientResource(sampleName3, sampleId3); UpsertOutcome sample4 = await CreatePatientResource(sampleName4, sampleId4); // Create the query <fhirserver>/Patient?foo=searchIndicesPatient1 var queryParams = new List<Tuple<string, string>> { new(searchParamCode, sampleName1) }; SearchResult searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // Confirm that the search parameter "foo" is marked as unsupported Assert.Equal(searchParamCode, searchResults.UnsupportedSearchParameters.FirstOrDefault()?.Item1); // When search parameters aren't recognized, they are ignored // Confirm that "foo" is dropped from the query string and all patients are returned Assert.Equal(4, searchResults.Results.Count()); var createReindexRequest = new CreateReindexRequest(1, 1, 500); CreateReindexResponse response = await SetUpForReindexing(createReindexRequest); var cancellationTokenSource = new CancellationTokenSource(); try { var cancelReindexHandler = new CancelReindexRequestHandler(_fhirOperationDataStore, DisabledFhirAuthorizationService.Instance); Task reindexWorkerTask = _reindexJobWorker.ExecuteAsync(cancellationTokenSource.Token); await cancelReindexHandler.Handle(new CancelReindexRequest(response.Job.JobRecord.Id), CancellationToken.None); var reindexWrapper = await _fhirOperationDataStore.GetReindexJobByIdAsync(response.Job.JobRecord.Id, cancellationTokenSource.Token); Assert.Equal(OperationStatus.Canceled, reindexWrapper.JobRecord.Status); } catch (RequestNotValidException ex) { // Despite the settings above of the create reindex request which processes only one resource // every 500ms, sometimes when the test runs the reindex job is completed before the // the cancellation request is processed. We will ignore this error if (!ex.Message.Contains("in state Completed and cannot be cancelled", StringComparison.OrdinalIgnoreCase)) { throw; } } finally { cancellationTokenSource.Cancel(); _searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement()); await _testHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample1.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample2.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample3.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample4.Wrapper.ToResourceKey(), CancellationToken.None); } } [Fact] public async Task GivenNewSearchParamCreatedAfterResourcesToBeIndexed_WhenReindexJobCompleted_ThenResourcesAreIndexedAndParamIsSearchable() { var randomName = Guid.NewGuid().ToString().ComputeHash().Substring(0, 14).ToLower(); string searchParamName = randomName; string searchParamCode = randomName + "Code"; string sampleName1 = randomName + "searchIndicesPatient1"; string sampleName2 = randomName + "searchIndicesPatient2"; string sampleId1 = Guid.NewGuid().ToString(); string sampleId2 = Guid.NewGuid().ToString(); UpsertOutcome sample1 = await CreatePatientResource(sampleName1, sampleId1); UpsertOutcome sample2 = await CreatePatientResource(sampleName2, sampleId2); SearchParameter searchParam = await CreateSearchParam(searchParamName, SearchParamType.String, ResourceType.Patient, "Patient.name", searchParamCode); // Create the query <fhirserver>/Patient?foo=searchIndicesPatient1 var queryParams = new List<Tuple<string, string>> { new(searchParamCode, sampleName1) }; SearchResult searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // Confirm that the search parameter "foo" is marked as unsupported Assert.Equal(searchParamCode, searchResults.UnsupportedSearchParameters.FirstOrDefault()?.Item1); // When search parameters aren't recognized, they are ignored // Confirm that "foo" is dropped from the query string and all patients are returned Assert.Equal(2, searchResults.Results.Count()); // Set up the values that the search index extraction should return during reindexing var searchValues = new List<(string, ISearchValue)> { (sampleId1, new StringSearchValue(sampleName1)), (sampleId2, new StringSearchValue(sampleName2)) }; MockSearchIndexExtraction(searchValues, searchParam); CreateReindexResponse response = await SetUpForReindexing(); var cancellationTokenSource = new CancellationTokenSource(); try { await PerformReindexingOperation(response, OperationStatus.Completed, cancellationTokenSource); // Rerun the same search as above searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // This time, foo should not be dropped from the query string Assert.Single(searchResults.Results); // The foo search parameter can be used to filter for the first test patient ResourceWrapper patient = searchResults.Results.FirstOrDefault().Resource; Assert.Contains(sampleName1, patient.RawResource.Data); // Confirm that the reindexing operation did not create a new version of the resource Assert.Equal("1", searchResults.Results.FirstOrDefault().Resource.Version); } finally { cancellationTokenSource.Cancel(); _searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement()); await _testHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample1.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sample2.Wrapper.ToResourceKey(), CancellationToken.None); } } [Fact] public async Task GivenNewSearchParamWithResourceBaseType_WhenReindexJobCompleted_ThenAllResourcesAreIndexedAndParamIsSearchable() { string patientId = Guid.NewGuid().ToString(); string observationId = Guid.NewGuid().ToString(); UpsertOutcome samplePatient = await CreatePatientResource("samplePatient", patientId); UpsertOutcome sampleObservation = await CreateObservationResource(observationId); const string searchParamName = "resourceFoo"; const string searchParamCode = "resourceFooCode"; SearchParameter searchParam = await CreateSearchParam(searchParamName, SearchParamType.Token, ResourceType.Resource, "Resource.id", searchParamCode); // Create the query <fhirserver>/Patient?resourceFooCode=<patientId> var queryParams = new List<Tuple<string, string>> { new(searchParamCode, patientId) }; SearchResult searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); // Confirm that the search parameter "resourceFoo" is marked as unsupported Assert.Equal(searchParamCode, searchResults.UnsupportedSearchParameters.FirstOrDefault()?.Item1); // Set up the values that the search index extraction should return during reindexing var searchValues = new List<(string, ISearchValue)> { (patientId, new TokenSearchValue(null, patientId, null)), (observationId, new TokenSearchValue(null, observationId, null)) }; MockSearchIndexExtraction(searchValues, searchParam); CreateReindexResponse response = await SetUpForReindexing(); var cancellationTokenSource = new CancellationTokenSource(); try { await PerformReindexingOperation(response, OperationStatus.Completed, cancellationTokenSource); // Rerun the same search as above searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); Assert.Single(searchResults.Results); // Confirm that the search parameter "resourceFoo" isn't marked as unsupported Assert.DoesNotContain(searchResults.UnsupportedSearchParameters, t => t.Item1 == searchParamCode); // Create the query <fhirserver>/Patient?resourceFooCode=<nonexistent-id> queryParams = new List<Tuple<string, string>> { new(searchParamCode, "nonexistent-id") }; // No resources should be returned searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None); Assert.Empty(searchResults.Results); // Create the query <fhirserver>/Observation?resourceFooCode=<observationId> queryParams = new List<Tuple<string, string>> { new(searchParamCode, observationId) }; // Check that the new search parameter can be used with a different type of resource searchResults = await _searchService.Value.SearchAsync("Observation", queryParams, CancellationToken.None); Assert.Single(searchResults.Results); // Confirm that the search parameter "resourceFoo" isn't marked as unsupported Assert.DoesNotContain(searchResults.UnsupportedSearchParameters, t => t.Item1 == searchParamCode); // Create the query <fhirserver>/Observation?resourceFooCode=<nonexistent-id> queryParams = new List<Tuple<string, string>> { new(searchParamCode, "nonexistent-id") }; // No resources should be returned searchResults = await _searchService.Value.SearchAsync("Observation", queryParams, CancellationToken.None); Assert.Empty(searchResults.Results); } finally { cancellationTokenSource.Cancel(); _searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement()); await _testHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(samplePatient.Wrapper.ToResourceKey(), CancellationToken.None); await _fixture.DataStore.HardDeleteAsync(sampleObservation.Wrapper.ToResourceKey(), CancellationToken.None); } } private async Task<ReindexJobWrapper> PerformReindexingOperation( CreateReindexResponse response, OperationStatus operationStatus, CancellationTokenSource cancellationTokenSource, int delay = 1000) { Task reindexWorkerTask = _reindexJobWorker.ExecuteAsync(cancellationTokenSource.Token); ReindexJobWrapper reindexJobWrapper = await _fhirOperationDataStore.GetReindexJobByIdAsync(response.Job.JobRecord.Id, cancellationTokenSource.Token); int delayCount = 0; while (reindexJobWrapper.JobRecord.Status != operationStatus && delayCount < 40) { await Task.Delay(delay); delayCount++; reindexJobWrapper = await _fhirOperationDataStore.GetReindexJobByIdAsync(response.Job.JobRecord.Id, cancellationTokenSource.Token); } Assert.Equal(operationStatus, reindexJobWrapper.JobRecord.Status); return reindexJobWrapper; } private async Task<CreateReindexResponse> SetUpForReindexing(CreateReindexRequest request = null) { if (request == null) { request = new CreateReindexRequest(); } CreateReindexResponse response = await _createReindexRequestHandler.Handle(request, CancellationToken.None); Assert.NotNull(response); Assert.False(string.IsNullOrWhiteSpace(response.Job.JobRecord.Id)); _reindexJobWorker = new ReindexJobWorker( () => _scopedOperationDataStore, Options.Create(_jobConfiguration), InitializeReindexJobTask, _searchParameterOperations, NullLogger<ReindexJobWorker>.Instance); await _reindexJobWorker.Handle(new SearchParametersInitializedNotification(), CancellationToken.None); return response; } private void MockSearchIndexExtraction(IEnumerable<(string id, ISearchValue searchValue)> searchValues, SearchParameter searchParam) { SearchParameterInfo searchParamInfo = searchParam.ToInfo(); foreach ((string id, ISearchValue searchValue) in searchValues) { var searchIndexValues = new List<SearchIndexEntry>(); searchIndexValues.Add(new SearchIndexEntry(searchParamInfo, searchValue)); _searchIndexer.Extract(Arg.Is<ResourceElement>(r => r.Id.Equals(id))).Returns(searchIndexValues); } } private async Task<SearchParameter> CreateSearchParam(string searchParamName, SearchParamType searchParamType, ResourceType baseType, string expression, string searchParamCode) { var searchParam = new SearchParameter { Url = $"http://hl7.org/fhir/SearchParameter/{baseType}-{searchParamName}", Type = searchParamType, Base = new List<ResourceType?> { baseType }, Expression = expression, Name = searchParamName, Code = searchParamCode, }; _searchParameterDefinitionManager.AddNewSearchParameters(new List<ITypedElement> { searchParam.ToTypedElement() }); // Add the search parameter to the datastore await _searchParameterStatusManager.UpdateSearchParameterStatusAsync(new List<string> { searchParam.Url }, SearchParameterStatus.Supported); return searchParam; } private ReindexJobTask InitializeReindexJobTask() { return new ReindexJobTask( () => _scopedOperationDataStore, () => _scopedDataStore, Options.Create(_jobConfiguration), () => _searchService, _supportedSearchParameterDefinitionManager, _reindexUtilities, _contextAccessor, _throttleController, ModelInfoProvider.Instance, NullLogger<ReindexJobTask>.Instance); } private ResourceWrapper CreatePatientResourceWrapper(string patientName, string patientId) { Patient patientResource = Samples.GetDefaultPatient().ToPoco<Patient>(); patientResource.Name = new List<HumanName> { new() { Family = patientName }}; patientResource.Id = patientId; patientResource.VersionId = "1"; var resourceElement = patientResource.ToResourceElement(); var rawResource = new RawResource(patientResource.ToJson(), FhirResourceFormat.Json, isMetaSet: false); var resourceRequest = new ResourceRequest(WebRequestMethods.Http.Put); var compartmentIndices = Substitute.For<CompartmentIndices>(); var searchIndices = _searchIndexer.Extract(resourceElement); var wrapper = new ResourceWrapper(resourceElement, rawResource, resourceRequest, false, searchIndices, compartmentIndices, new List<KeyValuePair<string, string>>(), _searchParameterDefinitionManager.GetSearchParameterHashForResourceType("Patient")); wrapper.SearchParameterHash = "hash"; return wrapper; } private ResourceWrapper CreateObservationResourceWrapper(string observationId) { Observation observationResource = Samples.GetDefaultObservation().ToPoco<Observation>(); observationResource.Id = observationId; observationResource.VersionId = "1"; var resourceElement = observationResource.ToResourceElement(); var rawResource = new RawResource(observationResource.ToJson(), FhirResourceFormat.Json, isMetaSet: false); var resourceRequest = new ResourceRequest(WebRequestMethods.Http.Put); var compartmentIndices = Substitute.For<CompartmentIndices>(); var searchIndices = _searchIndexer.Extract(resourceElement); var wrapper = new ResourceWrapper(resourceElement, rawResource, resourceRequest, false, searchIndices, compartmentIndices, new List<KeyValuePair<string, string>>(), _searchParameterDefinitionManager.GetSearchParameterHashForResourceType("Observation")); wrapper.SearchParameterHash = "hash"; return wrapper; } private async Task<UpsertOutcome> CreatePatientResource(string patientName, string patientId) { return await _scopedDataStore.Value.UpsertAsync(CreatePatientResourceWrapper(patientName, patientId), null, true, true, CancellationToken.None); } private async Task<UpsertOutcome> CreateObservationResource(string observationId) { return await _scopedDataStore.Value.UpsertAsync(CreateObservationResourceWrapper(observationId), null, true, true, CancellationToken.None); } } }
51.520674
265
0.68246
[ "MIT" ]
kannanMSFT/fhir-server
test/Microsoft.Health.Fhir.Shared.Tests.Integration/Features/Operations/Reindex/ReindexJobTests.cs
33,645
C#
namespace BookWorm.Core.Models { public class Shipping { public int Id { get; set; } public string Name { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public int ShoppingCartId { get; set; } public ShoppingCart ShoppingCart { get; set; } public string AppUserId { get; set; } public AppUser AppUser { get; set; } } }
19.4
54
0.571134
[ "MIT" ]
nesta-bg/BookWorm
BookWorm/Core/Models/Shipping.cs
487
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. ==================================================================== */ using System.Collections.Generic; /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace Npoi.Core.Util { /// <summary> /// Returns immutable Btfield instances. /// @author Jason Height (jheight at apache dot org) /// </summary> public class BitFieldFactory { //use Dictionary<object,object> to replace HashMap private static Dictionary<int, BitField> instances = new Dictionary<int, BitField>(); /// <summary> /// Gets the instance. /// </summary> /// <param name="mask">The mask.</param> /// <returns></returns> public static BitField GetInstance(int mask) { BitField bitField = null; if (instances.TryGetValue(mask, out bitField)) { return bitField; } bitField = new BitField(mask); instances.Add(mask, bitField); return bitField; } } }
37.482759
93
0.574057
[ "Apache-2.0" ]
Arch/Npoi.Core
src/Npoi.Core/Util/BitFieldFactory.cs
2,176
C#
namespace BookShop { using System; public class Book { private string title; private string author; private decimal price; public Book(string inputAuthor, string inputTitle, decimal inputPrice) { this.Title = inputTitle; this.Price = inputPrice; this.Author = inputAuthor; } public virtual decimal Price { get { return price; } protected set { if (value <= 0) { throw new ArgumentException("Price not valid!"); } price = value; } } public string Author { get { return this.author; } protected set { string[] authorNames = value.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); string authorSecondName = string.Empty; if (authorNames.Length > 1) { authorSecondName = authorNames[1]; if (char.IsDigit(authorSecondName[0])) { throw new ArgumentException("Author not valid!"); } } this.author = value; } } public string Title { get { return title; } protected set { const int minimumTitleLength = 3; if (value.Length < minimumTitleLength) { throw new ArgumentException("Title not valid!"); } title = value; } } public override string ToString() { return $"Type: {this.GetType().Name}" + Environment.NewLine + $"Title: {this.Title}" + Environment.NewLine + $"Author: {this.Author}" + Environment.NewLine + $"Price: {this.Price:f2}"; } } }
25.738095
108
0.421369
[ "MIT" ]
BoykoNeov/Entity-Framework-SoftUni-Oct2017
Inheritance/BookShop/Book.cs
2,164
C#
using System.ComponentModel.DataAnnotations; using Abp.Authorization.Users; using Abp.AutoMapper; using Abp.MultiTenancy; namespace Echo.MultiTenancy.Dto { [AutoMapTo(typeof(Tenant))] public class CreateTenantDto { [Required] [StringLength(AbpTenantBase.MaxTenancyNameLength)] [RegularExpression(AbpTenantBase.TenancyNameRegex)] public string TenancyName { get; set; } [Required] [StringLength(AbpTenantBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string AdminEmailAddress { get; set; } [StringLength(AbpTenantBase.MaxConnectionStringLength)] public string ConnectionString { get; set; } public bool IsActive {get; set;} } }
27.566667
63
0.689238
[ "MIT" ]
Versus-91/Echo
src/Echo.Application/MultiTenancy/Dto/CreateTenantDto.cs
827
C#
namespace p03.HornetAssault { using System; using System.Collections.Generic; using System.Linq; class HornetAssault //90/100 { static void Main(string[] args) { List<long> beehives = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions .RemoveEmptyEntries) .Select(long.Parse) .ToList(); List<long> hornets = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions .RemoveEmptyEntries) .Select(long.Parse) .ToList(); for (int i = 0; i < beehives.Count; i++) { if (hornets.Count == 0) { break; } if (hornets.Sum() > beehives[i]) { beehives.RemoveAt(i); i--; } else if (hornets.Sum() <= beehives[i]) { beehives[i] -= hornets.Sum(); hornets.RemoveAt(0); } } if (beehives.Where(x => x > 0).Count() > 0) { Console.WriteLine( string.Join(" ", beehives.Where(x => x > 0))); } else { Console.WriteLine(string.Join(" ", hornets)); } } } }
27.490909
66
0.377646
[ "MIT" ]
vesy53/SoftUni
Tech Module/Programming Fundamentals/Exams/Exam26February2017/p03HornetAssault/HornetAssault.cs
1,514
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.DataFactory.V20180601.Outputs { /// <summary> /// SSIS property override. /// </summary> [OutputType] public sealed class SSISPropertyOverrideResponse { /// <summary> /// Whether SSIS package property override value is sensitive data. Value will be encrypted in SSISDB if it is true /// </summary> public readonly bool? IsSensitive; /// <summary> /// SSIS package property override value. Type: string (or Expression with resultType string). /// </summary> public readonly object Value; [OutputConstructor] private SSISPropertyOverrideResponse( bool? isSensitive, object value) { IsSensitive = isSensitive; Value = value; } } }
29
123
0.641026
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataFactory/V20180601/Outputs/SSISPropertyOverrideResponse.cs
1,131
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SIL.Machine.Threading { /// <summary> /// An async-compatible producer/consumer collection. /// </summary> /// <typeparam name="T">The type of elements contained in the collection.</typeparam> public sealed class AsyncCollection<T> { /// <summary> /// The underlying collection. /// </summary> private readonly IProducerConsumerCollection<T> _collection; /// <summary> /// The maximum number of elements allowed in the collection. /// </summary> private readonly int _maxCount; /// <summary> /// The mutual-exclusion lock protecting the collection. /// </summary> private readonly AsyncLock _mutex; /// <summary> /// A condition variable that is signalled when the collection is not full. /// </summary> private readonly AsyncConditionVariable _notFull; /// <summary> /// A condition variable that is signalled when the collection is completed or not empty. /// </summary> private readonly AsyncConditionVariable _completedOrNotEmpty; /// <summary> /// A cancellation token source that is canceled when the collection is marked completed for adding. /// </summary> private readonly CancellationTokenSource _completed; /// <summary> /// A cached result that is common when calling <see cref="o:AsyncCollectionExtensions.TryTakeFromAnyAsync"/>. /// </summary> internal static readonly TakeResult FalseResult = new TakeResult(null, default(T)); /// <summary> /// Creates a new async-compatible producer/consumer collection wrapping the specified collection and with a maximum element count. /// </summary> /// <param name="collection">The collection to wrap.</param> /// <param name="maxCount">The maximum element count. This must be greater than zero.</param> public AsyncCollection(IProducerConsumerCollection<T> collection, int maxCount) { collection = collection ?? new ConcurrentQueue<T>(); if (maxCount <= 0) throw new ArgumentOutOfRangeException("maxCount", "The maximum count must be greater than zero."); if (maxCount < collection.Count) throw new ArgumentException("The maximum count cannot be less than the number of elements in the collection.", "maxCount"); _collection = collection; _maxCount = maxCount; _mutex = new AsyncLock(); _notFull = new AsyncConditionVariable(_mutex); _completedOrNotEmpty = new AsyncConditionVariable(_mutex); _completed = new CancellationTokenSource(); } /// <summary> /// Creates a new async-compatible producer/consumer collection wrapping the specified collection. /// </summary> /// <param name="collection">The collection to wrap.</param> public AsyncCollection(IProducerConsumerCollection<T> collection) : this(collection, int.MaxValue) { } /// <summary> /// Creates a new async-compatible producer/consumer collection with a maximum element count. /// </summary> /// <param name="maxCount">The maximum element count. This must be greater than zero.</param> public AsyncCollection(int maxCount) : this(null, maxCount) { } /// <summary> /// Creates a new async-compatible producer/consumer collection. /// </summary> public AsyncCollection() : this(null, int.MaxValue) { } /// <summary> /// Whether the collection is empty. /// </summary> private bool Empty { get { return _collection.Count == 0; } } /// <summary> /// Whether the collection is full. /// </summary> private bool Full { get { return _collection.Count == _maxCount; } } /// <summary> /// Asynchronously marks the producer/consumer collection as complete for adding. /// </summary> [Obsolete("Use CompleteAdding() instead.")] public async Task CompleteAddingAsync() { using (await _mutex.LockAsync().ConfigureAwait(false)) { if (_completed.IsCancellationRequested) return; _completed.Cancel(); _completedOrNotEmpty.NotifyAll(); } } /// <summary> /// Synchronously marks the producer/consumer collection as complete for adding. /// </summary> public void CompleteAdding() { using (_mutex.Lock()) { if (_completed.IsCancellationRequested) return; _completed.Cancel(); _completedOrNotEmpty.NotifyAll(); } } /// <summary> /// Attempts to add an item. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation. If <paramref name="abort"/> is not <c>null</c>, then this token must include signals from the <paramref name="abort"/> object.</param> /// <param name="abort">A synchronization object used to cancel related add operations. May be <c>null</c> if this is the only add operation.</param> internal async Task<AsyncCollection<T>> TryAddAsync(T item, CancellationToken cancellationToken, TaskCompletionSource abort) { try { using (var combinedToken = CancellationTokenHelpers.Normalize(_completed.Token, cancellationToken)) using (await _mutex.LockAsync().ConfigureAwait(false)) { // Wait for the collection to be not full. while (Full) await _notFull.WaitAsync(combinedToken.Token).ConfigureAwait(false); // Explicitly check whether the collection has been marked complete to prevent a race condition where notFull is signalled at the same time the collection is marked complete. if (_completed.IsCancellationRequested) return null; // Set the abort signal. If another collection has already set the abort signal, then abort. if (abort != null && !abort.TrySetCanceled()) return null; if (!_collection.TryAdd(item)) return null; _completedOrNotEmpty.Notify(); return this; } } catch (OperationCanceledException) { return null; } } /// <summary> /// Attempts to add an item. This method may block the calling thread. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> internal AsyncCollection<T> DoTryAdd(T item, CancellationToken cancellationToken) { try { using (var combinedToken = CancellationTokenHelpers.Normalize(_completed.Token, cancellationToken)) using (_mutex.Lock()) { // Wait for the collection to be not full. while (Full) _notFull.Wait(combinedToken.Token); // Explicitly check whether the collection has been marked complete to prevent a race condition where notFull is signalled at the same time the collection is marked complete. if (_completed.IsCancellationRequested) return null; if (!_collection.TryAdd(item)) return null; _completedOrNotEmpty.Notify(); return this; } } catch (OperationCanceledException) { return null; } } /// <summary> /// Attempts to add an item to the producer/consumer collection. Returns <c>false</c> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> public async Task<bool> TryAddAsync(T item, CancellationToken cancellationToken) { var ret = await TryAddAsync(item, cancellationToken, null).ConfigureAwait(false); if (ret != null) return true; cancellationToken.ThrowIfCancellationRequested(); return false; } /// <summary> /// Attempts to add an item to the producer/consumer collection. Returns <c>false</c> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> public bool TryAdd(T item, CancellationToken cancellationToken) { var ret = DoTryAdd(item, cancellationToken); if (ret != null) return true; cancellationToken.ThrowIfCancellationRequested(); return false; } /// <summary> /// Attempts to add an item to the producer/consumer collection. Returns <c>false</c> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. /// </summary> /// <param name="item">The item to add.</param> public Task<bool> TryAddAsync(T item) { return TryAddAsync(item, CancellationToken.None); } /// <summary> /// Attempts to add an item to the producer/consumer collection. Returns <c>false</c> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread. /// </summary> /// <param name="item">The item to add.</param> public bool TryAdd(T item) { return TryAdd(item, CancellationToken.None); } /// <summary> /// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> public async Task AddAsync(T item, CancellationToken cancellationToken) { var result = await TryAddAsync(item, cancellationToken).ConfigureAwait(false); if (!result) throw new InvalidOperationException("Add failed; the producer/consumer collection has completed adding or the underlying collection refused the item."); } /// <summary> /// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread. /// </summary> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> public void Add(T item, CancellationToken cancellationToken) { var result = TryAdd(item, cancellationToken); if (!result) throw new InvalidOperationException("Add failed; the producer/consumer collection has completed adding or the underlying collection refused the item."); } /// <summary> /// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. /// </summary> /// <param name="item">The item to add.</param> public Task AddAsync(T item) { return AddAsync(item, CancellationToken.None); } /// <summary> /// Adds an item to the producer/consumer collection. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding or if the item was rejected by the underlying collection. This method may block the calling thread. /// </summary> /// <param name="item">The item to add.</param> public void Add(T item) { Add(item, CancellationToken.None); } /// <summary> /// Asynchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the asynchronous wait.</param> public async Task<bool> OutputAvailableAsync(CancellationToken cancellationToken) { using (await _mutex.LockAsync().ConfigureAwait(false)) { while (!_completed.IsCancellationRequested && Empty) await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false); return !Empty; } } /// <summary> /// Asynchronously waits until an item is available to dequeue. Returns <c>false</c> if the producer/consumer collection has completed adding and there are no more items. /// </summary> public Task<bool> OutputAvailableAsync() { return OutputAvailableAsync(CancellationToken.None); } /// <summary> /// Provides a (synchronous) consuming enumerable for items in the producer/consumer collection. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the synchronous enumeration.</param> public IEnumerable<T> GetConsumingEnumerable(CancellationToken cancellationToken) { while (true) { var result = DoTryTake(cancellationToken); if (!result.Success) yield break; yield return result.Item; } } /// <summary> /// Provides a (synchronous) consuming enumerable for items in the producer/consumer queue. /// </summary> public IEnumerable<T> GetConsumingEnumerable() { return GetConsumingEnumerable(CancellationToken.None); } /// <summary> /// Attempts to take an item. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation. If <paramref name="abort"/> is not <c>null</c>, then this token must include signals from the <paramref name="abort"/> object.</param> /// <param name="abort">A synchronization object used to cancel related take operations. May be <c>null</c> if this is the only take operation.</param> internal async Task<TakeResult> TryTakeAsync(CancellationToken cancellationToken, TaskCompletionSource abort) { try { using (await _mutex.LockAsync().ConfigureAwait(false)) { while (!_completed.IsCancellationRequested && Empty) await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false); if (_completed.IsCancellationRequested && Empty) return FalseResult; if (abort != null && !abort.TrySetCanceled()) return FalseResult; T item; if (!_collection.TryTake(out item)) return FalseResult; _notFull.Notify(); return new TakeResult(this, item); } } catch (OperationCanceledException) { return FalseResult; } } /// <summary> /// Attempts to take an item. This method may block the calling thread. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> internal TakeResult DoTryTake(CancellationToken cancellationToken) { try { using (_mutex.Lock()) { while (!_completed.IsCancellationRequested && Empty) _completedOrNotEmpty.Wait(cancellationToken); if (_completed.IsCancellationRequested && Empty) return FalseResult; T item; if (!_collection.TryTake(out item)) return FalseResult; _notFull.Notify(); return new TakeResult(this, item); } } catch (OperationCanceledException) { return FalseResult; } } /// <summary> /// Attempts to take an item from the producer/consumer collection. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public async Task<TakeResult> TryTakeAsync(CancellationToken cancellationToken) { var ret = await TryTakeAsync(cancellationToken, null).ConfigureAwait(false); if (ret.Success) return ret; cancellationToken.ThrowIfCancellationRequested(); return ret; } /// <summary> /// Attempts to take an item from the producer/consumer collection. This method may block the calling thread. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public TakeResult TryTake(CancellationToken cancellationToken) { var ret = DoTryTake(cancellationToken); if (ret.Success) return ret; cancellationToken.ThrowIfCancellationRequested(); return ret; } /// <summary> /// Attempts to take an item from the producer/consumer collection. /// </summary> public Task<TakeResult> TryTakeAsync() { return TryTakeAsync(CancellationToken.None); } /// <summary> /// Attempts to take an item from the producer/consumer collection. This method may block the calling thread. /// </summary> public TakeResult TryTake() { return TryTake(CancellationToken.None); } /// <summary> /// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public async Task<T> TakeAsync(CancellationToken cancellationToken) { var ret = await TryTakeAsync(cancellationToken).ConfigureAwait(false); if (!ret.Success) throw new InvalidOperationException("Take failed; the producer/consumer collection has completed adding and is empty, or the take from the underlying collection failed."); return ret.Item; } /// <summary> /// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. This method may block the calling thread. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public T Take(CancellationToken cancellationToken) { var ret = TryTake(cancellationToken); if (!ret.Success) throw new InvalidOperationException("Take failed; the producer/consumer collection has completed adding and is empty, or the take from the underlying collection failed."); return ret.Item; } /// <summary> /// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. /// </summary> public Task<T> TakeAsync() { return TakeAsync(CancellationToken.None); } /// <summary> /// Takes an item from the producer/consumer collection. Returns the item. Throws <see cref="InvalidOperationException"/> if the producer/consumer collection has completed adding and is empty, or if the take from the underlying collection failed. This method may block the calling thread. /// </summary> public T Take() { return Take(CancellationToken.None); } public async Task<IReadOnlyCollection<T>> TakeAllAsync(CancellationToken cancellationToken) { try { using (await _mutex.LockAsync().ConfigureAwait(false)) { while (!_completed.IsCancellationRequested && Empty) await _completedOrNotEmpty.WaitAsync(cancellationToken).ConfigureAwait(false); if (_completed.IsCancellationRequested && Empty) return new T[0]; var result = new List<T>(); while (_collection.TryTake(out T item)) result.Add(item); _notFull.Notify(); return result; } } catch (OperationCanceledException) { return new T[0]; } } public Task<IReadOnlyCollection<T>> TakeAllAsync() { return TakeAllAsync(CancellationToken.None); } /// <summary> /// The result of a <c>TryTake</c>, <c>TakeFromAny</c>, or <c>TryTakeFromAny</c> operation. /// </summary> public sealed class TakeResult { internal TakeResult(AsyncCollection<T> collection, T item) { Collection = collection; Item = item; } /// <summary> /// The collection from which the item was taken, or <c>null</c> if the operation failed. /// </summary> public AsyncCollection<T> Collection { get; private set; } /// <summary> /// Whether the operation was successful. This is <c>true</c> if and only if <see cref="Collection"/> is not <c>null</c>. /// </summary> public bool Success { get { return Collection != null; } } /// <summary> /// The item. This is only valid if <see cref="Collection"/> is not <c>null</c>. /// </summary> public T Item { get; private set; } } } /// <summary> /// Provides methods for working on multiple <see cref="AsyncCollection{T}"/> instances. /// </summary> public static class AsyncCollectionExtensions { /// <summary> /// Attempts to add an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Returns <c>null</c> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static async Task<AsyncCollection<T>> TryAddToAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, T item, CancellationToken cancellationToken) { var abort = new TaskCompletionSource(); using (var abortCancellationToken = CancellationTokenHelpers.FromTask(abort.Task)) using (var combinedToken = CancellationTokenHelpers.Normalize(abortCancellationToken.Token, cancellationToken)) { var token = combinedToken.Token; var tasks = collections.Select(q => q.TryAddAsync(item, token, abort)); var results = await Task.WhenAll(tasks).ConfigureAwait(false); var ret = results.FirstOrDefault(x => x != null); if (ret == null) cancellationToken.ThrowIfCancellationRequested(); return ret; } } /// <summary> /// Attempts to add an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Returns <c>null</c> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static AsyncCollection<T> TryAddToAny<T>(this IEnumerable<AsyncCollection<T>> collections, T item, CancellationToken cancellationToken) { return TryAddToAnyAsync(collections, item, cancellationToken).WaitAndUnwrapException(); } /// <summary> /// Attempts to add an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Returns <c>null</c> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static Task<AsyncCollection<T>> TryAddToAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, T item) { return TryAddToAnyAsync(collections, item, CancellationToken.None); } /// <summary> /// Attempts to add an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Returns <c>null</c> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static AsyncCollection<T> TryAddToAny<T>(this IEnumerable<AsyncCollection<T>> collections, T item) { return TryAddToAny(collections, item, CancellationToken.None); } /// <summary> /// Adds an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Throws <see cref="InvalidOperationException"/> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static async Task<AsyncCollection<T>> AddToAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, T item, CancellationToken cancellationToken) { var ret = await TryAddToAnyAsync(collections, item, cancellationToken).ConfigureAwait(false); if (ret == null) throw new InvalidOperationException("Add failed; all producer/consumer collections have completed adding."); return ret; } /// <summary> /// Adds an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Throws <see cref="InvalidOperationException"/> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the add operation.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static AsyncCollection<T> AddToAny<T>(this IEnumerable<AsyncCollection<T>> collections, T item, CancellationToken cancellationToken) { var ret = TryAddToAny(collections, item, cancellationToken); if (ret == null) throw new InvalidOperationException("Add failed; all producer/consumer collections have completed adding."); return ret; } /// <summary> /// Adds an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Throws <see cref="InvalidOperationException"/> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static Task<AsyncCollection<T>> AddToAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, T item) { return AddToAnyAsync(collections, item, CancellationToken.None); } /// <summary> /// Adds an item to any of a number of producer/consumer collections. Returns the producer/consumer collection that received the item. Throws <see cref="InvalidOperationException"/> if all producer/consumer collections have completed adding, or if any add operation on an underlying collection failed. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="item">The item to add.</param> /// <returns>The producer/consumer collection that received the item.</returns> public static AsyncCollection<T> AddToAny<T>(this IEnumerable<AsyncCollection<T>> collections, T item) { return AddToAny(collections, item, CancellationToken.None); } /// <summary> /// Attempts to take an item from any of a number of producer/consumer collections. The operation "fails" if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public static async Task<AsyncCollection<T>.TakeResult> TryTakeFromAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, CancellationToken cancellationToken) { var abort = new TaskCompletionSource(); using (var abortCancellationToken = CancellationTokenHelpers.FromTask(abort.Task)) using (var combinedToken = CancellationTokenHelpers.Normalize(abortCancellationToken.Token, cancellationToken)) { var token = combinedToken.Token; var tasks = collections.Select(q => q.TryTakeAsync(token, abort)); var results = await Task.WhenAll(tasks).ConfigureAwait(false); var result = results.FirstOrDefault(x => x.Success); if (result != null) return result; cancellationToken.ThrowIfCancellationRequested(); return AsyncCollection<T>.FalseResult; } } /// <summary> /// Attempts to take an item from any of a number of producer/consumer collections. The operation "fails" if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public static AsyncCollection<T>.TakeResult TryTakeFromAny<T>(this IEnumerable<AsyncCollection<T>> collections, CancellationToken cancellationToken) { return TryTakeFromAnyAsync(collections, cancellationToken).WaitAndUnwrapException(); } /// <summary> /// Attempts to take an item from any of a number of producer/consumer collections. The operation "fails" if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. /// </summary> /// <param name="collections">The producer/consumer collections.</param> public static Task<AsyncCollection<T>.TakeResult> TryTakeFromAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections) { return TryTakeFromAnyAsync(collections, CancellationToken.None); } /// <summary> /// Attempts to take an item from any of a number of producer/consumer collections. The operation "fails" if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. This method may block the calling thread. /// </summary> /// <param name="collections">The producer/consumer collections.</param> public static AsyncCollection<T>.TakeResult TryTakeFromAny<T>(this IEnumerable<AsyncCollection<T>> collections) { return TryTakeFromAny(collections, CancellationToken.None); } /// <summary> /// Takes an item from any of a number of producer/consumer collections. Throws <see cref="InvalidOperationException"/> if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. /// </summary> /// <param name="collections">The array of producer/consumer collections.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public static async Task<AsyncCollection<T>.TakeResult> TakeFromAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections, CancellationToken cancellationToken) { var ret = await TryTakeFromAnyAsync(collections, cancellationToken).ConfigureAwait(false); if (!ret.Success) throw new InvalidOperationException("Take failed; all producer/consumer collections have completed adding and are empty."); return ret; } /// <summary> /// Takes an item from any of a number of producer/consumer collections. Throws <see cref="InvalidOperationException"/> if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. This method may block the calling thread. /// </summary> /// <param name="collections">The array of producer/consumer collections.</param> /// <param name="cancellationToken">A cancellation token that can be used to abort the take operation.</param> public static AsyncCollection<T>.TakeResult TakeFromAny<T>(this IEnumerable<AsyncCollection<T>> collections, CancellationToken cancellationToken) { var ret = TryTakeFromAny(collections, cancellationToken); if (!ret.Success) throw new InvalidOperationException("Take failed; all producer/consumer collections have completed adding and are empty."); return ret; } /// <summary> /// Takes an item from any of a number of producer/consumer collections. Throws <see cref="InvalidOperationException"/> if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. /// </summary> /// <param name="collections">The array of producer/consumer collections.</param> public static Task<AsyncCollection<T>.TakeResult> TakeFromAnyAsync<T>(this IEnumerable<AsyncCollection<T>> collections) { return TakeFromAnyAsync(collections, CancellationToken.None); } /// <summary> /// Takes an item from any of a number of producer/consumer collections. Throws <see cref="InvalidOperationException"/> if all the producer/consumer collections have completed adding and are empty, or if any take operation on an underlying collection fails. This method may block the calling thread. /// </summary> /// <param name="collections">The array of producer/consumer collections.</param> public static AsyncCollection<T>.TakeResult TakeFromAny<T>(this IEnumerable<AsyncCollection<T>> collections) { return TakeFromAny(collections, CancellationToken.None); } } }
45.977089
345
0.730998
[ "MIT" ]
russellmorley/machine
src/SIL.Machine/Threading/AsyncCollection.cs
34,117
C#
using System; using System.Collections; using System.Collections.Generic; using DataContext.Data; using DataContext.Data.Repository; using Microsoft.AspNetCore.Mvc; namespace ngWithJwt.Controllers { [Route("api/[controller]")] public class ProductController : Controller { private readonly Lazy<IRepository<Product>> _productRepository; public ProductController(Lazy<IRepository<Product>> productRepository) { _productRepository = productRepository; } [HttpGet] public IEnumerable<Product> GetProducts() { return _productRepository.Value.GetQuery(); } [HttpPost] public IActionResult AddProduct([FromBody] Product product) { product.ShopId = 1; _productRepository.Value.Add(product); if (product.Id > 0) _productRepository.Value.Update(product); _productRepository.Value.SaveChanges(); return Ok(product.Id); } [HttpDelete] public IActionResult DeleteProduct(int id) { var p = _productRepository.Value.FirstOrDefault(t => t.Id == id); _productRepository.Value.Delete(p); _productRepository.Value.SaveChanges(); return Ok(p.Id); } } }
28.340426
78
0.622372
[ "MIT" ]
oreshek123/shop2
ngWithJwt/Controllers/ProductController.cs
1,334
C#
using System; namespace UnityEngine.XR.ARSubsystems { /// <summary> /// Encapsulates the parameters for creating a new <see cref="XRCameraSubsystemDescriptor"/>. /// </summary> public struct XRCameraSubsystemCinfo : IEquatable<XRCameraSubsystemCinfo> { /// <summary> /// Specifies an identifier for the provider implementation of the subsystem. /// </summary> /// <value> /// The identifier for the provider implementation of the subsystem. /// </value> public string id { get; set; } /// <summary> /// Specifies the provider implementation type to use for instantiation. /// </summary> /// <value> /// The provider implementation type to use for instantiation. /// </value> public Type implementationType { get; set; } /// <summary> /// Specifies if current subsystem is allowed to provide average brightness. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide average brightness. Otherwise, <c>false</c>. /// </value> public bool supportsAverageBrightness { get; set; } /// <summary> /// Specifies if current subsystem is allowed to provide average camera temperature. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide average camera temperature. Otherwise, <c>false</c>. /// </value> public bool supportsAverageColorTemperature { get; set; } /// <summary> /// True if color correction is supported. /// </summary> public bool supportsColorCorrection { get; set; } /// <summary> /// Specifies if current subsystem is allowed to provide display matrix. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide display matrix. Otherwise, <c>false</c>. /// </value> public bool supportsDisplayMatrix { get; set; } /// <summary> /// Specifies if current subsystem is allowed to provide projection matrix. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide projection matrix. Otherwise, <c>false</c>. /// </value> public bool supportsProjectionMatrix { get; set; } /// <summary> /// Specifies if current subsystem is allowed to provide timestamp. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide timestamp. Otherwise, <c>false</c>. /// </value> public bool supportsTimestamp { get; set; } public bool Equals(XRCameraSubsystemCinfo other) { return (id.Equals(other.id) && implementationType.Equals(other.implementationType) && supportsAverageBrightness.Equals(other.supportsAverageBrightness) && supportsAverageColorTemperature.Equals(other.supportsAverageColorTemperature) && supportsDisplayMatrix.Equals(other.supportsDisplayMatrix) && supportsProjectionMatrix.Equals(other.supportsProjectionMatrix) && supportsTimestamp.Equals(other.supportsTimestamp)); } public override bool Equals(System.Object obj) { return ((obj is XRCameraSubsystemCinfo) && Equals((XRCameraSubsystemCinfo)obj)); } public static bool operator ==(XRCameraSubsystemCinfo lhs, XRCameraSubsystemCinfo rhs) { return lhs.Equals(rhs); } public static bool operator !=(XRCameraSubsystemCinfo lhs, XRCameraSubsystemCinfo rhs) { return !lhs.Equals(rhs); } public override int GetHashCode() { int hashCode = 486187739; unchecked { hashCode = (hashCode * 486187739) + id.GetHashCode(); hashCode = (hashCode * 486187739) + implementationType.GetHashCode(); hashCode = (hashCode * 486187739) + supportsAverageBrightness.GetHashCode(); hashCode = (hashCode * 486187739) + supportsAverageColorTemperature.GetHashCode(); hashCode = (hashCode * 486187739) + supportsDisplayMatrix.GetHashCode(); hashCode = (hashCode * 486187739) + supportsProjectionMatrix.GetHashCode(); hashCode = (hashCode * 486187739) + supportsTimestamp.GetHashCode(); } return hashCode; } } /// <summary> /// Specifies a functionality description that may be registered for each implementation that provides the /// <see cref="XRCameraSubsystem"/> interface. /// </summary> public sealed class XRCameraSubsystemDescriptor : SubsystemDescriptor<XRCameraSubsystem> { /// <summary> /// Constructs a <c>XRCameraSubsystemDescriptor</c> based on the given parameters. /// </summary> /// <param name="cameraSubsystemParams">The parameters required to initialize the descriptor.</param> XRCameraSubsystemDescriptor(XRCameraSubsystemCinfo cameraSubsystemParams) { id = cameraSubsystemParams.id; subsystemImplementationType = cameraSubsystemParams.implementationType; supportsAverageBrightness = cameraSubsystemParams.supportsAverageBrightness; supportsAverageColorTemperature = cameraSubsystemParams.supportsAverageColorTemperature; supportsDisplayMatrix = cameraSubsystemParams.supportsDisplayMatrix; supportsProjectionMatrix = cameraSubsystemParams.supportsProjectionMatrix; supportsTimestamp = cameraSubsystemParams.supportsTimestamp; } /// <summary> /// Specifies if current subsystem is allowed to provide average brightness. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide average brightness. Otherwise, <c>false</c>. /// </value> public bool supportsAverageBrightness { get; private set; } /// <summary> /// Specifies if current subsystem is allowed to provide average camera temperature. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide average camera temperature. Otherwise, <c>false</c>. /// </value> public bool supportsAverageColorTemperature { get; private set; } /// <summary> /// Specifies if current subsystem is allowed to provide display matrix. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide display matrix. Otherwise, <c>false</c>. /// </value> public bool supportsDisplayMatrix { get; private set; } /// <summary> /// Specifies if current subsystem is allowed to provide projection matrix. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide projection matrix. Otherwise, <c>false</c>. /// </value> public bool supportsProjectionMatrix { get; private set; } /// <summary> /// Specifies if current subsystem is allowed to provide timestamp. /// </summary> /// <value> /// <c>true</c> if current subsystem is allowed to provide timestamp. Otherwise, <c>false</c>. /// </value> public bool supportsTimestamp { get; private set; } /// <summary> /// Creates a <c>XRCameraSubsystemDescriptor</c> based on the given parameters validating that the /// <see cref="XRCameraSubsystemCinfo.id"/> and <see cref="XRCameraSubsystemCinfo.implementationType"/> /// properties are properly specified. /// </summary> /// <param name="cameraSubsystemParams">The parameters defining how to initialize the descriptor.</param> /// <returns> /// The created <c>XRCameraSubsystemDescriptor</c>. /// </returns> /// <exception cref="System.ArgumentException">Thrown when the values specified in the /// <see cref="XRCameraSubsystemCinfo"/> parameter are invalid. Typically, this will occur /// <list type="bullet"> /// <item> /// <description>if <see cref="XRCameraSubsystemCinfo.id"/> is <c>null</c> or empty</description> /// </item> /// <item> /// <description>if <see cref="XRCameraSubsystemCinfo.implementationType"/> is <c>null</c></description> /// </item> /// <item> /// <description>if <see cref="XRCameraSubsystemCinfo.implementationType"/> does not derive from the /// <see cref="XRCameraSubsystem"/> class /// </description> /// </item> /// </list> /// </exception> internal static XRCameraSubsystemDescriptor Create(XRCameraSubsystemCinfo cameraSubsystemParams) { if (String.IsNullOrEmpty(cameraSubsystemParams.id)) { throw new ArgumentException("Cannot create camera subsystem descriptor because id is invalid", "cameraSubsystemParams"); } if ((cameraSubsystemParams.implementationType == null) || !cameraSubsystemParams.implementationType.IsSubclassOf(typeof(XRCameraSubsystem))) { throw new ArgumentException("Cannot create camera subsystem descriptor because implementationType is invalid", "cameraSubsystemParams"); } return new XRCameraSubsystemDescriptor(cameraSubsystemParams); } } }
44.669725
126
0.614705
[ "MIT" ]
Jimmy5467/Entity-Lens
Library/PackageCache/com.unity.xr.arsubsystems@2.0.2/Runtime/CameraSubsystem/XRCameraSubsystemDescriptor.cs
9,738
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class PreciseAbstractFlowPass<LocalState> : BoundTreeVisitor where LocalState : AbstractFlowPass<LocalState>.AbstractLocalState { protected int _recursionDepth; /// <summary> /// The compilation in which the analysis is taking place. This is needed to determine which /// conditional methods will be compiled and which will be omitted. /// </summary> protected readonly CSharpCompilation compilation; /// <summary> /// The method whose body is being analyzed, or the field whose initializer is being analyzed. /// It is used for /// references to method parameters. Thus, 'member' should not be used directly, but /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used /// instead. /// </summary> private readonly Symbol _member; /// <summary> /// The bound node of the method or initializer being analyzed. /// </summary> protected readonly BoundNode methodMainNode; /// <summary> /// The flow analysis state at each label, computed by merging the state from branches to /// that label with the state when we fall into the label. Entries are created when the /// label is encountered. One case deserves special attention: when the destination of the /// branch is a label earlier in the code, it is possible (though rarely occurs in practice) /// that we are changing the state at a label that we've already analyzed. In that case we /// run another pass of the analysis to allow those changes to propagate. This repeats until /// no further changes to the state of these labels occurs. This can result in quadratic /// performance in unlikely but possible code such as this: "int x; if (cond) goto l1; x = /// 3; l5: print x; l4: goto l5; l3: goto l4; l2: goto l3; l1: goto l2;" /// </summary> private readonly PooledDictionary<LabelSymbol, LocalState> _labels; /// <summary> /// Set to true after an analysis scan if the analysis was incomplete due to a backward /// "goto" branch changing some analysis result. In this case the caller scans again (until /// this is false). Since the analysis proceeds by monotonically changing the state computed /// at each label, this must terminate. /// </summary> internal bool backwardBranchChanged; /// <summary> /// See property PendingBranches /// </summary> private ArrayBuilder<PendingBranch> _pendingBranches; /// <summary> /// All of the labels seen so far in this forward scan of the body /// </summary> private PooledHashSet<BoundStatement> _labelsSeen; /// <summary> /// If we are tracking exceptions, then by convention the first entry in the pending branches /// buffer contains a summary of the states that can arise from exceptions. /// </summary> private readonly bool _trackExceptions; /// <summary> /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump /// statements (goto, break, continue, return) are processed, they are placed in the /// pendingBranches buffer to be processed later by the code handling the destination /// statement. As a special case, the processing of try-finally statements might modify the /// contents of the pendingBranches buffer to take into account the behavior of /// "intervening" finally clauses. /// </summary> protected ArrayBuilder<PendingBranch> PendingBranches { get { return _pendingBranches; } } /// <summary> /// The definite assignment and/or reachability state at the point currently being analyzed. /// </summary> protected LocalState State; protected LocalState StateWhenTrue; protected LocalState StateWhenFalse; protected bool IsConditionalState; protected void SetConditionalState(LocalState whenTrue, LocalState whenFalse) { IsConditionalState = true; State = default(LocalState); StateWhenTrue = whenTrue; StateWhenFalse = whenFalse; } protected void SetState(LocalState newState) { StateWhenTrue = StateWhenFalse = default(LocalState); IsConditionalState = false; State = newState; } protected void Split() { Debug.Assert(!_trackExceptions || _pendingBranches[0].Branch == null); if (!IsConditionalState) { SetConditionalState(State, State.Clone()); } } protected void Unsplit() { Debug.Assert(!_trackExceptions || _pendingBranches[0].Branch == null); if (IsConditionalState) { IntersectWith(ref StateWhenTrue, ref StateWhenFalse); SetState(StateWhenTrue); } } /// <summary> /// Where all diagnostics are deposited. /// </summary> protected DiagnosticBag Diagnostics { get; } #region Region // For region analysis, we maintain some extra data. protected enum RegionPlace { Before, Inside, After }; protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region protected readonly BoundNode firstInRegion, lastInRegion; private readonly bool _trackRegions; /// <summary> /// A cache of the state at the backward branch point of each loop. This is not needed /// during normal flow analysis, but is needed for DataFlowsOut region analysis. /// </summary> private readonly Dictionary<BoundLoopStatement, LocalState> _loopHeadState; #endregion Region protected PreciseAbstractFlowPass( CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool trackExceptions = false) { Debug.Assert(node != null); if (firstInRegion != null && lastInRegion != null) { trackRegions = true; } if (trackRegions) { Debug.Assert(firstInRegion != null); Debug.Assert(lastInRegion != null); int startLocation = firstInRegion.Syntax.SpanStart; int endLocation = lastInRegion.Syntax.Span.End; int length = endLocation - startLocation; Debug.Assert(length > 0, "last comes before first"); this.RegionSpan = new TextSpan(startLocation, length); } _pendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); _labels = PooledDictionary<LabelSymbol, LocalState>.GetInstance(); this.Diagnostics = DiagnosticBag.GetInstance(); this.compilation = compilation; _member = member; this.methodMainNode = node; this.firstInRegion = firstInRegion; this.lastInRegion = lastInRegion; _loopHeadState = new Dictionary<BoundLoopStatement, LocalState>(ReferenceEqualityComparer.Instance); _trackRegions = trackRegions; _trackExceptions = trackExceptions; } protected abstract string Dump(LocalState state); protected string Dump() { return Dump(this.State); } #if DEBUG protected string DumpLabels() { StringBuilder result = new StringBuilder(); result.Append("Labels{"); bool first = true; foreach (var key in _labels.Keys) { if (!first) result.Append(", "); string name = key.Name; if (string.IsNullOrEmpty(name)) name = "<Label>" + key.GetHashCode(); result.Append(name).Append(": ").Append(this.Dump(_labels[key])); first = false; } result.Append("}"); return result.ToString(); } #endif /// <summary> /// Subclasses may override EnterRegion to perform any actions at the entry to the region. /// </summary> protected virtual void EnterRegion() { Debug.Assert(this.regionPlace == RegionPlace.Before); this.regionPlace = RegionPlace.Inside; } /// <summary> /// Subclasses may override LeaveRegion to perform any action at the end of the region. /// </summary> protected virtual void LeaveRegion() { Debug.Assert(IsInside); this.regionPlace = RegionPlace.After; } protected readonly TextSpan RegionSpan; protected bool RegionContains(TextSpan span) { // TODO: There are no scenarios involving a zero-length span // currently. If the assert fails, add a corresponding test. Debug.Assert(span.Length > 0); if (span.Length == 0) { return RegionSpan.Contains(span.Start); } return RegionSpan.Contains(span); } protected bool IsInside { get { return regionPlace == RegionPlace.Inside; } } public override BoundNode Visit(BoundNode node) { return VisitAlways(node); } protected BoundNode VisitAlways(BoundNode node) { BoundNode result = null; // We scan even expressions, because we must process lambdas contained within them. if (node != null) { if (_trackRegions) { if (node == this.firstInRegion && this.regionPlace == RegionPlace.Before) EnterRegion(); result = VisitWithStackGuard(node); if (node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) LeaveRegion(); } else { result = VisitWithStackGuard(node); } } return result; } private BoundNode VisitWithStackGuard(BoundNode node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; // just let the original exception to bubble up. } /// <summary> /// A pending branch. There are created for a return, break, continue, goto statement, /// yield return, yield break, await expression, and if PreciseAbstractFlowPass.trackExceptions /// is true for other /// constructs that can cause an exception to be raised such as a throw statement or method /// invocation. /// The idea is that we don't know if the branch will eventually reach its destination /// because of an intervening finally block that cannot complete normally. So we store them /// up and handle them as we complete processing each construct. At the end of a block, if /// there are any pending branches to a label in that block we process the branch. Otherwise /// we relay it up to the enclosing construct as a pending branch of the enclosing /// construct. /// </summary> internal class PendingBranch { public readonly BoundNode Branch; public LocalState State; public LabelSymbol Label { get { if (Branch == null) return null; switch (Branch.Kind) { case BoundKind.GotoStatement: return ((BoundGotoStatement)Branch).Label; case BoundKind.ConditionalGoto: return ((BoundConditionalGoto)Branch).Label; case BoundKind.BreakStatement: return ((BoundBreakStatement)Branch).Label; case BoundKind.ContinueStatement: return ((BoundContinueStatement)Branch).Label; default: return null; } } } public PendingBranch(BoundNode branch, LocalState state) { this.Branch = branch; this.State = state; } } abstract protected LocalState ReachableState(); abstract protected LocalState UnreachableState(); /// <summary> /// Perform a single pass of flow analysis. Note that after this pass, /// this.backwardBranchChanged indicates if a further pass is required. /// </summary> protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion) { var oldPending = SavePending(); Visit(methodMainNode); RestorePending(oldPending); if (_trackRegions && regionPlace != RegionPlace.After) badRegion = true; ImmutableArray<PendingBranch> result = RemoveReturns(); return result; } protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion) { ImmutableArray<PendingBranch> returns; do { // the entry point of a method is assumed reachable regionPlace = RegionPlace.Before; this.State = ReachableState(); _pendingBranches.Clear(); if (_trackExceptions) _pendingBranches.Add(new PendingBranch(null, ReachableState())); this.backwardBranchChanged = false; this.Diagnostics.Clear(); returns = this.Scan(ref badRegion); } while (this.backwardBranchChanged); return returns; } protected virtual void Free() { this.Diagnostics.Free(); _pendingBranches.Free(); _labelsSeen.Free(); _labels.Free(); } /// <summary> /// If a method is currently being analyzed returns its parameters, returns an empty array /// otherwise. /// </summary> protected ImmutableArray<ParameterSymbol> MethodParameters { get { var method = _member as MethodSymbol; return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters; } } /// <summary> /// If a method is currently being analyzed returns its 'this' parameter, returns null /// otherwise. /// </summary> protected ParameterSymbol MethodThisParameter { get { var method = _member as MethodSymbol; return (object)method == null ? null : method.ThisParameter; } } /// <summary> /// Specifies whether or not method's out parameters should be analyzed. If there's more /// than one location in the method being analyzed, then the method is partial and we prefer /// to report an out parameter in partial method error. /// </summary> /// <param name="location">location to be used</param> /// <returns>true if the out parameters of the method should be analyzed</returns> protected bool ShouldAnalyzeOutParameters(out Location location) { var method = _member as MethodSymbol; if ((object)method == null || method.Locations.Length != 1) { location = null; return false; } else { location = method.Locations[0]; return true; } } /// <summary> /// Return the flow analysis state associated with a label. /// </summary> /// <param name="label"></param> /// <returns></returns> protected virtual LocalState LabelState(LabelSymbol label) { LocalState result; if (_labels.TryGetValue(label, out result)) { return result; } result = UnreachableState(); _labels.Add(label, result); return result; } /// <summary> /// Return to the caller the set of pending return statements. /// </summary> /// <returns></returns> protected virtual ImmutableArray<PendingBranch> RemoveReturns() { ImmutableArray<PendingBranch> result; if (_trackExceptions) { // when we are tracking exceptions, we use pendingBranches[0] to // track exception states. result = _pendingBranches .Where(b => b.Branch != null) .AsImmutableOrNull(); var oldExceptions = _pendingBranches[0]; Debug.Assert(oldExceptions.Branch == null); _pendingBranches.Clear(); _pendingBranches.Add(oldExceptions); } else { result = _pendingBranches.ToImmutable(); _pendingBranches.Clear(); } // The caller should have handled and cleared labelsSeen. Debug.Assert(_labelsSeen.Count == 0); return result; } /// <summary> /// Set the current state to one that indicates that it is unreachable. /// </summary> protected void SetUnreachable() { this.State = UnreachableState(); } protected void VisitLvalue(BoundExpression node) { if (_trackRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before) EnterRegion(); switch (node.Kind) { case BoundKind.Parameter: VisitLvalueParameter((BoundParameter)node); break; case BoundKind.Local: case BoundKind.ThisReference: case BoundKind.BaseReference: // no need for it to be previously assigned: it is on the left. break; case BoundKind.PropertyAccess: var access = (BoundPropertyAccess)node; if (Binder.AccessingAutopropertyFromConstructor(access, _member)) { var backingField = (access.PropertySymbol as SourcePropertySymbol)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(access.ReceiverOpt, backingField); break; } } goto default; case BoundKind.FieldAccess: { BoundFieldAccess node1 = (BoundFieldAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol); break; } case BoundKind.EventAccess: { BoundEventAccess node1 = (BoundEventAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField); break; } default: VisitRvalue(node); break; } if (_trackRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) LeaveRegion(); } /// <summary> /// Visit a boolean condition expression. /// </summary> /// <param name="node"></param> protected void VisitCondition(BoundExpression node) { Visit(node); AdjustConditionalState(node); } private void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { Unsplit(); SetConditionalState(this.State, UnreachableState()); } else if (IsConstantFalse(node)) { Unsplit(); SetConditionalState(UnreachableState(), this.State); } else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean) { // a dynamic type or a type with operator true/false Unsplit(); } Split(); } /// <summary> /// Visit a general expression, where we will only need to determine if variables are /// assigned (or not). That is, we will not be needing AssignedWhenTrue and /// AssignedWhenFalse. /// </summary> /// <param name="node"></param> protected BoundNode VisitRvalue(BoundExpression node) { Debug.Assert(!_trackExceptions || this.PendingBranches.Count > 0 && this.PendingBranches[0].Branch == null); var result = Visit(node); Unsplit(); return result; } /// <summary> /// Visit a statement. /// </summary> [DebuggerHidden] protected virtual void VisitStatement(BoundStatement statement) { Debug.Assert(!_trackExceptions || this.PendingBranches.Count > 0 && this.PendingBranches[0].Branch == null); Visit(statement); } private static bool IsConstantTrue(BoundExpression node) { return node.ConstantValue == ConstantValue.True; } private static bool IsConstantFalse(BoundExpression node) { return node.ConstantValue == ConstantValue.False; } private static bool IsConstantNull(BoundExpression node) { return node.ConstantValue == ConstantValue.Null; } /// <summary> /// Called at the point in a loop where the backwards branch would go to. /// </summary> private void LoopHead(BoundLoopStatement node) { LocalState previousState; if (_loopHeadState.TryGetValue(node, out previousState)) { IntersectWith(ref this.State, ref previousState); } _loopHeadState[node] = this.State.Clone(); } /// <summary> /// Called at the point in a loop where the backward branch is placed. /// </summary> private void LoopTail(BoundLoopStatement node) { var oldState = _loopHeadState[node]; if (IntersectWith(ref oldState, ref this.State)) { _loopHeadState[node] = oldState; this.backwardBranchChanged = true; } } /// <summary> /// Used to resolve break statements in each statement form that has a break statement /// (loops, switch). /// </summary> private void ResolveBreaks(LocalState breakState, LabelSymbol label) { var pendingBranches = _pendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { IntersectWith(ref breakState, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } SetState(breakState); } /// <summary> /// Used to resolve continue statements in each statement form that supports it. /// </summary> private void ResolveContinues(LabelSymbol continueLabel) { var pendingBranches = _pendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == continueLabel) { // Technically, nothing in the language specification depends on the state // at the continue label, so we could just discard them instead of merging // the states. In fact, we need not have added continue statements to the // pending jump queue in the first place if we were interested solely in the // flow analysis. However, region analysis (in support of extract method) // and other forms of more precise analysis // depend on continue statements appearing in the pending branch queue, so // we process them from the queue here. IntersectWith(ref this.State, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } } /// <summary> /// Subclasses override this if they want to take special actions on processing a goto /// statement, when both the jump and the label have been located. /// </summary> protected virtual void NoteBranch(PendingBranch pending, BoundStatement gotoStmt, BoundStatement target) { target.AssertIsLabeledStatement(); } protected virtual void NotePossibleException(BoundNode node) { Debug.Assert(_trackExceptions); IntersectWith(ref _pendingBranches[0].State, ref this.State); } /// <summary> /// To handle a label, we resolve all branches to that label. Returns true if the state of /// the label changes as a result. /// </summary> /// <param name="label">Target label</param> /// <param name="target">Statement containing the target label</param> private bool ResolveBranches(LabelSymbol label, BoundStatement target) { if (target != null) { target.AssertIsLabeledStatementWithLabel(label); } bool labelStateChanged = false; var pendingBranches = _pendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { ResolveBranch(pending, label, target, ref labelStateChanged); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } return labelStateChanged; } protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) { var state = LabelState(label); if (target != null) NoteBranch(pending, (BoundStatement)pending.Branch, target); var changed = IntersectWith(ref state, ref pending.State); if (changed) { labelStateChanged = true; _labels[label] = state; } } private bool ResolveBranches(BoundLabeledStatement target) { return ResolveBranches(target.Label, target); } protected struct SavedPending { public readonly ArrayBuilder<PendingBranch> PendingBranches; public readonly PooledHashSet<BoundStatement> LabelsSeen; public SavedPending(ref ArrayBuilder<PendingBranch> pendingBranches, ref PooledHashSet<BoundStatement> labelsSeen) { this.PendingBranches = pendingBranches; this.LabelsSeen = labelsSeen; pendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); } } /// <summary> /// Since branches cannot branch into constructs, only out, we save the pending branches /// when visiting more nested constructs. When tracking exceptions, we store the current /// state as the exception state for the following code. /// </summary> protected SavedPending SavePending() { var result = new SavedPending(ref _pendingBranches, ref _labelsSeen); if (_trackExceptions) { _pendingBranches.Add(new PendingBranch(null, this.State.Clone())); } return result; } /// <summary> /// We use this to restore the old set of pending branches after visiting a construct that contains nested statements. /// </summary> /// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param> protected void RestorePending(SavedPending oldPending) { foreach (var node in _labelsSeen) { switch (node.Kind) { case BoundKind.LabeledStatement: { var label = (BoundLabeledStatement)node; backwardBranchChanged |= ResolveBranches(label.Label, label); } break; case BoundKind.LabelStatement: { var label = (BoundLabelStatement)node; backwardBranchChanged |= ResolveBranches(label.Label, label); } break; case BoundKind.SwitchSection: { var sec = (BoundSwitchSection)node; foreach (var label in sec.BoundSwitchLabels) { backwardBranchChanged |= ResolveBranches(label.Label, sec); } } break; default: // there are no other kinds of labels throw ExceptionUtilities.UnexpectedValue(node.Kind); } } int i = 0; int n = _pendingBranches.Count; if (_trackExceptions) { Debug.Assert(oldPending.PendingBranches[0].Branch == null); Debug.Assert(this.PendingBranches[0].Branch == null); this.IntersectWith(ref oldPending.PendingBranches[0].State, ref this.PendingBranches[0].State); i++; } for (; i < n; i++) { oldPending.PendingBranches.Add(this.PendingBranches[i]); } _pendingBranches.Free(); _pendingBranches = oldPending.PendingBranches; // We only use SavePending/RestorePending when there could be no branch into the region between them. // So there is no need to save the labels seen between the calls. If there were such a need, we would // do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment _labelsSeen.Free(); _labelsSeen = oldPending.LabelsSeen; } #region visitors /// <summary> /// Since each language construct must be handled according to the rules of the language specification, /// the default visitor reports that the construct for the node is not implemented in the compiler. /// </summary> public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?"); return null; } public override BoundNode VisitAttribute(BoundAttribute node) { // No flow analysis is ever done in attributes (or their arguments). return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); VisitRvalue(node.InitializerExpressionOpt); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { VisitRvalue(node.ReceiverOpt); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { VisitRvalue(node.Receiver); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { VisitRvalue(node.Expression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { foreach (var expr in node.Parts) { VisitRvalue(expr); } return null; } public override BoundNode VisitStringInsert(BoundStringInsert node) { VisitRvalue(node.Value); if (node.Alignment != null) VisitRvalue(node.Alignment); if (node.Format != null) VisitRvalue(node.Format); return null; } public override BoundNode VisitArgList(BoundArgList node) { // The "__arglist" expression that is legal inside a varargs method has no // effect on flow analysis and it has no children. return null; } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { // When we have M(__arglist(x, y, z)) we must visit x, y and z. VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { // Note that we require that the variable whose reference we are taking // has been initialized; it is similar to passing the variable as a ref parameter. VisitRvalue(node.Operand); return null; } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) { VisitStatement(node.Statement); return null; } public override BoundNode VisitLambda(BoundLambda node) { if (_trackExceptions) NotePossibleException(node); // Control-flow analysis does NOT dive into a lambda, while data-flow analysis does. return null; } public override BoundNode VisitLocal(BoundLocal node) { return null; } public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) { if (node.InitializerOpt != null) { VisitRvalue(node.InitializerOpt); // analyze the expression } return null; } public override BoundNode VisitBlock(BoundBlock node) { foreach (var statement in node.Statements) VisitStatement(statement); return null; } public override BoundNode VisitFieldInitializer(BoundFieldInitializer node) { Visit(node.InitialValue); return null; } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitCall(BoundCall node) { // If the method being called is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree); LocalState savedState = default(LocalState); if (callsAreOmitted) { savedState = this.State.Clone(); SetUnreachable(); } VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Method); UpdateStateForCall(node); VisitReceiverAfterCall(node.ReceiverOpt, node.Method); if (callsAreOmitted) { this.State = savedState; } return null; } protected virtual void UpdateStateForCall(BoundCall node) { if (_trackExceptions) NotePossibleException(node); } private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) { if ((object)method == null || method.MethodKind != MethodKind.Constructor) { VisitRvalue(receiverOpt); } } private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) { NamedTypeSymbol containingType; if (receiverOpt != null && ((object)method == null || method.MethodKind == MethodKind.Constructor || (object)(containingType = method.ContainingType) != null && !method.IsStatic && !containingType.IsReferenceType && !TypeIsImmutable(containingType))) { WriteArgument(receiverOpt, (object)method != null && method.MethodKind == MethodKind.Constructor ? RefKind.Out : RefKind.Ref, method); } } /// <summary> /// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on /// the type is known (by flow analysis) not to write the receiver. /// </summary> /// <param name="t"></param> /// <returns></returns> private static bool TypeIsImmutable(TypeSymbol t) { switch (t.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; default: var ont = t.OriginalDefinition as TypeSymbol; return (object)ont != null && ont.SpecialType == SpecialType.System_Nullable_T; } } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { VisitRvalue(node.ReceiverOpt); var method = node.Indexer.GetOwnOrInheritedGetMethod() ?? node.Indexer.SetMethod; VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); if (_trackExceptions && (object)method != null) NotePossibleException(node); if ((object)method != null) VisitReceiverAfterCall(node.ReceiverOpt, method); return null; } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { VisitRvalue(node.ReceiverOpt); VisitRvalue(node.Argument); if (_trackExceptions) NotePossibleException(node); return null; } private void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { if (refKindsOpt.IsDefault) { for (int i = 0; i < arguments.Length; i++) { VisitRvalue(arguments[i]); } } else { // first value and ref parameters are read... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = refKindsOpt.Length <= i ? RefKind.None : refKindsOpt[i]; if (refKind != RefKind.Out) { VisitRvalue(arguments[i]); } else { VisitLvalue(arguments[i]); } } // and then ref and out parameters are written... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = refKindsOpt.Length <= i ? RefKind.None : refKindsOpt[i]; if (refKind != RefKind.None) { WriteArgument(arguments[i], refKind, method); } } } } protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) { } public override BoundNode VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { VisitRvalue(child as BoundExpression); } if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitBadStatement(BoundBadStatement node) { foreach (var child in node.ChildBoundNodes) { if (child is BoundStatement) VisitStatement(child as BoundStatement); else VisitRvalue(child as BoundExpression); } if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { foreach (var child in node.Initializers) { VisitRvalue(child); } return null; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { var methodGroup = node.Argument as BoundMethodGroup; if (methodGroup != null) { if ((object)node.MethodOpt != null && !node.MethodOpt.IsStatic) { if (_trackRegions) { if (methodGroup == this.firstInRegion && this.regionPlace == RegionPlace.Before) EnterRegion(); VisitRvalue(methodGroup.ReceiverOpt); if (methodGroup == this.lastInRegion && IsInside) LeaveRegion(); } else { VisitRvalue(methodGroup.ReceiverOpt); } } } else { VisitRvalue(node.Argument); } if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitTypeExpression(BoundTypeExpression node) { return null; } public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. return this.Visit(node.Data.ValueExpression); } public override BoundNode VisitLiteral(BoundLiteral node) { return null; } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.MethodGroup) { if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && !node.SymbolOpt.IsStatic)) { BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt; // A method group's "implicit this" is only used for instance methods. if (_trackRegions) { if (node.Operand == this.firstInRegion && this.regionPlace == RegionPlace.Before) EnterRegion(); Visit(receiver); if (node.Operand == this.lastInRegion && IsInside) LeaveRegion(); } else { Visit(receiver); } } } else { Visit(node.Operand); if (_trackExceptions && node.HasExpressionSymbols()) NotePossibleException(node); } return null; } public override BoundNode VisitIfStatement(BoundIfStatement node) { // 5.3.3.5 If statements VisitCondition(node.Condition); LocalState trueState = StateWhenTrue; LocalState falseState = StateWhenFalse; SetState(trueState); VisitStatement(node.Consequence); trueState = this.State; SetState(falseState); if (node.AlternativeOpt != null) { VisitStatement(node.AlternativeOpt); } IntersectWith(ref this.State, ref trueState); return null; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var oldPending = SavePending(); // we do not allow branches into a try statement var initialState = this.State.Clone(); VisitStatement(node.TryBlock); var endState = this.State; var tryPending = SavePending(); if (!node.CatchBlocks.IsEmpty) { var catchState = initialState.Clone(); foreach (var pend in tryPending.PendingBranches) { IntersectWith(ref catchState, ref pend.State); } foreach (var catchBlock in node.CatchBlocks) { SetState(catchState.Clone()); if (catchBlock.ExceptionSourceOpt != null) { VisitLvalue(catchBlock.ExceptionSourceOpt); } if (catchBlock.ExceptionFilterOpt != null) { VisitCondition(catchBlock.ExceptionFilterOpt); SetState(StateWhenTrue); } VisitStatement(catchBlock.Body); IntersectWith(ref endState, ref this.State); } } if (node.FinallyBlockOpt != null) { // branches from the finally block, while illegal, should still not be considered // to execute the finally block before occurring. Also, we do not handle branches // *into* the finally block. SetState(endState); var catchPending = SavePending(); VisitStatement(node.FinallyBlockOpt); endState = this.State; foreach (var pend in tryPending.PendingBranches) { if (pend.Branch != null && pend.Branch.Kind != BoundKind.YieldReturnStatement) { SetState(pend.State); VisitStatement(node.FinallyBlockOpt); pend.State = this.State; } } foreach (var pend in catchPending.PendingBranches) { if (pend.Branch != null && pend.Branch.Kind != BoundKind.YieldReturnStatement) { SetState(pend.State); VisitStatement(node.FinallyBlockOpt); pend.State = this.State; } } SetState(endState); RestorePending(catchPending); } else { SetState(endState); } RestorePending(tryPending); RestorePending(oldPending); return null; } protected virtual LocalState AllBitsSet() // required for DataFlowsOutWalker { return default(LocalState); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { var result = VisitRvalue(node.ExpressionOpt); _pendingBranches.Add(new PendingBranch(node, this.State)); SetUnreachable(); return result; } public override BoundNode VisitThisReference(BoundThisReference node) { return null; } public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { return null; } public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { return null; } public override BoundNode VisitParameter(BoundParameter node) { return null; } protected virtual void VisitLvalueParameter(BoundParameter node) { } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { if (_trackExceptions) NotePossibleException(node); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNewT(BoundNewT node) { VisitRvalue(node.InitializerExpressionOpt); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitRvalue(node.InitializerExpressionOpt); if (_trackExceptions) NotePossibleException(node); return null; } // represents anything that occurs at the invocation of the property setter protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) { if (_trackExceptions) NotePossibleException(node); VisitReceiverAfterCall(receiver, setter); } // returns false if expression is not a property access // or if the property has a backing field // and accessed in a corresponding constructor private bool RegularPropertyAccess(BoundExpression expr) { if (expr.Kind != BoundKind.PropertyAccess) { return false; } return !Binder.AccessingAutopropertyFromConstructor((BoundPropertyAccess)expr, _member); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; var method = property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; VisitReceiverBeforeCall(left.ReceiverOpt, method); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, method, node.Right); } else { VisitLvalue(node.Left); VisitRvalue(node.Right); } return null; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; var readMethod = property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; var writeMethod = property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); if (_trackExceptions) NotePossibleException(node); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, writeMethod); if (_trackExceptions) NotePossibleException(node); VisitReceiverAfterCall(left.ReceiverOpt, writeMethod); } else { VisitRvalue(node.Left); VisitRvalue(node.Right); if (_trackExceptions && node.HasExpressionSymbols()) NotePossibleException(node); } return null; } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); return null; } private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { if (MayRequireTracking(receiverOpt, fieldSymbol) || (object)fieldSymbol != null && fieldSymbol.IsFixed) { VisitLvalue(receiverOpt); } else { VisitRvalue(receiverOpt); } } public override BoundNode VisitFieldInfo(BoundFieldInfo node) { return null; } public override BoundNode VisitMethodInfo(BoundMethodInfo node) { return null; } protected static bool MayRequireTracking(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { return (object)fieldSymbol != null && //simplifies calling pattern for events receiverOpt != null && !fieldSymbol.IsStatic && !fieldSymbol.IsFixed && receiverOpt.Type.IsStructType() && !receiverOpt.Type.IsPrimitiveRecursiveStruct(); } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; if (Binder.AccessingAutopropertyFromConstructor(node, _member)) { var backingField = (property as SourcePropertySymbol)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(node.ReceiverOpt, backingField); return null; } } var method = property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; VisitReceiverBeforeCall(node.ReceiverOpt, method); if (_trackExceptions) NotePossibleException(node); VisitReceiverAfterCall(node.ReceiverOpt, method); return null; // TODO: In an expression such as // M().Prop = G(); // Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor // occur after both. The precise abstract flow pass does not yet currently have this quite right. // Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read) // which should assume that the receiver will have been handled by the caller. This can be invoked // twice for read/write operations such as // M().Prop += 1 // or at the appropriate place in the sequence for read or write operations. // Do events require any special handling too? } public override BoundNode VisitEventAccess(BoundEventAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { // query variables are always definitely assigned; no need to analyze return null; } public override BoundNode VisitQueryClause(BoundQueryClause node) { VisitRvalue(node.UnoptimizedForm ?? node.Value); return null; } public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { foreach (var v in node.LocalDeclarations) Visit(v); return null; } public override BoundNode VisitWhileStatement(BoundWhileStatement node) { // while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel: LoopHead(node); VisitCondition(node.Condition); LocalState bodyState = StateWhenTrue; LocalState breakState = StateWhenFalse; SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitSwitchStatement(BoundSwitchStatement node) { // visit switch header LocalState breakState = VisitSwitchHeader(node); SetUnreachable(); // visit switch block VisitSwitchBlock(node); IntersectWith(ref breakState, ref this.State); ResolveBreaks(breakState, node.BreakLabel); return null; } private LocalState VisitSwitchHeader(BoundSwitchStatement node) { // Initial value for the Break state for a switch statement is established as follows: // Break state = UnreachableState if either of the following is true: // (1) there is a default label, or // (2) the switch expression is constant and there is a matching case label. // Otherwise, the Break state = current state. // visit switch expression VisitRvalue(node.BoundExpression); LocalState breakState = this.State; // For a switch statement, we simulate a possible jump to the switch labels to ensure that // the label is not treated as an unused label and a pending branch to the label is noted. // However, if switch expression is a constant, we must have determined the single target label // at bind time, i.e. node.ConstantTargetOpt, and we must simulate a jump only to this label. var constantTargetOpt = node.ConstantTargetOpt; if ((object)constantTargetOpt == null) { bool hasDefaultLabel = false; foreach (var section in node.SwitchSections) { foreach (var boundSwitchLabel in section.BoundSwitchLabels) { var label = boundSwitchLabel.Label; hasDefaultLabel = hasDefaultLabel || label.IdentifierNodeOrToken.Kind() == SyntaxKind.DefaultSwitchLabel; SetState(breakState.Clone()); var simulatedGoto = new BoundGotoStatement(node.Syntax, label); VisitGotoStatement(simulatedGoto); } } if (hasDefaultLabel) { // Condition (1) for an unreachable break state is satisfied breakState = UnreachableState(); } } else if (!node.BreakLabel.Equals(constantTargetOpt)) { SetState(breakState.Clone()); var simulatedGoto = new BoundGotoStatement(node.Syntax, constantTargetOpt); VisitGotoStatement(simulatedGoto); // Condition (1) or (2) for an unreachable break state is satisfied breakState = UnreachableState(); } return breakState; } private void VisitSwitchBlock(BoundSwitchStatement node) { var afterSwitchState = UnreachableState(); var switchSections = node.SwitchSections; var iLastSection = (switchSections.Length - 1); // visit switch sections for (var iSection = 0; iSection <= iLastSection; iSection++) { VisitSwitchSection(switchSections[iSection], iSection == iLastSection); // Even though it is illegal for the end of a switch section to be reachable, in erroneous // code it may be reachable. We treat that as an implicit break (branch to afterSwitchState). IntersectWith(ref afterSwitchState, ref this.State); } SetState(afterSwitchState); } public virtual BoundNode VisitSwitchSection(BoundSwitchSection node, bool lastSection) { return VisitSwitchSection(node); } public override BoundNode VisitSwitchSection(BoundSwitchSection node) { // visit switch section labels foreach (var boundSwitchLabel in node.BoundSwitchLabels) { VisitRvalue(boundSwitchLabel.ExpressionOpt); VisitSwitchSectionLabel(boundSwitchLabel.Label, node); } // visit switch section body VisitStatementList(node); return null; } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { VisitRvalue(node.Expression); foreach (var i in node.Indices) { VisitRvalue(i); } if (_trackExceptions && node.HasExpressionSymbols()) NotePossibleException(node); return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { if (node.OperatorKind.IsLogical()) { Debug.Assert(!node.OperatorKind.IsUserDefined()); VisitBinaryLogicalOperatorChildren(node); } else { VisitBinaryOperatorChildren(node); } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { VisitBinaryLogicalOperatorChildren(node); return null; } private void VisitBinaryLogicalOperatorChildren(BoundExpression node) { // Do not blow the stack due to a deep recursion on the left. var stack = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression binary; BoundExpression child = node; while (true) { var childKind = child.Kind; if (childKind == BoundKind.BinaryOperator) { var binOp = (BoundBinaryOperator)child; if (!binOp.OperatorKind.IsLogical()) { break; } binary = child; child = binOp.Left; } else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator) { binary = child; child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left; } else { break; } stack.Push(binary); } Debug.Assert(stack.Count > 0); VisitCondition(child); while (true) { binary = stack.Pop(); BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)binary; kind = binOp.OperatorKind; right = binOp.Right; break; case BoundKind.UserDefinedConditionalLogicalOperator: var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; kind = udBinOp.OperatorKind; right = udBinOp.Right; break; default: throw ExceptionUtilities.Unreachable; } var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; Debug.Assert(isAnd || op == BinaryOperatorKind.Or); var leftTrue = this.StateWhenTrue; var leftFalse = this.StateWhenFalse; SetState(isAnd ? leftTrue : leftFalse); VisitCondition(right); if (!isBool) { this.Unsplit(); this.Split(); } var resultTrue = this.StateWhenTrue; var resultFalse = this.StateWhenFalse; if (isAnd) { IntersectWith(ref resultFalse, ref leftFalse); } else { IntersectWith(ref resultTrue, ref leftTrue); } SetConditionalState(resultTrue, resultFalse); if (!isBool) { this.Unsplit(); } if (_trackExceptions && binary.HasExpressionSymbols()) { NotePossibleException(binary); } if (stack.Count == 0) { break; } AdjustConditionalState(binary); } Debug.Assert((object)binary == node); stack.Free(); } private void VisitBinaryOperatorChildren(BoundBinaryOperator node) { // It is common in machine-generated code for there to be deep recursion on the left side of a binary // operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left // hand side. To mitigate the risk of stack overflow we use an explicit stack. // // Of course we must ensure that we visit the left hand side before the right hand side. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); stack.Push(node); BoundBinaryOperator binary; BoundExpression child = node.Left; while (true) { binary = child as BoundBinaryOperator; if (binary == null || binary.OperatorKind.IsLogical()) { break; } stack.Push(binary); child = binary.Left; } VisitRvalue(child); while (true) { binary = stack.Pop(); VisitRvalue(binary.Right); if (_trackExceptions && binary.HasExpressionSymbols()) { NotePossibleException(binary); } if (stack.Count == 0) { break; } Unsplit(); // VisitRvalue does this } Debug.Assert((object)binary == node); stack.Free(); } public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { // We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26) VisitCondition(node.Operand); // it inverts the sense of assignedWhenTrue and assignedWhenFalse. SetConditionalState(StateWhenFalse, StateWhenTrue); } else { VisitRvalue(node.Operand); if (_trackExceptions && node.HasExpressionSymbols()) NotePossibleException(node); } return null; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { VisitRvalue(node.Expression); _pendingBranches.Add(new PendingBranch(node, this.State.Clone())); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { // TODO: should we also specially handle events? if (RegularPropertyAccess(node.Operand)) { var left = (BoundPropertyAccess)node.Operand; var property = left.PropertySymbol; var readMethod = property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; var writeMethod = property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); if (_trackExceptions) NotePossibleException(node); // a read VisitReceiverAfterCall(left.ReceiverOpt, readMethod); PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write } else { VisitRvalue(node.Operand); if (_trackExceptions && node.HasExpressionSymbols()) NotePossibleException(node); } return null; } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { foreach (var e1 in node.Bounds) VisitRvalue(e1); if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault) { foreach (var element in node.InitializerOpt.Initializers) VisitRvalue(element); } if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitForStatement(BoundForStatement node) { if (node.Initializer != null) { VisitStatement(node.Initializer); } LoopHead(node); LocalState bodyState, breakState; if (node.Condition != null) { VisitCondition(node.Condition); bodyState = this.StateWhenTrue; breakState = this.StateWhenFalse; } else { bodyState = this.State; breakState = UnreachableState(); } SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); if (node.Increment != null) { VisitStatement(node.Increment); } LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitForEachStatement(BoundForEachStatement node) { // foreach ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel: VisitRvalue(node.Expression); var breakState = this.State.Clone(); LoopHead(node); VisitForEachIterationVariable(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public virtual void VisitForEachIterationVariable(BoundForEachStatement node) { } public override BoundNode VisitAsOperator(BoundAsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitIsOperator(BoundIsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { if (node.ReceiverOpt != null) { // An explicit or implicit receiver, for example in an expression such as (x.Foo is Action, or Foo is Action), is considered to be read. VisitRvalue(node.ReceiverOpt); } return null; } public override BoundNode VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { VisitRvalue(node.LeftOperand); if (IsConstantNull(node.LeftOperand)) { VisitRvalue(node.RightOperand); } else { var savedState = this.State.Clone(); if (node.LeftOperand.ConstantValue != null) { SetUnreachable(); } VisitRvalue(node.RightOperand); IntersectWith(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalAccess(BoundConditionalAccess node) { VisitRvalue(node.Receiver); if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver)) { VisitRvalue(node.AccessExpression); } else { var savedState = this.State.Clone(); if (IsConstantNull(node.Receiver)) { SetUnreachable(); } VisitRvalue(node.AccessExpression); IntersectWith(ref this.State, ref savedState); } return null; } public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { VisitRvalue(node.Receiver); var savedState = this.State.Clone(); VisitRvalue(node.WhenNotNull); IntersectWith(ref this.State, ref savedState); if (node.WhenNullOpt != null) { savedState = this.State.Clone(); VisitRvalue(node.WhenNullOpt); IntersectWith(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { return null; } public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) { var savedState = this.State.Clone(); VisitRvalue(node.ValueTypeReceiver); IntersectWith(ref this.State, ref savedState); savedState = this.State.Clone(); VisitRvalue(node.ReferenceTypeReceiver); IntersectWith(ref this.State, ref savedState); return null; } public override BoundNode VisitSequence(BoundSequence node) { var sideEffects = node.SideEffects; if (!sideEffects.IsEmpty) { foreach (var se in sideEffects) { VisitRvalue(se); } } VisitRvalue(node.Value); return null; } public override BoundNode VisitSequencePoint(BoundSequencePoint node) { VisitStatement(node.StatementOpt); return null; } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) { VisitStatement(node.StatementOpt); return null; } public override BoundNode VisitStatementList(BoundStatementList node) { return VisitStatementListWorker(node); } private BoundNode VisitStatementListWorker(BoundStatementList node) { foreach (var statement in node.Statements) { VisitStatement(statement); } return null; } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { return VisitStatementListWorker(node); } public override BoundNode VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. return VisitLambda(node.BindForErrorRecovery()); } public override BoundNode VisitBreakStatement(BoundBreakStatement node) { _pendingBranches.Add(new PendingBranch(node, this.State)); SetUnreachable(); return null; } public override BoundNode VisitContinueStatement(BoundContinueStatement node) { // While continue statements do no affect definite assignment, subclasses // such as region flow analysis depend on their presence as pending branches. _pendingBranches.Add(new PendingBranch(node, this.State)); SetUnreachable(); return null; } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { VisitCondition(node.Condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; if (IsConstantTrue(node.Condition)) { SetState(alternativeState); Visit(node.Alternative); SetState(consequenceState); Visit(node.Consequence); // it may be a boolean state at this point. } else if (IsConstantFalse(node.Condition)) { SetState(consequenceState); Visit(node.Consequence); SetState(alternativeState); Visit(node.Alternative); // it may be a boolean state at this point. } else { SetState(consequenceState); Visit(node.Consequence); Unsplit(); consequenceState = this.State; SetState(alternativeState); Visit(node.Alternative); Unsplit(); IntersectWith(ref this.State, ref consequenceState); // it may not be a boolean state at this point (5.3.3.28) } return null; } public override BoundNode VisitBaseReference(BoundBaseReference node) { // TODO: in a struct constructor, "this" is not initially assigned. return null; } public override BoundNode VisitDoStatement(BoundDoStatement node) { // do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel: LoopHead(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); VisitCondition(node.Condition); LocalState breakState = this.StateWhenFalse; SetState(this.StateWhenTrue); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { _pendingBranches.Add(new PendingBranch(node, this.State)); SetUnreachable(); return null; } private void VisitLabel(LabelSymbol label, BoundStatement node) { node.AssertIsLabeledStatementWithLabel(label); ResolveBranches(label, node); var state = LabelState(label); IntersectWith(ref this.State, ref state); _labels[label] = this.State.Clone(); _labelsSeen.Add(node); } protected virtual void VisitLabel(BoundLabeledStatement node) { VisitLabel(node.Label, node); } protected virtual void VisitSwitchSectionLabel(LabelSymbol label, BoundSwitchSection node) { VisitLabel(label, node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { VisitLabel(node.Label, node); return null; } public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) { VisitLabel(node); VisitStatement(node.Body); return null; } public override BoundNode VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); if (_trackExceptions) NotePossibleException(node); VisitStatement(node.Body); return null; } public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) { return null; } public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) { return null; } public override BoundNode VisitUsingStatement(BoundUsingStatement node) { if (node.ExpressionOpt != null) { VisitRvalue(node.ExpressionOpt); } if (node.DeclarationsOpt != null) { VisitStatement(node.DeclarationsOpt); } if (_trackExceptions) NotePossibleException(node); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedStatement(BoundFixedStatement node) { VisitStatement(node.Declarations); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundExpression expr = node.ExpressionOpt; if (expr != null) { VisitRvalue(expr); } if (_trackExceptions) NotePossibleException(node); SetUnreachable(); return null; } public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { _pendingBranches.Add(new PendingBranch(node, this.State)); SetUnreachable(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { VisitRvalue(node.Expression); _pendingBranches.Add(new PendingBranch(node, this.State.Clone())); return null; } public override BoundNode VisitDefaultOperator(BoundDefaultOperator node) { return null; } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { VisitTypeExpression(node.SourceType); return null; } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { var savedState = this.State; SetState(UnreachableState()); Visit(node.Argument); SetState(savedState); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { VisitAddressOfOperator(node, shouldReadOperand: false); return null; } /// <summary> /// If the operand is definitely assigned, we may want to perform a read (in addition to /// a write) so that the operand can show up as ReadInside/DataFlowsIn. /// </summary> protected void VisitAddressOfOperator(BoundAddressOfOperator node, bool shouldReadOperand) { BoundExpression operand = node.Operand; if (shouldReadOperand) { this.VisitRvalue(operand); } else { this.VisitLvalue(operand); } this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned. } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { VisitRvalue(node.Expression); VisitRvalue(node.Index); return null; } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { return null; } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { VisitRvalue(node.Count); return null; } public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // visit arguments as r-values VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor); // ignore declarations //node.Declarations if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitArrayLength(BoundArrayLength node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { VisitRvalue(node.Condition); _pendingBranches.Add(new PendingBranch(node, this.State.Clone())); return null; } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers) { foreach (var initializer in initializers) { VisitRvalue(initializer); if (_trackExceptions) NotePossibleException(initializer); } return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { var arguments = node.Arguments; if (!arguments.IsDefaultOrEmpty) { foreach (var argument in arguments) { VisitRvalue(argument); } } return null; } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { return null; } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) { // If the underlying add method is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. LocalState savedState = savedState = this.State.Clone(); SetUnreachable(); VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); this.State = savedState; } else { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); } if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null); if (_trackExceptions) NotePossibleException(node); return null; } public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) { return null; } #endregion visitors } }
36.522843
262
0.557845
[ "Apache-2.0" ]
aanshibudhiraja/Roslyn
src/Compilers/CSharp/Portable/FlowAnalysis/PreciseAbstractFlowPass.cs
93,537
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901 { using static Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Extensions; /// <summary>The list of credential result response.</summary> public partial class CredentialResults : Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResults, Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResultsInternal { /// <summary>Backing field for <see cref="Kubeconfig" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult[] _kubeconfig; /// <summary>Base64-encoded Kubernetes configuration file.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult[] Kubeconfig { get => this._kubeconfig; } /// <summary>Internal Acessors for Kubeconfig</summary> Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult[] Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResultsInternal.Kubeconfig { get => this._kubeconfig; set { {_kubeconfig = value;} } } /// <summary>Creates an new <see cref="CredentialResults" /> instance.</summary> public CredentialResults() { } } /// The list of credential result response. public partial interface ICredentialResults : Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IJsonSerializable { /// <summary>Base64-encoded Kubernetes configuration file.</summary> [Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info( Required = false, ReadOnly = true, Description = @"Base64-encoded Kubernetes configuration file.", SerializedName = @"kubeconfigs", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult) })] Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult[] Kubeconfig { get; } } /// The list of credential result response. internal partial interface ICredentialResultsInternal { /// <summary>Base64-encoded Kubernetes configuration file.</summary> Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.ICredentialResult[] Kubeconfig { get; set; } } }
50.938776
242
0.71234
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/Aks/Aks.Autorest/generated/api/Models/Api20200901/CredentialResults.cs
2,448
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using ExtendedControls.ExtendedToolkit.Controls.Navigator.Classes; using ExtendedControls.ExtendedToolkit.Controls.Navigator.UI; using ExtendedControls.Properties; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace ExtendedControls.ExtendedToolkit.Controls.Navigator.Controls { [DefaultEvent("ButtonClicked")] [ToolboxBitmap(typeof(TableLayoutPanel))] public class OutlookBar : Control { private IPalette _palette; private PaletteRedirect _paletteRedirect; private PaletteBackInheritRedirect _paletteBack; private PaletteBorderInheritRedirect _paletteBorder; private PaletteContentInheritRedirect _paletteContent; private IDisposable _mementoBack; #region ... constructor ... public OutlookBar() { Paint += OutlookBar_Paint; MouseUp += OutlookBar_MouseUp; MouseMove += OutlookBar_MouseMove; MouseLeave += OutlookBar_MouseLeave; MouseDown += OutlookBar_MouseDown; MouseClick += OutlookBar_MouseClick; this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this._Buttons = new OutlookBarButtonCollection(this); // add Palette Handler if (_palette != null) _palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); KryptonManager.GlobalPaletteChanged += new EventHandler(OnGlobalPaletteChanged); _palette = KryptonManager.CurrentGlobalPalette; _paletteRedirect = new PaletteRedirect(_palette); _paletteBack = new PaletteBackInheritRedirect(_paletteRedirect); _paletteBorder = new PaletteBorderInheritRedirect(_paletteRedirect); _paletteContent = new PaletteContentInheritRedirect(_paletteRedirect); //only if Krypton if (Renderer == Renderer.Krypton) InitColors(); } public event ButtonClickedEventHandler ButtonClicked; public delegate void ButtonClickedEventHandler(object sender, System.EventArgs e); //Needed because this way the buttons can raise the ButtonClicked event... public void SetSelectionChanged(OutlookBarButton button) { this._SelectedButton = button; this.Invalidate(); if (ButtonClicked != null) { ButtonClicked(this, new System.EventArgs()); } } #endregion #region " Members... " //Private Members... private ToolTip oToolTip = new ToolTip(); private ContextMenuStrip oContextMenuStrip; private OutlookBarButtonCollection _Buttons; private Renderer _Renderer = Renderer.Custom; private const int ImageDimension_Large = 24; private const int ImageDimension_Small = 18; private bool _DropDownHovering; private OutlookBarButton _HoveringButton; private OutlookBarButton _LeftClickedButton; private OutlookBarButton _RightClickedButton; internal OutlookBarButton _SelectedButton; private bool IsResizing; private bool CanGrow; private bool CanShrink; private Color _OutlookBarLineColour; private int _ButtonHeight = 35; private Color _ForeColourSelected; private Color _ButtonColourHoveringTop; private Color _ButtonColourSelectedTop; private Color _ButtonColourSelectedAndHoveringTop; private Color _ButtonColourPassiveTop; private Color _ButtonColourHoveringBottom; private Color _ButtonColourSelectedBottom; private Color _ButtonColourSelectedAndHoveringBottom; private Color _ButtonColoruPassiveBottom; private Color _GridColourDark; private Color _GridColourLight; private bool _DrawBorders; private bool _RemoveTopBorder; private bool isDebugMode = false; //Public Members... [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Category("Behavior")] public OutlookBarButtonCollection Buttons { get { return this._Buttons; } } [Browsable(true)] public OutlookBarButton SelectedButton { get { return this._SelectedButton; } } [Browsable(true)] public int SelectedIndex { get { return this.Buttons.SelectedIndex(_SelectedButton); } } [Category("Appearance")] [DefaultValue(typeof(bool), "False")] public bool DrawBorders { get { return this._DrawBorders; } set { this._DrawBorders = value; this.Invalidate(); } } [Category("Appearance")] [DefaultValue(typeof(bool), "False")] public bool RemoveTopBorder { get { return this._RemoveTopBorder; } set { this._RemoveTopBorder = value; this.Invalidate(); } } [Category("Appearance")] public Renderer Renderer { get { return this._Renderer; } set { this._Renderer = value; this.InitColors(); this.Invalidate(); } } public override Size MinimumSize { get { return new Size(this.GetBottomContainerLeftMargin(), this.GetBottomContainerRectangle().Height + GetGripRectangle().Height); } //do nothing... set { } } [Category("Appearance"), DisplayName("LineColour")] public Color OutlookBarLineColour { get { return this._OutlookBarLineColour; } set { this._OutlookBarLineColour = value; this.Invalidate(); } } [Category("Appearance")] public int ButtonHeight { get { return this._ButtonHeight; } set { if (value < 5) value = 5; this._ButtonHeight = value; this.Invalidate(); } } [DisplayName("ForeColorNotSelected")] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; this.Invalidate(); } } [Category("Appearance")] public Color ForeColourSelected { get { return this._ForeColourSelected; } set { this._ForeColourSelected = value; this.Invalidate(); } } [DisplayName("ButtonFont")] public override Font Font { get { return base.Font; } set { base.Font = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonHovering1")] public Color ButtonColourHoveringTop { get { return this._ButtonColourHoveringTop; } set { this._ButtonColourHoveringTop = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonSelected1")] public Color ButtonColourSelectedTop { get { return this._ButtonColourSelectedTop; } set { this._ButtonColourSelectedTop = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonSelectedHovering1")] public Color ButtonColourSelectedAndHoveringTop { get { return this._ButtonColourSelectedAndHoveringTop; } set { this._ButtonColourSelectedAndHoveringTop = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonPassive1")] public Color ButtonColourPassiveTop { get { return this._ButtonColourPassiveTop; } set { this._ButtonColourPassiveTop = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonHovering2")] public Color ButtonColourHoveringBottom { get { return this._ButtonColourHoveringBottom; } set { this._ButtonColourHoveringBottom = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonSelected2")] public Color ButtonColourSelectedBottom { get { return this._ButtonColourSelectedBottom; } set { this._ButtonColourSelectedBottom = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonSelectedHovering2")] public Color ButtonColourSelectedAndHoveringBottom { get { return this._ButtonColourSelectedAndHoveringBottom; } set { this._ButtonColourSelectedAndHoveringBottom = value; this.Invalidate(); } } [Category("Appearance"), DisplayName("ButtonPassive2")] public Color ButtonColourPassiveBottom { get { return this._ButtonColoruPassiveBottom; } set { this._ButtonColoruPassiveBottom = value; this.Invalidate(); } } // #endregion #region " Control events " private void OutlookBar_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) { _RightClickedButton = null; OutlookBarButton mButton = this.Buttons[e.X, e.Y]; if ((mButton != null)) { switch (e.Button) { case MouseButtons.Left: this._SelectedButton = mButton; if (ButtonClicked != null) { ButtonClicked(this, new System.EventArgs()); } this.Invalidate(); break; case MouseButtons.Right: this._RightClickedButton = mButton; this.Invalidate(); break; } } else { if (this.GetDropDownRectangle().Contains(e.X, e.Y)) { this.CreateContextMenu(); } } } private void OutlookBar_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { IsResizing = GetGripRectangle().Contains(e.X, e.Y); } private void OutlookBar_MouseLeave(object sender, System.EventArgs e) { if (this._RightClickedButton == null) { this._HoveringButton = null; this._DropDownHovering = false; this.Invalidate(); } } private void OutlookBar_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { this._HoveringButton = null; //string EmptyLineVar = null; this._DropDownHovering = false; if (IsResizing) { if (e.Y < -GetButtonHeight()) { if (CanGrow) { this.Height += GetButtonHeight(); } else { return; } } else if (e.Y > GetButtonHeight()) { if (CanShrink) { this.Height -= GetButtonHeight(); } else { return; } } } else { if (this.GetGripRectangle().Contains(e.X, e.Y)) { this.Cursor = Cursors.SizeNS; } else if (GetDropDownRectangle().Contains(e.X, e.Y)) { this.Cursor = Cursors.Hand; this._DropDownHovering = true; this.Invalidate(); // //adjust Tooltip... if ((oToolTip.Tag != null)) { if (!oToolTip.Tag.Equals("Configure")) { this.oToolTip.Active = true; this.oToolTip.SetToolTip(this, "Configure buttons"); this.oToolTip.Tag = "Configure"; } } else { this.oToolTip.Active = true; this.oToolTip.SetToolTip(this, "Configure buttons"); this.oToolTip.Tag = "Configure"; } //EmptyLineVar = null; } else if ((this.Buttons[e.X, e.Y] != null)) { this.Cursor = Cursors.Hand; this._HoveringButton = this.Buttons[e.X, e.Y]; this.Invalidate(); //string EmptyLineVar = null; //adjust tooltip... if (!this.Buttons[e.X, e.Y].isLarge) { if (oToolTip.Tag == null) { this.oToolTip.Active = true; this.oToolTip.SetToolTip(this, this.Buttons[e.X, e.Y].Text); this.oToolTip.Tag = this.Buttons[e.X, e.Y]; } else { if (!oToolTip.Tag.Equals(this.Buttons[e.X, e.Y])) { this.oToolTip.Active = true; this.oToolTip.SetToolTip(this, this.Buttons[e.X, e.Y].Text); this.oToolTip.Tag = this.Buttons[e.X, e.Y]; } } } else { this.oToolTip.Active = false; } } else { this.Cursor = Cursors.Default; } } } private void OutlookBar_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { this.IsResizing = false; this._LeftClickedButton = null; } #endregion #region " Graphics " private int MaxLargeButtonCount; private int MaxSmallButtonCount; internal void OutlookBar_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { //string EmptyLineVar = null; this.MaxLargeButtonCount = (int)Math.Round(Math.Floor((double)(((double)((this.Height - this.GetBottomContainerRectangle().Height) - this.GetGripRectangle().Height)) / ((double)this.GetButtonHeight())))); if (this.Buttons.CountVisible() < MaxLargeButtonCount) MaxLargeButtonCount = this.Buttons.CountVisible(); CanShrink = (MaxLargeButtonCount != 0); CanGrow = (MaxLargeButtonCount < this.Buttons.CountVisible()); this.Height = (MaxLargeButtonCount * GetButtonHeight()) + GetGripRectangle().Height + GetBottomContainerRectangle().Height; //Paint Grip... this.PaintGripRectangle(e.Graphics); //Paint Large Buttons... int SyncLargeButtons = 0; int IterateLargeButtons = 0; for (IterateLargeButtons = 0; IterateLargeButtons <= this.Buttons.Count - 1; IterateLargeButtons++) { if (this.Buttons[IterateLargeButtons].Visible) { Rectangle rec = new Rectangle(0, (SyncLargeButtons * GetButtonHeight()) + GetGripRectangle().Height, this.Width, GetButtonHeight()); Buttons[IterateLargeButtons].Rectangle = rec; Buttons[IterateLargeButtons].isLarge = true; this.PaintButton(Buttons[IterateLargeButtons], e.Graphics, (MaxLargeButtonCount != SyncLargeButtons)); if (SyncLargeButtons == MaxLargeButtonCount) break; // TODO: might not be correct. Was : Exit For SyncLargeButtons += 1; } } //Paint Small Buttons... this.MaxSmallButtonCount = (int)Math.Round(Math.Floor((double)(((double)((this.Width - this.GetDropDownRectangle().Width) - this.GetBottomContainerLeftMargin())) / ((double)this.GetSmallButtonWidth())))); if ((this.Buttons.CountVisible() - MaxLargeButtonCount) <= 0) { MaxSmallButtonCount = 0; } if (MaxSmallButtonCount >= (this.Buttons.CountVisible() - MaxLargeButtonCount)) { MaxSmallButtonCount = (this.Buttons.CountVisible() - MaxLargeButtonCount); } int StartX = this.Width - GetDropDownRectangle().Width - (MaxSmallButtonCount * this.GetSmallButtonWidth()); int SyncSmallButtons = 0; int IterateSmallButtons = 0; for (IterateSmallButtons = IterateLargeButtons; IterateSmallButtons <= this.Buttons.Count - 1; IterateSmallButtons++) { if (SyncSmallButtons == MaxSmallButtonCount) break; // TODO: might not be correct. Was : Exit For if (this.Buttons[IterateSmallButtons].Visible) { Rectangle rec = new Rectangle(StartX + (SyncSmallButtons * GetSmallButtonWidth()), GetBottomContainerRectangle().Y, GetSmallButtonWidth(), GetBottomContainerRectangle().Height); this.Buttons[IterateSmallButtons].Rectangle = rec; this.Buttons[IterateSmallButtons].isLarge = false; //OutlookBarButton refBtn = Buttons[IterateLargeButtons]; this.PaintButton(this.Buttons[IterateSmallButtons], e.Graphics, false); SyncSmallButtons += 1; } } for (int IterateMenuItems = IterateSmallButtons; IterateMenuItems <= this.Buttons.CountVisible() - 1; IterateMenuItems++) { this.Buttons[IterateMenuItems].Rectangle = new Rectangle(); } //Draw Empty Space... Rectangle recEmptySpace = this.GetBottomContainerRectangle(); { recEmptySpace.Width = this.Width - (MaxSmallButtonCount * this.GetSmallButtonWidth()) - this.GetDropDownRectangle().Width; } this.FillButton(recEmptySpace, e.Graphics, ButtonState.Passive, true, true, (isDebugMode)); //Paint DropDown... this.PaintDropDownRectangle(e.Graphics); //Finally, paint the bottom line... e.Graphics.DrawLine(new Pen(this.GetOutlookBarLineColour()), 0, this.Height - 1, this.Width - 1, this.Height - 1); } private void PaintButton(OutlookBarButton Button, Graphics graphics, bool IsLastLarge) { if (Button.Equals(_HoveringButton)) { if (_LeftClickedButton == null) { if (Button.Equals(this.SelectedButton)) { FillButton(Button.Rectangle, graphics, ButtonState.HoveringSelected, true, Button.isLarge, Button.isLarge); } else { this.FillButton(Button.Rectangle, graphics, ButtonState.Hovering, true, Button.isLarge, Button.isLarge); } } else { this.FillButton(Button.Rectangle, graphics, ButtonState.Selected, true, Button.isLarge, Button.isLarge); } } else { if (Button.Equals(SelectedButton)) { FillButton(Button.Rectangle, graphics, ButtonState.Selected, true, Button.isLarge, Button.isLarge); } else { FillButton(Button.Rectangle, graphics, ButtonState.Passive, true, Button.isLarge, Button.isLarge); } } //string EmptyLineVar = null; //Text and icons... if (Button.isLarge & IsLastLarge == true) { graphics.DrawString(Button.Text, this.GetButtonFont(), this.GetButtonTextBrush(Button.Equals(this.SelectedButton)), 10 + ImageDimension_Large + 8, (float)Button.Rectangle.Y + ((GetButtonHeight() / 2) - (this.GetButtonFont().Height / 2)) + 2); } Rectangle recIma = new Rectangle(); switch (Button.isLarge) { case true: { recIma.Width = ImageDimension_Large; recIma.Height = ImageDimension_Large; recIma.X = 10; recIma.Y = Button.Rectangle.Y + (int)Math.Floor((double)(GetButtonHeight() / 2) - (double)(ImageDimension_Large / 2)); } break; case false: { recIma.Width = ImageDimension_Small; recIma.Height = ImageDimension_Small; recIma.X = Button.Rectangle.X + (int)Math.Floor((double)(GetSmallButtonWidth() / 2) - (double)(ImageDimension_Small / 2)); recIma.Y = Button.Rectangle.Y + (int)Math.Floor((double)(GetButtonHeight() / 2) - (double)(ImageDimension_Small / 2)); } break; } if (Button.isLarge & IsLastLarge == true) graphics.DrawImage(Button.Image.ToBitmap(), recIma); if (Button.isLarge == false) graphics.DrawImage(Button.Image.ToBitmap(), recIma); //Debug if (isDebugMode) graphics.DrawRectangle(new Pen(Color.Red), recIma); } private void FillButton(Rectangle rectangle, Graphics graphics, ButtonState buttonState, bool DrawTopBorder, bool DrawLeftBorder, bool DrawRightBorder) { switch (this.Renderer) { case Renderer.Outlook2003: Brush aBrush = new LinearGradientBrush(rectangle, this.GetButtonColor(buttonState, 0), this.GetButtonColor(buttonState, 1), LinearGradientMode.Vertical); graphics.FillRectangle(aBrush, rectangle); aBrush.Dispose(); break; case Renderer.Outlook2007: //string EmptyLineVar = null; //Filling the top part of the button... Rectangle TopRectangle = rectangle; Brush TopBrush = new LinearGradientBrush(TopRectangle, this.GetButtonColor(buttonState, 0), this.GetButtonColor(buttonState, 1), LinearGradientMode.Vertical); TopRectangle.Height = (GetButtonHeight() * 15) / 32; graphics.FillRectangle(TopBrush, TopRectangle); TopBrush.Dispose(); //and the bottom part... Rectangle BottomRectangle = rectangle; Brush BottomBrush = new LinearGradientBrush(BottomRectangle, this.GetButtonColor(buttonState, 2), this.GetButtonColor(buttonState, 3), LinearGradientMode.Vertical); BottomRectangle.Y += (GetButtonHeight() * 12) / 32; BottomRectangle.Height -= (GetButtonHeight() * 12) / 32; graphics.FillRectangle(BottomBrush, BottomRectangle); BottomBrush.Dispose(); break; case Renderer.Custom: Brush bBrush = new LinearGradientBrush(rectangle, this.GetButtonColor(buttonState, 0), this.GetButtonColor(buttonState, 1), LinearGradientMode.Vertical); graphics.FillRectangle(bBrush, rectangle); bBrush.Dispose(); break; case Renderer.Krypton: using (GraphicsPath path = new GraphicsPath()) { IRenderer renderer = _palette.GetRenderer(); path.AddRectangle(rectangle); using (RenderContext context = new RenderContext(this, graphics, rectangle, renderer)) { PaletteState ps = PaletteState.Normal; switch (buttonState) { case ButtonState.Hovering: ps = PaletteState.Tracking; break; case ButtonState.Passive: ps = PaletteState.Normal; break; case ButtonState.Selected: ps = PaletteState.Pressed; break; case ButtonState.HoveringSelected: ps = PaletteState.CheckedTracking; break; } _paletteBack.Style = PaletteBackStyle.ButtonNavigatorStack; _paletteBorder.Style = PaletteBorderStyle.ButtonNavigatorStack; //check on renderer type if (renderer.ToString() == "ComponentFactory.Krypton.Toolkit.RenderSparkle") { _paletteBack.Style = PaletteBackStyle.ButtonInputControl; } _mementoBack = renderer.RenderStandardBack.DrawBack(context, rectangle, path, _paletteBack, VisualOrientation.Top, ps, _mementoBack); /*renderer.RenderStandardBorder.DrawBorder(context, rectangle, _paletteBorder, VisualOrientation.Top, ps); */ } } break; } //Draw Top Border... if (DrawTopBorder) graphics.DrawLine(new Pen(GetOutlookBarLineColour()), rectangle.X, rectangle.Y, rectangle.Width + rectangle.X, rectangle.Y); //DrawBorders? if (_DrawBorders) { //Draw Left Border... if (DrawLeftBorder) graphics.DrawLine(new Pen(GetOutlookBarLineColour()), rectangle.X, rectangle.Y, rectangle.X, rectangle.Y + rectangle.Height); //Draw Right Border... if (DrawRightBorder) graphics.DrawLine(new Pen(GetOutlookBarLineColour()), rectangle.X + rectangle.Width - 1, rectangle.Y, rectangle.X + rectangle.Width - 1, rectangle.Y + rectangle.Height); } } private void PaintGripRectangle(Graphics graphics) { //Paint the backcolor... graphics.FillRectangle(this.GetGripBrush(), this.GetGripRectangle()); //Draw the icon... Icon oIcon = this.GetGripIcon(); Rectangle RectangleIcon = new Rectangle((int)((int)this.Width / 2) - ((int)oIcon.Width / 2), (((int)(GetGripRectangle().Height) / 2) - (int)(oIcon.Height / 2)) + 1, oIcon.Width, oIcon.Height); if (Renderer != Renderer.Krypton) { //Icon from file graphics.DrawIcon(oIcon, RectangleIcon); } else { //Painted PaintGrip(graphics, RectangleIcon, _GridColourDark, _GridColourLight); } oIcon.Dispose(); //RemoveTopBorder? if (!_RemoveTopBorder) { graphics.DrawLine(new Pen(this.GetGripTopColor(), 1), 0, 0, this.Width, 0); } //DrawBorders? if (_DrawBorders) { graphics.DrawLine(new Pen(this.GetOutlookBarLineColour(), 1), 0, 0, 0, GetGripRectangle().Height); graphics.DrawLine(new Pen(this.GetOutlookBarLineColour(), 1), GetGripRectangle().Width - 1, 0, GetGripRectangle().Width - 1, this.GetGripRectangle().Height); } } private void PaintGrip(Graphics graphics, Rectangle RectangleIcon, Color GripDark, Color GripLight) { // White Grip - Shadow Rectangle IGrip = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) - 10, (int)(RectangleIcon.Y + RectangleIcon.Height / 2), 2, 2); Rectangle IIGrip = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) - 5, (int)(RectangleIcon.Y + RectangleIcon.Height / 2), 2, 2); Rectangle IIIGrip = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2), (int)(RectangleIcon.Y + RectangleIcon.Height / 2), 2, 2); Rectangle IVGrip = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) + 5, (int)(RectangleIcon.Y + RectangleIcon.Height / 2), 2, 2); Rectangle VGrip = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) + 10, (int)(RectangleIcon.Y + RectangleIcon.Height / 2), 2, 2); graphics.FillRectangle(new SolidBrush(GripLight), IGrip); graphics.FillRectangle(new SolidBrush(GripLight), IIGrip); graphics.FillRectangle(new SolidBrush(GripLight), IIIGrip); graphics.FillRectangle(new SolidBrush(GripLight), IVGrip); graphics.FillRectangle(new SolidBrush(GripLight), VGrip); // dark Grip - Shadow Rectangle IGripDark = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) - 11, (int)(RectangleIcon.Y + RectangleIcon.Height / 2) - 1, 2, 2); Rectangle IIGripDark = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) - 6, (int)(RectangleIcon.Y + RectangleIcon.Height / 2) - 1, 2, 2); Rectangle IIIGripDark = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) - 1, (int)(RectangleIcon.Y + RectangleIcon.Height / 2) - 1, 2, 2); Rectangle IVGripDark = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) + 4, (int)(RectangleIcon.Y + RectangleIcon.Height / 2) - 1, 2, 2); Rectangle VGripDark = new Rectangle((int)(RectangleIcon.X + RectangleIcon.Width / 2) + 9, (int)(RectangleIcon.Y + RectangleIcon.Height / 2) - 1, 2, 2); graphics.FillRectangle(new SolidBrush(GripDark), IGripDark); graphics.FillRectangle(new SolidBrush(GripDark), IIGripDark); graphics.FillRectangle(new SolidBrush(GripDark), IIIGripDark); graphics.FillRectangle(new SolidBrush(GripDark), IVGripDark); graphics.FillRectangle(new SolidBrush(GripDark), VGripDark); } private void PaintDropDownRectangle(Graphics graphics) { //string EmptyLineVar = null; //Repaint the backcolor if the mouse is hovering... switch (this._DropDownHovering) { case true: this.FillButton(this.GetDropDownRectangle(), graphics, ButtonState.Hovering, true, false, true); break; case false: this.FillButton(this.GetDropDownRectangle(), graphics, ButtonState.Passive, true, false, true); break; } //Debug if (isDebugMode) graphics.DrawRectangle(new Pen(Color.Green), this.GetDropDownRectangle()); //Draw the icon... Icon oIcon = this.GetDropDownIcon(); Rectangle RectangleIcon = new Rectangle((this.GetDropDownRectangle().X + ((this.GetDropDownRectangle().Width / 2) - (oIcon.Width / 2))), (this.GetDropDownRectangle().Y + (((this.GetDropDownRectangle().Height / 2) - (oIcon.Height / 2)) + 1)), oIcon.Width, oIcon.Height); if (Renderer != Renderer.Krypton) { //draw icon from file graphics.DrawIcon(oIcon, RectangleIcon); } else { //paint the arrow PaintDropDown(graphics, RectangleIcon, _GridColourDark, _GridColourLight); } //Debug if (isDebugMode) graphics.DrawRectangle(new Pen(Color.Red), RectangleIcon); //graphics.DrawIcon(oIcon, RectangleIcon); oIcon.Dispose(); } private void PaintDropDown(Graphics graphics, Rectangle RectangleIcon, Color GripDark, Color GripLight) { //draw White part Point[] ptWhite = new Point[3]; ptWhite[0] = new Point(RectangleIcon.Left - 1, RectangleIcon.Top); ptWhite[1] = new Point(RectangleIcon.Left + RectangleIcon.Width / 2, RectangleIcon.Bottom + 1); ptWhite[2] = new Point(RectangleIcon.Right + 1, RectangleIcon.Top); graphics.FillPolygon(new SolidBrush(GripLight), ptWhite); //draw Colored part Point[] pt = new Point[3]; pt[0] = new Point(RectangleIcon.Left - 1, RectangleIcon.Top); pt[1] = new Point(RectangleIcon.Left + RectangleIcon.Width / 2, RectangleIcon.Bottom); pt[2] = new Point(RectangleIcon.Right + 1, RectangleIcon.Top); graphics.FillPolygon(new SolidBrush(GripDark), pt); } #endregion #region " Renderer-dependent values " private Color GetOutlookBarLineColour() { switch (this.Renderer) { case Renderer.Outlook2003: return Color.FromArgb(0, 45, 150); case Renderer.Outlook2007: return Color.FromArgb(101, 147, 207); case Renderer.Krypton: return this.OutlookBarLineColour; case Renderer.Custom: return this.OutlookBarLineColour; } return this.OutlookBarLineColour; } private Brush GetButtonTextBrush(bool isSelected) { switch (this.Renderer) { case Renderer.Outlook2003: return Brushes.Black; case Renderer.Outlook2007: switch (isSelected) { case false: return new SolidBrush(Color.FromArgb(32, 77, 137)); case true: return Brushes.Black; } break; case Renderer.Krypton: switch (isSelected) { case false: return new SolidBrush(this.ForeColor); case true: return new SolidBrush(this.ForeColourSelected); } break; case Renderer.Custom: switch (isSelected) { case false: return new SolidBrush(this.ForeColor); case true: return new SolidBrush(this.ForeColourSelected); } break; } return null; } private Font GetButtonFont() { switch (this.Renderer) { case Renderer.Krypton: return new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0); case Renderer.Outlook2003: return new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0); case Renderer.Outlook2007: return new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0); case Renderer.Custom: return this.Font; } return null; } private Color GetButtonColor(ButtonState buttonstate, int colorIndex) { switch (this.Renderer) { case Renderer.Outlook2003: switch (buttonstate) { case ButtonState.Hovering | ButtonState.Selected: if (colorIndex == 0) return Color.FromArgb(232, 127, 8); if (colorIndex == 1) return Color.FromArgb(247, 218, 124); break; case ButtonState.Hovering: if (colorIndex == 0) return Color.FromArgb(255, 255, 220); if (colorIndex == 1) return Color.FromArgb(247, 192, 91); break; case ButtonState.Selected: if (colorIndex == 0) return Color.FromArgb(247, 218, 124); if (colorIndex == 1) return Color.FromArgb(232, 127, 8); break; case ButtonState.Passive: if (colorIndex == 0) return Color.FromArgb(203, 225, 252); if (colorIndex == 1) return Color.FromArgb(125, 166, 223); break; } break; case Renderer.Outlook2007: switch (buttonstate) { case ButtonState.Hovering | ButtonState.Selected: if (colorIndex == 0) return Color.FromArgb(255, 189, 105); if (colorIndex == 1) return Color.FromArgb(255, 172, 66); if (colorIndex == 2) return Color.FromArgb(251, 140, 60); if (colorIndex == 3) return Color.FromArgb(254, 211, 101); break; case ButtonState.Hovering: if (colorIndex == 0) return Color.FromArgb(255, 254, 228); if (colorIndex == 1) return Color.FromArgb(255, 232, 166); if (colorIndex == 2) return Color.FromArgb(255, 215, 103); if (colorIndex == 3) return Color.FromArgb(255, 230, 159); break; case ButtonState.Selected: if (colorIndex == 0) return Color.FromArgb(255, 217, 170); if (colorIndex == 1) return Color.FromArgb(255, 187, 109); if (colorIndex == 2) return Color.FromArgb(255, 171, 63); if (colorIndex == 3) return Color.FromArgb(254, 225, 123); break; case ButtonState.Passive: if (colorIndex == 0) return Color.FromArgb(227, 239, 255); if (colorIndex == 1) return Color.FromArgb(196, 221, 255); if (colorIndex == 2) return Color.FromArgb(173, 209, 255); if (colorIndex == 3) return Color.FromArgb(193, 219, 255); break; } break; case Renderer.Krypton: switch (buttonstate) { case ButtonState.Hovering | ButtonState.Selected: if (colorIndex == 0) return this.ButtonColourSelectedAndHoveringTop; if (colorIndex == 1) return this.ButtonColourSelectedAndHoveringBottom; break; case ButtonState.Hovering: if (colorIndex == 0) return this.ButtonColourHoveringTop; if (colorIndex == 1) return this.ButtonColourHoveringBottom; break; case ButtonState.Selected: if (colorIndex == 0) return this.ButtonColourSelectedTop; if (colorIndex == 1) return this.ButtonColourSelectedBottom; break; case ButtonState.Passive: if (colorIndex == 0) return this.ButtonColourPassiveTop; if (colorIndex == 1) return this.ButtonColourPassiveBottom; break; } break; case Renderer.Custom: switch (buttonstate) { case ButtonState.Hovering | ButtonState.Selected: if (colorIndex == 0) return this.ButtonColourSelectedAndHoveringTop; if (colorIndex == 1) return this.ButtonColourSelectedAndHoveringBottom; break; case ButtonState.Hovering: if (colorIndex == 0) return this.ButtonColourHoveringTop; if (colorIndex == 1) return this.ButtonColourHoveringBottom; break; case ButtonState.Selected: if (colorIndex == 0) return this.ButtonColourSelectedTop; if (colorIndex == 1) return this.ButtonColourSelectedBottom; break; case ButtonState.Passive: if (colorIndex == 0) return this.ButtonColourPassiveTop; if (colorIndex == 1) return this.ButtonColourPassiveBottom; break; } break; } return Color.FromArgb(247, 218, 124); } private int GetButtonHeight() { switch (this.Renderer) { case Renderer.Outlook2003: return 32; case Renderer.Outlook2007: return 32; case Renderer.Krypton: return 32; case Renderer.Custom: return this.ButtonHeight; } return 32; } private Rectangle GetBottomContainerRectangle() { return new Rectangle(0, this.Height - this.GetButtonHeight(), this.Width, this.GetButtonHeight()); } private int GetBottomContainerLeftMargin() { switch (this.Renderer) { case Renderer.Outlook2003: return 15; case Renderer.Outlook2007: return 16; case Renderer.Krypton: return 16; case Renderer.Custom: return 16; } return 16; } private int GetSmallButtonWidth() { switch (this.Renderer) { case Renderer.Outlook2003: return 22; case Renderer.Outlook2007: return 26; case Renderer.Krypton: return 26; case Renderer.Custom: return 25; } return 25; } private Brush GetGripBrush() { switch (this.Renderer) { case Renderer.Outlook2003: return new LinearGradientBrush(this.GetGripRectangle(), Color.FromArgb(89, 135, 214), Color.FromArgb(0, 45, 150), LinearGradientMode.Vertical); case Renderer.Outlook2007: return new LinearGradientBrush(this.GetGripRectangle(), Color.FromArgb(227, 239, 255), Color.FromArgb(179, 212, 255), LinearGradientMode.Vertical); case Renderer.Krypton: return new LinearGradientBrush(this.GetGripRectangle(), this.ButtonColourPassiveTop, this.ButtonColourPassiveBottom, LinearGradientMode.Vertical); case Renderer.Custom: return new LinearGradientBrush(this.GetGripRectangle(), this.ButtonColourPassiveTop, this.ButtonColourPassiveBottom, LinearGradientMode.Vertical); } return null; } private Rectangle GetGripRectangle() { int Height = 0; switch (this.Renderer) { case Renderer.Outlook2003: Height = 6; break; case Renderer.Outlook2007: Height = 8; break; case Renderer.Krypton: Height = 8; break; case Renderer.Custom: Height = 8; break; } return new Rectangle(0, 0, this.Width, Height); } private Icon GetGripIcon() { switch (this.Renderer) { case Renderer.Outlook2003: return Resources.Grip2003; case Renderer.Outlook2007: return Resources.Grip2007; case Renderer.Krypton: return Resources.Grip2007; case Renderer.Custom: return Resources.Grip2007; } return null; } private Color GetGripTopColor() { switch (this.Renderer) { case Renderer.Outlook2003: return Color.Transparent; case Renderer.Outlook2007: return GetOutlookBarLineColour(); case Renderer.Krypton: return GetOutlookBarLineColour(); case Renderer.Custom: return Color.Transparent; } return Color.Transparent; } private Rectangle GetDropDownRectangle() { return new Rectangle((this.Width - GetSmallButtonWidth()), (this.Height - GetButtonHeight()), GetSmallButtonWidth(), GetButtonHeight()); } private Icon GetDropDownIcon() { switch (this.Renderer) { case Renderer.Outlook2003: return Resources.DropDown2003; case Renderer.Outlook2007: return Resources.DropDown2007; case Renderer.Krypton: return Resources.DropDown2007; case Renderer.Custom: return Resources.DropDown2007; } return null; } #endregion #region " MenuItems and Options " private void CreateContextMenu() { this.oContextMenuStrip = new ContextMenuStrip(); this.oContextMenuStrip.Items.Add("Show &More Buttons", Resources.Arrow_Up.ToBitmap(), ShowMoreButtons); this.oContextMenuStrip.Items.Add("Show Fe&wer Buttons", Resources.Arrow_Down.ToBitmap(), ShowFewerButtons); if (this.MaxLargeButtonCount >= this.Buttons.CountVisible()) this.oContextMenuStrip.Items[0].Enabled = false; if (this.MaxLargeButtonCount == 0) this.oContextMenuStrip.Items[1].Enabled = false; this.oContextMenuStrip.Items.Add("Na&vigation Pane Options...", null, NavigationPaneOptions); ToolStripMenuItem mnuAdd = new ToolStripMenuItem("&Add or Remove Buttons", null); this.oContextMenuStrip.Items.Add(mnuAdd); foreach (OutlookBarButton oButton in this.Buttons) { if (oButton.Allowed) { ToolStripMenuItem mnuA = new ToolStripMenuItem(); { mnuA.Text = oButton.Text; mnuA.Image = oButton.Image.ToBitmap(); mnuA.CheckOnClick = true; mnuA.Checked = oButton.Visible; mnuA.Tag = oButton; } mnuA.Click += ToggleVisible; mnuAdd.DropDownItems.Add(mnuA); } } int c = 0; foreach (OutlookBarButton oButton in this.Buttons) { if (oButton.Visible) { if (oButton.Rectangle == null) c += 1; } } if (c > 0) this.oContextMenuStrip.Items.Add(new ToolStripSeparator()); foreach (OutlookBarButton oButton in this.Buttons) { if (oButton.Rectangle == null) { if (oButton.Visible) { ToolStripMenuItem mnu = new ToolStripMenuItem(); { mnu.Text = oButton.Text; mnu.Image = oButton.Image.ToBitmap(); mnu.Tag = oButton; mnu.CheckOnClick = true; if ((this.SelectedButton != null)) { if (this.SelectedButton.Equals(oButton)) mnu.Checked = true; } } mnu.Click += MnuClicked; this.oContextMenuStrip.Items.Add(mnu); } } } this.oContextMenuStrip.Show(this, new Point(this.Width, this.Height - (GetButtonHeight() / 2))); } private void ShowMoreButtons(object sender, System.EventArgs e) { this.Height += GetButtonHeight(); } private void ShowFewerButtons(object sender, System.EventArgs e) { this.Height -= GetButtonHeight(); } private void NavigationPaneOptions(object sender, System.EventArgs e) { this._RightClickedButton = null; this._HoveringButton = null; this.Invalidate(); OutlookBarNavigationPaneOptions frm = new OutlookBarNavigationPaneOptions(this.Buttons); frm.ShowDialog(); this.Invalidate(); } private void ToggleVisible(object sender, System.EventArgs e) { OutlookBarButton oButton = (OutlookBarButton)((ToolStripMenuItem)sender).Tag; oButton.Visible = !oButton.Visible; this.Invalidate(); } private void MnuClicked(object sender, System.EventArgs e) { OutlookBarButton oButton = (OutlookBarButton)((ToolStripMenuItem)sender).Tag; this._SelectedButton = oButton; if (ButtonClicked != null) { ButtonClicked(this, new System.EventArgs()); } } #endregion #region ... Krypton ... private void InitColors() { if (Renderer == Renderer.Krypton) { this._ButtonColourHoveringBottom = _palette.GetBackColor2(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Tracking); this._ButtonColourHoveringTop = _palette.GetBackColor1(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Tracking); this._ButtonColourSelectedBottom = _palette.GetBackColor2(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Pressed); this._ButtonColourSelectedTop = _palette.GetBackColor1(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Pressed); this._ButtonColoruPassiveBottom = _palette.GetBackColor2(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Normal); this._ButtonColourPassiveTop = _palette.GetBackColor1(PaletteBackStyle.ButtonNavigatorStack, PaletteState.Normal); this._ButtonColourSelectedAndHoveringBottom = _palette.GetBackColor2(PaletteBackStyle.ButtonNavigatorStack, PaletteState.CheckedTracking); this._ButtonColourSelectedAndHoveringTop = _palette.GetBackColor1(PaletteBackStyle.ButtonNavigatorStack, PaletteState.CheckedTracking); this._OutlookBarLineColour = _palette.ColorTable.ToolStripBorder; this._ForeColourSelected = _palette.GetContentShortTextColor1(PaletteContentStyle.ButtonNavigatorStack, PaletteState.Pressed);//Color.Black;// _palette.ColorTable.MenuStripText; this.ForeColor = _palette.GetContentShortTextColor1(PaletteContentStyle.ButtonNavigatorStack, PaletteState.Normal); this._GridColourDark = _palette.ColorTable.GripDark; this._GridColourLight = _palette.ColorTable.GripLight; } } //Kripton Palette Events private void OnGlobalPaletteChanged(object sender, EventArgs e) { if (_palette != null) _palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); _palette = KryptonManager.CurrentGlobalPalette; _paletteRedirect.Target = _palette; if (_palette != null) { _palette.PalettePaint += new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); //repaint with new values InitColors(); } Invalidate(); } //Kripton Palette Events private void OnPalettePaint(object sender, PaletteLayoutEventArgs e) { Invalidate(); } protected override void Dispose(bool disposing) { if (disposing) { // Unhook from the palette events if (_palette != null) { _palette.PalettePaint -= new EventHandler<PaletteLayoutEventArgs>(OnPalettePaint); _palette = null; } // Unhook from the static events, otherwise we cannot be garbage collected KryptonManager.GlobalPaletteChanged -= new EventHandler(OnGlobalPaletteChanged); } base.Dispose(disposing); } #endregion } #region ... Enums ... internal enum ButtonState { Passive, Hovering, Selected, HoveringSelected } public enum Renderer { Outlook2003, Outlook2007, Krypton, Custom } #endregion }
41.851574
281
0.522013
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Controls/Navigator/Controls/OutlookBar.cs
55,832
C#
using NUnit.Framework; using MPT.CSI.API.Core.Program; using MPT.CSI.API.Core.Program.ModelBehavior.Definition; using MPT.CSI.API.Core.Program.ModelBehavior.Definition.LoadCase; using MPT.CSI.API.Core.Support; namespace MPT.CSI.API.EndToEndTests.Core.Program.ModelBehavior.Definition.LoadCase { [TestFixture] public class TimeHistoryDirectLinear_Get : CsiGet { public void GetLoads(string name, ref eLoadType[] loadTypes, ref string[] loadNames, ref string[] functions, ref double[] scaleFactor, ref double[] timeFactor, ref double[] arrivalTime, ref string[] coordinateSystems, ref double[] angles) { } #if !BUILD_ETABS2015 && !BUILD_ETABS2016 && !BUILD_ETABS2017 public void GetInitialCase(string name, ref string initialCase) { } public void GetDampingProportional(string name, ref eDampingTypeProportional dampingType, ref double massProportionalDampingCoefficient, ref double stiffnessProportionalDampingCoefficient, ref double periodOrFrequencyPt1, ref double periodOrFrequencyPt2, ref double dampingPt1, ref double dampingPt2) { } public void GetTimeStep(string name, ref int numberOfOutputSteps, ref double timeStepSize) { } public void GetTimeIntegration(string name, ref eTimeIntegrationType integrationType, ref double alpha, ref double beta, ref double gamma, ref double theta, ref double alphaM) { } #endif } [TestFixture] public class TimeHistoryDirectLinear_Set : CsiSet { public void SetCase(string name) { } public void SetInitialCase(string name, string initialCase) { } public void SetLoads(string name, eLoadType[] loadTypes, string[] loadNames, string[] functions, double[] scaleFactor, double[] timeFactor, double[] arrivalTime, string[] coordinateSystems, double[] angles) { } public void SetDampingProportional(string name, eDampingTypeProportional dampingType, double massProportionalDampingCoefficient, double stiffnessProportionalDampingCoefficient, double periodOrFrequencyPt1, double periodOrFrequencyPt2, double dampingPt1, double dampingPt2) { } public void SetTimeStep(string name, int numberOfOutputSteps, double timeStepSize) { } #if !BUILD_ETABS2015 && !BUILD_ETABS2016 && !BUILD_ETABS2017 public void SetTimeIntegration(string name, eTimeIntegrationType integrationType, double alpha, double beta, double gamma, double theta, double alphaM) { } #endif } }
25.488722
82
0.552507
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.API.EndToEndTests/Core/Program/ModelBehavior/Definition/LoadCase/TimeHistoryDirectLinearTests.cs
3,392
C#
using System; using System.Collections.Generic; using System.Text; namespace code_challenge.menuoption { class PerfSequence { public static void PerfectSequence(string name) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(""); Console.WriteLine("Type in numbers of choice with comma in-between each number of numbers to check if its perfect sequence"); Console.ForegroundColor = ConsoleColor.White; string userInput = Console.ReadLine(); bool checkComma = userInput.Contains(","); while (!checkComma) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Please include comma ^-_-;"); Console.ForegroundColor = ConsoleColor.White; userInput = Console.ReadLine(); checkComma = userInput.Contains(","); } Console.Beep(); string[] newArray = userInput.Split(","); int[] numArray = Array.ConvertAll( newArray, str => int.Parse(str)); int count = 0; int countMult = 1; foreach (var value in numArray) { if (value < 0) { Console.WriteLine("{2}, you entered {0} and you've entered negative value of {1}", userInput, value, name); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No, it is not a perfect sqeuence."); Console.ForegroundColor = ConsoleColor.White; return; } else { count += value; countMult *= value; } } if (count == countMult) { Console.Beep(); Console.BackgroundColor = ConsoleColor.DarkGreen; Console.WriteLine("{1}, you entered {0}", userInput, name); Console.WriteLine("Yes, it is perfect sequence!"); Console.ResetColor(); } else { Console.WriteLine("{1}, you entered {0}", userInput, name); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No, it is not a perfect sqeuence."); Console.ResetColor(); } } } }
39
138
0.495858
[ "MIT" ]
jinwoov/C-CS
Prework-CodeChallenges/menuoption/PerfectSequence.cs
2,537
C#
using System; using System.Collections; using Org.BouncyCastle.Asn1.Ocsp; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1.Esf { /// <remarks> /// RFC 3126: 4.3.2 Revocation Values Attribute Definition /// <code> /// RevocationValues ::= SEQUENCE { /// crlVals [0] SEQUENCE OF CertificateList OPTIONAL, /// ocspVals [1] SEQUENCE OF BasicOCSPResponse OPTIONAL, /// otherRevVals [2] OtherRevVals /// } /// </code> /// </remarks> public class RevocationValues : Asn1Encodable { private readonly Asn1Sequence crlVals; private readonly Asn1Sequence ocspVals; private readonly OtherRevVals otherRevVals; public static RevocationValues GetInstance( object obj) { if (obj == null || obj is RevocationValues) return (RevocationValues) obj; if (obj is Asn1Sequence) return new RevocationValues((Asn1Sequence) obj); throw new ArgumentException( "Unknown object in 'RevocationValues' factory: " + obj.GetType().Name, "obj"); } private RevocationValues( Asn1Sequence seq) { if (seq == null) throw new ArgumentNullException("seq"); if (seq.Count < 1 || seq.Count > 3) throw new ArgumentException("Bad sequence size: " + seq.Count, "seq"); bool otherRevValsFound = false; foreach (Asn1TaggedObject taggedObj in seq) { Asn1Object asn1Obj = taggedObj.GetObject(); switch (taggedObj.TagNo) { case 0: Asn1Sequence crlValsSeq = (Asn1Sequence) asn1Obj; foreach (Asn1Encodable ae in crlValsSeq) { CertificateList.GetInstance(ae.ToAsn1Object()); } this.crlVals = crlValsSeq; break; case 1: Asn1Sequence ocspValsSeq = (Asn1Sequence) asn1Obj; foreach (Asn1Encodable ae in ocspValsSeq) { BasicOcspResponse.GetInstance(ae.ToAsn1Object()); } this.ocspVals = ocspValsSeq; break; case 2: this.otherRevVals = OtherRevVals.GetInstance(asn1Obj); otherRevValsFound = true; break; default: throw new ArgumentException(@"Illegal tag in RevocationValues", "seq"); } } if (!otherRevValsFound) throw new ArgumentException(@"No otherRevVals found", "seq"); } public RevocationValues( CertificateList[] crlVals, BasicOcspResponse[] ocspVals, OtherRevVals otherRevVals) { if (otherRevVals == null) throw new ArgumentNullException("otherRevVals"); if (crlVals != null) { this.crlVals = new DerSequence(crlVals); } if (ocspVals != null) { this.ocspVals = new DerSequence(ocspVals); } this.otherRevVals = otherRevVals; } public RevocationValues( IEnumerable crlVals, IEnumerable ocspVals, OtherRevVals otherRevVals) { if (otherRevVals == null) throw new ArgumentNullException("otherRevVals"); if (crlVals != null) { if (!CollectionUtilities.CheckElementsAreOfType(crlVals, typeof(CertificateList))) throw new ArgumentException(@"Must contain only 'CertificateList' objects", "crlVals"); this.crlVals = new DerSequence( Asn1EncodableVector.FromEnumerable(crlVals)); } if (ocspVals != null) { if (!CollectionUtilities.CheckElementsAreOfType(ocspVals, typeof(BasicOcspResponse))) throw new ArgumentException(@"Must contain only 'BasicOcspResponse' objects", "ocspVals"); this.ocspVals = new DerSequence( Asn1EncodableVector.FromEnumerable(ocspVals)); } this.otherRevVals = otherRevVals; } public CertificateList[] GetCrlVals() { CertificateList[] result = new CertificateList[crlVals.Count]; for (int i = 0; i < crlVals.Count; ++i) { result[i] = CertificateList.GetInstance(crlVals[i].ToAsn1Object()); } return result; } public BasicOcspResponse[] GetOcspVals() { BasicOcspResponse[] result = new BasicOcspResponse[ocspVals.Count]; for (int i = 0; i < ocspVals.Count; ++i) { result[i] = BasicOcspResponse.GetInstance(ocspVals[i].ToAsn1Object()); } return result; } public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(); if (crlVals != null) { v.Add(new DerTaggedObject(true, 0, crlVals)); } if (ocspVals != null) { v.Add(new DerTaggedObject(true, 1, ocspVals)); } v.Add(new DerTaggedObject(true, 2, otherRevVals.ToAsn1Object())); return new DerSequence(v); } } }
25.176136
95
0.678628
[ "MIT" ]
SchmooseSA/Schmoose-BouncyCastle
Crypto/asn1/esf/RevocationValues.cs
4,431
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using ApiServer.Models; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace ApiServer.Controllers { [Route("api/[controller]")] public class TrailsController : Controller { private readonly List<Trail> Trails = new List<Trail> { new Trail { TrailId = 1, Name = "Mission Bay" }, new Trail { TrailId = 2, Name = "Memorial Loop" }, new Trail { TrailId = 3, Name = "Katy Trail" } }; // GET: api/values [HttpGet] public IEnumerable<Trail> Get() { return Trails; } // GET api/values/5 [HttpGet("{id}")] public Trail Get(int id) { return Trails.ElementAt(id); } // POST api/values [HttpPost] public void Post([FromBody]Trail value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]Trail value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
19.709091
115
0.655904
[ "MIT" ]
bcasner/OnGitHub
ApiServer/src/ApiServer/Controllers/TrailsController.cs
1,086
C#
// Copyright (c) Microsoft. All rights reserved. using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Azure.IoTSolutions.StorageAdapter.Services.Diagnostics; using Microsoft.Azure.IoTSolutions.StorageAdapter.Services.Runtime; using Microsoft.Azure.IoTSolutions.StorageAdapter.WebService.Runtime; namespace Microsoft.Azure.IoTSolutions.StorageAdapter.WebService { /// <summary>Application entry point</summary> public class Program { public static void Main(string[] args) { var config = new Config(new ConfigData(new Logger(Uptime.ProcessId, LogLevel.Info))); /* Print some information to help development and debugging, like runtime and configuration settings */ Console.WriteLine($"[{Uptime.ProcessId}] Starting web service started, process ID: " + Uptime.ProcessId); Console.WriteLine($"[{Uptime.ProcessId}] Web service listening on port " + config.Port); Console.WriteLine($"[{Uptime.ProcessId}] Web service health check at: http://127.0.0.1:" + config.Port + "/" + v1.Version.PATH + "/status"); /* Kestrel is a cross-platform HTTP server based on libuv, a cross-platform asynchronous I/O library. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers */ var host = new WebHostBuilder() .UseUrls("http://*:" + config.Port) .UseKestrel(options => { options.AddServerHeader = false; }) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
40.261905
152
0.629805
[ "MIT" ]
Azure/Azure_IoT_Solution_Accelerators_dotnet
storage-adapter/WebService/Program.cs
1,693
C#
/****************************************************************************** * Copyright (C) Ultraleap, Inc. 2011-2021. * * * * Use subject to the terms of the Apache License 2.0 available at * * http://www.apache.org/licenses/LICENSE-2.0, or another agreement * * between Ultraleap and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; namespace Leap.Interaction.Internal.InteractionEngineUtility { public static class ColliderUtil { //************* //GENRAL HELPER /// <summary> /// Returns whether or not a given vector is within a given radius to a center point /// </summary> public static bool WithinDistance(Vector3 point, Vector3 center, float radius) { return (point - center).sqrMagnitude < radius * radius; } public static bool WithinDistance(Vector3 pointToOrigin, float radius) { return pointToOrigin.sqrMagnitude < radius * radius; } /// <summary> /// Given a point and a center, return a new point that is along the axis created by the /// two vectors, and is a given distance from the center /// </summary> public static Vector3 GetPointAtDistance(Vector3 point, Vector3 center, float distance) { return (point - center).normalized * distance + center; } /// <summary> /// Given a collider and a position relative to the colliders transform, return whether or not the /// position lies within the collider. Can also optionally extrude the collider. /// /// Warning: MeshColliders are not fully supported; this will only support testing against a MeshCollider's /// bounding box, with no extrusion. /// </summary> public static bool IsPointInside(this Collider collider, Vector3 localPosition, float extrude = 0.0f) { if (collider is SphereCollider) return (collider as SphereCollider).IsPointInside(localPosition, extrude); if (collider is BoxCollider) return (collider as BoxCollider).IsPointInside(localPosition, extrude); if (collider is CapsuleCollider) return (collider as CapsuleCollider).IsPointInside(localPosition, extrude); if (collider is MeshCollider) return collider.bounds.Contains(collider.transform.TransformPoint(localPosition)); throw nullOrInvalidException(collider); } /// <summary> /// Given a collider and a position relative to the colliders transform, return the point on the surface /// of the collider closest to the position. Can also optionally extrude the collider. /// /// Warning: If you are using a version of Unity pre-5.6, MeshColliders are not fully supported; this will /// only find the closest point on a MeshCollider's bounding box, with no extrusion. /// </summary> public static Vector3 ClosestPointOnSurface(this Collider collider, Vector3 localPosition, float extrude = 0.0f) { if (collider is SphereCollider) return (collider as SphereCollider).ClosestPointOnSurface(localPosition, extrude); if (collider is BoxCollider) return (collider as BoxCollider).ClosestPointOnSurface(localPosition, extrude); if (collider is CapsuleCollider) return (collider as CapsuleCollider).ClosestPointOnSurface(localPosition, extrude); if (collider is MeshCollider) return collider.transform.InverseTransformPoint(collider.ClosestPointOnBounds(collider.transform.TransformPoint(localPosition))); throw nullOrInvalidException(collider); } /// <summary> /// Given a list of colliders and a position in global space, return whether or not the position lies /// within any of the colliders. Can also optionally extrude the collider. /// </summary> public static bool IsPointInside(List<Collider> colliders, Vector3 globalPosition, float extrude = 0.0f) { for (int i = 0; i < colliders.Count; i++) { Collider collider = colliders[i]; Vector3 localPosition = collider.transform.InverseTransformPoint(globalPosition); if (collider.IsPointInside(localPosition, extrude)) { return true; } } return false; } /// <summary> /// Given a list of colliders and a position in global space, return the point on the surface of any /// of the colliders that is closest to the given position. NOTE that this point might be inside of /// a collider! Can also optionally extrude the colliders. /// </summary> public static Vector3 ClosestPointOnSurfaces(List<Collider> colliders, Vector3 globalPosition, float extrude = 0.0f) { Transform chosenTransform = null; Vector3 closestPoint = Vector3.zero; float closestDistance = float.MaxValue; for (int i = 0; i < colliders.Count; i++) { Collider collider = colliders[i]; Vector3 localPoint = collider.transform.InverseTransformPoint(globalPosition); Vector3 point = collider.ClosestPointOnSurface(localPoint, extrude); float distance = (globalPosition - point).sqrMagnitude; if (distance < closestDistance) { chosenTransform = collider.transform; closestDistance = distance; closestPoint = point; } } return chosenTransform.TransformPoint(closestPoint); } //*************** //Raycasting public static bool SegmentCast(List<Collider> colliders, Vector3 worldStart, Vector3 worldEnd, out RaycastHit hitInfo) { Ray ray = new Ray(worldStart, worldEnd - worldStart); float dist = Vector3.Distance(worldStart, worldEnd); hitInfo = new RaycastHit(); bool hitAny = false; RaycastHit tempHit; foreach (Collider collider in colliders) { if (collider.Raycast(ray, out tempHit, dist)) { if (!hitAny || tempHit.distance < hitInfo.distance) { hitInfo = tempHit; hitAny = true; } } } return hitAny; } //*************** //SPHERE COLLIDER public static bool IsPointInside(this SphereCollider collider, Vector3 localPosition, float extrude = 0.0f) { localPosition -= collider.center; return WithinDistance(localPosition, collider.radius + extrude); } public static Vector3 ClosestPointOnSurface(this SphereCollider collider, Vector3 localPosition, float extrude = 0.0f) { return GetPointAtDistance(localPosition, collider.center, collider.radius + extrude); } //************ //BOX COLLIDER public static bool IsPointInside(this BoxCollider collider, Vector3 localPosition, float extrude = 0.0f) { localPosition -= collider.center; if (Mathf.Abs(localPosition.x) > (collider.size.x / 2.0f) + (extrude / collider.transform.lossyScale.x)) { return false; } if (Mathf.Abs(localPosition.y) > (collider.size.y / 2.0f) + (extrude / collider.transform.lossyScale.y)) { return false; } if (Mathf.Abs(localPosition.z) > (collider.size.z / 2.0f) + (extrude / collider.transform.lossyScale.z)) { return false; } return true; } public static Vector3 ClosestPointOnSurface(this BoxCollider collider, Vector3 localPosition, float extrude = 0.0f) { localPosition -= collider.center; Vector3 radius = collider.size / 2.0f; radius.x += extrude; radius.y += extrude; radius.z += extrude; localPosition.x = Mathf.Clamp(localPosition.x, -radius.x, radius.x); localPosition.y = Mathf.Clamp(localPosition.y, -radius.y, radius.y); localPosition.z = Mathf.Clamp(localPosition.z, -radius.z, radius.z); //If an internal point if (Mathf.Abs(localPosition.x) < radius.x && Mathf.Abs(localPosition.y) < radius.y && Mathf.Abs(localPosition.z) < radius.z) { //Snap closest axis to the bounds //Farthest from the center if (Mathf.Abs(localPosition.x) > Mathf.Abs(localPosition.y)) { if (Mathf.Abs(localPosition.x) > Mathf.Abs(localPosition.z)) { //x is farthest localPosition.x = (localPosition.x > 0) ? radius.x : -radius.x; } else { //z is farthest localPosition.z = (localPosition.z > 0) ? radius.z : -radius.z; } } else { if (Mathf.Abs(localPosition.y) > Mathf.Abs(localPosition.z)) { //y is farthest localPosition.y = (localPosition.y > 0) ? radius.y : -radius.y; } else { //z is farthest localPosition.z = (localPosition.z > 0) ? radius.z : -radius.z; } } } localPosition += collider.center; return localPosition; } //**************** //CAPSULE COLLIDER /// <summary> /// A capsule is defined as a line segment with a radius. This method returns the two endpoints /// of that segment, as well as it's length, in local space. /// </summary> public static void GetSegmentInfo(this CapsuleCollider collider, out Vector3 localV0, out Vector3 localV1, out float length) { Vector3 axis = Vector3.right; if (collider.direction == 1) { axis = Vector3.up; } else { axis = Vector3.forward; } length = Mathf.Max(0, collider.height - collider.radius * 2); localV0 = axis * length / 2.0f + collider.center; localV1 = -axis * length / 2.0f + collider.center; } public static bool IsPointInside(this CapsuleCollider collider, Vector3 localPosition, float tolerance = 0.0f) { Vector3 v0, v1; float length; collider.GetSegmentInfo(out v0, out v1, out length); if (length == 0.0f) { return WithinDistance(localPosition, collider.radius + tolerance); } float t = Vector3.Dot(localPosition - v0, v1 - v0) / (length * length); if (t <= 0.0f) { return WithinDistance(localPosition, v0, collider.radius + tolerance); } if (t >= 1.0f) { return WithinDistance(localPosition, v1, collider.radius + tolerance); } Vector3 projection = v0 + t * (v1 - v0); return WithinDistance(localPosition, projection, collider.radius + tolerance); } public static Vector3 ClosestPointOnSurface(this CapsuleCollider collider, Vector3 localPosition, float extrude = 0.0f) { Vector3 v0, v1; float length; collider.GetSegmentInfo(out v0, out v1, out length); if (length == 0.0f) { return GetPointAtDistance(localPosition, collider.center, collider.radius); } float t = Vector3.Dot(localPosition - v0, v1 - v0) / (length * length); if (t <= 0.0f) { return GetPointAtDistance(localPosition, v0, collider.radius + extrude); } if (t >= 1.0f) { return GetPointAtDistance(localPosition, v1, collider.radius + extrude); } Vector3 projection = v0 + t * (v1 - v0); return GetPointAtDistance(localPosition, projection, collider.radius + extrude); } public static float DistanceToSegment(Vector3 a, Vector3 b, Vector3 p) { float t = Vector3.Dot(p - a, b - a) / Vector3.Dot(a - b, a - b); if (t <= 0.0f) { return Vector3.Distance(p, a); } if (t >= 1.0f) { return Vector3.Distance(p, b); } Vector3 projection = a + t * (b - a); return Vector3.Distance(p, projection); } private static Exception nullOrInvalidException(Collider collider) { if (collider == null) { return new ArgumentNullException(); } else { return new ArgumentException("Collider type of " + collider.GetType() + " is not supported."); } } } }
40.834808
171
0.544896
[ "MIT" ]
Gustav-Rixon/M7012E-DRv3
Remote control/Assets/ThirdParty/Ultraleap/Tracking/Interaction Engine/Runtime/Plugins/ColliderUtil.cs
13,843
C#
using System; using System.Collections.Generic; using System.Text; namespace AbpBlog.ToolKits.Base.Paged { public interface IHasTotalCount { /// <summary> /// 总数 /// </summary> int Total { get; set; } } }
16.733333
37
0.585657
[ "MIT" ]
Y7-11/AbpBlog
src/AbpBlog.ToolKits/Base/Paged/IHasTotalCount.cs
257
C#
using System; using System.Collections.Generic; using System.Linq; using Souvenir; using UnityEngine; public partial class SouvenirModule { private IEnumerable<object> ProcessKudosudoku(KMBombModule module) { var comp = GetComponent(module, "KudosudokuModule"); var fldSolved = GetField<bool>(comp, "_isSolved"); var shown = GetArrayField<bool>(comp, "_shown").Get(expectedLength: 16).ToArray(); // Take a copy of the array because the module changes it while (!fldSolved.Get()) yield return new WaitForSeconds(.1f); _modulesSolved.IncSafe(_Kudosudoku); addQuestions(module, makeQuestion(Question.KudosudokuPrefilled, _Kudosudoku, formatArgs: new[] { "pre-filled" }, correctAnswers: Enumerable.Range(0, 16).Where(ix => shown[ix]).Select(coord => new Coord(4, 4, coord)).ToArray()), makeQuestion(Question.KudosudokuPrefilled, _Kudosudoku, formatArgs: new[] { "not pre-filled" }, correctAnswers: Enumerable.Range(0, 16).Where(ix => !shown[ix]).Select(coord => new Coord(4, 4, coord)).ToArray())); } }
45.24
149
0.671972
[ "MIT" ]
Eltrick/KtaneSouvenir
Lib/ModulesK.cs
1,133
C#
namespace BlockchainSimulator.Node.BusinessLogic.Model.Transaction { public class TransactionDetails { public string BlockId { get; set; } public long BlocksBehind { get; set; } public bool IsConfirmed { get; set; } } }
28.333333
66
0.666667
[ "MIT" ]
abinkowski94/blockchain-simulator
src/BlockchainSimulator/BlockchainSimulator.Node.BusinessLogic/Model/Transaction/TransactionDetails.cs
255
C#
using System; using System.Collections.Generic; using System.Reactive.Linq; using FluentAssertions; using NSubstitute; using Toggl.Foundation.DataSources.Interfaces; using Toggl.Foundation.Sync; using Toggl.Foundation.Sync.States.Push; using Toggl.PrimeRadiant; using Xunit; namespace Toggl.Foundation.Tests.Sync.States.Push { public sealed class LookForSingletonChangeToPushStateTests { private readonly ISingletonDataSource<IThreadSafeTestModel> dataSource = Substitute.For<ISingletonDataSource<IThreadSafeTestModel>>(); [Fact, LogIfTooSlow] public void ConstructorThrowsWithNullDataSource() { Action creatingWithNullArgument = () => new LookForSingletonChangeToPushState<IThreadSafeTestModel>(null); creatingWithNullArgument.Should().Throw<ArgumentNullException>(); } [Theory, LogIfTooSlow] [InlineData(SyncStatus.InSync)] [InlineData(SyncStatus.SyncFailed)] public void ReturnsNothingToPushTransitionWhenTheSingleEntityDoesNotNeedSyncing(SyncStatus syncStatus) { var entity = new TestModel(1, syncStatus); var state = new LookForSingletonChangeToPushState<IThreadSafeTestModel>(dataSource); dataSource.Get().Returns(Observable.Return(entity)); var transition = state.Start().SingleAsync().Wait(); transition.Result.Should().Be(state.NoMoreChanges); } [Fact, LogIfTooSlow] public void ReturnsPushEntityTransitionWhenTheRepositoryReturnsSomeEntity() { var state = new LookForSingletonChangeToPushState<IThreadSafeTestModel>(dataSource); var entity = new TestModel(1, SyncStatus.SyncNeeded); dataSource.Get().Returns(Observable.Return(entity)); var transition = state.Start().SingleAsync().Wait(); var parameter = ((Transition<IThreadSafeTestModel>)transition).Parameter; transition.Result.Should().Be(state.ChangeFound); parameter.Should().BeEquivalentTo(entity, options => options.IncludingProperties()); } [Fact, LogIfTooSlow] public void ThrowsWhenRepositoryThrows() { var state = new LookForSingletonChangeToPushState<IThreadSafeTestModel>(dataSource); dataSource.Get().Returns(Observable.Throw<IThreadSafeTestModel>(new Exception())); Action callingStart = () => state.Start().SingleAsync().Wait(); callingStart.Should().Throw<Exception>(); } } }
38.19403
118
0.692849
[ "BSD-3-Clause" ]
kelimebilgisi/mobileapp
Toggl.Foundation.Tests/Sync/States/Push/LookForSingletonChangeToPushStateTests.cs
2,561
C#
using System; using Newtonsoft.Json; using TracerAttributes; namespace Xels.Features.FederatedPeg.Models { public class ConcreteConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) => true; [NoTrace] public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return serializer.Deserialize<T>(reader); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } } }
27.391304
124
0.679365
[ "MIT" ]
xels-io/SideChain-SmartContract
src/Xels.Features.FederatedPeg/Models/ConcreteTypeConverter.cs
632
C#
using System; using System.ComponentModel; using System.Data; using System.Linq; using System.Windows.Forms; using WoWFormatLib.FileReaders; namespace WoWExport { public partial class Form_ADTExport : Form { private readonly BackgroundWorker exportworker = new BackgroundWorker(); public String filename; public static string[] AlphaType = { "RGB", "RGB (63)", "Alpha", "Alpha (63)", "Splatmaps" }; public Form_ADTExport(string receivedFilename) { InitializeComponent(); filename = receivedFilename; exportworker.DoWork += exportworker_DoWork; exportworker.RunWorkerCompleted += exportworker_RunWorkerCompleted; exportworker.ProgressChanged += exportworker_ProgressChanged; exportworker.WorkerReportsProgress = true; } private void Form_ADTExport_Load(object sender, EventArgs e) { comboBox1.Items.AddRange(AlphaType); comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; label4.Hide(); checkBox1.Checked = Managers.ConfigurationManager.ADTExportM2; checkBox1.Text = "Export doodads"; checkBox2.Checked = Managers.ConfigurationManager.ADTExportWMO; checkBox2.Text = "Export world models"; checkBox3.Checked = Managers.ConfigurationManager.WMOExportM2; checkBox3.Text = "Export WMO doodads"; if (checkBox2.Checked) { checkBox3.Enabled = true; checkBox10.Enabled = true; checkBox11.Enabled = true; } else { checkBox3.Enabled = false; checkBox10.Enabled = false; checkBox11.Enabled = false; } checkBox4.Checked = Managers.ConfigurationManager.ADTExportFoliage; checkBox4.Text = "Export foliage"; checkBox5.Checked = Managers.ConfigurationManager.ADTexportTextures; checkBox5.Text = "Export ground textures"; checkBox12.Checked = Managers.ConfigurationManager.ADTPreserveTextureStruct; checkBox12.Text = "Preserve textures path"; if (checkBox5.Checked) { checkBox12.Enabled = true; checkBox13.Enabled = true; } else { checkBox12.Enabled = false; checkBox13.Enabled = false; } checkBox6.Checked = Managers.ConfigurationManager.ADTexportAlphaMaps; checkBox6.Text = "Export alphamaps"; comboBox1.SelectedIndex = Managers.ConfigurationManager.ADTAlphaMode; checkBox7.Checked = Managers.ConfigurationManager.ADTIgnoreHoles; checkBox7.Text = "Ignore holes"; checkBox8.Text = "Use transparency"; checkBox8.Checked = Managers.ConfigurationManager.ADTAlphaUseA; checkBox9.Text = "ADT model placement global paths"; checkBox9.Checked = Managers.ConfigurationManager.ADTModelsPlacementGlobalPath; checkBox10.Text = "WMO Doodads use global paths"; checkBox10.Checked = Managers.ConfigurationManager.WMODoodadsGlobalPath; checkBox11.Text = "WMO Doodads placement global paths"; checkBox11.Checked = Managers.ConfigurationManager.WMODoodadsPlacementGlobalPath; button1.Text = "Export"; this.Text = filename; checkBox13.Text = "Export ground \"specular?\" textures"; checkBox13.Checked = Managers.ConfigurationManager.ADTExportSpecularTextures; //------------------------------------------------------------------------------------- //Not really the intended use for this function, but for now it will stay like this. //------------------------------------------------------------------------------------- checkBox14.Text = "Split materials per chunk"; if (Managers.ConfigurationManager.ADTQuality == "high") { checkBox14.Checked = true; } else { checkBox14.Checked = false; } //------------------------------------------------------------------------------------- if (checkBox14.Checked) { checkBox15.Enabled = true; } else { checkBox15.Enabled = false; } checkBox15.Text = "Split mesh per chunk"; checkBox15.Checked = Managers.ConfigurationManager.ADTSplitChunks; checkBox16.Checked = Managers.ConfigurationManager.ADTExportHeightmap; checkBox16.Text = "Export heightmap"; try { ADTReader reader = new ADTReader(); if (Managers.ConfigurationManager.Profile <= 3) //WoTLK and below { reader.Load335ADT(filename); } else { reader.LoadADT(filename); } listBox1.Items.AddRange(reader.m2Files.Select(s => s.ToLowerInvariant()).ToArray()); listBox2.Items.AddRange(reader.wmoFiles.Select(s => s.ToLowerInvariant()).ToArray()); label1.Text = "Textures (" + reader.adtfile.textures.filenames.Count() + ")"; label2.Text = "Doodads (" + reader.m2Files.Count() + ")"; label3.Text = "WMOs (" + reader.wmoFiles.Count() + ")"; } catch (Exception ex) { throw new Exception(ex.Message); } } private void UpdateConfiguration() { Managers.ConfigurationManager.ADTExportM2 = checkBox1.Checked; Managers.ConfigurationManager.ADTExportWMO = checkBox2.Checked; Managers.ConfigurationManager.WMOExportM2 = checkBox3.Checked; Managers.ConfigurationManager.ADTExportFoliage = checkBox4.Checked; Managers.ConfigurationManager.ADTexportTextures = checkBox5.Checked; Managers.ConfigurationManager.ADTexportAlphaMaps = checkBox6.Checked; Managers.ConfigurationManager.ADTIgnoreHoles = checkBox7.Checked; Managers.ConfigurationManager.ADTExportHeightmap = checkBox16.Checked; Managers.ConfigurationManager.ADTAlphaMode = comboBox1.SelectedIndex; Managers.ConfigurationManager.ADTAlphaUseA = checkBox8.Checked; Managers.ConfigurationManager.ADTModelsPlacementGlobalPath = checkBox9.Checked; Managers.ConfigurationManager.WMODoodadsGlobalPath = checkBox10.Checked; Managers.ConfigurationManager.WMODoodadsPlacementGlobalPath = checkBox11.Checked; Managers.ConfigurationManager.ADTPreserveTextureStruct = checkBox12.Checked; Managers.ConfigurationManager.ADTExportSpecularTextures = checkBox13.Checked; //---------------------------------------------------------------- //Again, not the intended use for this... //---------------------------------------------------------------- if (checkBox14.Checked) { Managers.ConfigurationManager.ADTQuality = "high"; } else { Managers.ConfigurationManager.ADTQuality = "low"; } //---------------------------------------------------------------- Managers.ConfigurationManager.ADTSplitChunks = checkBox15.Checked; } private void exportworker_DoWork(object sender, DoWorkEventArgs e) { Exporters.OBJ.ADTExporter.exportADT(filename, Managers.ConfigurationManager.OutputDirectory, Managers.ConfigurationManager.ADTQuality, exportworker); } private void exportworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { button1.Enabled = true; label4.Hide(); progressBar1.Value = 100; MessageBox.Show("Done"); } private void exportworker_ProgressChanged(object sender, ProgressChangedEventArgs e) { var state = (string)e.UserState; if (!string.IsNullOrEmpty(state)) { label4.Text = state; } progressBar1.Value = e.ProgressPercentage; } private void checkBox2_CheckedChanged(object sender, EventArgs e) { if (checkBox2.Checked) { checkBox3.Enabled = true; checkBox10.Enabled = true; checkBox11.Enabled = true; } else { checkBox3.Enabled = false; checkBox10.Enabled = false; checkBox11.Enabled = false; } if (checkBox2.Checked || checkBox1.Checked) { checkBox9.Enabled = true; } else { checkBox9.Enabled = false; } } private void button1_Click(object sender, EventArgs e) { UpdateConfiguration(); if (Managers.ConfigurationManager.OutputDirectory != null) { label4.Show(); button1.Enabled = false; exportworker.RunWorkerAsync(); } else { throw new Exception("No output direcotry set"); } } private void checkBox6_CheckedChanged(object sender, EventArgs e) { if (checkBox6.Checked) { comboBox1.Enabled = true; if (comboBox1.SelectedIndex > 1) { checkBox8.Enabled = true; } } else { comboBox1.Enabled = false; checkBox8.Enabled = false; } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedIndex > 1 && comboBox1.SelectedIndex != 4) { checkBox8.Enabled = true; } else { checkBox8.Enabled = false; } } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked || checkBox2.Checked) { checkBox9.Enabled = true; } else { checkBox9.Enabled = false; } } private void checkBox5_CheckedChanged(object sender, EventArgs e) { if (checkBox5.Checked) { checkBox12.Enabled = true; checkBox13.Enabled = true; } else { checkBox12.Enabled = false; checkBox13.Enabled = false; } } private void checkBox14_CheckedChanged(object sender, EventArgs e) { if (checkBox14.Checked) { checkBox15.Enabled = true; } else { checkBox15.Enabled = false; } } } }
35.387692
161
0.53178
[ "MIT" ]
izzyus/WoWExport
WoWExport/WoWExport/Form_ADTExport.cs
11,503
C#
#if URP using UnityEngine.Rendering.Universal; #endif using UnityEditor.Rendering; namespace SCPE { #if URP [VolumeComponentEditor(typeof(DoubleVision))] sealed class DoubleVisionEditor : VolumeComponentEditor { SerializedDataParameter mode; SerializedDataParameter intensity; private bool isSetup; public override void OnEnable() { base.OnEnable(); var o = new PropertyFetcher<DoubleVision>(serializedObject); isSetup = AutoSetup.ValidEffectSetup<DoubleVisionRenderer>(); mode = Unpack(o.Find(x => x.mode)); intensity = Unpack(o.Find(x => x.intensity)); } public override void OnInspectorGUI() { SCPE_GUI.DisplayDocumentationButton("double-vision"); SCPE_GUI.DisplaySetupWarning<DoubleVisionRenderer>(ref isSetup); PropertyField(mode); PropertyField(intensity); } } } #endif
23.95122
76
0.635438
[ "MIT" ]
Walter-Hulsebos/Adrift
Assets/SC Post Effects/Editor/Editors/DoubleVisionEditor.cs
984
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions { internal abstract class AbstractSnippetFunctionSimpleTypeName : AbstractSnippetFunction { private readonly string _fieldName; private readonly string _fullyQualifiedName; public AbstractSnippetFunctionSimpleTypeName( AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName ) : base(snippetExpansionClient, subjectBuffer) { _fieldName = fieldName; _fullyQualifiedName = fullyQualifiedName; } protected abstract bool TryGetSimplifiedTypeName( Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName ); protected override void GetDefaultValue( CancellationToken cancellationToken, out string value, out bool hasCurrentValue ) { value = _fullyQualifiedName; hasCurrentValue = true; if (!TryGetDocument(out var document)) { throw new System.Exception(); } if ( !TryGetDocumentWithFullyQualifiedTypeName( document, out var updatedTextSpan, out var documentWithFullyQualifiedTypeName ) ) { throw new System.Exception(); } if ( !TryGetSimplifiedTypeName( documentWithFullyQualifiedTypeName, updatedTextSpan, cancellationToken, out var simplifiedName ) ) { throw new System.Exception(); } value = simplifiedName; hasCurrentValue = true; } private bool TryGetDocumentWithFullyQualifiedTypeName( Document document, out TextSpan updatedTextSpan, [NotNullWhen(returnValue: true)] out Document? documentWithFullyQualifiedTypeName ) { documentWithFullyQualifiedTypeName = null; updatedTextSpan = default; Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var surfaceBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan( _fieldName ); if ( !_snippetExpansionClient.TryGetSubjectBufferSpan( surfaceBufferFieldSpan, out var subjectBufferFieldSpan ) ) { return false; } var originalTextSpan = new TextSpan( subjectBufferFieldSpan.Start, subjectBufferFieldSpan.Length ); updatedTextSpan = new TextSpan( subjectBufferFieldSpan.Start, _fullyQualifiedName.Length ); var textChange = new TextChange(originalTextSpan, _fullyQualifiedName); var newText = document .GetTextSynchronously(CancellationToken.None) .WithChanges(textChange); documentWithFullyQualifiedTypeName = document.WithText(newText); return true; } } }
32.795082
95
0.594601
[ "MIT" ]
belav/roslyn
src/EditorFeatures/Core.Cocoa/Snippets/SnippetFunctions/AbstractSnippetFunctionSimpleTypeName.cs
4,003
C#
namespace Vurdalakov.WebSequenceDiagrams { using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Timers; using System.Windows; using System.Windows.Input; using System.Windows.Media.Imaging; using Microsoft.Win32; using LibGit2Sharp; public class MainViewModel : ViewModelBase { private String _wsdScript; public String WsdScript { get { return this._wsdScript; } set { if (value != this._wsdScript) { this._wsdScript = value; this.OnPropertyChanged(() => this.WsdScript); this._timer.Stop(); this._timer.Start(); } } } public String LoadWsdScript { get; private set; } private void SetWsdScript(String wsdScript) { this.LoadWsdScript = wsdScript; this.OnPropertyChanged(() => this.LoadWsdScript); } public WebSequenceDiagramsStyle Style { get { return (WebSequenceDiagramsStyle)this._settings.Get("WsdStyle", WebSequenceDiagramsStyle.Default); } set { if (value != this.Style) { this._settings.Set("WsdStyle", value); this.OnPropertyChanged(() => value); this.Refresh(); } } } private Int32 _currentLine = 1; public Int32 CurrentLine { get { return this._currentLine; } set { if (value != this._currentLine) { this._currentLine = value; this.OnPropertyChanged(() => this.CurrentLine); } } } private Int32 _currentColumn = 1; public Int32 CurrentColumn { get { return this._currentColumn; } set { if (value != this._currentColumn) { this._currentColumn = value; this.OnPropertyChanged(() => this.CurrentColumn); } } } private Boolean _setFocusOnScript = false; public Boolean SetFocusOnScript { get { return this._setFocusOnScript; } set { if (value != this._setFocusOnScript) { this._setFocusOnScript = value; this.OnPropertyChanged(() => this.SetFocusOnScript); } } } public Int32 MainWindowLeft { get { return this._settings.Get("MainWindowLeft", 64); } set { if (value != this.MainWindowLeft) { this._settings.Set("MainWindowLeft", value); this.OnPropertyChanged(() => this.MainWindowLeft); } } } public Int32 MainWindowTop { get { return this._settings.Get("MainWindowTop", 64); } set { if (value != this.MainWindowTop) { this._settings.Set("MainWindowTop", value); this.OnPropertyChanged(() => this.MainWindowWidth); } } } public Int32 MainWindowWidth { get { return this._settings.Get("MainWindowWidth", 1024); } set { if (value != this.MainWindowWidth) { this._settings.Set("MainWindowWidth", value); this.OnPropertyChanged(() => this.MainWindowWidth); } } } public Int32 MainWindowHeight { get { return this._settings.Get("MainWindowHeight", 768); } set { if (value != this.MainWindowHeight) { this._settings.Set("MainWindowHeight", value); this.OnPropertyChanged(() => this.MainWindowHeight); } } } private String GetFileTitle() { return null == this.ScriptFilePath ? "<New File>" : Path.GetFileName(this.ScriptFilePath); } public String MainWindowTitle { get { return String.Format("{0} - {1} {2}", this.ApplicationTitleAndVersion, this.GetFileTitle(), this.DirtyFlag ? "*" : ""); } } public String ScriptFileName { get; private set; } private String _scriptFilePath; public String ScriptFilePath { get { return this._scriptFilePath; } set { if (value != this._scriptFilePath) { this._scriptFilePath = value; this.OnPropertyChanged(() => this.ScriptFilePath); this.ScriptFileName = Path.GetFileName(this._scriptFilePath); this.OnPropertyChanged(() => this.ScriptFileName); this.OnPropertyChanged(() => this.MainWindowTitle); } } } private Boolean _dirtyFlag = false; public Boolean DirtyFlag { get { return this._dirtyFlag; } set { if (value != this._dirtyFlag) { this._dirtyFlag = value; this.OnPropertyChanged(() => this.DirtyFlag); this.OnPropertyChanged(() => this.MainWindowTitle); } } } public BitmapImage WsdImage { get; private set; } private Int32 _actualWsdImageWidth; public Int32 ActualWsdImageWidth { get { return this._actualWsdImageWidth; } set { if (value != this._actualWsdImageWidth) { this._actualWsdImageWidth = value; this.OnPropertyChanged(() => this.ActualWsdImageWidth); this.OnPropertyChanged(() => this.WsdImageWidth); } } } public Int32 WsdImageWidth { get { return Convert.ToInt32((float)this.ActualWsdImageWidth * this.Zoom / 100.0); } } private Int32 _zoom = 100; public Int32 Zoom { get { return this._zoom; } set { if (value != this._zoom) { this._zoom = value; this.OnPropertyChanged(() => this.Zoom); this.OnPropertyChanged(() => this.WsdImageWidth); } } } public Boolean SyntaxHighlighting { get { return this._settings.Get("SyntaxHighlighting", true); } set { if (value != this.SyntaxHighlighting) { this._settings.Set("SyntaxHighlighting", value); this.OnPropertyChanged(() => this.SyntaxHighlighting); this.OnPropertyChanged(() => this.SyntaxHighlightingFromResource); } } } public String ApiKey { get { return this._settings.Get("ApiKey", null); } set { if (value != this.ApiKey) { this._settings.Set("ApiKey", value); } } } public Boolean OpenLastEditedFileOnStartup { get { return this._settings.Get("OpenLastEditedFileOnStartup", false); } set { this._settings.Set("OpenLastEditedFileOnStartup", value); } } public String NewFileContent { get { return this._settings.Get("NewFileContent", "title Simple Sequence Diagram\r\nClient->Server: send request\r\nServer-->Client: return response").Replace("$$$$$", Environment.NewLine); } set { this._settings.Set("NewFileContent", value.Replace(Environment.NewLine, "$$$$$")); } } public String SyntaxHighlightingFromResource { get { return this.SyntaxHighlighting ? "Vurdalakov.WebSequenceDiagrams.SyntaxHighlighting.WebSequenceDiagrams.xshd" : null; } } public RecentFiles RecentFilesMenuItems { get; private set; } public ThreadSafeObservableCollection<MenuItemViewModel> PluginMenuItems { get; private set; } public ThreadSafeObservableCollection<ErrorViewModel> Errors { get; private set; } private PermanentSettings _settings; private Timer _timer; public MainViewModel(Window window) : base(window) { this._settings = new PermanentSettings(); // File this.FileNewCommand = new CommandBase(this.OnFileNewCommand); this.FileOpenCommand = new CommandBase(this.OnFileOpenCommand); this.FileOpenRecentCommand = new CommandBase<String>(this.OnFileOpenRecentCommand); this.FileSaveCommand = new CommandBase(this.OnFileSaveCommand); this.FileSaveAsCommand = new CommandBase(this.OnFileSaveAsCommand); this.FileSaveImageAsCommand = new CommandBase(this.OnFileSaveImageAsCommand); this.FileExportImageAsCommand = new CommandBase(this.OnFileExportImageAsCommand); this.ExitCommand = new CommandBase(this.OnExitCommand); // Edit // View this.ViewZoom100Command = new CommandBase(this.OnViewZoom100Command); this.ViewZoomInCommand = new CommandBase(this.OnViewZoomInCommand); this.ViewZoomOutCommand = new CommandBase(this.OnViewZoomOutCommand); this.RefreshCommand = new CommandBase(this.OnRefreshCommand); // Style // Git this.GitAddCommand = new CommandBase(this.OnGitAddCommand); this.GitCommitCommand = new CommandBase(this.OnGitCommitCommand); this.GitPushCommand = new CommandBase(this.OnGitPushCommand); this.GitPullCommand = new CommandBase(this.OnGitPullCommand); this.GitCommandLineCommand = new CommandBase(this.OnGitCommandLineCommand); this.GitExtensionsBrowseCommand = new CommandBase(this.OnGitExtensionsBrowseCommand); // Plugins // Tools this.ToolsOptionsCommand = new CommandBase(this.OnToolsOptionsCommand); // Help this.AboutCommand = new CommandBase(this.OnAboutCommand); this.ErrorSelectedCommand = new CommandBase<Int32>(OnErrorSelectedCommand); this.Errors = new ThreadSafeObservableCollection<ErrorViewModel>(); this._timer = new Timer(1000); this._timer.Elapsed += OnTimerElapsed; this.RecentFilesMenuItems = new RecentFiles(this._settings, this.FileOpenRecentCommand); this.PluginMenuItems = new ThreadSafeObservableCollection<MenuItemViewModel>(); var plugins = PluginManager.FindPlugins(); foreach (var plugin in plugins) { this.PluginMenuItems.Add(new MenuItemViewModel(plugin.GetMenuName(), new CommandBase(() => this.WsdScript = plugin.ModifyScript(this.WsdScript)))); } } public override void OnMainWindowLoaded() { var args = Environment.GetCommandLineArgs(); if (args.Length > 1) { if (!OpenFile(args[1])) { this.FileNewCommand.Execute(null); } return; } var lastEditedFile = this.RecentFilesMenuItems.GetMostRecentFile(); if (!this.OpenLastEditedFileOnStartup || String.IsNullOrEmpty(lastEditedFile) || !OpenFile(lastEditedFile)) { this.FileNewCommand.Execute(null); } } public override Boolean OnMainWindowClosing() { return !ConfirmSave(); } public ICommand FileNewCommand { get; private set; } public void OnFileNewCommand() { if (!ConfirmSave()) { return; } this.ScriptFilePath = null; this.OnPropertyChanged(() => this.MainWindowTitle); this.GitCheckFile(null); SetWsdScript(this.NewFileContent); } public ICommand FileOpenCommand { get; private set; } public void OnFileOpenCommand() { if (!this.ConfirmSave()) { return; } var dlg = new OpenFileDialog(); dlg.AddExtension = true; dlg.CheckFileExists = true; dlg.CheckPathExists = true; dlg.DefaultExt = ".wsd"; dlg.Filter = "WSD Files (*.wsd)|*.wsd|All Files (*.*)|*.*"; dlg.InitialDirectory = this._settings.Get("CurrentDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal)); if ((Boolean)dlg.ShowDialog()) { this.OpenFile(dlg.FileName); } } public ICommand FileOpenRecentCommand { get; private set; } public void OnFileOpenRecentCommand(String fileName) { if (!this.OpenFile(fileName)) { this.RecentFilesMenuItems.RemoveFile(fileName); } } private Boolean OpenFile(String fileName) { try { SetWsdScript(File.ReadAllText(fileName)); this.ScriptFilePath = fileName; this.RecentFilesMenuItems.AddFile(fileName); this._settings.Set("CurrentDirectory", Path.GetDirectoryName(fileName)); this.GitCheckFile(fileName); return true; } catch (Exception ex) { MsgBox.Error(ex, "Cannot open file\n{0}", fileName); return false; } } public ICommand FileSaveCommand { get; private set; } public void OnFileSaveCommand() { if (this._scriptFilePath != null) { File.WriteAllText(this._scriptFilePath, this.WsdScript); this.DirtyFlag = false; this.GitCheckFile(this._scriptFilePath); } } public ICommand FileSaveAsCommand { get; private set; } public void OnFileSaveAsCommand() { SaveFileAs(); } public Boolean SaveFileAs() { var dlg = new SaveFileDialog(); dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.DefaultExt = ".wsd"; dlg.Filter = "WSD Files (*.wsd)|*.wsd"; dlg.InitialDirectory = this._settings.Get("CurrentDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal)); dlg.OverwritePrompt = true; if ((Boolean)dlg.ShowDialog()) { this.ScriptFilePath = dlg.FileName; try { File.WriteAllText(this.ScriptFilePath, this.WsdScript); this.DirtyFlag = false; this.RecentFilesMenuItems.AddFile(dlg.FileName); this._settings.Set("CurrentDirectory", Path.GetDirectoryName(dlg.FileName)); this.GitCheckFile(dlg.FileName); return true; } catch (Exception ex) { MsgBox.Error(ex, "Cannot save file", dlg.FileName); return false; } } return false; } private Boolean ConfirmSave() { if (!this.DirtyFlag) { return true; } switch (MessageBox.Show(Application.Current.MainWindow, String.Format("Save file {0}?", this.GetFileTitle()), "Save", MessageBoxButton.YesNoCancel, MessageBoxImage.Question)) { case MessageBoxResult.No: return true; case MessageBoxResult.Cancel: return false; } if (null == this.ScriptFilePath) { return SaveFileAs(); } else { this.FileSaveCommand.Execute(null); return true; } } public ICommand FileSaveImageAsCommand { get; private set; } public void OnFileSaveImageAsCommand() { var dlg = new SaveFileDialog(); dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.Filter = "Windows Bitmap (*.bmp)|*.bmp|Graphics Interchange Format (*.gif)|*.gif|JPEG / JFIF (*.jpg)|*.jpg|Portable Network Graphics (*.png)|*.png|Tagged Image File Format (*.tiff)|*.tiff"; dlg.FilterIndex = this._settings.Get("FileSaveImageAsFilterIndex", 3); dlg.InitialDirectory = this._settings.Get("CurrentDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal)); dlg.OverwritePrompt = true; if ((Boolean)dlg.ShowDialog()) { try { this._webSequenceDiagramsResult.SaveImage(dlg.FileName, dlg.FilterIndex); this._settings.Set("CurrentDirectory", Path.GetDirectoryName(dlg.FileName)); this._settings.Set("FileSaveImageAsFilterIndex", dlg.FilterIndex); } catch (Exception ex) { MsgBox.Error(ex, "Cannot export image to\n{0}", dlg.FileName); } } } public ICommand FileExportImageAsCommand { get; private set; } public void OnFileExportImageAsCommand() { var dlg = new SaveFileDialog(); dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.Filter = "Portable Network Graphics (*.png)|*.png|Portable Document Format (*.pdf)|*.pdf|Scalable Vector Graphics (*.svg)|*.svg"; dlg.FilterIndex = this._settings.Get("FileExportImageAsFilterIndex", 1); dlg.InitialDirectory = this._settings.Get("CurrentDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal)); dlg.OverwritePrompt = true; if ((Boolean)dlg.ShowDialog()) { try { var format = ""; switch (dlg.FilterIndex) { case 1: format = "png"; break; case 2: format = "pdf"; break; case 3: format = "svg"; break; default: throw new ArgumentException("Unsupported output format"); } var webSequenceDiagramsResult = WebSequenceDiagrams.DownloadDiagram(this._wsdScript, this.Style.ToString().ToLower().Replace('_', '-'), format, this.ApiKey); webSequenceDiagramsResult.SaveFile(dlg.FileName); this._settings.Set("CurrentDirectory", Path.GetDirectoryName(dlg.FileName)); this._settings.Set("FileExportImageAsFilterIndex", dlg.FilterIndex); } catch (Exception ex) { MsgBox.Error(ex, "Cannot export image to\n{0}", dlg.FileName); } } } public ICommand ExitCommand { get; private set; } public void OnExitCommand() { Application.Current.MainWindow.Close(); } public ICommand ViewZoom100Command { get; private set; } public void OnViewZoom100Command() { this.Zoom = 100; } public ICommand ViewZoomInCommand { get; private set; } public void OnViewZoomInCommand() { if (this.Zoom < 800) { this.Zoom *= 2; } } public ICommand ViewZoomOutCommand { get; private set; } public void OnViewZoomOutCommand() { if (this.Zoom > 25) { this.Zoom /= 2; } } public ICommand RefreshCommand { get; private set; } public void OnRefreshCommand() { this.Refresh(); } public ICommand AboutCommand { get; private set; } public void OnAboutCommand() { var aboutWindow = new AboutWindow(Application.Current.MainWindow); aboutWindow.ShowDialog(); } public ICommand ToolsOptionsCommand { get; private set; } public void OnToolsOptionsCommand() { var optionsWindow = new OptionsWindow(Application.Current.MainWindow, this); optionsWindow.ShowDialog(); } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { this._timer.Stop(); this.Refresh(); } private WebSequenceDiagramsResult _webSequenceDiagramsResult; private String refreshStatus; public String RefreshStatus { get { return this.refreshStatus; } set { if (value != this.refreshStatus) { this.refreshStatus = value; this.OnPropertyChanged(() => this.RefreshStatus); } } } private void Refresh() { RefreshStatus = "Updating image..."; var task = Task.Factory.StartNew(() => this._webSequenceDiagramsResult = WebSequenceDiagrams.DownloadDiagram(this._wsdScript, this.Style.ToString().ToLower().Replace('_', '-'), "png", this.ApiKey)); task.ContinueWith(t => { this.Errors.Clear(); if (task.Exception != null) { RefreshStatus = "Error(s) detected"; var ex = task.Exception.InnerException; if (ex is WebSequenceDiagramsException) { foreach (var error in (ex as WebSequenceDiagramsException).Errors) { this.Errors.Add(new ErrorViewModel(error.Line, error.Message)); } } else { this.Errors.Add(new ErrorViewModel(0, ex.Message)); } } else { RefreshStatus = "Ready"; } this.WsdImage = this._webSequenceDiagramsResult.GetBitmapImage(); this.OnPropertyChanged(() => this.WsdImage); this.ActualWsdImageWidth = this._webSequenceDiagramsResult.ActualImageWidth; }); } private void DownloadImage() { this._webSequenceDiagramsResult = WebSequenceDiagrams.DownloadDiagram(this._wsdScript, this.Style.ToString().ToLower().Replace('_', '-'), "png", this.ApiKey); } public ICommand ErrorSelectedCommand { get; private set; } private void OnErrorSelectedCommand(Int32 lineNumber) { this.CurrentLine = lineNumber; this.CurrentColumn = 1; this.SetFocusOnScript = false; this.SetFocusOnScript = true; } #region Git support private GitViewModel gitViewModel; public String GitExtensionsPathName { get; private set; } public Boolean GitFileInRepo { get; private set; } public Boolean GitFileAdd { get; private set; } public Boolean GitFileCommit { get; private set; } public Boolean GitRemoteAvailable { get; private set; } private void GitCheckFile(String fileName) { // GitFileInRepo this.GitFileInRepo = false; if (!String.IsNullOrEmpty(fileName) && File.Exists(fileName)) { try { this.gitViewModel = new GitViewModel(fileName); this.GitFileInRepo = true; var fileStatus = this.gitViewModel.GetFileStatus(fileName); this.GitFileAdd = FileStatus.NewInWorkdir == fileStatus; this.OnPropertyChanged(() => this.GitFileAdd); this.GitFileCommit = FileStatus.ModifiedInWorkdir == fileStatus; this.OnPropertyChanged(() => this.GitFileCommit); this.GitRemoteAvailable = this.gitViewModel.AreRemotesAvailable(); this.OnPropertyChanged(() => this.GitRemoteAvailable); } catch { } } this.OnPropertyChanged(() => this.GitFileInRepo); // GitExtensionsAvailable this.GitExtensionsPathName = null; try { var gitExtensionsPathName = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\GitExtensions\"). GetValue("InstallDir", null, RegistryValueOptions.None) as String; if (!String.IsNullOrEmpty(gitExtensionsPathName)) { gitExtensionsPathName = Path.Combine(gitExtensionsPathName , "GitExtensions.exe"); if (File.Exists(gitExtensionsPathName)) { this.GitExtensionsPathName = gitExtensionsPathName; } } } catch { } this.OnPropertyChanged(() => this.GitExtensionsPathName); } public ICommand GitAddCommand { get; private set; } private void OnGitAddCommand() { try { var commitMessage = this.gitViewModel.ShowCommitMessageDialog("Add File"); if (!String.IsNullOrEmpty(commitMessage)) { this.gitViewModel.AddFile(this.ScriptFilePath, commitMessage); this.GitCheckFile(this.ScriptFilePath); } } catch (Exception ex) { MsgBox.Error(ex, "Cannot add file to repository:"); } } public ICommand GitCommitCommand { get; private set; } private void OnGitCommitCommand() { try { var commitMessage = this.gitViewModel.ShowCommitMessageDialog("Commit"); if (!String.IsNullOrEmpty(commitMessage)) { this.gitViewModel.CommitFile(this.ScriptFilePath, commitMessage); this.GitCheckFile(this.ScriptFilePath); } } catch (Exception ex) { MsgBox.Error(ex, "Cannot commit to repository:"); } } public ICommand GitPushCommand { get; private set; } private void OnGitPushCommand() { try { if (this.gitViewModel.ShowRemoteDialog("Push")) { this.gitViewModel.Push(this.gitViewModel.RemoteName, this.gitViewModel.BranchName, this.gitViewModel.UserName, this.gitViewModel.Password); } } catch (Exception ex) { MsgBox.Error(ex, "Cannot push to repository:"); } } public ICommand GitPullCommand { get; private set; } private void OnGitPullCommand() { try { if (this.gitViewModel.ShowRemoteDialog("Pull")) { this.gitViewModel.Pull(this.gitViewModel.UserName, this.gitViewModel.Password); } } catch (Exception ex) { MsgBox.Error(ex, "Cannot pull from repository:"); } } public ICommand GitCommandLineCommand { get; private set; } private void OnGitCommandLineCommand() { try { var processStartInfo = new ProcessStartInfo("cmd.exe", "/k dir *.wsd /d"); processStartInfo.WorkingDirectory = Path.GetDirectoryName(this.ScriptFilePath); Process.Start(processStartInfo); } catch (Exception ex) { MsgBox.Error(ex, "Cannot start Git command line:"); } } public ICommand GitExtensionsBrowseCommand { get; private set; } private void OnGitExtensionsBrowseCommand() { try { var processStartInfo = new ProcessStartInfo(this.GitExtensionsPathName, "browse"); processStartInfo.WorkingDirectory = this.gitViewModel.Repository.Info.WorkingDirectory; Process.Start(processStartInfo); } catch (Exception ex) { MsgBox.Error(ex, "Cannot start GitExtensions Browse:"); } } #endregion } }
32.654877
210
0.507927
[ "MIT" ]
vurdalakov/websequencediagrams
src/WebSequenceDiagrams/MainViewModel.cs
30,469
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using OpenTK.Mathematics; using OpenTK.Graphics.OpenGL; using OTKVoxelEngine.Engine; namespace OTKVoxelEngine.Renderer { public class Mesh { // PUBLIC: public List<Vertex> vertices = new List<Vertex>(); public List<uint> indices = new List<uint>(); public List<Texture> textures = new List<Texture>(); public Color4 col = Color4.DarkGreen; public Vector3 pos = new Vector3(0,0,0); public Mesh(List<Vertex> _verts, List<uint> _indc, List<Texture> _texs) { vertices = _verts; indices = _indc; textures = _texs; setupMesh(); } public void Draw(Shader shad) { GL.BindVertexArray(VAO); //shad.SetVector3("pos", pos); shad.SetMatrix4("model", Matrix4.Identity * Matrix4.CreateTranslation(pos)); shad.SetVector3("inColor", ((Vector4)col).Xyz); GL.DrawElements(PrimitiveType.Triangles, indices.Count, DrawElementsType.UnsignedInt, 0); GL.BindVertexArray(0); } /// <summary> /// Generates a 1x1x1 cube. /// </summary> /// <returns>A cube mesh.</returns> public static Mesh GenCubeMesh() { List<Vertex> vertices = new List<Vertex>(); vertices.Add(new Vertex(new Vector3(-1, -1, -1))); vertices.Add(new Vertex(new Vector3(1, -1, -1))); vertices.Add(new Vertex(new Vector3(1, 1, -1))); vertices.Add(new Vertex(new Vector3(-1, 1, -1))); vertices.Add(new Vertex(new Vector3(-1, -1, 1))); vertices.Add(new Vertex(new Vector3(1, -1, 1))); vertices.Add(new Vertex(new Vector3(1, 1, 1))); vertices.Add(new Vertex(new Vector3(-1, 1, 1))); List<uint> indices = new List<uint> { 0, 1, 3, 3, 1, 2, 1, 5, 2, 2, 5, 6, 5, 4, 6, 6, 4, 7, 4, 0, 7, 7, 0, 3, 3, 2, 7, 7, 2, 6, 4, 5, 0, 0, 5, 1 }; Mesh msh = new Mesh ( vertices, indices, new List<Texture>() ); return msh; } // PRIVATE: private uint VAO, VBO, EBO; private unsafe void setupMesh() { GL.GenVertexArrays(1, out VAO); GL.GenBuffers(1, out VBO); GL.GenBuffers(1, out EBO); GL.BindVertexArray(VAO); GL.BindBuffer(BufferTarget.ArrayBuffer, VBO); IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(vertices.ToArray(), 0); IntPtr indiPtr = Marshal.UnsafeAddrOfPinnedArrayElement(indices.ToArray(), 0); GL.BufferData(BufferTarget.ArrayBuffer, vertices.Count * Marshal.SizeOf(typeof(Vertex)), intPtr, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ElementArrayBuffer, EBO); GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Count * sizeof(uint), indiPtr, BufferUsageHint.StaticDraw); GL.EnableVertexAttribArray(0); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, sizeof(Vertex), 0); GL.EnableVertexAttribArray(1); GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, sizeof(Vertex), Marshal.OffsetOf(typeof(Vertex), "normal")); GL.EnableVertexAttribArray(2); GL.VertexAttribPointer(2, 3, VertexAttribPointerType.Float, false, sizeof(Vertex), Marshal.OffsetOf(typeof(Vertex), "texCoords")); GL.BindVertexArray(0); } } }
36.850467
143
0.554147
[ "Apache-2.0" ]
Carcass-Project/OTKVoxelEngine
OTKVoxelEngine/Renderer/Mesh.cs
3,945
C#
using System; namespace BioWorld.Application.Category.Commands.CreateCategory { public class CreateCategoryDto { public Guid Id { get; set; } public string RouteName { get; set; } public string DisplayName { get; set; } public string Note { get; set; } } }
25.166667
63
0.639073
[ "MIT" ]
Zhilong-Yang/BioWorldBlog
BioWorld.Application/Category/Commands/CreateCategory/CreateCategoryDto.cs
304
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 BasicUsage { 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.076923
61
0.661667
[ "MIT" ]
304NotModified/ApplicationInsights-Kubernetes
examples/BasicUsage/Program.cs
602
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace VideoLibrary.WebUi.Models.AccountViewModels { public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }
23.538462
53
0.650327
[ "MIT" ]
evant123/VideoLibrary
VideoLibrary.WebUi/VideoLibrary.WebUi/Models/AccountViewModels/VerifyCodeViewModel.cs
614
C#
// <copyright file="HandleParallelMessageOptions.cs" company="nett"> // Copyright (c) 2015 All Right Reserved, http://q.nett.gr // Please see the License.txt file for more information. All other rights reserved. // </copyright> // <author>James Kavakopoulos</author> // <email>ofthetimelords@gmail.com</email> // <date>2015/02/06</date> // <summary> // // </summary> using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using TheQ.Utilities.CloudTools.Storage.ExtendedQueue; using TheQ.Utilities.CloudTools.Storage.Internal; namespace TheQ.Utilities.CloudTools.Storage.Models { /// <summary> /// <para>Input arguments for the ExtendedQueue framework.</para> /// </summary> public class HandleMessagesParallelOptions : HandleMessagesSerialOptions { /// <summary> /// <para>Initializes a new instance of the <see cref="HandleMessagesParallelOptions" /></para> /// <para>class.</para> /// </summary> /// <param name="timeWindow"> /// <para>The time window within which a message is still valid for processing (older messages will be discarded). Use <see cref="System.TimeSpan.Zero" /></para> /// <para>to ignore this check.</para> /// </param> /// <param name="messageLeaseTime">The amount of time between periodic refreshes on the lease of a message.</param> /// <param name="pollFrequency">The frequency with which the queue is being polled for new messages.</param> /// <param name="poisonMessageThreshold">The amount of times a message can be enqueued.</param> /// <param name="maximumCurrentMessages">The maximum amount of messages that can be processed at the same batch.</param> /// <param name="cancelToken">A cancellation token to allow cancellation of this process.</param> /// <param name="messageHandler">An action that specifies how a message should be handled. Returns a value indicating whether the message has been handled successfully and should be removed.</param> /// <param name="poisonHandler"> /// <para>An action that specifies how a poison message should be handled, which fires before <see cref="TheQ.Utilities.CloudTools.Storage.Models.HandleSerialOptions.MessageHandler" /></para> /// <para>. Returns a value indicating whether the message has been handled successfully and should be removed.</para> /// </param> /// <param name="exceptionHandler">An action that specifies how an exception should be handled.</param> /// <exception cref="ArgumentException">Parameter <paramref name="maximumCurrentMessages" /> exceeded 32 which is the maximum allowed value by Azure</exception> /// <exception cref="ArgumentNullException">cancelToken;The Cancellation Token parameter is required or messageHandler;The Message Handler <see langword="delegate" /> is required</exception> /// <exception cref="ArgumentException"> /// Message Lease Time cannot be lower than 30 seconds! or Poll Frequency cannot be lower than 1 second! or Poison Message Threshold cannot be lower than 1. /// </exception> public HandleMessagesParallelOptions( TimeSpan timeWindow, TimeSpan messageLeaseTime, TimeSpan pollFrequency, int poisonMessageThreshold, int maximumCurrentMessages, CancellationToken cancelToken, [NotNull] Func<QueueMessageWrapper, Task<bool>> messageHandler, [CanBeNull] Func<QueueMessageWrapper, Task<bool>> poisonHandler = null, [CanBeNull] Action<Exception> exceptionHandler = null) : base(timeWindow, messageLeaseTime, pollFrequency, poisonMessageThreshold, cancelToken, messageHandler, poisonHandler, exceptionHandler) { this.MaximumCurrentMessages = maximumCurrentMessages; } /// <summary> /// Gets the maximum amount of messages that can be processed at the same batch. /// </summary> public int MaximumCurrentMessages { get; private set; } } }
51.373333
200
0.740722
[ "MIT" ]
ofthetimelords/CloudTools
TheQ.Utilities.CloudTools/Models/HandleMessagesParallelOptions.cs
3,855
C#
namespace DeleteUnusedTextNoteTypes { partial class TextNotesForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TextNotesForm)); this.clbUnused = new System.Windows.Forms.CheckedListBox(); this.lbxUsedTypes = new System.Windows.Forms.ListBox(); this.btnAll = new System.Windows.Forms.Button(); this.btnNone = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.lblItemsChecked = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lblTotalItems = new System.Windows.Forms.Label(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.lblUsed = new System.Windows.Forms.Label(); this.lblUnused = new System.Windows.Forms.Label(); this.lblTotalUsed = new System.Windows.Forms.Label(); this.lblTotalUnused = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.LblLineSeparator = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.CheckButton = new System.Windows.Forms.ToolTip(this.components); this.panel1.SuspendLayout(); this.panel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // clbUnused // this.clbUnused.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.clbUnused.CheckOnClick = true; this.clbUnused.FormattingEnabled = true; this.clbUnused.HorizontalScrollbar = true; this.clbUnused.IntegralHeight = false; this.clbUnused.Location = new System.Drawing.Point(295, 100); this.clbUnused.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.clbUnused.Name = "clbUnused"; this.clbUnused.Size = new System.Drawing.Size(255, 325); this.clbUnused.TabIndex = 0; this.clbUnused.SelectedIndexChanged += new System.EventHandler(this.clbUnused_SelectedIndexChanged); // // lbxUsedTypes // this.lbxUsedTypes.BackColor = System.Drawing.SystemColors.ButtonFace; this.lbxUsedTypes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lbxUsedTypes.ForeColor = System.Drawing.SystemColors.InfoText; this.lbxUsedTypes.FormattingEnabled = true; this.lbxUsedTypes.ItemHeight = 17; this.lbxUsedTypes.Location = new System.Drawing.Point(20, 100); this.lbxUsedTypes.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.lbxUsedTypes.Name = "lbxUsedTypes"; this.lbxUsedTypes.SelectionMode = System.Windows.Forms.SelectionMode.None; this.lbxUsedTypes.Size = new System.Drawing.Size(255, 325); this.lbxUsedTypes.Sorted = true; this.lbxUsedTypes.TabIndex = 4; this.lbxUsedTypes.SelectedIndexChanged += new System.EventHandler(this.lbxUsedTypes_SelectedIndexChanged); // // btnAll // this.btnAll.FlatAppearance.BorderSize = 0; this.btnAll.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(172)))), ((int)(((byte)(0))))); this.btnAll.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnAll.Image = ((System.Drawing.Image)(resources.GetObject("btnAll.Image"))); this.btnAll.Location = new System.Drawing.Point(550, 100); this.btnAll.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.btnAll.Name = "btnAll"; this.btnAll.Size = new System.Drawing.Size(50, 35); this.btnAll.TabIndex = 5; this.CheckButton.SetToolTip(this.btnAll, "Check All"); this.btnAll.UseVisualStyleBackColor = true; this.btnAll.Click += new System.EventHandler(this.btnAll_Click); // // btnNone // this.btnNone.FlatAppearance.BorderSize = 0; this.btnNone.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(172)))), ((int)(((byte)(0))))); this.btnNone.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnNone.Image = ((System.Drawing.Image)(resources.GetObject("btnNone.Image"))); this.btnNone.Location = new System.Drawing.Point(550, 143); this.btnNone.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.btnNone.Name = "btnNone"; this.btnNone.Size = new System.Drawing.Size(50, 35); this.btnNone.TabIndex = 6; this.CheckButton.SetToolTip(this.btnNone, "Uncheck All"); this.btnNone.UseVisualStyleBackColor = true; this.btnNone.Click += new System.EventHandler(this.btnNone_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.label1.Location = new System.Drawing.Point(20, 468); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(111, 19); this.label1.TabIndex = 7; this.label1.Text = "Items to Purge:"; // // lblItemsChecked // this.lblItemsChecked.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblItemsChecked.Location = new System.Drawing.Point(180, 468); this.lblItemsChecked.Name = "lblItemsChecked"; this.lblItemsChecked.Size = new System.Drawing.Size(40, 20); this.lblItemsChecked.TabIndex = 8; this.lblItemsChecked.Text = "0"; this.lblItemsChecked.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(20, 443); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(157, 19); this.label2.TabIndex = 9; this.label2.Text = "Total Text Note Types:"; // // lblTotalItems // this.lblTotalItems.Location = new System.Drawing.Point(180, 443); this.lblTotalItems.Name = "lblTotalItems"; this.lblTotalItems.Size = new System.Drawing.Size(40, 20); this.lblTotalItems.TabIndex = 10; this.lblTotalItems.Text = "0"; this.lblTotalItems.TextAlign = System.Drawing.ContentAlignment.TopRight; // // btnOK // this.btnOK.BackColor = System.Drawing.Color.Transparent; this.btnOK.Dock = System.Windows.Forms.DockStyle.Left; this.btnOK.FlatAppearance.BorderSize = 0; this.btnOK.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(172)))), ((int)(((byte)(0))))); this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnOK.Font = new System.Drawing.Font("Segoe UI", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnOK.ForeColor = System.Drawing.Color.White; this.btnOK.Location = new System.Drawing.Point(0, 0); this.btnOK.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(162, 60); this.btnOK.TabIndex = 11; this.btnOK.Text = "Purge"; this.btnOK.UseVisualStyleBackColor = false; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Dock = System.Windows.Forms.DockStyle.Right; this.btnCancel.FlatAppearance.BorderSize = 0; this.btnCancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(172)))), ((int)(((byte)(0))))); this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCancel.Font = new System.Drawing.Font("Segoe UI", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnCancel.ForeColor = System.Drawing.Color.White; this.btnCancel.Location = new System.Drawing.Point(440, 0); this.btnCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(162, 60); this.btnCancel.TabIndex = 12; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // lblUsed // this.lblUsed.AutoSize = true; this.lblUsed.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblUsed.Location = new System.Drawing.Point(20, 70); this.lblUsed.Name = "lblUsed"; this.lblUsed.Size = new System.Drawing.Size(46, 19); this.lblUsed.TabIndex = 13; this.lblUsed.Text = "Used:"; // // lblUnused // this.lblUnused.AutoSize = true; this.lblUnused.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblUnused.Location = new System.Drawing.Point(291, 70); this.lblUnused.Name = "lblUnused"; this.lblUnused.Size = new System.Drawing.Size(62, 19); this.lblUnused.TabIndex = 14; this.lblUnused.Text = "Unused:"; // // lblTotalUsed // this.lblTotalUsed.Location = new System.Drawing.Point(78, 70); this.lblTotalUsed.Name = "lblTotalUsed"; this.lblTotalUsed.Size = new System.Drawing.Size(65, 18); this.lblTotalUsed.TabIndex = 15; this.lblTotalUsed.Text = "0"; this.lblTotalUsed.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // lblTotalUnused // this.lblTotalUnused.Location = new System.Drawing.Point(352, 70); this.lblTotalUnused.Name = "lblTotalUnused"; this.lblTotalUnused.Size = new System.Drawing.Size(68, 18); this.lblTotalUnused.TabIndex = 16; this.lblTotalUnused.Text = "0"; this.lblTotalUnused.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // panel1 // this.panel1.BackColor = System.Drawing.Color.Gray; this.panel1.Controls.Add(this.btnOK); this.panel1.Controls.Add(this.btnCancel); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 501); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(602, 60); this.panel1.TabIndex = 17; // // panel3 // this.panel3.BackColor = System.Drawing.Color.WhiteSmoke; this.panel3.Controls.Add(this.LblLineSeparator); this.panel3.Controls.Add(this.pictureBox1); this.panel3.Dock = System.Windows.Forms.DockStyle.Top; this.panel3.Location = new System.Drawing.Point(0, 0); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(602, 50); this.panel3.TabIndex = 32; // // LblLineSeparator // this.LblLineSeparator.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.LblLineSeparator.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.LblLineSeparator.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.LblLineSeparator.ForeColor = System.Drawing.SystemColors.ControlText; this.LblLineSeparator.Location = new System.Drawing.Point(10, 40); this.LblLineSeparator.Name = "LblLineSeparator"; this.LblLineSeparator.Size = new System.Drawing.Size(578, 2); this.LblLineSeparator.TabIndex = 32; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(10, 10); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(150, 25); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // TextNotesForm // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.WhiteSmoke; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(602, 561); this.Controls.Add(this.panel3); this.Controls.Add(this.panel1); this.Controls.Add(this.lblTotalUnused); this.Controls.Add(this.lblTotalUsed); this.Controls.Add(this.lblUnused); this.Controls.Add(this.lblUsed); this.Controls.Add(this.lblTotalItems); this.Controls.Add(this.label2); this.Controls.Add(this.lblItemsChecked); this.Controls.Add(this.label1); this.Controls.Add(this.btnNone); this.Controls.Add(this.btnAll); this.Controls.Add(this.lbxUsedTypes); this.Controls.Add(this.clbUnused); this.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.MaximizeBox = false; this.MinimumSize = new System.Drawing.Size(618, 600); this.Name = "TextNotesForm"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Purge Text Note Types"; this.Load += new System.EventHandler(this.TextNotesForm_Load); this.panel1.ResumeLayout(false); this.panel3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.CheckedListBox clbUnused; private System.Windows.Forms.ListBox lbxUsedTypes; private System.Windows.Forms.Button btnAll; private System.Windows.Forms.Button btnNone; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblItemsChecked; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label lblTotalItems; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label lblUsed; private System.Windows.Forms.Label lblUnused; private System.Windows.Forms.Label lblTotalUsed; private System.Windows.Forms.Label lblTotalUnused; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Label LblLineSeparator; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.ToolTip CheckButton; } }
54.053571
163
0.611386
[ "MIT" ]
angelrps/ARP_Toolkit
2020/DeleteUnusedTextNoteTypes/VS_DeleteUnusedTextNoteTypes/Form/TextNotesForm.Designer.cs
18,164
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using SignalR.Client.Infrastructure; using SignalR.Infrastructure; namespace SignalR.Client.Http { internal static class HttpHelper { public static Task<HttpWebResponse> GetHttpResponseAsync(this HttpWebRequest request) { try { return Task.Factory.FromAsync<HttpWebResponse>(request.BeginGetResponse, ar => (HttpWebResponse)request.EndGetResponse(ar), null); } catch (Exception ex) { return TaskAsyncHelper.FromError<HttpWebResponse>(ex); } } public static Task<Stream> GetHttpRequestStreamAsync(this HttpWebRequest request) { try { return Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null); } catch (Exception ex) { return TaskAsyncHelper.FromError<Stream>(ex); } } public static Task<HttpWebResponse> GetAsync(string url) { return GetAsync(url, requestPreparer: null); } public static Task<HttpWebResponse> GetAsync(string url, Action<HttpWebRequest> requestPreparer) { HttpWebRequest request = CreateWebRequest(url); if (requestPreparer != null) { requestPreparer(request); } return request.GetHttpResponseAsync(); } public static Task<HttpWebResponse> PostAsync(string url) { return PostInternal(url, requestPreparer: null, postData: null); } public static Task<HttpWebResponse> PostAsync(string url, IDictionary<string, string> postData) { return PostInternal(url, requestPreparer: null, postData: postData); } public static Task<HttpWebResponse> PostAsync(string url, Action<HttpWebRequest> requestPreparer) { return PostInternal(url, requestPreparer, postData: null); } public static Task<HttpWebResponse> PostAsync(string url, Action<HttpWebRequest> requestPreparer, IDictionary<string, string> postData) { return PostInternal(url, requestPreparer, postData); } public static string ReadAsString(this HttpWebResponse response) { try { using (response) { using (Stream stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } } catch (Exception ex) { #if NET35 Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Failed to read response: {0}", ex)); #else Debug.WriteLine("Failed to read response: {0}", ex); #endif // Swallow exceptions when reading the response stream and just try again. return null; } } private static Task<HttpWebResponse> PostInternal(string url, Action<HttpWebRequest> requestPreparer, IDictionary<string, string> postData) { HttpWebRequest request = CreateWebRequest(url); if (requestPreparer != null) { requestPreparer(request); } byte[] buffer = ProcessPostData(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; #if !WINDOWS_PHONE && !SILVERLIGHT // Set the content length if the buffer is non-null request.ContentLength = buffer != null ? buffer.LongLength : 0; #endif if (buffer == null) { // If there's nothing to be written to the request then just get the response return request.GetHttpResponseAsync(); } // Write the post data to the request stream return request.GetHttpRequestStreamAsync() .Then(stream => stream.WriteAsync(buffer).Then(() => stream.Dispose())) .Then(() => request.GetHttpResponseAsync()); } private static byte[] ProcessPostData(IDictionary<string, string> postData) { if (postData == null || postData.Count == 0) { return null; } var sb = new StringBuilder(); foreach (var pair in postData) { if (sb.Length > 0) { sb.Append("&"); } if (String.IsNullOrEmpty(pair.Value)) { continue; } sb.AppendFormat("{0}={1}", pair.Key, UriQueryUtility.UrlEncode(pair.Value)); } return Encoding.UTF8.GetBytes(sb.ToString()); } private static HttpWebRequest CreateWebRequest(string url) { HttpWebRequest request = null; #if WINDOWS_PHONE request = (HttpWebRequest)WebRequest.Create(url); request.AllowReadStreamBuffering = false; #elif SILVERLIGHT request = (HttpWebRequest)System.Net.Browser.WebRequestCreator.ClientHttp.Create(new Uri(url)); request.AllowReadStreamBuffering = false; #else request = (HttpWebRequest)WebRequest.Create(url); #endif return request; } } }
33.517442
147
0.564614
[ "MIT" ]
Icenium/SignalR
SignalR.Client/Http/HttpHelper.cs
5,767
C#
using AO.Models.Enums; using Dapper; using Dapper.CX.Abstract; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Data; using Tests.Models; namespace Tests { public abstract class IntegrationBase<TIdentity> { protected abstract IDbConnection GetConnection(); protected abstract SqlCrudProvider<TIdentity> GetProvider(); protected void NewObjShouldBeNewBase() { var emp = GetTestEmployee(); var provider = GetProvider(); Assert.IsTrue(provider.IsNew(emp)); } protected void InsertBase() { using (var cn = GetConnection()) { Employee emp = GetTestEmployee(); var provider = GetProvider(); provider.InsertAsync(cn, emp).Wait(); Assert.IsTrue(emp.Id != default); } } protected void UpdateBase() { using (var cn = GetConnection()) { var emp = GetTestEmployee(); var provider = GetProvider(); TIdentity id = provider.InsertAsync(cn, emp).Result; const string newName = "Wonga"; emp.FirstName = newName; provider.UpdateAsync(cn, emp).Wait(); emp = provider.GetAsync<Employee>(cn, id).Result; Assert.IsTrue(emp.FirstName.Equals(newName)); } } protected void DeleteBase() { using (var cn = GetConnection()) { var emp = GetTestEmployee(); var provider = GetProvider(); TIdentity id = provider.InsertAsync(cn, emp).Result; provider.DeleteAsync<Employee>(cn, id).Wait(); emp = provider.GetAsync<Employee>(cn, id).Result; Assert.IsNull(emp); } } protected void ExistsBase() { using (var cn = GetConnection()) { var provider = GetProvider(); var emp = GetTestEmployee(); TIdentity id = provider.SaveAsync(cn, emp).Result; Assert.IsTrue(provider.ExistsAsync<Employee>(cn, id).Result); } } protected void ExistsWhereBase() { using (var cn = GetConnection()) { cn.Execute("TRUNCATE TABLE [dbo].[Employee]"); var provider = GetProvider(); var emp = GetTestEmployee(); provider.SaveAsync(cn, emp).Wait(); var criteria = new { emp.FirstName, emp.LastName }; Assert.IsTrue(provider.ExistsWhereAsync<Employee>(cn, criteria).Result); } } protected void MergeExplicitPropsBase() { using (var cn = GetConnection()) { cn.Execute("TRUNCATE TABLE [dbo].[Employee]"); var emp = GetTestEmployee(); emp.IsExempt = true; var provider = GetProvider(); TIdentity id = provider.SaveAsync(cn, emp).Result; var mergeEmp = GetTestEmployee(); mergeEmp.IsExempt = false; provider.MergeAsync(cn, mergeEmp, new string[] { nameof(Employee.FirstName), nameof(Employee.LastName) }, onSave: (action, model) => { switch (action) { case SaveAction.Insert: model.Comments = "inserting"; break; case SaveAction.Update: model.Comments = "updating"; break; } }).Wait(); var findEmp = provider.GetAsync<Employee>(cn, id).Result; Assert.IsFalse(findEmp.IsExempt); Assert.IsTrue(findEmp.Comments.Equals("updating")); } } protected void MergePKPropsBase() { using (var cn = GetConnection()) { cn.Execute("TRUNCATE TABLE [dbo].[Employee]"); var emp = GetTestEmployee(); emp.IsExempt = true; var provider = GetProvider(); TIdentity id = provider.SaveAsync(cn, emp).Result; var mergeEmp = GetTestEmployee(); mergeEmp.IsExempt = false; provider.MergeAsync(cn, mergeEmp, onSave: (action, model) => OnSave(action, model)).Wait(); var findEmp = provider.GetAsync<Employee>(cn, id).Result; Assert.IsFalse(findEmp.IsExempt); Assert.IsTrue(findEmp.Comments.Equals("updating")); void OnSave(SaveAction action, Employee model) { switch (action) { case SaveAction.Insert: model.Comments = "inserting"; break; case SaveAction.Update: model.Comments = "updating"; break; } } } } private static Employee GetTestEmployee() { return new Employee() { FirstName = "Test", LastName = "Person", HireDate = DateTime.Today, IsExempt = true }; } } }
31.005464
122
0.47233
[ "MIT" ]
adamfoneil/Dapper.CX
Tests.SqlServer/IntegrationBase.cs
5,676
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System.Threading; using System.Threading.Tasks; using Azure.Storage.Blobs; using Microsoft.Health.Blob.Configs; namespace Microsoft.Health.Blob.Features.Storage { /// <summary> /// Provides methods for performing tests against blob storage. /// </summary> public interface IBlobClientTestProvider { /// <summary> /// Performs a test against blob storage. /// </summary> /// <param name="client">Client to connect to blob storage.</param> /// <param name="blobContainerConfiguration">Configuration specific to one container.</param> /// <param name="cancellationToken">Optional cancellation token.</param> /// <returns>A <see cref="Task"/>.</returns> Task PerformTestAsync(BlobServiceClient client, BlobContainerConfiguration blobContainerConfiguration, CancellationToken cancellationToken = default); } }
45
158
0.595238
[ "MIT" ]
ECGKit/healthcare-shared-components
src/Microsoft.Health.Blob/Features/Storage/IBlobClientTestProvider.cs
1,262
C#
using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Shiny; namespace ShinyTest.Droid { [Activity(Label = "ShinyTest", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); AndroidShinyHost.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
44
184
0.716667
[ "MIT" ]
ricardoprestes/shinytest
src/ShinyTest.Android/MainActivity.cs
1,322
C#
// ********************************************************************* // Created by : Latebound Constants Generator 1.2020.2.1 for XrmToolBox // Author : Jonas Rapp https://twitter.com/rappen // GitHub : https://github.com/rappen/LCG-UDG // Source Org : https://drivard-dev.crm.dynamics.com/ // Filename : C:\Users\DavidRivard\Desktop\Publisher.cs // Created : 2020-11-16 21:14:47 // ********************************************************************* namespace XTB.CustomApiManager.Entities { /// <summary>OwnershipType: OrganizationOwned, IntroducedVersion: 5.0.0.0</summary> public static class Publisher { public const string EntityName = "publisher"; public const string EntityCollectionName = "publishers"; #region Attributes /// <summary>Type: Uniqueidentifier, RequiredLevel: SystemRequired</summary> public const string PrimaryKey = "publisherid"; /// <summary>Type: String, RequiredLevel: SystemRequired, MaxLength: 256, Format: Text</summary> public const string PrimaryName = "friendlyname"; /// <summary>Type: Lookup, RequiredLevel: None, Targets: systemuser</summary> public const string CreatedBy = "createdby"; /// <summary>Type: DateTime, RequiredLevel: None, Format: DateAndTime, DateTimeBehavior: UserLocal</summary> public const string CreatedOn = "createdon"; /// <summary>Type: String, RequiredLevel: None, MaxLength: 2000, Format: TextArea</summary> public const string Description = "description"; /// <summary>Type: String, RequiredLevel: None, MaxLength: 100, Format: Email</summary> public const string Email = "emailaddress"; /// <summary>Type: Uniqueidentifier, RequiredLevel: None</summary> public const string EntityImageId = "entityimageid"; /// <summary>Type: Boolean, RequiredLevel: SystemRequired, True: 1, False: 0, DefaultValue: False</summary> public const string IsRead_OnlyPublisher = "isreadonly"; /// <summary>Type: Lookup, RequiredLevel: None, Targets: systemuser</summary> public const string ModifiedBy = "modifiedby"; /// <summary>Type: DateTime, RequiredLevel: None, Format: DateAndTime, DateTimeBehavior: UserLocal</summary> public const string ModifiedOn = "modifiedon"; /// <summary>Type: String, RequiredLevel: SystemRequired, MaxLength: 256, Format: Text</summary> public const string Name = "uniquename"; /// <summary>Type: Integer, RequiredLevel: SystemRequired, MinValue: 10000, MaxValue: 99999</summary> public const string OptionValuePrefix = "customizationoptionvalueprefix"; /// <summary>Type: Lookup, RequiredLevel: SystemRequired, Targets: organization</summary> public const string Organization = "organizationid"; /// <summary>Type: String, RequiredLevel: None, MaxLength: 16, Format: Text</summary> public const string pinpointpublisherdefaultlocale = "pinpointpublisherdefaultlocale"; /// <summary>Type: BigInt, RequiredLevel: None, MinValue: -9223372036854775808, MaxValue: 9223372036854775807</summary> public const string pinpointpublisherid = "pinpointpublisherid"; /// <summary>Type: String, RequiredLevel: SystemRequired, MaxLength: 8, Format: Text</summary> public const string Prefix = "customizationprefix"; /// <summary>Type: String, RequiredLevel: None, MaxLength: 200, Format: Url</summary> public const string Website = "supportingwebsiteurl"; #endregion Attributes #region Relationships /// <summary>Parent: "Publisher" Child: "Solution" Lookup: "Publisher"</summary> public const string Rel1M_SolutionPublisher = "publisher_solution"; #endregion Relationships } }
59.6875
127
0.670681
[ "MIT" ]
drivardxrm/XTB.CustomApiManager
XTB.CustomApiManager/Entities/Publisher.cs
3,820
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable namespace Microsoft.Azure.Quantum.Authentication { using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using global::Azure.Core; using global::Azure.Identity; using Microsoft.Azure.Quantum.Utility; /// <summary> /// Implements a custom TokenCredential to use a local file as the source for an AzureQuantum token. /// /// It will only use the local file if the <c>AZURE_QUANTUM_TOKEN_FILE</c> environment variable is set, and references /// an existing json file that contains the access_token and expires_on timestamp in milliseconds. /// /// If the environment variable is not set, the file does not exist, or the token is invalid in any way(expired, for example), /// then the credential will throw <see cref="CredentialUnavailableError" />, so that DefaultQuantumCredential can fallback to other methods. /// </summary> public class TokenFileCredential : TokenCredential { /// <summary> /// Environment variable name for the token file path. /// </summary> private const string TokenFileEnvironmentVariable = "AZURE_QUANTUM_TOKEN_FILE"; /// <summary> /// File system dependency injected so that unit testing is possible. /// </summary> private readonly IFileSystem _fileSystem; /// <summary> /// The path to the token file. /// </summary> private readonly string? _tokenFilePath; /// <summary> /// Initializes a new instance of the <see cref="TokenFileCredential"/> class. /// </summary> /// <param name="fileSystem">The file system.</param> public TokenFileCredential(IFileSystem? fileSystem = null) { _fileSystem = fileSystem ?? new FileSystem(); _tokenFilePath = Environment.GetEnvironmentVariable(TokenFileEnvironmentVariable); } /// <summary> /// Attempts to acquire an <see cref="AccessToken"/> synchronously from a local token file. /// </summary> /// <param name="requestContext">The details of the authentication request.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="AccessToken"/> found in the token file.</returns> /// <exception cref="CredentialUnavailableException">When token is not found or valid.</exception> public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) => GetTokenImplAsync(false, requestContext, cancellationToken).GetAwaiter().GetResult(); /// <summary> /// Attempts to acquire an <see cref="AccessToken"/> asynchronously from a local token file. /// </summary> /// <param name="requestContext">The details of the authentication request.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="AccessToken"/> found in the token file.</returns> /// <exception cref="CredentialUnavailableException">When token is not found or valid.</exception> public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) => await GetTokenImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false); private async ValueTask<AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken) { AccessToken token; if (string.IsNullOrWhiteSpace(_tokenFilePath)) { throw new CredentialUnavailableException("Token file location not set."); } if (!_fileSystem.FileExists(_tokenFilePath)) { throw new CredentialUnavailableException($"Token file at {_tokenFilePath} does not exist."); } try { token = await ParseTokenFile(async, _tokenFilePath, cancellationToken); } catch (JsonException) { throw new CredentialUnavailableException("Failed to parse token file: Invalid JSON."); } catch (MissingFieldException ex) { throw new CredentialUnavailableException($"Failed to parse token file: Missing expected value: '{ex.Message}'"); } catch (Exception ex) { throw new CredentialUnavailableException($"Failed to parse token file: {ex.Message}"); } if (token.ExpiresOn <= DateTimeOffset.UtcNow) { throw new CredentialUnavailableException($"Token already expired at {token.ExpiresOn:u}"); } return token; } private async ValueTask<AccessToken> ParseTokenFile(bool async, string tokenFilePath, CancellationToken cancellationToken) { var data = async ? await _fileSystem.GetFileContentAsync<TokenFileContent>(tokenFilePath, cancellationToken) : _fileSystem.GetFileContent<TokenFileContent>(tokenFilePath); if (string.IsNullOrEmpty(data.AccessToken)) { throw new MissingFieldException("access_token"); } if (data.ExpiresOn == 0) { throw new MissingFieldException("expires_on"); } DateTimeOffset expiresOn = DateTimeOffset.FromUnixTimeMilliseconds(data.ExpiresOn); return new AccessToken(data.AccessToken, expiresOn); } } }
44.633588
147
0.648025
[ "MIT" ]
Bradben/qsharp-runtime
src/Azure/Azure.Quantum.Client/Authentication/TokenFileCredential.cs
5,847
C#
using YJC.Toolkit.Sys; namespace YJC.Toolkit.Right { public sealed class ObjectOperateRightConfigFactory : BaseXmlConfigFactory { public const string REG_NAME = "_tk_xml_ObjectOperateRight"; internal const string DESCRIPTION = "基于对象的操作权限的配置插件工厂"; public ObjectOperateRightConfigFactory() : base(REG_NAME, DESCRIPTION) { } } }
24.5625
78
0.679389
[ "BSD-3-Clause" ]
madiantech/tkcore
Data/YJC.Toolkit.Data/Right/_ObjectOperator/ObjectOperateRightConfigFactory.cs
427
C#
using System.Collections.Generic; using System.Net; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using NSubstitute; using sfa.Tl.Marketing.Communication.Application.Interfaces; using sfa.Tl.Marketing.Communication.Controllers; using sfa.Tl.Marketing.Communication.Models; using sfa.Tl.Marketing.Communication.UnitTests.Builders; using Xunit; namespace sfa.Tl.Marketing.Communication.UnitTests.Web.Controllers { public class StudentControllerRedirectTests { private const string AllowedExternalUri = "https://notevil.com"; private const string AllowedExternalProviderUri = "https://www.abingdon-witney.ac.uk/whats-new/t-levels"; private const string DisallowedExternalUri = "https://evil.com"; private const string LocalUri = "/students"; private readonly StudentController _controller; public StudentControllerRedirectTests() { var allowedUrls = new Dictionary<string, string> { { WebUtility.UrlDecode(AllowedExternalUri), AllowedExternalUri }, { WebUtility.UrlDecode(AllowedExternalProviderUri), AllowedExternalProviderUri } }; var providerDataService = Substitute.For<IProviderDataService>(); providerDataService.GetWebsiteUrls().Returns(allowedUrls); var urlHelper = Substitute.For<IUrlHelper>(); urlHelper.IsLocalUrl(Arg.Any<string>()) .Returns(args => (string)args[0] == LocalUri); _controller = new StudentControllerBuilder().BuildStudentController(providerDataService, urlHelper: urlHelper); } [Fact] public void Student_Controller_Redirect_Returns_Expected_Redirect_For_Local_Uri() { var result = _controller.Redirect(new RedirectViewModel { Url = LocalUri }); var redirectResult = result as RedirectResult; redirectResult.Should().NotBeNull(); redirectResult?.Url.Should().Be(LocalUri); } [Fact] public void Student_Controller_Redirect_Returns_Expected_Redirect_For_Valid_Uri() { var result = _controller.Redirect(new RedirectViewModel { Url = AllowedExternalProviderUri }); var redirectResult = result as RedirectResult; redirectResult.Should().NotBeNull(); redirectResult?.Url.Should().Be(AllowedExternalProviderUri); } [Fact] public void Student_Controller_Redirect_Returns_Students_Home_For_Invalid_Uri() { var result = _controller.Redirect(new RedirectViewModel { Url = DisallowedExternalUri }); var redirectResult = result as RedirectResult; redirectResult.Should().NotBeNull(); redirectResult?.Url.Should().Be("/students"); } [Fact] public void Student_Controller_Redirect_Returns_Students_Home_For_Empty_Uri() { var result = _controller.Redirect(new RedirectViewModel { Url = "" }); var redirectResult = result as RedirectResult; redirectResult.Should().NotBeNull(); redirectResult?.Url.Should().Be("/students"); } } }
38.73494
123
0.672784
[ "MIT" ]
SkillsFundingAgency/tl-marketing-and-communication
Tests/sfa.Tl.Marketing.Communication.Tests/Web/Controllers/StudentControllerRedirectTests.cs
3,217
C#
namespace PipelineHandlers; public interface ILogic<TEntity> where TEntity : class { void SetupRun(TryProcess<TEntity> process); bool TryRun(TEntity entity, out TEntity? output); }
27.142857
54
0.763158
[ "MIT" ]
JasonJCross/PipelineHandlers
PiplineHandlers/Contracts/ILogic.cs
192
C#
using System; using System.Reflection; using System.Collections.Generic; using System.Text; using Jetsons.JSON.Internal; namespace Jetsons.JSON.Resolvers { /// <summary> /// Get formatter from [JsonFormatter] attribute. /// </summary> public sealed class AttributeFormatterResolver : IJsonFormatterResolver { public static IJsonFormatterResolver Instance = new AttributeFormatterResolver(); AttributeFormatterResolver() { } public IJsonFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IJsonFormatter<T> formatter; static FormatterCache() { #if (UNITY_METRO || UNITY_WSA) && !NETFX_CORE var attr = (JsonFormatterAttribute)typeof(T).GetCustomAttributes(typeof(JsonFormatterAttribute), true).FirstOrDefault(); #else var attr = typeof(T).GetTypeInfo().GetCustomAttribute<JsonFormatterAttribute>(); #endif if (attr == null) { return; } try { if (attr.FormatterType.IsGenericType && !attr.FormatterType.GetTypeInfo().IsConstructedGenericType) { var t = attr.FormatterType.MakeGenericType(typeof(T)); // use T self formatter = (IJsonFormatter<T>)Activator.CreateInstance(t, attr.Arguments); } else { formatter = (IJsonFormatter<T>)Activator.CreateInstance(attr.FormatterType, attr.Arguments); } } catch (Exception ex) { throw new InvalidOperationException("Can not create formatter from JsonFormatterAttribute, check the target formatter is public and has constructor with right argument. FormatterType:" + attr.FormatterType.Name, ex); } } } } }
33.83871
236
0.570543
[ "MIT" ]
jetsons/JetPack.Data.Net
JSON/Resolvers/AttributeFormatterResolver.cs
2,100
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace UniversalGUI { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = UiData = new MainWindowData(); UiData.DefaultTitle = this.Title; IniConfigManager = new IniManager(GetIniConfigFile()); ImportIniConfig(IniConfigManager); SetLanguage(); } private MainWindowData UiData; private void MainWindow_Loaded(object sender, RoutedEventArgs e) { Task.Run(StartMonitorAsync); } private void MainWindow_Closing(object sender, CancelEventArgs e) { StopTask(); StartTaskButton.Focus(); //Ensure that the binding data are saved SaveIniConfig(IniConfigManager); } private string QueryLangDict(string key) { return Application.Current.FindResource(key).ToString(); } private void SetLanguage() { var dictionaryList = new List<ResourceDictionary>(); foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries) { dictionaryList.Add(dictionary); } string culture = Thread.CurrentThread.CurrentCulture.ToString(); string requestedCulture = string.Format(@"Resources\Language\{0}.xaml", culture); var resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture)); if (resourceDictionary == null) { requestedCulture = @"Resources\Language\en-US.xaml"; resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture)); } Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary); Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); } private async void StartTaskButton_Click(object sender, RoutedEventArgs e) { if (UiData.TaskRunning) { StopTask(); } else if (CheckConfig()) { UiData.TaskRunning = true; SetProgress(0); StartTaskButton.Content = QueryLangDict("Button_StartTask_Stop"); taskFiles = new TaskFiles(FilesList.Items); await Task.Run(StartTask); StartTaskButton.Content = QueryLangDict("Button_StartTask_Finished"); SetProgress(1); await Task.Delay(3000); UiData.TaskRunning = false; SetProgress(); StartTaskButton.Content = QueryLangDict("Button_StartTask_Start"); } } private void SetProgress(double multiple = -1) { Dispatcher.Invoke(() => { if (multiple >= 0 && multiple <= 1) // Change { int percent = Convert.ToInt32(Math.Round(multiple * 100)); SetTitleSuffix(percent + "%"); TaskProgressBar.Value = percent; TaskbarManager.SetProgressValue(percent, 100); TaskbarManager.SetProgressState(TaskbarProgressBarState.Normal); } else if (multiple == -1) // Reset { SetTitleSuffix(); TaskProgressBar.Value = 0; TaskbarManager.SetProgressValue(0, 100); TaskbarManager.SetProgressState(TaskbarProgressBarState.NoProgress); } else { throw new ArgumentException(); } }); } private void SetTitleSuffix(string suffix = "") { Title = suffix == "" ? UiData.DefaultTitle : UiData.DefaultTitle + " - " + suffix; } private async void StartMonitorAsync() { var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); var ramInUseCounter = new PerformanceCounter("Process", "Working Set", "_Total"); var ramAvailableCounter = new PerformanceCounter("Memory", "Available Bytes"); float ramTotal; float ramInUse; while (true) { ramInUse = ramInUseCounter.NextValue(); ramTotal = ramInUse + ramAvailableCounter.NextValue(); UiData.CpuUsage = Math.Round(cpuCounter.NextValue()) + "%"; UiData.RamUsage = Math.Round(ramInUse / ramTotal * 100) + "%"; await Task.Delay(1000); } } private bool CheckConfig() { string errorTitle = QueryLangDict("Message_Title_Error"); if (FilesList.Items.Count == 0) { MessageBox.Show( QueryLangDict("Message_FileslistIsEmpty"), errorTitle ); return false; } else if (UiData.AppPath == "") { MessageBox.Show( QueryLangDict("Message_CommandAppUnspecified"), errorTitle ); return false; } else if (UiData.OutputFloder == "" && UiData.OutputExtension == "" && UiData.OutputSuffix == "") { var result = MessageBox.Show( QueryLangDict("Message_OutputSettingsDangerous"), errorTitle, MessageBoxButton.YesNo ); if (result == MessageBoxResult.No) { return false; } } else if (UiData.ThreadCount == 0 || (CustomThreadCountItem.IsSelected && CustomThreadCountTextBox.Text == "")) { MessageBox.Show( QueryLangDict("Message_ThreadNumberIsIllegal"), errorTitle ); return false; } else if (UiData.SimulateCmd == 2 && UiData.AppPath.IndexOf(' ') != -1) { MessageBox.Show( QueryLangDict("Message_SimulateCmdIsIllegal"), errorTitle ); return false; } return true; } private void AddFilesListItems(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog() { DereferenceLinks = true, Multiselect = true, }; if (openFileDialog.ShowDialog() == true) { foreach (string file in openFileDialog.FileNames) { FilesList.Items.Add(file); } } } private void RemoveFilesListItems(object sender, RoutedEventArgs e) { if (FilesList.SelectedItems.Count == FilesList.Items.Count) { FilesList.Items.Clear(); } else { var selectedItems = FilesList.SelectedItems; for (int i = selectedItems.Count - 1; i > -1; i--) { FilesList.Items.Remove(selectedItems[i]); } } } private void EmptyFilesList(object sender, RoutedEventArgs e) { FilesList.Items.Clear(); } private void FilesList_DragOver(object sender, DragEventArgs e) { e.Effects = DragDropEffects.Copy; } private void FilesList_Drop(object sender, DragEventArgs e) { string[] dropFiles = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in dropFiles) { FilesList.Items.Add(file); } } private void SwitchAppPath(object sender, RoutedEventArgs e) { var openFileDialog = new Microsoft.Win32.OpenFileDialog() { Filter = "Executable program (*.exe)|*.exe|Dynamic link library (*.dll)|*.dll", DereferenceLinks = true, }; if (openFileDialog.ShowDialog() == true) { UiData.AppPath = openFileDialog.FileName; } } private void DropFileTextBox_PreviewDragOver(object sender, DragEventArgs e) { e.Effects = DragDropEffects.Copy; e.Handled = true; } private void DropFileTextBox_PreviewDrop(object senderObj, DragEventArgs e) { var sender = (TextBox)senderObj; string[] dropFiles = (string[])e.Data.GetData(DataFormats.FileDrop); sender.Text = dropFiles[0]; sender.Focus(); } private void InsertArgsTempletMark(object senderObj, RoutedEventArgs e) { var sender = (MenuItem)senderObj; string insertContent = sender.Header.ToString(); int originSelectionStart = ArgsTemplet.SelectionStart; ArgsTemplet.Text = ArgsTemplet.Text.Insert(ArgsTemplet.SelectionStart, insertContent); ArgsTemplet.SelectionStart = originSelectionStart + insertContent.Length; ArgsTemplet.Focus(); } private void ShowArgsTempletHelp(object sender, RoutedEventArgs e) { MessageBox.Show( QueryLangDict("Message_ArgsTempletHelp"), QueryLangDict("Message_Title_Hint") ); } private void SwitchOutputFloder(object sender, RoutedEventArgs e) { var folderBrowser = new System.Windows.Forms.FolderBrowserDialog(); if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UiData.OutputFloder = folderBrowser.SelectedPath; } } private void AutoSelectTextBox_PreviewMouseDown(object senderObj, MouseButtonEventArgs e) { var sender = (TextBox)senderObj; if (!sender.IsFocused) { sender.Focus(); e.Handled = true; } } private void AutoSelectTextBox_GotFocus(object senderObj, RoutedEventArgs e) { var sender = (TextBox)senderObj; sender.SelectAll(); } private void CustomThreadCountTextBox_LostFocus(object sender, RoutedEventArgs e) { CustomThreadCountItem.IsSelected = true; } private void CustomThreadCountTextBox_TextChanged(object senderObj, TextChangedEventArgs e) { var sender = (TextBox)senderObj; CustomThreadCountItem.Tag = sender.Text; try { Convert.ToUInt16(sender.Text); } catch { sender.Text = ""; } } } public partial class MainWindow : Window { private const string IniConfigFileName = "Config.ini"; private const string IniConfigFileVersion = "1.0.1.1"; // Configfile's version, not app version private readonly IniManager IniConfigManager; private string GetIniConfigFile() { string iniConfigFilePath; if (File.Exists(Environment.CurrentDirectory + "\\Portable") == true) { iniConfigFilePath = Environment.CurrentDirectory; } else { iniConfigFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\UniversalGUI"; } string IniConfigFile = Path.Combine(iniConfigFilePath, IniConfigFileName); return IniConfigFile; } private void ImportIniConfig(IniManager ini) { if (!File.Exists(ini.IniFilePath) || File.ReadAllBytes(ini.IniFilePath).Length == 0) { return; } else if (ini.Read("Versions", "ConfigFile") != IniConfigFileVersion) { MessageBox.Show( QueryLangDict("Message_UseBuildInConfigfile"), QueryLangDict("Message_Title_Hint") ); return; } else { try { this.Width = Convert.ToDouble(ini.Read("Window", "Width")); this.Height = Convert.ToDouble(ini.Read("Window", "Height")); UiData.AppPath = ini.Read("Command", "AppPath"); UiData.ArgsTemplet = ini.Read("Command", "ArgsTemplet"); UiData.UserArgs = ini.Read("Command", "UserArgs"); UiData.OutputExtension = ini.Read("Output", "Extension"); UiData.OutputSuffix = ini.Read("Output", "Suffix"); UiData.OutputFloder = ini.Read("Output", "Floder"); UiData.Priority = Convert.ToInt32(ini.Read("Process", "Priority")); int threadCount = Convert.ToInt32(ini.Read("Process", "ThreadCount")); if (threadCount > 8) { CustomThreadCountTextBox.Text = threadCount.ToString(); } UiData.ThreadCount = threadCount; UiData.WindowStyle = Convert.ToInt32(ini.Read("Process", "WindowStyle")); UiData.SimulateCmd = Convert.ToInt32(ini.Read("Process", "SimulateCmd")); string culture = ini.Read("Language", "Culture"); if (culture != "") { Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); } } catch (Exception e) { MessageBox.Show( QueryLangDict("Message_ConfigfileFormatMistake") + "\n\n" + e.TargetSite + "\n\n" + e.Message, QueryLangDict("Message_Title_Error") ); } } } private void SaveIniConfig(IniManager ini) { if (!File.Exists(ini.IniFilePath)) { try { ini.CreatFile(); } catch { MessageBox.Show( QueryLangDict("Message_CanNotWriteConfigfile"), QueryLangDict("Message_Title_Error") ); return; } } else if (ini.Read("Versions", "ConfigFile") != IniConfigFileVersion || File.ReadAllBytes(ini.IniFilePath).Length == 0) { var result = MessageBox.Show( QueryLangDict("Message_CreatNewConfigfile"), QueryLangDict("Message_Title_Hint"), MessageBoxButton.YesNo ); if (result == MessageBoxResult.Yes) { ini.CreatFile(); } } else { ini.Write("Versions", "ConfigFile", IniConfigFileVersion); ini.Write("Window", "Width", this.Width); ini.Write("Window", "Height", this.Height); ini.Write("Command", "AppPath", UiData.AppPath); ini.Write("Command", "ArgsTemplet", UiData.ArgsTemplet); ini.Write("Command", "UserArgs", UiData.UserArgs); ini.Write("Output", "Extension", UiData.OutputExtension); ini.Write("Output", "Suffix", UiData.OutputSuffix); ini.Write("Output", "Floder", UiData.OutputFloder); ini.Write("Process", "Priority", UiData.Priority); ini.Write("Process", "ThreadCount", UiData.ThreadCount); ini.Write("Process", "WindowStyle", UiData.WindowStyle); ini.Write("Process", "SimulateCmd", UiData.SimulateCmd); } } } public class MainWindowData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public string DefaultTitle; private string _appPath; public string AppPath { get => _appPath; set { _appPath = value; NotifyPropertyChanged("AppPath"); } } private string _argsTemplet; public string ArgsTemplet { get => _argsTemplet; set { _argsTemplet = value; NotifyPropertyChanged("ArgsTemplet"); } } private string _userArgs; public string UserArgs { get => _userArgs; set { _userArgs = value; NotifyPropertyChanged("UserArgs"); } } private string _outputSuffix = "_Output"; public string OutputSuffix { get => _outputSuffix; set { _outputSuffix = value; NotifyPropertyChanged("OutputSuffix"); } } private string _outputExtension; public string OutputExtension { get => _outputExtension; set { _outputExtension = value; NotifyPropertyChanged("OutputExtension"); } } private string _outputFloder; public string OutputFloder { get => _outputFloder; set { _outputFloder = value; NotifyPropertyChanged("OutputFloder"); } } private int _priority = 3; public int Priority { get => _priority; set { _priority = value; NotifyPropertyChanged("Priority"); } } private int _threadCount = 1; public int ThreadCount { get => _threadCount; set { _threadCount = value; NotifyPropertyChanged("ThreadCount"); } } private int _windowStyle = 1; public int WindowStyle { get => _windowStyle; set { _windowStyle = value; NotifyPropertyChanged("WindowStyle"); } } private int _simulateCmd = 1; public int SimulateCmd { get => _simulateCmd; set { _simulateCmd = value; NotifyPropertyChanged("SimulateCmd"); } } private bool _taskRunning = false; public bool TaskRunning { get => _taskRunning; set { _taskRunning = value; ConfigVariable = !value; NotifyPropertyChanged("TaskRunning"); } } public bool ConfigVariable { get => !TaskRunning; set => NotifyPropertyChanged("ConfigVariable"); // Throw set value } private string _cpuUsage = "--%"; public string CpuUsage { get => _cpuUsage; set { _cpuUsage = value; NotifyPropertyChanged("CpuUsage"); } } private string _ramUsage = "--%"; public string RamUsage { get => _ramUsage; set { _ramUsage = value; NotifyPropertyChanged("RamUsage"); } } } }
35.197531
130
0.526282
[ "MIT" ]
kkocdko/UniversalGUI
UniversalGUI/MainWindow.xaml.cs
19,957
C#
using System.Collections.Generic; namespace ConfigurationService.Persistence { public interface IStatePersister { void Persist(List<Configuration> transactions); List<Configuration> Read(); void Clean(); } }
20.5
55
0.686992
[ "MIT" ]
Paraintom/ConfigurationService
ConfigurationService/Persistence/IStatePersister.cs
248
C#
using System; namespace Synercoding.FileFormats.Pdf.LowLevel.XRef { internal struct Entry { public Entry(uint data) : this(data, 0, false) { } public Entry(uint data, ushort generation, bool isFree) { Data = data; GenerationNumber = generation; IsFree = isFree; } public uint Data { get; } public ushort GenerationNumber { get; } public bool IsFree { get; } public void FillSpan(Span<byte> bytes) { _fillSpanLeadingZero(bytes.Slice(0, 10), Data); bytes[10] = 0x20; _fillSpanLeadingZero(bytes.Slice(11, 5), GenerationNumber); bytes[16] = 0x20; bytes[17] = (byte)( IsFree ? 0x66 : 0x6E ); bytes[18] = 0x0D; bytes[19] = 0x0A; } public int ByteSize() { return 20; } private void _fillSpanLeadingZero(Span<byte> span, uint data) { uint val = data; for (int i = span.Length - 1; i >= 0; i--) { span[i] = (byte)( '0' + ( val % 10 ) ); val /= 10; } } private void _fillSpanLeadingZero(Span<byte> span, ushort data) { int val = data; for (int i = span.Length - 1; i >= 0; i--) { span[i] = (byte)( '0' + ( val % 10 ) ); val /= 10; } } } }
24.435484
71
0.452145
[ "MIT" ]
synercoder/FileFormats.Pdf
src/Synercoding.FileFormats.Pdf/LowLevel/XRef/Entry.cs
1,515
C#
using System; using System.Collections.Generic; namespace AoC2019.Puzzle12 { public class CycleFinder<TElement, THash> where TElement : notnull where THash : notnull { public CycleFinder(Func<TElement, THash> hashFunc) { _hashFunc = hashFunc; } public bool Found { get; private set; } = false; public long CycleLength { get; private set; } private readonly Func<TElement, THash> _hashFunc; private readonly Dictionary<THash, long> _visited = new Dictionary<THash, long>(); private long _i = 0; public void Add(TElement element) { var hash = _hashFunc(element); if (_visited.TryGetValue(hash, out var first)) { if (!Found) { Found = true; CycleLength = _i - first; } } else { _visited.Add(hash, _i); } _i++; } } }
25.536585
91
0.501433
[ "MIT" ]
GreenOlvi/AdventOfCode
2019/AoC2019/Puzzle12/CycleFinder.cs
1,049
C#
using Foundation; using UIKit; namespace HighlightRouteMapDemo.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { //const string MapsApiKey = "AIzaSyD5gI6RKUjJ-20MuGBpt8exJM5PfJEtQyA"; // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new HighlightRouteMapDemo.App()); return base.FinishedLaunching(app, options); } } }
34.387097
96
0.733583
[ "MIT" ]
Xamarians/HighlightRouteMapSample
HighlightRouteMapDemo/HighlightRouteMapDemo/HighlightRouteMapDemo.iOS/AppDelegate.cs
1,068
C#
namespace Machine.Specifications.Runner { public class AssemblyInfo { public AssemblyInfo(string name, string location) { Name = name; Location = location; } public string Name { get; private set; } public string Location { get; private set; } public string CapturedOutput { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != typeof(AssemblyInfo)) { return false; } return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { unchecked { return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Location != null ? Location.GetHashCode() : 0); } } } }
26.275
121
0.47098
[ "MIT" ]
einari/Machine.Specifications.Core
Source/Machine.Specifications.Core/Runner/AssemblyInfo.cs
1,053
C#
<?cs include:"templates/header.cs" ?> <div align="center"> <form method="post" action="<?cs var:action ?>"> <table> <tr> <td>Username</td><td><input type="text" name="username" size="25" /></td> </tr> <tr> <td>Password</td><td><input type="password" name="password" size="25" /></td> </tr> <tr> <td/><td><input type="submit" value="Login"/></td> </tr> </table> </form> </div> <?cs include:"templates/footer.cs" ?>
25.444444
83
0.556769
[ "MIT" ]
Infoss/conf-profile-4-android
ConfProfile/jni/strongswan/src/manager/templates/auth/login.cs
458
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100b_092c-5e3bf253")] public void Method_100b_092c() { ii(0x100b_092c, 5); push(0x24); /* push 0x24 */ ii(0x100b_0931, 5); call(Definitions.sys_check_available_stack_size, 0xb_541c);/* call 0x10165d52 */ ii(0x100b_0936, 1); push(ebx); /* push ebx */ ii(0x100b_0937, 1); push(ecx); /* push ecx */ ii(0x100b_0938, 1); push(esi); /* push esi */ ii(0x100b_0939, 1); push(edi); /* push edi */ ii(0x100b_093a, 1); push(ebp); /* push ebp */ ii(0x100b_093b, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100b_093d, 6); sub(esp, 0xc); /* sub esp, 0xc */ ii(0x100b_0943, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_0946, 3); mov(memd[ss, ebp - 4], edx); /* mov [ebp-0x4], edx */ ii(0x100b_0949, 7); test(memd[ss, ebp - 4], 4); /* test dword [ebp-0x4], 0x4 */ ii(0x100b_0950, 2); if(jz(0x100b_0966, 0x14)) goto l_0x100b_0966;/* jz 0x100b0966 */ ii(0x100b_0952, 5); mov(edx, 0x101b_515c); /* mov edx, 0x101b515c */ ii(0x100b_0957, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_095a, 5); call(Definitions.sys_call_dtor_arr, 0xb_5659);/* call 0x10165fb8 */ ii(0x100b_095f, 5); call(Definitions.sys_delete_arr, 0xb_5674);/* call 0x10165fd8 */ ii(0x100b_0964, 2); jmp(0x100b_09dd, 0x77); goto l_0x100b_09dd;/* jmp 0x100b09dd */ l_0x100b_0966: ii(0x100b_0966, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_0969, 7); mov(memd[ds, eax + 2], 0x101b_53b4); /* mov dword [eax+0x2], 0x101b53b4 */ ii(0x100b_0970, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_0972, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_0975, 3); add(eax, 0x27); /* add eax, 0x27 */ ii(0x100b_0978, 5); call(0x1008_8cbc, -0x2_7cc1); /* call 0x10088cbc */ ii(0x100b_097d, 3); sub(eax, 0x27); /* sub eax, 0x27 */ ii(0x100b_0980, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_0983, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_0985, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_0988, 3); add(eax, 0x23); /* add eax, 0x23 */ ii(0x100b_098b, 5); call(0x1008_8d4c, -0x2_7c44); /* call 0x10088d4c */ ii(0x100b_0990, 3); sub(eax, 0x23); /* sub eax, 0x23 */ ii(0x100b_0993, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_0996, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_0998, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_099b, 3); add(eax, 0x19); /* add eax, 0x19 */ ii(0x100b_099e, 5); call(0x100b_7610, 0x6c6d); /* call 0x100b7610 */ ii(0x100b_09a3, 3); sub(eax, 0x19); /* sub eax, 0x19 */ ii(0x100b_09a6, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_09a9, 2); xor(edx, edx); /* xor edx, edx */ ii(0x100b_09ab, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_09ae, 3); add(eax, 0x15); /* add eax, 0x15 */ ii(0x100b_09b1, 5); call(0x1007_5f2c, -0x3_aa8a); /* call 0x10075f2c */ ii(0x100b_09b6, 3); sub(eax, 0x15); /* sub eax, 0x15 */ ii(0x100b_09b9, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_09bc, 5); mov(edx, 1); /* mov edx, 0x1 */ ii(0x100b_09c1, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_09c4, 5); call(0x100a_284c, -0xe17d); /* call 0x100a284c */ ii(0x100b_09c9, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_09cc, 7); test(memd[ss, ebp - 4], 2); /* test dword [ebp-0x4], 0x2 */ ii(0x100b_09d3, 2); if(jz(0x100b_09dd, 8)) goto l_0x100b_09dd;/* jz 0x100b09dd */ ii(0x100b_09d5, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_09d8, 5); call(Definitions.sys_delete, 0xb_5587);/* call 0x10165f64 */ l_0x100b_09dd: ii(0x100b_09dd, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_09e0, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */ ii(0x100b_09e3, 3); mov(eax, memd[ss, ebp - 12]); /* mov eax, [ebp-0xc] */ ii(0x100b_09e6, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100b_09e8, 1); pop(ebp); /* pop ebp */ ii(0x100b_09e9, 1); pop(edi); /* pop edi */ ii(0x100b_09ea, 1); pop(esi); /* pop esi */ ii(0x100b_09eb, 1); pop(ecx); /* pop ecx */ ii(0x100b_09ec, 1); pop(ebx); /* pop ebx */ ii(0x100b_09ed, 1); ret(); /* ret */ } } }
78.897436
114
0.440851
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100b-092c.cs
6,154
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace AzusaERP.OldStuff { class PwDatabase { public void Open(IOConnectionInfo connectionInfo, CompositeKey compositeKey, object o) { throw new NotImplementedException(); } public PwGroup RootGroup { get; set; } } class PwGroup { public IEnumerable<PwEntry> Entries { get; set; } public IEnumerable<PwGroup> Groups { get; set; } public string Name { get; set; } } class IOConnectionInfo { public static IOConnectionInfo FromPath(string fullName) { throw new NotImplementedException(); } } class KcpPassword { private string pw; public KcpPassword(string pw) { this.pw = pw; } } class CompositeKey { public void AddUserKey(KcpPassword kcpPassword) { throw new NotImplementedException(); } } [Serializable] public class InvalidCompositeKeyException : Exception { // // For guidelines regarding the creation of new exception types, see // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp // and // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp // public InvalidCompositeKeyException() { } public InvalidCompositeKeyException(string message) : base(message) { } public InvalidCompositeKeyException(string message, Exception inner) : base(message, inner) { } protected InvalidCompositeKeyException( SerializationInfo info, StreamingContext context) : base(info, context) { } } class PwEntry { public PwStringTable Strings { get; set; } } class PwStringTable { public PwString Get(string username) { throw new NotImplementedException(); } } class PwString { public string ReadString() { throw new NotImplementedException(); } } }
22.980583
132
0.598226
[ "BSD-2-Clause" ]
feyris-tan/azusa
AzusaERP.OldStuff/MockKeepass.cs
2,369
C#
using NuKeeper.Abstractions; using NuKeeper.Abstractions.CollaborationModels; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Formats; using NuKeeper.Abstractions.Logging; using Octokit; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Organization = NuKeeper.Abstractions.CollaborationModels.Organization; using PullRequestRequest = NuKeeper.Abstractions.CollaborationModels.PullRequestRequest; using Repository = NuKeeper.Abstractions.CollaborationModels.Repository; using SearchCodeRequest = NuKeeper.Abstractions.CollaborationModels.SearchCodeRequest; using SearchCodeResult = NuKeeper.Abstractions.CollaborationModels.SearchCodeResult; using User = NuKeeper.Abstractions.CollaborationModels.User; using Newtonsoft.Json; namespace NuKeeper.GitHub { public class OctokitClient : ICollaborationPlatform { private readonly INuKeeperLogger _logger; private bool _initialised = false; private IGitHubClient _client; private Uri _apiBase; public OctokitClient(INuKeeperLogger logger) { _logger = logger; } public void Initialise(AuthSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } _apiBase = settings.ApiBase; _client = new GitHubClient(new ProductHeaderValue("NuKeeper"), _apiBase) { Credentials = new Credentials(settings.Token) }; _initialised = true; } private void CheckInitialised() { if (!_initialised) { throw new NuKeeperException("Github has not been initialised"); } } public async Task<User> GetCurrentUser() { CheckInitialised(); return await ExceptionHandler(async () => { var user = await _client.User.Current(); _logger.Detailed($"Read github user '{user?.Login}'"); return new User(user?.Login, user?.Name, user?.Email); }); } public async Task<IReadOnlyList<Organization>> GetOrganizations() { CheckInitialised(); return await ExceptionHandler(async () => { var githubOrgs = await _client.Organization.GetAll(); _logger.Normal($"Read {githubOrgs.Count} organisations"); return githubOrgs .Select(org => new Organization(org.Name ?? org.Login)) .ToList(); }); } public async Task<IReadOnlyList<Repository>> GetRepositoriesForOrganisation(string organisationName) { CheckInitialised(); return await ExceptionHandler(async () => { var repos = await _client.Repository.GetAllForOrg(organisationName); _logger.Normal($"Read {repos.Count} repos for org '{organisationName}'"); return repos.Select(repo => new GitHubRepository(repo)).ToList(); }); } public async Task<Repository> GetUserRepository(string userName, string repositoryName) { CheckInitialised(); _logger.Detailed($"Looking for user fork for {userName}/{repositoryName}"); return await ExceptionHandler(async () => { try { var result = await _client.Repository.Get(userName, repositoryName); _logger.Normal($"User fork found at {result.GitUrl} for {result.Owner.Login}"); return new GitHubRepository(result); } catch (NotFoundException) { _logger.Detailed("User fork not found"); return null; } }); } public async Task<Repository> MakeUserFork(string owner, string repositoryName) { CheckInitialised(); _logger.Detailed($"Making user fork for {repositoryName}"); return await ExceptionHandler(async () => { var result = await _client.Repository.Forks.Create(owner, repositoryName, new NewRepositoryFork()); _logger.Normal($"User fork created at {result.GitUrl} for {result.Owner.Login}"); return new GitHubRepository(result); }); } public async Task<bool> RepositoryBranchExists(string userName, string repositoryName, string branchName) { CheckInitialised(); return await ExceptionHandler(async () => { try { await _client.Repository.Branch.Get(userName, repositoryName, branchName); _logger.Detailed($"Branch found for {userName} / {repositoryName} / {branchName}"); return true; } catch (NotFoundException) { _logger.Detailed($"No branch found for {userName} / {repositoryName} / {branchName}"); return false; } }); } public async Task<bool> PullRequestExists(ForkData target, string headBranch, string baseBranch) { CheckInitialised(); return await ExceptionHandler(async () => { _logger.Normal($"Checking if PR exists onto '{_apiBase} {target.Owner}/{target.Name}: {baseBranch} <= {headBranch}"); var prRequest = new Octokit.PullRequestRequest { State = ItemStateFilter.Open, SortDirection = SortDirection.Descending, SortProperty = PullRequestSort.Created, Head = $"{target.Owner}:{headBranch}", }; var pullReqList = await _client.PullRequest.GetAllForRepository(target.Owner, target.Name, prRequest).ConfigureAwait(false); return pullReqList.Any(pr => pr.Base.Ref.EndsWith(baseBranch, StringComparison.InvariantCultureIgnoreCase)); }); } public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable<string> labels) { CheckInitialised(); await ExceptionHandler(async () => { _logger.Normal($"Making PR onto '{_apiBase} {target.Owner}/{target.Name} from {request.Head}"); _logger.Detailed($"PR title: {request.Title}"); var createdPullRequest = await _client.PullRequest.Create(target.Owner, target.Name, new NewPullRequest(request.Title, request.Head, request.BaseRef) { Body = request.Body }); await AddLabelsToIssue(target, createdPullRequest.Number, labels); return Task.CompletedTask; }); } public async Task<SearchCodeResult> Search(SearchCodeRequest search) { CheckInitialised(); return await ExceptionHandler(async () => { var repos = new RepositoryCollection(); foreach (var repo in search.Repos) { repos.Add(repo.Owner, repo.Name); } var result = await _client.Search.SearchCode( new Octokit.SearchCodeRequest(search.Term) { Repos = repos, In = new[] { CodeInQualifier.Path }, PerPage = search.PerPage }); return new SearchCodeResult(result.TotalCount); }); } private async Task AddLabelsToIssue(ForkData target, int issueNumber, IEnumerable<string> labels) { var labelsToApply = labels? .Where(l => !string.IsNullOrWhiteSpace(l)) .ToArray(); if (labelsToApply != null && labelsToApply.Any()) { _logger.Normal( $"Adding label(s) '{labelsToApply.JoinWithCommas()}' to issue " + $"'{_apiBase} {target.Owner}/{target.Name} {issueNumber}'"); try { await _client.Issue.Labels.AddToIssue(target.Owner, target.Name, issueNumber, labelsToApply); } catch (ApiException ex) { _logger.Error("Failed to add labels. Continuing", ex); } } } private static async Task<T> ExceptionHandler<T>(Func<Task<T>> funcToCheck) { try { T retval = await funcToCheck(); return retval; } catch (ApiException ex) { if (ex.HttpResponse?.Body != null) { dynamic response = JsonConvert.DeserializeObject(ex.HttpResponse.Body.ToString()); if (response?.errors != null && response.errors.Count > 0) { throw new NuKeeperException(response.errors.First.message.ToString(), ex); } } throw new NuKeeperException(ex.Message, ex); } } } }
36.17803
191
0.554602
[ "Apache-2.0" ]
johntyrrell/NuKeeper
NuKeeper.GitHub/OctokitClient.cs
9,551
C#
using AdminWebsite.Models; using AdminWebsite.Security; using AdminWebsite.Services; using FluentAssertions; using FluentValidation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Moq; using NotificationApi.Client; using NUnit.Framework; using System; using System.Threading.Tasks; using BookingsApi.Client; using BookingsApi.Contract.Requests; using BookingsApi.Contract.Requests.Enums; using VideoApi.Client; using Microsoft.Extensions.Options; using AdminWebsite.Configuration; using Autofac.Extras.Moq; using VideoApi.Contract.Responses; namespace AdminWebsite.UnitTests.Controllers.HearingsController { public class CancelHearingTests { private AutoMock _mocker; private AdminWebsite.Controllers.HearingsController _controller; [SetUp] public void Setup() { _mocker = AutoMock.GetLoose(); _mocker.Mock<IConferenceDetailsService>().Setup(cs => cs.GetConferenceDetailsByHearingId(It.IsAny<Guid>())) .ReturnsAsync(new ConferenceDetailsResponse { MeetingRoom = new MeetingRoomResponse { AdminUri = "AdminUri", JudgeUri = "JudgeUri", ParticipantUri = "ParticipantUri", PexipNode = "PexipNode", PexipSelfTestNode = "PexipSelfTestNode", TelephoneConferenceId = "expected_conference_phone_id" } }); _controller = _mocker.Create<AdminWebsite.Controllers.HearingsController>(); } [Test] public async Task Should_update_status_of_hearing_to_cancelled_given_status_and_updatedby() { // Arrange var bookingGuid = Guid.NewGuid(); var updateBookingStatusRequest = new UpdateBookingStatusRequest { Status = UpdateBookingStatus.Cancelled, UpdatedBy = "admin user" }; // Act var response = await _controller.UpdateBookingStatus(bookingGuid, updateBookingStatusRequest); // Assert var result = (OkObjectResult) response; result.StatusCode.Should().Be(StatusCodes.Status200OK); result.Value.Should().NotBeNull() .And.BeAssignableTo<UpdateBookingStatusResponse>() .Subject.Success.Should().BeTrue(); } } }
35.202703
119
0.616891
[ "MIT" ]
hmcts/vh-admin-web
AdminWebsite/AdminWebsite.UnitTests/Controllers/HearingsController/CancelHearingTests.cs
2,607
C#
using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Serilog.Context; namespace CleanArchitecture.Blazor.Infrastructure.Middlewares; internal class ExceptionMiddleware : IMiddleware { private readonly ICurrentUserService _currentUserService; private readonly ILogger<ExceptionMiddleware> _logger; private readonly IStringLocalizer<ExceptionMiddleware> _localizer; public ExceptionMiddleware( ICurrentUserService currentUserService , ILogger<ExceptionMiddleware> logger, IStringLocalizer<ExceptionMiddleware> localizer) { _currentUserService = currentUserService; _logger = logger; _localizer = localizer; } public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (Exception exception) { var userId = _currentUserService.UserId; if (!string.IsNullOrEmpty(userId)) LogContext.PushProperty("UserId", userId); string errorId = Guid.NewGuid().ToString(); LogContext.PushProperty("ErrorId", errorId); LogContext.PushProperty("StackTrace", exception.StackTrace); var responseModel = await Result.FailureAsync(new string[] { exception.Message }); var response = context.Response; response.ContentType = "application/json"; if (exception.InnerException != null) { while (exception.InnerException != null) { exception = exception.InnerException; } } switch (exception) { case ValidationException e: response.StatusCode = (int)HttpStatusCode.BadRequest; responseModel = await Result.FailureAsync(e.Errors.Select(x => $"{x.Key}:{string.Join(',', x.Value)}")); break; case NotFoundException e: response.StatusCode = (int)HttpStatusCode.NotFound; responseModel = await Result.FailureAsync(new string[] { e.Message }); break; case KeyNotFoundException: response.StatusCode = (int)HttpStatusCode.NotFound; break; default: response.StatusCode = (int)HttpStatusCode.InternalServerError; responseModel = await Result.FailureAsync(new string[] { exception.Message }); break; } _logger.LogError(exception, $"{exception}. Request failed with Status Code {response.StatusCode}"); await response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(responseModel)); } } }
38.918919
124
0.6125
[ "Apache-2.0" ]
JustCallMeAD/CleanArchitectureWithBlazorServer
src/Infrastructure/Middlewares/ExceptionMiddleware.cs
2,880
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; namespace Newtonsoft.Json.Serialization { /// <summary> /// Used by <see cref="JsonSerializer"/> to resolve a <see cref="JsonContract"/> for a given <see cref="Type"/>. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeContractResolverObject" title="IContractResolver Class" /> /// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeContractResolverExample" title="IContractResolver Example" /> /// </example> public interface IContractResolver { /// <summary> /// Resolves the contract for a given type. /// </summary> /// <param name="type">The type to resolve a contract for.</param> /// <returns>The contract for a given type.</returns> JsonContract ResolveContract(Type type); } }
46.195652
195
0.720941
[ "MIT" ]
1Konto/Newtonsoft.Json
Src/Newtonsoft.Json/Serialization/IContractResolver.cs
2,127
C#
// This file was modified by Kin Ecosystem (2019) using Newtonsoft.Json; using Kin.Base.responses.effects; using Kin.Base.responses.operations; using Kin.Base.responses.page; namespace Kin.Base.responses { public class AccountResponseLinks { public AccountResponseLinks(Link<Page<EffectResponse>> effects, Link<Page<OfferResponse>> offers, Link<Page<OperationResponse>> operations, Link<AccountResponse> self, Link<Page<TransactionResponse>> transactions) { Effects = effects; Offers = offers; Operations = operations; Self = self; Transactions = transactions; } [JsonProperty(PropertyName = "effects")] public Link<Page<EffectResponse>> Effects { get; private set; } [JsonProperty(PropertyName = "offers")] public Link<Page<OfferResponse>> Offers { get; private set; } [JsonProperty(PropertyName = "operations")] public Link<Page<OperationResponse>> Operations { get; private set; } [JsonProperty(PropertyName = "self")] public Link<AccountResponse> Self { get; private set; } [JsonProperty(PropertyName = "transactions")] public Link<Page<TransactionResponse>> Transactions { get; private set; } } }
32.75
105
0.656489
[ "Apache-2.0" ]
kinecosystem/dotnet-stellar-sdk
kin-base/responses/AccountResponseLinks.cs
1,310
C#
namespace GlobalcachingApplication.Plugins.OV2 { partial class ExportOV2Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.checkBoxDifficulty = new System.Windows.Forms.CheckBox(); this.checkBoxTerrain = new System.Windows.Forms.CheckBox(); this.checkBoxFavorites = new System.Windows.Forms.CheckBox(); this.checkBoxOwner = new System.Windows.Forms.CheckBox(); this.checkBoxContainer = new System.Windows.Forms.CheckBox(); this.checkBoxCacheType = new System.Windows.Forms.CheckBox(); this.checkBoxNote = new System.Windows.Forms.CheckBox(); this.checkBoxHints = new System.Windows.Forms.CheckBox(); this.checkBoxCoords = new System.Windows.Forms.CheckBox(); this.checkBoxName = new System.Windows.Forms.CheckBox(); this.checkBoxCode = new System.Windows.Forms.CheckBox(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); this.buttonOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.checkBoxDifficulty); this.groupBox1.Controls.Add(this.checkBoxTerrain); this.groupBox1.Controls.Add(this.checkBoxFavorites); this.groupBox1.Controls.Add(this.checkBoxOwner); this.groupBox1.Controls.Add(this.checkBoxContainer); this.groupBox1.Controls.Add(this.checkBoxCacheType); this.groupBox1.Controls.Add(this.checkBoxNote); this.groupBox1.Controls.Add(this.checkBoxHints); this.groupBox1.Controls.Add(this.checkBoxCoords); this.groupBox1.Controls.Add(this.checkBoxName); this.groupBox1.Controls.Add(this.checkBoxCode); this.groupBox1.Location = new System.Drawing.Point(16, 15); this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); this.groupBox1.Size = new System.Drawing.Size(453, 172); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Fields"; // // checkBoxDifficulty // this.checkBoxDifficulty.AutoSize = true; this.checkBoxDifficulty.Location = new System.Drawing.Point(169, 126); this.checkBoxDifficulty.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxDifficulty.Name = "checkBoxDifficulty"; this.checkBoxDifficulty.Size = new System.Drawing.Size(83, 21); this.checkBoxDifficulty.TabIndex = 10; this.checkBoxDifficulty.Text = "Difficulty"; this.checkBoxDifficulty.UseVisualStyleBackColor = true; // // checkBoxTerrain // this.checkBoxTerrain.AutoSize = true; this.checkBoxTerrain.Location = new System.Drawing.Point(169, 97); this.checkBoxTerrain.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxTerrain.Name = "checkBoxTerrain"; this.checkBoxTerrain.Size = new System.Drawing.Size(76, 21); this.checkBoxTerrain.TabIndex = 9; this.checkBoxTerrain.Text = "Terrain"; this.checkBoxTerrain.UseVisualStyleBackColor = true; // // checkBoxFavorites // this.checkBoxFavorites.AutoSize = true; this.checkBoxFavorites.Location = new System.Drawing.Point(307, 97); this.checkBoxFavorites.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxFavorites.Name = "checkBoxFavorites"; this.checkBoxFavorites.Size = new System.Drawing.Size(88, 21); this.checkBoxFavorites.TabIndex = 8; this.checkBoxFavorites.Text = "Favorites"; this.checkBoxFavorites.UseVisualStyleBackColor = true; // // checkBoxOwner // this.checkBoxOwner.AutoSize = true; this.checkBoxOwner.Location = new System.Drawing.Point(27, 126); this.checkBoxOwner.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxOwner.Name = "checkBoxOwner"; this.checkBoxOwner.Size = new System.Drawing.Size(71, 21); this.checkBoxOwner.TabIndex = 7; this.checkBoxOwner.Text = "Owner"; this.checkBoxOwner.UseVisualStyleBackColor = true; // // checkBoxContainer // this.checkBoxContainer.AutoSize = true; this.checkBoxContainer.Location = new System.Drawing.Point(307, 69); this.checkBoxContainer.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxContainer.Name = "checkBoxContainer"; this.checkBoxContainer.Size = new System.Drawing.Size(91, 21); this.checkBoxContainer.TabIndex = 6; this.checkBoxContainer.Text = "Container"; this.checkBoxContainer.UseVisualStyleBackColor = true; // // checkBoxCacheType // this.checkBoxCacheType.AutoSize = true; this.checkBoxCacheType.Location = new System.Drawing.Point(27, 97); this.checkBoxCacheType.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxCacheType.Name = "checkBoxCacheType"; this.checkBoxCacheType.Size = new System.Drawing.Size(101, 21); this.checkBoxCacheType.TabIndex = 5; this.checkBoxCacheType.Text = "Cache type"; this.checkBoxCacheType.UseVisualStyleBackColor = true; // // checkBoxNote // this.checkBoxNote.AutoSize = true; this.checkBoxNote.Enabled = false; this.checkBoxNote.Location = new System.Drawing.Point(307, 41); this.checkBoxNote.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxNote.Name = "checkBoxNote"; this.checkBoxNote.Size = new System.Drawing.Size(60, 21); this.checkBoxNote.TabIndex = 4; this.checkBoxNote.Text = "Note"; this.checkBoxNote.UseVisualStyleBackColor = true; // // checkBoxHints // this.checkBoxHints.AutoSize = true; this.checkBoxHints.Location = new System.Drawing.Point(169, 69); this.checkBoxHints.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxHints.Name = "checkBoxHints"; this.checkBoxHints.Size = new System.Drawing.Size(62, 21); this.checkBoxHints.TabIndex = 3; this.checkBoxHints.Text = "Hints"; this.checkBoxHints.UseVisualStyleBackColor = true; // // checkBoxCoords // this.checkBoxCoords.AutoSize = true; this.checkBoxCoords.Location = new System.Drawing.Point(169, 41); this.checkBoxCoords.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxCoords.Name = "checkBoxCoords"; this.checkBoxCoords.Size = new System.Drawing.Size(75, 21); this.checkBoxCoords.TabIndex = 2; this.checkBoxCoords.Text = "Coords"; this.checkBoxCoords.UseVisualStyleBackColor = true; // // checkBoxName // this.checkBoxName.AutoSize = true; this.checkBoxName.Location = new System.Drawing.Point(27, 69); this.checkBoxName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxName.Name = "checkBoxName"; this.checkBoxName.Size = new System.Drawing.Size(67, 21); this.checkBoxName.TabIndex = 1; this.checkBoxName.Text = "Name"; this.checkBoxName.UseVisualStyleBackColor = true; // // checkBoxCode // this.checkBoxCode.AutoSize = true; this.checkBoxCode.Location = new System.Drawing.Point(27, 41); this.checkBoxCode.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.checkBoxCode.Name = "checkBoxCode"; this.checkBoxCode.Size = new System.Drawing.Size(63, 21); this.checkBoxCode.TabIndex = 0; this.checkBoxCode.Text = "Code"; this.checkBoxCode.UseVisualStyleBackColor = true; // // saveFileDialog1 // this.saveFileDialog1.Filter = "OV2 files|*.ov2"; // // buttonOK // this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Enabled = false; this.buttonOK.Location = new System.Drawing.Point(185, 271); this.buttonOK.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(116, 28); this.buttonOK.TabIndex = 1; this.buttonOK.Text = "OK"; this.buttonOK.UseVisualStyleBackColor = true; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(17, 197); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 17); this.label1.TabIndex = 2; this.label1.Text = "File"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(21, 218); this.textBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(395, 22); this.textBox1.TabIndex = 3; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // button1 // this.button1.Location = new System.Drawing.Point(425, 214); this.button1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(44, 28); this.button1.TabIndex = 4; this.button1.Text = "..."; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // ExportOV2Form // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(481, 314); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Controls.Add(this.buttonOK); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExportOV2Form"; this.Text = "ExportOV2Form"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.CheckBox checkBoxCode; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.CheckBox checkBoxName; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.CheckBox checkBoxNote; private System.Windows.Forms.CheckBox checkBoxHints; private System.Windows.Forms.CheckBox checkBoxCoords; private System.Windows.Forms.CheckBox checkBoxContainer; private System.Windows.Forms.CheckBox checkBoxCacheType; private System.Windows.Forms.CheckBox checkBoxFavorites; private System.Windows.Forms.CheckBox checkBoxOwner; private System.Windows.Forms.CheckBox checkBoxDifficulty; private System.Windows.Forms.CheckBox checkBoxTerrain; } }
49.090909
107
0.602635
[ "MIT" ]
GlobalcachingEU/GAPP
DefaultPlugins/GlobalcachingApplication.Plugins.OV2/ExportOV2Form.Designer.cs
14,042
C#
using DynamicMVC.DynamicEntityMetadataLibrary.Models; using DynamicMVC.UI.DynamicMVC.ViewModels; namespace DynamicMVC.UI.DynamicMVC.Interfaces { public interface IDynamicDetailsViewModelBuilder { DynamicDetailsViewModel Build(DynamicEntityMetadata dynamicEntityMetadata, dynamic detailModel); } }
31.8
104
0.820755
[ "MIT" ]
ashumeow/noobs
bootstrap_ef6_MVC/bootstrap_ef6_MVC/DynamicMVC/Interfaces/IDynamicDetailsViewModelBuilder.cs
320
C#
using System.Web.UI.HtmlControls; using System; using System.Diagnostics; using System.Data; using System.Web.UI.WebControls; using Microsoft.VisualBasic; using System.Collections; using System.Web.UI; using System.Web; //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DNNStuff.SQLViewPro.StandardReports { public partial class TemplateReportControl { ///<summary> ///phContent control. ///</summary> ///<remarks> ///Auto-generated field. ///To modify move field declaration from designer file to code-behind file. ///</remarks> protected System.Web.UI.WebControls.PlaceHolder phContent; ///<summary> ///cmdExportExcel control. ///</summary> ///<remarks> ///Auto-generated field. ///To modify move field declaration from designer file to code-behind file. ///</remarks> protected System.Web.UI.WebControls.LinkButton cmdExportExcel; } }
24.1
80
0.619087
[ "MIT" ]
UpendoVentures/dnnstuff.sqlviewpro
Reports/Standard/Report/TemplateReportControl.ascx.designer.cs
1,205
C#
using PG.Commons.Xml.Values; namespace PG.StarWarsGame.Commons.Xml.Tags.Engine.FoC { public sealed class MaxGalacticZoomDistanceXmlTagDefinition : AXmlTagDefinition { private const string KEY_ID = "Max_Galactic_Zoom_Distance"; private const XmlValueType PG_TYPE = XmlValueType.Float; private const XmlValueTypeInternal INTERNAL_TYPE = XmlValueTypeInternal.Undefined; private const bool IS_SINGLETON = true; public override string Id => KEY_ID; public override XmlValueType Type => PG_TYPE; public override XmlValueTypeInternal TypeInternal => INTERNAL_TYPE; public override bool IsSingleton => IS_SINGLETON; } }
40.529412
90
0.741655
[ "MIT" ]
AlamoEngine-Tools/PetroglyphTools
PG.StarWarsGame/PG.StarWarsGame/Commons/Xml/Tags/Engine/FoC/MaxGalacticZoomDistanceXmlTagDefinition.cs
689
C#
using System.Threading.Tasks; using NetB.Dependency; using NetB.Runtime.Session; namespace NetB.Application.Features { /// <summary> /// Default implementation for <see cref="IFeatureChecker"/>. /// </summary> public class FeatureChecker : IFeatureChecker, ITransientDependency { /// <summary> /// Reference to current session. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Reference to the store used to get feature values. /// </summary> public IFeatureValueStore FeatureValueStore { get; set; } private readonly IFeatureManager _featureManager; /// <summary> /// Creates a new <see cref="FeatureChecker"/> object. /// </summary> public FeatureChecker(IFeatureManager featureManager) { _featureManager = featureManager; FeatureValueStore = NullFeatureValueStore.Instance; AbpSession = NullAbpSession.Instance; } /// <inheritdoc/> public Task<string> GetValueAsync(string name) { if (!AbpSession.TenantId.HasValue) { throw new AbpException("FeatureChecker can not get a feature value by name. TenantId is not set in the IAbpSession!"); } return GetValueAsync(AbpSession.TenantId.Value, name); } /// <inheritdoc/> public async Task<string> GetValueAsync(int tenantId, string name) { var feature = _featureManager.Get(name); var value = await FeatureValueStore.GetValueOrNullAsync(tenantId, feature); if (value == null) { return feature.DefaultValue; } return value; } } }
30.15
134
0.59204
[ "MIT" ]
liuyuliuyu520/AbpLearn
NetB/NetB/Application/Features/FeatureChecker.cs
1,811
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace AIBots { public partial class NetworkForm<World, Bot, Settings> : Form where Settings : AbstractSettings where Bot : AbstractBot<World,Settings> where World : IWorld<Bot, Settings> { private IMainForm<Bot> parent; public NetworkForm(IMainForm<Bot> parent) { this.parent = parent; InitializeComponent(); DoubleBuffered = true; } protected override void OnResize(EventArgs e) { base.OnResize(e); Invalidate(); } protected override void OnPaint(PaintEventArgs e) { Bot b = parent.SelectedBot; if (b != null) { NeuralNetworkDrawer.DrawNetwork(b.Network, b.CurrentNeuronState, e.Graphics, this.ClientSize.Width, this.ClientSize.Height); } base.OnPaint(e); } private void tmr_Tick(object sender, EventArgs e) { Invalidate(); } } }
26.270833
141
0.568596
[ "MIT" ]
drake7707/botworld
AIBots/AIBots/NetworkForm.cs
1,263
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using GoCardless.Internals; using GoCardless.Resources; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace GoCardless.Services { /// <summary> /// Service class for working with creditor resources. /// /// Each [payment](#core-endpoints-payments) taken through the API is linked /// to a "creditor", to whom the payment is then paid out. In most cases /// your organisation will have a single "creditor", but the API also /// supports collecting payments on behalf of others. /// /// Please get in touch if you wish to use this endpoint. Currently, for /// Anti Money Laundering reasons, any creditors you add must be directly /// related to your organisation. /// </summary> public class CreditorService { private readonly GoCardlessClient _goCardlessClient; /// <summary> /// Constructor. Users of this library should not call this. An instance of this /// class can be accessed through an initialised GoCardlessClient. /// </summary> public CreditorService(GoCardlessClient goCardlessClient) { _goCardlessClient = goCardlessClient; } /// <summary> /// Creates a new creditor. /// </summary> /// <param name="request">An optional `CreditorCreateRequest` representing the body for this create request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A single creditor resource</returns> public Task<CreditorResponse> CreateAsync(CreditorCreateRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorCreateRequest(); var urlParams = new List<KeyValuePair<string, object>> {}; return _goCardlessClient.ExecuteAsync<CreditorResponse>(HttpMethod.Post, "/creditors", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "creditors", customiseRequestMessage); } /// <summary> /// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of /// your creditors. /// </summary> /// <param name="request">An optional `CreditorListRequest` representing the query parameters for this list request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A set of creditor resources</returns> public Task<CreditorListResponse> ListAsync(CreditorListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorListRequest(); var urlParams = new List<KeyValuePair<string, object>> {}; return _goCardlessClient.ExecuteAsync<CreditorListResponse>(HttpMethod.Get, "/creditors", urlParams, request, null, null, customiseRequestMessage); } /// <summary> /// Get a lazily enumerated list of creditors. /// This acts like the #list method, but paginates for you automatically. /// </summary> public IEnumerable<Creditor> All(CreditorListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorListRequest(); string cursor = null; do { request.After = cursor; var result = Task.Run(() => ListAsync(request, customiseRequestMessage)).Result; foreach (var item in result.Creditors) { yield return item; } cursor = result.Meta?.Cursors?.After; } while (cursor != null); } /// <summary> /// Get a lazily enumerated list of creditors. /// This acts like the #list method, but paginates for you automatically. /// </summary> public IEnumerable<Task<IReadOnlyList<Creditor>>> AllAsync(CreditorListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorListRequest(); return new TaskEnumerable<IReadOnlyList<Creditor>, string>(async after => { request.After = after; var list = await this.ListAsync(request, customiseRequestMessage); return Tuple.Create(list.Creditors, list.Meta?.Cursors?.After); }); } /// <summary> /// Retrieves the details of an existing creditor. /// </summary> /// <param name="identity">Unique identifier, beginning with "CR".</param> /// <param name="request">An optional `CreditorGetRequest` representing the query parameters for this get request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A single creditor resource</returns> public Task<CreditorResponse> GetAsync(string identity, CreditorGetRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorGetRequest(); if (identity == null) throw new ArgumentException(nameof(identity)); var urlParams = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("identity", identity), }; return _goCardlessClient.ExecuteAsync<CreditorResponse>(HttpMethod.Get, "/creditors/:identity", urlParams, request, null, null, customiseRequestMessage); } /// <summary> /// Updates a creditor object. Supports all of the fields supported when /// creating a creditor. /// </summary> /// <param name="identity">Unique identifier, beginning with "CR".</param> /// <param name="request">An optional `CreditorUpdateRequest` representing the body for this update request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A single creditor resource</returns> public Task<CreditorResponse> UpdateAsync(string identity, CreditorUpdateRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new CreditorUpdateRequest(); if (identity == null) throw new ArgumentException(nameof(identity)); var urlParams = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("identity", identity), }; return _goCardlessClient.ExecuteAsync<CreditorResponse>(HttpMethod.Put, "/creditors/:identity", urlParams, request, null, "creditors", customiseRequestMessage); } } /// <summary> /// Creates a new creditor. /// </summary> public class CreditorCreateRequest : IHasIdempotencyKey { /// <summary> /// The first line of the creditor's address. /// </summary> [JsonProperty("address_line1")] public string AddressLine1 { get; set; } /// <summary> /// The second line of the creditor's address. /// </summary> [JsonProperty("address_line2")] public string AddressLine2 { get; set; } /// <summary> /// The third line of the creditor's address. /// </summary> [JsonProperty("address_line3")] public string AddressLine3 { get; set; } /// <summary> /// The city of the creditor's address. /// </summary> [JsonProperty("city")] public string City { get; set; } /// <summary> /// [ISO /// 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) /// alpha-2 code. /// </summary> [JsonProperty("country_code")] public string CountryCode { get; set; } /// <summary> /// Linked resources. /// </summary> [JsonProperty("links")] public IDictionary<string, string> Links { get; set; } /// <summary> /// The creditor's name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The creditor's postal code. /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; set; } /// <summary> /// The creditor's address region, county or department. /// </summary> [JsonProperty("region")] public string Region { get; set; } /// <summary> /// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures. /// Any requests, where supported, to create a resource with a key that has previously been used will not succeed. /// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys /// </summary> [JsonIgnore] public string IdempotencyKey { get; set; } } /// <summary> /// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your /// creditors. /// </summary> public class CreditorListRequest { /// <summary> /// Cursor pointing to the start of the desired set. /// </summary> [JsonProperty("after")] public string After { get; set; } /// <summary> /// Cursor pointing to the end of the desired set. /// </summary> [JsonProperty("before")] public string Before { get; set; } /// <summary> /// Limit to records created within certain times. /// </summary> [JsonProperty("created_at")] public CreatedAtParam CreatedAt { get; set; } /// <summary> /// Specify filters to limit records by creation time. /// </summary> public class CreatedAtParam { /// <summary> /// Limit to records created after the specified date-time. /// </summary> [JsonProperty("gt")] public DateTimeOffset? GreaterThan { get; set; } /// <summary> /// Limit to records created on or after the specified date-time. /// </summary> [JsonProperty("gte")] public DateTimeOffset? GreaterThanOrEqual { get; set; } /// <summary> /// Limit to records created before the specified date-time. /// </summary> [JsonProperty("lt")] public DateTimeOffset? LessThan { get; set; } /// <summary> ///Limit to records created on or before the specified date-time. /// </summary> [JsonProperty("lte")] public DateTimeOffset? LessThanOrEqual { get; set; } } /// <summary> /// Number of records to return. /// </summary> [JsonProperty("limit")] public int? Limit { get; set; } } /// <summary> /// Retrieves the details of an existing creditor. /// </summary> public class CreditorGetRequest { } /// <summary> /// Updates a creditor object. Supports all of the fields supported when /// creating a creditor. /// </summary> public class CreditorUpdateRequest { /// <summary> /// The first line of the creditor's address. /// </summary> [JsonProperty("address_line1")] public string AddressLine1 { get; set; } /// <summary> /// The second line of the creditor's address. /// </summary> [JsonProperty("address_line2")] public string AddressLine2 { get; set; } /// <summary> /// The third line of the creditor's address. /// </summary> [JsonProperty("address_line3")] public string AddressLine3 { get; set; } /// <summary> /// The city of the creditor's address. /// </summary> [JsonProperty("city")] public string City { get; set; } /// <summary> /// [ISO /// 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) /// alpha-2 code. /// </summary> [JsonProperty("country_code")] public string CountryCode { get; set; } /// <summary> /// Linked resources. /// </summary> [JsonProperty("links")] public CreditorLinks Links { get; set; } /// <summary> /// Linked resources for a Creditor. /// </summary> public class CreditorLinks { /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in AUD. /// </summary> [JsonProperty("default_aud_payout_account")] public string DefaultAudPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in DKK. /// </summary> [JsonProperty("default_dkk_payout_account")] public string DefaultDkkPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in EUR. /// </summary> [JsonProperty("default_eur_payout_account")] public string DefaultEurPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in GBP. /// </summary> [JsonProperty("default_gbp_payout_account")] public string DefaultGbpPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in NZD. /// </summary> [JsonProperty("default_nzd_payout_account")] public string DefaultNzdPayoutAccount { get; set; } /// <summary> /// ID of the [bank account](#core-endpoints-creditor-bank-accounts) /// which is set up to receive payouts in SEK. /// </summary> [JsonProperty("default_sek_payout_account")] public string DefaultSekPayoutAccount { get; set; } } /// <summary> /// The creditor's name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The creditor's postal code. /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; set; } /// <summary> /// The creditor's address region, county or department. /// </summary> [JsonProperty("region")] public string Region { get; set; } } /// <summary> /// An API response for a request returning a single creditor. /// </summary> public class CreditorResponse : ApiResponse { /// <summary> /// The creditor from the response. /// </summary> [JsonProperty("creditors")] public Creditor Creditor { get; private set; } } /// <summary> /// An API response for a request returning a list of creditors. /// </summary> public class CreditorListResponse : ApiResponse { /// <summary> /// The list of creditors from the response. /// </summary> [JsonProperty("creditors")] public IReadOnlyList<Creditor> Creditors { get; private set; } /// <summary> /// Response metadata (e.g. pagination cursors) /// </summary> public Meta Meta { get; private set; } } }
37.020408
208
0.589489
[ "MIT" ]
peterdeme/gocardless-dotnet
GoCardless/Services/CreditorService.cs
16,326
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// DispatchInterface OLEFormat /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836234.aspx ///</summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class OLEFormat : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(OLEFormat); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public OLEFormat(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public OLEFormat(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822184.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff841084.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff195035.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); ICOMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838576.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public object Object { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Object", paramsArray); ICOMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff823197.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public string ProgId { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ProgId", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840335.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public void Activate() { object[] paramsArray = null; Invoker.Method(this, "Activate", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838598.aspx /// </summary> /// <param name="verb">optional object Verb</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public void Verb(object verb) { object[] paramsArray = Invoker.ValidateParamsArray(verb); Invoker.Method(this, "Verb", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838598.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public void Verb() { object[] paramsArray = null; Invoker.Method(this, "Verb", paramsArray); } #endregion #pragma warning restore } }
32.388889
193
0.682016
[ "MIT" ]
brunobola/NetOffice
Source/Excel/DispatchInterfaces/OLEFormat.cs
7,581
C#
namespace TestAssembly.CommonInterface.TestObjects { internal interface IService21 : IService2 {} }
25.75
50
0.805825
[ "MIT" ]
sunloving/photosphere
src/tests/test-assemblies/TestAssembly.CommonInterface/TestObjects/IService21.cs
103
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Threading.Tasks; using FluentAssertions; using WorkspaceServer.Packaging; using WorkspaceServer.Tests.Packaging; using Xunit; namespace WorkspaceServer.Tests { public class PackageRegistryTests { private readonly PackageRegistry _registry = new PackageRegistry(); [Fact(Skip = "Cache is disabled for the moment")] public async Task PackageRegistry_will_return_same_instance_of_a_package() { // FIX: (PackageRegistry_will_return_same_instance_of_a_package) var packageName = PackageUtilities.CreateDirectory(nameof(PackageRegistry_will_return_same_instance_of_a_package)).Name; _registry.Add(packageName, options => options.CreateUsingDotnet("console")); var package1 = await _registry.Get<IPackage>(packageName); var package2 = await _registry.Get<IPackage>(packageName); package1.Should().BeSameAs(package2); } } }
36.15625
132
0.71478
[ "MIT" ]
AzureMentor/try
WorkspaceServer.Tests/PackageRegistryTests.cs
1,157
C#
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using InstallerLib; using dotNetUnitTestsRunner; using System.IO; using Microsoft.Win32; using System.Diagnostics; namespace dotNetInstallerUnitTests { [TestFixture] public class PromptForOptionalUnitTests { [Test] public void TestPromptForOptionalNotSet() { Console.WriteLine("TestPromptForOptionalNotSet"); // configuration with a required and optional component that will auto-start // and won't prompt or execute the optional component string markerFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); setupConfiguration.auto_start = true; setupConfiguration.auto_close_if_installed = true; setupConfiguration.prompt_for_optional_components = false; setupConfiguration.installation_completed = ""; setupConfiguration.installation_none = ""; configFile.Children.Add(setupConfiguration); // dummy required component ComponentCmd component_required = new ComponentCmd(); setupConfiguration.Children.Add(component_required); component_required.required_install = true; component_required.supports_install = true; component_required.command = "dummy"; InstalledCheckRegistry check_required = new InstalledCheckRegistry(); check_required.fieldname = ""; check_required.path = "SOFTWARE"; check_required.comparison = installcheckregistry_comparison.exists; component_required.Children.Add(check_required); // dummy optional component ComponentCmd component_optional = new ComponentCmd(); setupConfiguration.Children.Add(component_optional); component_optional.required_install = false; component_optional.supports_install = true; component_optional.command = string.Format("cmd.exe /C dir > \"{0}\"", markerFilename); InstalledCheckFile check_optional = new InstalledCheckFile(); check_optional.filename = markerFilename; check_optional.comparison = installcheckfile_comparison.exists; component_optional.Children.Add(check_optional); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // will not auto close since all components installed successfully dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.quiet = false; options.autostart = true; Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options)); Assert.IsFalse(File.Exists(markerFilename)); File.Delete(configFilename); } [Test] public void TestPromptForOptionalSet() { Console.WriteLine("TestPromptForOptionalSet"); // configuration with a required and optional component // will prompt for the optional component, auto-start and install it string markerFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); ConfigFile configFile = new ConfigFile(); SetupConfiguration setupConfiguration = new SetupConfiguration(); setupConfiguration.auto_start = true; setupConfiguration.auto_close_if_installed = true; setupConfiguration.prompt_for_optional_components = true; setupConfiguration.installation_completed = ""; setupConfiguration.installation_none = ""; configFile.Children.Add(setupConfiguration); // dummy required component ComponentCmd component_required = new ComponentCmd(); setupConfiguration.Children.Add(component_required); component_required.required_install = true; component_required.supports_install = true; component_required.command = "dummy"; InstalledCheckRegistry check_required = new InstalledCheckRegistry(); check_required.fieldname = ""; check_required.path = "SOFTWARE"; check_required.comparison = installcheckregistry_comparison.exists; component_required.Children.Add(check_required); // dummy optional component ComponentCmd component_optional = new ComponentCmd(); setupConfiguration.Children.Add(component_optional); component_optional.required_install = false; component_optional.supports_install = true; component_optional.command = string.Format("cmd.exe /C dir > \"{0}\"", markerFilename); InstalledCheckFile check_optional = new InstalledCheckFile(); check_optional.filename = markerFilename; check_optional.comparison = installcheckfile_comparison.exists; component_optional.Children.Add(check_optional); string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml"); Console.WriteLine("Writing '{0}'", configFilename); configFile.SaveAs(configFilename); // will not auto close since all components installed successfully dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename); options.quiet = false; options.autostart = true; Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options)); Assert.IsTrue(File.Exists(markerFilename)); File.Delete(configFilename); File.Delete(markerFilename); } } }
43.717391
112
0.670479
[ "MIT" ]
sanjeevpunj/dotnetinstaller
UnitTests/dotNetInstallerUnitTests/PromptForOptionalUnitTests.cs
6,033
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2014-11-06.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CloudFront.Model { ///<summary> /// CloudFront exception /// </summary> public class TooManyOriginsException : AmazonCloudFrontException { /// <summary> /// Constructs a new TooManyOriginsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public TooManyOriginsException(string message) : base(message) {} /// <summary> /// Construct instance of TooManyOriginsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TooManyOriginsException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of TooManyOriginsException /// </summary> /// <param name="innerException"></param> public TooManyOriginsException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of TooManyOriginsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyOriginsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of TooManyOriginsException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyOriginsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} } }
38.924051
165
0.630244
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/TooManyOriginsException.cs
3,075
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Pipeline; namespace Azure.Data.AppConfiguration { /// <summary> /// Options that allow to configure the management of the request sent to the service /// </summary> public class ConfigurationClientOptions : ClientOptions { /// <summary> /// The latest service version supported by this client library. /// </summary> internal const ServiceVersion LatestVersion = ServiceVersion.Default; /// <summary> /// The versions of App Config Service supported by this client library. /// </summary> public enum ServiceVersion { /// <summary> /// Uses the latest service version /// </summary> Default = 0 } /// <summary> /// Gets the <see cref="ServiceVersion"/> of the service API used when /// making requests. /// </summary> public ServiceVersion Version { get; } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationClientOptions"/> /// class. /// </summary> /// <param name="version"> /// The <see cref="ServiceVersion"/> of the service API used when /// making requests. /// </param> public ConfigurationClientOptions(ServiceVersion version = ServiceVersion.Default) { this.Version = version; } } }
31.204082
90
0.584696
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/appconfiguration/Azure.Data.AppConfiguration/src/ConfigurationClientOptions.cs
1,531
C#
using System; namespace Demo.Engine.Core.Interfaces.Platform { public interface IOSMessageHandler { /// <summary> /// Call this on each tick of the main loop to process all Windows messages in the queue /// </summary> /// <returns>if the Tick is successful</returns> /// <exception cref="InvalidOperationException">An error occured</exception> bool DoEvents(IRenderingControl control); } }
32.142857
96
0.662222
[ "MIT" ]
DemoBytom/DemoEngine
src/Demo.Engine.Core/Interfaces/Platform/IOSMessageHandler.cs
450
C#
namespace GreenPipes.BenchmarkConsole.Collections { using System; public class SinglePayloadCollection : BasePayloadCollection { readonly IReadOnlyPayloadCollection _parent; readonly IPayloadValue _payload; public SinglePayloadCollection(IPayloadValue payload, IReadOnlyPayloadCollection parent = null) : base(parent) { _payload = payload; _parent = parent; } public override bool HasPayloadType(Type payloadType) { if (_payload.Implements(payloadType)) return true; return base.HasPayloadType(payloadType); } public override bool TryGetPayload<TPayload>(out TPayload payload) { if (_payload.TryGetValue(out TPayload payloadValue)) { payload = payloadValue; return true; } return base.TryGetPayload(out payload); } public override IPayloadCollection Add(IPayloadValue payload) { return new ArrayPayloadCollection(_parent, payload, _payload); } } }
26.363636
103
0.602586
[ "Apache-2.0" ]
MassTransit/GreenPipes
tests/GreenPipes.BenchmarkConsole/Collections/SinglePayloadCollection.cs
1,160
C#
using System; using System.Collections.Generic; namespace SFA.DAS.EAS.Account.Api.Types { public class TransactionViewModel { public string Description { get; set; } public TransactionItemType TransactionType { get; set; } public DateTime TransactionDate { get; set; } public DateTime DateCreated { get; set; } public decimal Amount { get; set; } public decimal Balance { get; set; } public List<TransactionViewModel> SubTransactions { get; set; } public string ResourceUri { get; set; } } }
31.666667
71
0.659649
[ "MIT" ]
SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EAS.Account.Api.Types/TransactionViewModel.cs
572
C#