commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
7a97c257d80b8e77455ec9ed210d6c7a4898c8ad
Azuria/Middleware/StaticHeaderMiddleware.cs
Azuria/Middleware/StaticHeaderMiddleware.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azuria.ErrorHandling; using Azuria.Requests.Builder; namespace Azuria.Middleware { /// <summary> /// Adds some static headers to the request. They indicate things like application, version and api key used. /// </summary> public class StaticHeaderMiddleware : IMiddleware { private readonly IDictionary<string, string> _staticHeaders; /// <summary> /// /// </summary> /// <param name="staticHeaders"></param> public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders) { this._staticHeaders = staticHeaders; } /// <inheritdoc /> public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next, CancellationToken cancellationToken = default) { return next(request.WithHeader(this._staticHeaders), cancellationToken); } /// <inheritdoc /> public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request, MiddlewareAction<T> next, CancellationToken cancellationToken = default) { return next(request.WithHeader(this._staticHeaders), cancellationToken); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azuria.ErrorHandling; using Azuria.Requests.Builder; namespace Azuria.Middleware { /// <summary> /// Adds some static headers to the request. They indicate things like application, version and api key used. /// </summary> public class StaticHeaderMiddleware : IMiddleware { /// <summary> /// /// </summary> /// <param name="staticHeaders"></param> public StaticHeaderMiddleware(IDictionary<string, string> staticHeaders) { this.Header = staticHeaders; } /// <summary> /// /// </summary> /// <value></value> public IDictionary<string, string> Header { get; } /// <inheritdoc /> public Task<IProxerResult> Invoke(IRequestBuilder request, MiddlewareAction next, CancellationToken cancellationToken = default) { return next(request.WithHeader(this.Header), cancellationToken); } /// <inheritdoc /> public Task<IProxerResult<T>> InvokeWithResult<T>(IRequestBuilderWithResult<T> request, MiddlewareAction<T> next, CancellationToken cancellationToken = default) { return next(request.WithHeader(this.Header), cancellationToken); } } }
Make header of header middleware publicly accessible
Make header of header middleware publicly accessible
C#
mit
InfiniteSoul/Azuria
fbff56d52482b7739481d7c09118f7f779c60d6a
src/SIM.Pipelines/Install/Containers/InstallContainerArgs.cs
src/SIM.Pipelines/Install/Containers/InstallContainerArgs.cs
using System; using System.Globalization; using ContainerInstaller; using SIM.Pipelines.Processors; namespace SIM.Pipelines.Install.Containers { public enum Topology { Xm1, Xp0, Xp1 } public static class StringExtentions { public static Topology ToTopology(this string tpl) { if (tpl.Equals("xp0", StringComparison.InvariantCultureIgnoreCase)) { return Topology.Xp0; } if (tpl.Equals("xp1", StringComparison.InvariantCultureIgnoreCase)) { return Topology.Xp1; } if (tpl.Equals("xm1", StringComparison.InvariantCultureIgnoreCase)) { return Topology.Xm1; } throw new InvalidOperationException("Topology cannot be resolved from '" + tpl + "'"); } } public class InstallContainerArgs : ProcessorArgs { public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology) { this.EnvModel = model; this.FilesRoot = filesRoot; this.Destination = destination; this.Topology = topology.ToTopology(); } public EnvModel EnvModel { get; } public string Destination { get; set; } public Topology Topology { get; } public string FilesRoot { get; } } }
using System; using System.Globalization; using ContainerInstaller; using SIM.Pipelines.Processors; namespace SIM.Pipelines.Install.Containers { public enum Topology { Xm1, Xp0, Xp1 } public class InstallContainerArgs : ProcessorArgs { public InstallContainerArgs(EnvModel model, string destination, string filesRoot, string topology) { this.EnvModel = model; this.FilesRoot = filesRoot; this.Destination = destination; this.Topology = (Topology)Enum.Parse(typeof(Topology), topology, true); } public EnvModel EnvModel { get; } public string Destination { get; set; } public Topology Topology { get; } public string FilesRoot { get; } } }
Simplify parsing string to Topology enum
Simplify parsing string to Topology enum
C#
mit
Sitecore/Sitecore-Instance-Manager
4d854ee10073b7f91985c35298f1c81a580543f4
EDDiscovery/EliteDangerous/JournalEvents/JournalFileHeader.cs
EDDiscovery/EliteDangerous/JournalEvents/JournalFileHeader.cs
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EDDiscovery.EliteDangerous.JournalEvents { public class JournalFileHeader : JournalEntry { public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader) { GameVersion = Tools.GetStringDef(evt["gameversion"]); Build = Tools.GetStringDef(evt["build"]); Language = Tools.GetStringDef(evt["language"]); } public string GameVersion { get; set; } public string Build { get; set; } public string Language { get; set; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EDDiscovery.EliteDangerous.JournalEvents { public class JournalFileHeader : JournalEntry { public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader) { GameVersion = Tools.GetStringDef(evt["gameversion"]); Build = Tools.GetStringDef(evt["build"]); Language = Tools.GetStringDef(evt["language"]); } public string GameVersion { get; set; } public string Build { get; set; } public string Language { get; set; } public bool Beta { get { if (GameVersion.Contains("Beta")) return true; if (GameVersion.Equals("2.2") && Build.Contains("r121645/r0")) return true; return false; } } } }
Add Beta property on FleaHeader event
Add Beta property on FleaHeader event
C#
apache-2.0
EDDiscovery/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery,EDDiscovery/EDDiscovery,EDDiscovery/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery,klightspeed/EDDiscovery
2854b9e8ad075e99f9915493ed99ba078bde5302
Ets.Mobile/Ets.Mobile.Shared/Views/Pages/Account/LoginPage.cs
Ets.Mobile/Ets.Mobile.Shared/Views/Pages/Account/LoginPage.cs
using Ets.Mobile.ViewModel.Pages.Account; using ReactiveUI; using System; using System.Reactive.Linq; using Windows.UI.Xaml; namespace Ets.Mobile.Pages.Account { public partial class LoginPage : IViewFor<LoginViewModel> { #region IViewFor<T> public LoginViewModel ViewModel { get { return (LoginViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } } public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null)); object IViewFor.ViewModel { get { return ViewModel; } set { ViewModel = (LoginViewModel)value; } } #endregion public LoginPage() { InitializeComponent(); // When ViewModel is set this.WhenAnyValue(x => x.ViewModel) .Where(x => x != null) .Subscribe(x => { #if DEBUG ViewModel.UserName = ""; ViewModel.Password = ""; #endif Login.Click += (sender, arg) => { ErrorMessage.Visibility = Visibility.Collapsed; }; }); // Error Handling UserError.RegisterHandler(ue => { ErrorMessage.Text = ue.ErrorMessage; ErrorMessage.Visibility = Visibility.Visible; return Observable.Return(RecoveryOptionResult.CancelOperation); }); this.BindCommand(ViewModel, x => x.Login, x => x.Login); PartialInitialize(); } partial void PartialInitialize(); } }
using Ets.Mobile.ViewModel.Pages.Account; using ReactiveUI; using System; using System.Reactive.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; namespace Ets.Mobile.Pages.Account { public partial class LoginPage : IViewFor<LoginViewModel> { #region IViewFor<T> public LoginViewModel ViewModel { get { return (LoginViewModel)GetValue(ViewModelProperty); } set { SetValue(ViewModelProperty, value); } } public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(LoginViewModel), typeof(LoginPage), new PropertyMetadata(null)); object IViewFor.ViewModel { get { return ViewModel; } set { ViewModel = (LoginViewModel)value; } } #endregion public LoginPage() { InitializeComponent(); // When ViewModel is set this.WhenAnyValue(x => x.ViewModel) .Where(x => x != null) .Subscribe(x => { Login.Events().Click.Subscribe(arg => ErrorMessage.Visibility = Visibility.Collapsed); }); // Error Handling UserError.RegisterHandler(ue => { ErrorMessage.Text = ue.ErrorMessage; ErrorMessage.Visibility = Visibility.Visible; return Observable.Return(RecoveryOptionResult.CancelOperation); }); PartialInitialize(); } partial void PartialInitialize(); } }
Use ReactiveUI Events for Click Handler
Use ReactiveUI Events for Click Handler
C#
apache-2.0
ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms
d5af3177ac0a82410dac85f5ffd25cd250ee6a74
AllReadyApp/Web-App/AllReady.UnitTest/TestBase.cs
AllReadyApp/Web-App/AllReady.UnitTest/TestBase.cs
using AllReady.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting.Internal; namespace AllReady.UnitTest { /// <summary> /// Inherit from this type to implement tests that /// have access to a service provider, empty in-memory /// database, and basic configuration. /// </summary> public abstract class TestBase { protected IServiceProvider ServiceProvider { get; private set; } public TestBase() { if (ServiceProvider == null) { var services = new ServiceCollection(); // set up empty in-memory test db services.AddEntityFramework() .AddEntityFrameworkInMemoryDatabase() .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase()); // add identity service services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<AllReadyContext>(); var context = new DefaultHttpContext(); context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature()); services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context }); // Setup hosting environment IHostingEnvironment hostingEnvironment = new HostingEnvironment(); hostingEnvironment.EnvironmentName = "Development"; services.AddSingleton(x => hostingEnvironment); // set up service provider for tests ServiceProvider = services.BuildServiceProvider(); } } } }
using AllReady.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting.Internal; namespace AllReady.UnitTest { /// <summary> /// Inherit from this type to implement tests that /// have access to a service provider, empty in-memory /// database, and basic configuration. /// </summary> public abstract class TestBase { protected IServiceProvider ServiceProvider { get; private set; } public TestBase() { if (ServiceProvider == null) { var services = new ServiceCollection(); // set up empty in-memory test db services .AddEntityFrameworkInMemoryDatabase() .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider())); // add identity service services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<AllReadyContext>(); var context = new DefaultHttpContext(); context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature()); services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context }); // Setup hosting environment IHostingEnvironment hostingEnvironment = new HostingEnvironment(); hostingEnvironment.EnvironmentName = "Development"; services.AddSingleton(x => hostingEnvironment); // set up service provider for tests ServiceProvider = services.BuildServiceProvider(); } } } }
Fix for EFCore using the same InMemoryDatabase Instance when running tests.
Fix for EFCore using the same InMemoryDatabase Instance when running tests.
C#
mit
timstarbuck/allReady,GProulx/allReady,binaryjanitor/allReady,jonatwabash/allReady,HamidMosalla/allReady,colhountech/allReady,HamidMosalla/allReady,HTBox/allReady,gitChuckD/allReady,gitChuckD/allReady,forestcheng/allReady,pranap/allReady,chinwobble/allReady,VishalMadhvani/allReady,mheggeseth/allReady,mheggeseth/allReady,GProulx/allReady,MisterJames/allReady,gftrader/allReady,colhountech/allReady,stevejgordon/allReady,c0g1t8/allReady,colhountech/allReady,VishalMadhvani/allReady,timstarbuck/allReady,arst/allReady,forestcheng/allReady,MisterJames/allReady,jonatwabash/allReady,enderdickerson/allReady,forestcheng/allReady,shanecharles/allReady,mgmccarthy/allReady,arst/allReady,JowenMei/allReady,BillWagner/allReady,forestcheng/allReady,anobleperson/allReady,binaryjanitor/allReady,GProulx/allReady,GProulx/allReady,dpaquette/allReady,bcbeatty/allReady,stevejgordon/allReady,HamidMosalla/allReady,dpaquette/allReady,bcbeatty/allReady,mipre100/allReady,gftrader/allReady,pranap/allReady,enderdickerson/allReady,anobleperson/allReady,anobleperson/allReady,shanecharles/allReady,gitChuckD/allReady,timstarbuck/allReady,mheggeseth/allReady,c0g1t8/allReady,chinwobble/allReady,dpaquette/allReady,BillWagner/allReady,VishalMadhvani/allReady,BillWagner/allReady,VishalMadhvani/allReady,jonatwabash/allReady,colhountech/allReady,stevejgordon/allReady,JowenMei/allReady,BillWagner/allReady,binaryjanitor/allReady,binaryjanitor/allReady,MisterJames/allReady,c0g1t8/allReady,pranap/allReady,mgmccarthy/allReady,bcbeatty/allReady,bcbeatty/allReady,mgmccarthy/allReady,gftrader/allReady,arst/allReady,mipre100/allReady,HTBox/allReady,shanecharles/allReady,timstarbuck/allReady,gftrader/allReady,enderdickerson/allReady,mipre100/allReady,pranap/allReady,c0g1t8/allReady,HamidMosalla/allReady,chinwobble/allReady,HTBox/allReady,JowenMei/allReady,jonatwabash/allReady,anobleperson/allReady,chinwobble/allReady,arst/allReady,stevejgordon/allReady,MisterJames/allReady,mipre100/allReady,mgmccarthy/allReady,enderdickerson/allReady,HTBox/allReady,shanecharles/allReady,JowenMei/allReady,dpaquette/allReady,gitChuckD/allReady,mheggeseth/allReady
10e1701ef0457c09d918d63c5c053bf60546cb66
src/SpaFallback/SpaFallbackOptions.cs
src/SpaFallback/SpaFallbackOptions.cs
using System; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackOptions { public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = _ => "/index.html"; public bool AllowFileExtensions { get; set; } = false; public bool ThrowIfFallbackFails { get; set; } = true; } }
using System; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackOptions { private static readonly Func<HttpContext, PathString> DefaultFallbackPathFactory = _ => "/index.html"; public Func<HttpContext, PathString> FallbackPathFactory { get; set; } = DefaultFallbackPathFactory; public bool AllowFileExtensions { get; set; } = false; public bool ThrowIfFallbackFails { get; set; } = true; } }
Make default fallback path factory static
Make default fallback path factory static
C#
mit
khellang/Middleware,khellang/Middleware
4cb2ff87b980506afa7e4dab269029cacd8a505e
src/NHibernate.Test/CfgTest/ConfigurationFixture.cs
src/NHibernate.Test/CfgTest/ConfigurationFixture.cs
using System; using NHibernate.Cfg; using NUnit.Framework; namespace NHibernate.Test.CfgTest { /// <summary> /// Summary description for ConfigurationFixture. /// </summary> [TestFixture] public class ConfigurationFixture { [SetUp] public void SetUp() { System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true); } [TearDown] public void TearDown() { System.IO.File.Delete("hibernate.cfg.xml"); } /// <summary> /// Verify that NHibernate can read the configuration from a hibernate.cfg.xml /// file and that the values override what is in the app.config. /// </summary> [Test] public void ReadCfgXmlFromDefaultFile() { Configuration cfg = new Configuration(); cfg.Configure(); Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]); Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]); } } }
using System; using NHibernate.Cfg; using NUnit.Framework; namespace NHibernate.Test.CfgTest { /// <summary> /// Summary description for ConfigurationFixture. /// </summary> [TestFixture] public class ConfigurationFixture { [SetUp] public void SetUp() { System.IO.File.Copy("..\\..\\hibernate.cfg.xml", "hibernate.cfg.xml", true); } [TearDown] public void TearDown() { System.IO.File.Delete("hibernate.cfg.xml"); } /// <summary> /// Verify that NHibernate can read the configuration from a hibernate.cfg.xml /// file and that the values override what is in the app.config. /// </summary> [Test] public void ReadCfgXmlFromDefaultFile() { string origQuerySubst = Cfg.Environment.Properties[Cfg.Environment.QuerySubstitutions] as string; string origConnString = Cfg.Environment.Properties[Cfg.Environment.ConnectionString] as string; Configuration cfg = new Configuration(); cfg.Configure(); Assert.AreEqual( "true 1, false 0, yes 'Y', no 'N'", cfg.Properties[Cfg.Environment.QuerySubstitutions]); Assert.AreEqual( "Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI", cfg.Properties[Cfg.Environment.ConnectionString]); cfg.Properties[Cfg.Environment.QuerySubstitutions] = origQuerySubst; cfg.Properties[Cfg.Environment.ConnectionString] = origConnString; } } }
Test now restores Environment properties back to their original values.
Test now restores Environment properties back to their original values. SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@707
C#
lgpl-2.1
ManufacturingIntelligence/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core
f358778ec834576b199d7c7f4cd5a42deb2d9a49
src/Pioneer.Blog/Views/Home/_HomeLatestPosts.cshtml
src/Pioneer.Blog/Views/Home/_HomeLatestPosts.cshtml
@model List<Post> <section class="home-latest-posts"> <h3 class="header-surround-bar"><span>Latest Posts</span></h3> <div class="row width-100"> @foreach (var post in Model.Take(4)) { <div class="large-3 columns end"> @Html.Partial("_HomePostCard", post) </div> } </div> <div class="row width-100"> @foreach (var post in Model.Skip(4)) { <div class="large-3 columns end"> @Html.Partial("_HomePostCard", post) </div> } </div> </section>
@model List<Post> <section class="home-latest-posts"> <h3 class="header-surround-bar"><span>Latest Posts</span></h3> <div class="row width-100"> @foreach (var post in Model.Take(4)) { <div class="large-3 medium-6 columns end"> @Html.Partial("_HomePostCard", post) </div> } </div> <div class="row width-100"> @foreach (var post in Model.Skip(4)) { <div class="large-3 medium-6 columns end"> @Html.Partial("_HomePostCard", post) </div> } </div> </section>
Add medium breakpoint to home latests posts.
Add medium breakpoint to home latests posts.
C#
mit
PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog
01dd90dad43bb8e87b7c6ad87c0c8a01dd2c8ebd
src/GitTools.IssueTrackers/IssueTrackers/Jira/Extensions/StringExtensions.cs
src/GitTools.IssueTrackers/IssueTrackers/Jira/Extensions/StringExtensions.cs
namespace GitTools.IssueTrackers.Jira { public static class StringExtensions { public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND") { if (!string.IsNullOrWhiteSpace(value)) { value += string.Format(" {0} ", joinText); } else { value = string.Empty; } value += additionalValue; return value; } } }
namespace GitTools.IssueTrackers.Jira { internal static class StringExtensions { public static string AddJiraFilter(this string value, string additionalValue, string joinText = "AND") { if (!string.IsNullOrWhiteSpace(value)) { value += string.Format(" {0} ", joinText); } else { value = string.Empty; } value += additionalValue; return value; } } }
Change class visibility from public to internal for Jira string extensions
Change class visibility from public to internal for Jira string extensions
C#
mit
GitTools/GitTools.IssueTrackers
965d0603ce4346f6be847568336eff24c4b469e0
osu.Game.Rulesets.Osu/Skinning/Argon/ArgonSliderScorePoint.cs
osu.Game.Rulesets.Osu/Skinning/Argon/ArgonSliderScorePoint.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Objects.Drawables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Argon { public class ArgonSliderScorePoint : CircularContainer { private Bindable<Color4> accentColour = null!; private const float size = 12; [BackgroundDependencyLoader] private void load(DrawableHitObject hitObject) { Masking = true; Origin = Anchor.Centre; Size = new Vector2(size); BorderThickness = 3; BorderColour = Color4.White; Child = new Box { RelativeSizeAxes = Axes.Both, AlwaysPresent = true, Alpha = 0, }; accentColour = hitObject.AccentColour.GetBoundCopy(); accentColour.BindValueChanged(accent => BorderColour = accent.NewValue); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Objects.Drawables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Argon { public class ArgonSliderScorePoint : CircularContainer { private Bindable<Color4> accentColour = null!; private const float size = 12; [BackgroundDependencyLoader] private void load(DrawableHitObject hitObject) { Masking = true; Origin = Anchor.Centre; Size = new Vector2(size); BorderThickness = 3; BorderColour = Color4.White; Child = new Box { RelativeSizeAxes = Axes.Both, AlwaysPresent = true, Alpha = 0, }; accentColour = hitObject.AccentColour.GetBoundCopy(); accentColour.BindValueChanged(accent => BorderColour = accent.NewValue, true); } } }
Fix slider tick colour not being applied properly
Fix slider tick colour not being applied properly
C#
mit
peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
3cf6834b495ed68f433e6de8289b30cd3efcd7d7
test/Zuehlke.Eacm.Web.Backend.Tests/CQRS/EventAggregatorExtensionsFixture.cs
test/Zuehlke.Eacm.Web.Backend.Tests/CQRS/EventAggregatorExtensionsFixture.cs
using System; using Xunit; using Zuehlke.Eacm.Web.Backend.CQRS; namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel { public class EventAggregatorExtensionsFixture { [Fact] public void PublishEvent_() { // arrange // act // assert } private class TestEvent : IEvent { public Guid CorrelationId { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Guid Id { get { throw new NotImplementedException(); } } public Guid SourceId { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public DateTime Timestamp { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } } }
using System; using Xunit; using Zuehlke.Eacm.Web.Backend.CQRS; using Zuehlke.Eacm.Web.Backend.Utils.PubSubEvents; namespace Zuehlke.Eacm.Web.Backend.Tests.DomainModel { public class EventAggregatorExtensionsFixture { [Fact] public void PublishEvent_EventAggregatorIsNull_ThrowsException() { // arrange IEventAggregator eventAggegator = null; IEvent e = new TestEvent(); // act Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e)); } [Fact] public void PublishEvent_EventIsNull_ThrowsException() { // arrange IEventAggregator eventAggegator = new EventAggregator(); IEvent e = null; // act Assert.ThrowsAny<ArgumentNullException>(() => CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e)); } [Fact] public void PublishEvent_WithEventSubscription_HandlerGetsCalleds() { // arrange IEventAggregator eventAggegator = new EventAggregator(); IEvent e = new TestEvent(); bool executed = false; eventAggegator.Subscribe<TestEvent>(ev => executed = true); // act CQRS.EventAggregatorExtensions.PublishEvent(eventAggegator, e); Assert.True(executed); } private class TestEvent : IEvent { public Guid CorrelationId { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Guid Id { get { throw new NotImplementedException(); } } public Guid SourceId { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public DateTime Timestamp { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } } }
Implement tests for the EventAggregatorExtensions class.
refactor(configurationproject): Implement tests for the EventAggregatorExtensions class.
C#
mit
lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager,lehmamic/EnterpriseApplicationConfigurationManager
9bc830cacc57dd6e197e3235df614d70419d8250
Project-Aurora/Project-Aurora/Profiles/TModLoader/GSI/GameState_TModLoader.cs
Project-Aurora/Project-Aurora/Profiles/TModLoader/GSI/GameState_TModLoader.cs
using Aurora.Profiles.Generic.GSI.Nodes; using Aurora.Profiles.TModLoader.GSI.Nodes; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aurora.Profiles.TModLoader.GSI { public class GameState_TModLoader : GameState<GameState_TModLoader> { public ProviderNode Provider => NodeFor<ProviderNode>("provider"); public WorldNode World => NodeFor<WorldNode>("world"); public PlayerNode Player => NodeFor<PlayerNode>("player"); public GameState_TModLoader() : base() { } /// <summary> /// Creates a GameState_Terraria instance based on the passed JSON data. /// </summary> /// <param name="JSONstring"></param> public GameState_TModLoader(string JSONstring) : base(JSONstring) { } } }
using Aurora.Profiles.Generic.GSI.Nodes; using Aurora.Profiles.TModLoader.GSI.Nodes; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aurora.Profiles.TModLoader.GSI { public class GameState_TModLoader : GameState { public ProviderNode Provider => NodeFor<ProviderNode>("provider"); public WorldNode World => NodeFor<WorldNode>("world"); public PlayerNode Player => NodeFor<PlayerNode>("player"); public GameState_TModLoader() : base() { } /// <summary> /// Creates a GameState_Terraria instance based on the passed JSON data. /// </summary> /// <param name="JSONstring"></param> public GameState_TModLoader(string JSONstring) : base(JSONstring) { } } }
Fix error with merge on TModLoader GameState.
Fix error with merge on TModLoader GameState.
C#
mit
antonpup/Aurora,antonpup/Aurora,antonpup/Aurora,antonpup/Aurora,antonpup/Aurora
9b3afdfca1db4a1a204d8c0fb472cab102b0ee0e
TechProFantasySoccer/TechProFantasySoccer/App_Start/RouteConfig.cs
TechProFantasySoccer/TechProFantasySoccer/App_Start/RouteConfig.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.Routing; using Microsoft.AspNet.FriendlyUrls; namespace TechProFantasySoccer { public static class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { /*var settings = new FriendlyUrlSettings(); settings.AutoRedirectMode = RedirectMode.Permanent; routes.EnableFriendlyUrls(settings);*/ //Commenting the above code and using the below line gets rid of the master mobile site. routes.EnableFriendlyUrls(); } } }
using System; using System.Collections.Generic; using System.Web; using System.Web.Routing; using Microsoft.AspNet.FriendlyUrls; namespace TechProFantasySoccer { public static class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { var settings = new FriendlyUrlSettings(); settings.AutoRedirectMode = RedirectMode.Permanent; routes.EnableFriendlyUrls(settings); //Commenting the above code and using the below line gets rid of the master mobile site. //routes.EnableFriendlyUrls(); } } }
Switch the settings back for the mobile site. Fix this later
Switch the settings back for the mobile site. Fix this later
C#
mit
GeraldBecker/TechProFantasySoccer,GeraldBecker/TechProFantasySoccer,GeraldBecker/TechProFantasySoccer
e6c3f72d32df17e8a1e49940f4797fca28a49479
exercises/simple-linked-list/Example.cs
exercises/simple-linked-list/Example.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public class SimpleLinkedList<T> : IEnumerable<T> { public SimpleLinkedList(T value) : this(new[] { value }) { } public SimpleLinkedList(IEnumerable<T> values) { var array = values.ToArray(); if (array.Length == 0) { throw new ArgumentException("Cannot create tree from empty list"); } Value = array[0]; Next = null; foreach (var value in array.Skip(1)) { Add(value); } } public T Value { get; } public SimpleLinkedList<T> Next { get; private set; } public SimpleLinkedList<T> Add(T value) { var last = this; while (last.Next != null) { last = last.Next; } last.Next = new SimpleLinkedList<T>(value); return this; } public SimpleLinkedList<T> Reverse() { return new SimpleLinkedList<T>(this.AsEnumerable().Reverse()); } public IEnumerator<T> GetEnumerator() { yield return Value; foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>()) { yield return next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public class SimpleLinkedList<T> : IEnumerable<T> { public SimpleLinkedList(T value) : this(new[] { value }) { } public SimpleLinkedList(IEnumerable<T> values) { var array = values.ToArray(); if (array.Length == 0) { throw new ArgumentException("Cannot create tree from empty list"); } Value = array[0]; Next = null; foreach (var value in array.Skip(1)) { Add(value); } } public T Value { get; } public SimpleLinkedList<T> Next { get; private set; } public SimpleLinkedList<T> Add(T value) { var last = this; while (last.Next != null) { last = last.Next; } last.Next = new SimpleLinkedList<T>(value); return this; } public IEnumerator<T> GetEnumerator() { yield return Value; foreach (var next in Next?.AsEnumerable() ?? Enumerable.Empty<T>()) { yield return next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Remove unnecessary Reverse() method in simple-linked-list
Remove unnecessary Reverse() method in simple-linked-list
C#
mit
GKotfis/csharp,robkeim/xcsharp,exercism/xcsharp,robkeim/xcsharp,ErikSchierboom/xcsharp,ErikSchierboom/xcsharp,exercism/xcsharp,GKotfis/csharp
fabb0eeb29a35c7e0d212d9c7be9f1aad8e90c35
osu.Game/Online/Rooms/BeatmapAvailability.cs
osu.Game/Online/Rooms/BeatmapAvailability.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> public readonly float? DownloadProgress; [JsonConstructor] private BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> [Key(1)] public readonly float? DownloadProgress; [JsonConstructor] private BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
Add signalr messagepack key attribute
Add signalr messagepack key attribute
C#
mit
peppy/osu,peppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu
b406ab3eea9a36c5369eba81417af7899c3d0ac5
EpubSharp.Tests/EpubWriterTests.cs
EpubSharp.Tests/EpubWriterTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EpubSharp.Tests { [TestClass] public class EpubWriterTests { [TestMethod] public void SaveTest() { var book = EpubReader.Read(@"../../Samples/epub-assorted/iOS Hackers Handbook.epub"); var writer = new EpubWriter(book); writer.Save("saved.epub"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EpubSharp.Tests { [TestClass] public class EpubWriterTests { [TestMethod] public void SaveTest() { var book = EpubReader.Read(@"../../Samples/epub-assorted/Inversions - Iain M. Banks.epub"); var writer = new EpubWriter(book); writer.Save("saved.epub"); } } }
Use smaller epub for saving test, so that online validators accept the size.
Use smaller epub for saving test, so that online validators accept the size.
C#
mpl-2.0
Asido/EpubSharp,pgung/EpubSharp
68cf269af067a2959685e93111f594fbc29b4377
CefSharp.BrowserSubprocess/CefRenderProcess.cs
CefSharp.BrowserSubprocess/CefRenderProcess.cs
using CefSharp.Internals; using System.Collections.Generic; using System.ServiceModel; namespace CefSharp.BrowserSubprocess { public class CefRenderProcess : CefSubProcess, IRenderProcess { private DuplexChannelFactory<IBrowserProcess> channelFactory; private CefBrowserBase browser; public CefBrowserBase Browser { get { return browser; } } public CefRenderProcess(IEnumerable<string> args) : base(args) { } protected override void DoDispose(bool isDisposing) { //DisposeMember(ref renderprocess); DisposeMember(ref browser); base.DoDispose(isDisposing); } public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper) { browser = cefBrowserWrapper; if (ParentProcessId == null) { return; } channelFactory = new DuplexChannelFactory<IBrowserProcess>( this, new NetNamedPipeBinding(), new EndpointAddress(RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId)) ); channelFactory.Open(); Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects()); } public object EvaluateScript(int frameId, string script, double timeout) { var result = Browser.EvaluateScript(frameId, script, timeout); return result; } public override IBrowserProcess CreateBrowserProxy() { return channelFactory.CreateChannel(); } } }
using CefSharp.Internals; using System.Collections.Generic; using System.ServiceModel; namespace CefSharp.BrowserSubprocess { public class CefRenderProcess : CefSubProcess, IRenderProcess { private DuplexChannelFactory<IBrowserProcess> channelFactory; private CefBrowserBase browser; public CefBrowserBase Browser { get { return browser; } } public CefRenderProcess(IEnumerable<string> args) : base(args) { } protected override void DoDispose(bool isDisposing) { //DisposeMember(ref renderprocess); DisposeMember(ref browser); base.DoDispose(isDisposing); } public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper) { browser = cefBrowserWrapper; if (ParentProcessId == null) { return; } var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId); channelFactory = new DuplexChannelFactory<IBrowserProcess>( this, new NetNamedPipeBinding(), new EndpointAddress(serviceName) ); channelFactory.Open(); Bind(CreateBrowserProxy().GetRegisteredJavascriptObjects()); } public object EvaluateScript(int frameId, string script, double timeout) { var result = Browser.EvaluateScript(frameId, script, timeout); return result; } public override IBrowserProcess CreateBrowserProxy() { return channelFactory.CreateChannel(); } } }
Move serviceName to variable - makes for easier debugging
Move serviceName to variable - makes for easier debugging
C#
bsd-3-clause
battewr/CefSharp,twxstar/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,battewr/CefSharp,VioletLife/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,twxstar/CefSharp,yoder/CefSharp,twxstar/CefSharp,Octopus-ITSM/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,zhangjingpu/CefSharp,rover886/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,rover886/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,rover886/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,AJDev77/CefSharp,windygu/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,joshvera/CefSharp,Livit/CefSharp,windygu/CefSharp,ITGlobal/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,Haraguroicha/CefSharp,ruisebastiao/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,Octopus-ITSM/CefSharp,joshvera/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,Octopus-ITSM/CefSharp,battewr/CefSharp,windygu/CefSharp,windygu/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,rover886/CefSharp
ad297f0b9ef1dce9fd78f5eb6a2ff8dbe47fbc6d
Solution/App/Infrastructure/UWPBootstrapper.cs
Solution/App/Infrastructure/UWPBootstrapper.cs
using System; using App.Services; using App.Services.Contracts; using App.ViewModels; using App.ViewModels.Contracts; using Microsoft.Practices.Unity; namespace App.Infrastructure { // ReSharper disable once InconsistentNaming public sealed class UWPBootstrapper : CaliburnBootstrapper { public UWPBootstrapper(Action createWindow) : base(createWindow) { } protected override void Configure() { base.Configure(); this.UnityContainer.RegisterType<IOpenFolderService, OpenFolderService>(); this.UnityContainer.RegisterType<IShellViewModel, ShellViewModel>(); } public override void Dispose() { base.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.SuppressFinalize(this); } } }
using System; using App.Services; using App.Services.Contracts; using App.ViewModels; using App.ViewModels.Contracts; using Microsoft.Practices.Unity; namespace App.Infrastructure { // ReSharper disable once InconsistentNaming public sealed class UWPBootstrapper : CaliburnBootstrapper { public UWPBootstrapper(Action createWindow) : base(createWindow) { } protected override void Configure() { base.Configure(); this.UnityContainer .RegisterType<IOpenFolderService, OpenFolderService>() .RegisterType<IShellViewModel, ShellViewModel>(); } public override void Dispose() { base.Dispose(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.SuppressFinalize(this); } } }
Use the chain way for registering services and view models.
Use the chain way for registering services and view models.
C#
mit
minidfx/BulkRename
28a4cde5dd7568b7c91602d9822db16d3a4119f1
osu.Framework.Benchmarks/BenchmarkTabletDriver.cs
osu.Framework.Benchmarks/BenchmarkTabletDriver.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #if NET5_0 using BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; using OpenTabletDriver; using osu.Framework.Input.Handlers.Tablet; namespace osu.Framework.Benchmarks { public class BenchmarkTabletDriver : BenchmarkTest { private TabletDriver driver; public override void SetUp() { var collection = new DriverServiceCollection() .AddTransient<TabletDriver>(); var serviceProvider = collection.BuildServiceProvider(); driver = serviceProvider.GetRequiredService<TabletDriver>(); } [Benchmark] public void DetectBenchmark() { driver.Detect(); } } } #endif
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #if NET5_0 using BenchmarkDotNet.Attributes; using osu.Framework.Input.Handlers.Tablet; namespace osu.Framework.Benchmarks { public class BenchmarkTabletDriver : BenchmarkTest { private TabletDriver driver; public override void SetUp() { driver = TabletDriver.Create(); } [Benchmark] public void DetectBenchmark() { driver.Detect(); } } } #endif
Fix remaining usage of DI instead of direct `Create()` call
Fix remaining usage of DI instead of direct `Create()` call
C#
mit
ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework
55607634b4cebcd74c1130293222845923099525
osu.Game/Beatmaps/Drawables/UpdateableBeatmapBackgroundSprite.cs
osu.Game/Beatmaps/Drawables/UpdateableBeatmapBackgroundSprite.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Beatmaps.Drawables { /// <summary> /// Display a baetmap background from a local source, but fallback to online source if not available. /// </summary> public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo> { public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>(); [Resolved] private BeatmapManager beatmaps { get; set; } public UpdateableBeatmapBackgroundSprite() { Beatmap.BindValueChanged(b => Model = b); } protected override Drawable CreateDrawable(BeatmapInfo model) { Drawable drawable; var localBeatmap = beatmaps.GetWorkingBeatmap(model); if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null) drawable = new BeatmapSetCover(model.BeatmapSet); else drawable = new BeatmapBackgroundSprite(localBeatmap); drawable.RelativeSizeAxes = Axes.Both; drawable.Anchor = Anchor.Centre; drawable.Origin = Anchor.Centre; drawable.FillMode = FillMode.Fill; return drawable; } protected override double FadeDuration => 400; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Beatmaps.Drawables { /// <summary> /// Display a baetmap background from a local source, but fallback to online source if not available. /// </summary> public class UpdateableBeatmapBackgroundSprite : ModelBackedDrawable<BeatmapInfo> { public readonly IBindable<BeatmapInfo> Beatmap = new Bindable<BeatmapInfo>(); [Resolved] private BeatmapManager beatmaps { get; set; } public UpdateableBeatmapBackgroundSprite() { Beatmap.BindValueChanged(b => Model = b); } protected override Drawable CreateDrawable(BeatmapInfo model) { return new DelayedLoadUnloadWrapper(() => { Drawable drawable; var localBeatmap = beatmaps.GetWorkingBeatmap(model); if (localBeatmap.BeatmapInfo.ID == 0 && model?.BeatmapSet?.OnlineInfo != null) drawable = new BeatmapSetCover(model.BeatmapSet); else drawable = new BeatmapBackgroundSprite(localBeatmap); drawable.RelativeSizeAxes = Axes.Both; drawable.Anchor = Anchor.Centre; drawable.Origin = Anchor.Centre; drawable.FillMode = FillMode.Fill; drawable.OnLoadComplete = d => d.FadeInFromZero(400); return drawable; }, 500, 10000); } protected override double FadeDuration => 0; } }
Fix covers being loaded even when off-screen
Fix covers being loaded even when off-screen
C#
mit
2yangk23/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,2yangk23/osu,DrabWeb/osu,ppy/osu,naoey/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,smoogipooo/osu,peppy/osu-new,smoogipoo/osu,DrabWeb/osu,ZLima12/osu,smoogipoo/osu,naoey/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,naoey/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu
330ec127adf7276f9235d50f089892b5719e434f
Nerdle.AutoConfig.Tests.Integration/UsingDefaultConfigFilePath.cs
Nerdle.AutoConfig.Tests.Integration/UsingDefaultConfigFilePath.cs
using FluentAssertions; using NUnit.Framework; namespace Nerdle.AutoConfig.Tests.Integration { [TestFixture] public class UsingDefaultConfigFilePath { [Test] #if NETCOREAPP [Ignore("Buggy interaction between the test runner and System.Configuration.ConfigurationManager, see https://github.com/nunit/nunit3-vs-adapter/issues/356")] #endif public void Mapping_from_the_default_file_path() { var foo = AutoConfig.Map<IFoo>(); var bar = AutoConfig.Map<IFoo>("bar"); foo.Should().NotBeNull(); foo.Name.Should().Be("foo"); bar.Should().NotBeNull(); bar.Name.Should().Be("bar"); } public interface IFoo { string Name { get; } } } }
using FluentAssertions; using NUnit.Framework; namespace Nerdle.AutoConfig.Tests.Integration { [TestFixture] public class UsingDefaultConfigFilePath #if NETCOREAPP : System.IDisposable { private readonly string _configFilePath; // In order to workaround flaky interaction between the test runner and System.Configuration.ConfigurationManager // See https://github.com/nunit/nunit3-vs-adapter/issues/356#issuecomment-700754225 public UsingDefaultConfigFilePath() { _configFilePath = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath; System.IO.File.Copy($"{System.Reflection.Assembly.GetExecutingAssembly().Location}.config", _configFilePath, overwrite: true); } public void Dispose() { System.IO.File.Delete(_configFilePath); } #else { #endif [Test] public void Mapping_from_the_default_file_path() { var foo = AutoConfig.Map<IFoo>(); var bar = AutoConfig.Map<IFoo>("bar"); foo.Should().NotBeNull(); foo.Name.Should().Be("foo"); bar.Should().NotBeNull(); bar.Name.Should().Be("bar"); } public interface IFoo { string Name { get; } } } }
Use a workaround to make Mapping_from_the_default_file_path pass on .NET Core
Use a workaround to make Mapping_from_the_default_file_path pass on .NET Core See https://github.com/nunit/nunit3-vs-adapter/issues/356#issuecomment-700754225
C#
mit
edpollitt/Nerdle.AutoConfig
bdaa15dbfbbb26805795f5abf63e0db56aadb12e
Calculator/Calculator.cs
Calculator/Calculator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Antlr4; using Antlr4.Runtime; namespace Rubberduck.Math { public static class Calculator { public static int Evaluate(string expression) { var lexer = new BasicMathLexer(new AntlrInputStream(expression)); lexer.RemoveErrorListeners(); lexer.AddErrorListener(new ThrowExceptionErrorListener()); var tokens = new CommonTokenStream(lexer); var parser = new BasicMathParser(tokens); var tree = parser.compileUnit(); var visitor = new IntegerMathVisitor(); return visitor.Visit(tree); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Antlr4; using Antlr4.Runtime; namespace Rubberduck.Math { public static class Calculator { public static int Evaluate(string expression) { var lexer = new BasicMathLexer(new AntlrInputStream(expression)); lexer.RemoveErrorListeners(); lexer.AddErrorListener(new ThrowExceptionErrorListener()); var tokens = new CommonTokenStream(lexer); var parser = new BasicMathParser(tokens); var tree = parser.compileUnit(); var exprCount = tree.expression().Count; if (exprCount > 1) { throw new ArgumentException(String.Format("Too many expressions. Only one can be evaluated. {0} expressions were entered.", exprCount)); } var visitor = new IntegerMathVisitor(); return visitor.Visit(tree); } } }
Throw exception if more than one expression is passed to Evaluate
Throw exception if more than one expression is passed to Evaluate
C#
mit
ckuhn203/Antlr4Calculator
e33c778ad8633864afc3c8587b6acb11a8dc18e4
Editor/GameObjectCommand/GameObjectCommand.cs
Editor/GameObjectCommand/GameObjectCommand.cs
using System.IO; using UnityEditor; using UnityEngine; namespace DTCommandPalette { public abstract class GameObjectCommand : ICommand { // PRAGMA MARK - ICommand public string DisplayTitle { get { return _obj.name; } } public string DisplayDetailText { get { return _obj.FullName(); } } public abstract Texture2D DisplayIcon { get; } public bool IsValid() { return _obj != null; } public abstract void Execute(); // PRAGMA MARK - Constructors public GameObjectCommand(GameObject obj) { _obj = obj; } // PRAGMA MARK - Internal protected GameObject _obj; } }
using System.IO; using UnityEditor; using UnityEngine; namespace DTCommandPalette { public abstract class GameObjectCommand : ICommand { // PRAGMA MARK - ICommand public string DisplayTitle { get { if (!IsValid()) { return ""; } return _obj.name; } } public string DisplayDetailText { get { if (!IsValid()) { return ""; } return _obj.FullName(); } } public abstract Texture2D DisplayIcon { get; } public bool IsValid() { return _obj != null; } public abstract void Execute(); // PRAGMA MARK - Constructors public GameObjectCommand(GameObject obj) { _obj = obj; } // PRAGMA MARK - Internal protected GameObject _obj; } }
Fix null references when game object is destroyed
Fix null references when game object is destroyed
C#
mit
DarrenTsung/DTCommandPalette
bd7e87553c93021f3a9ee5edb414c2a4b07a3401
Pixie/MarkupNode.cs
Pixie/MarkupNode.cs
using System; namespace Pixie { /// <summary> /// A base class for markup nodes: composable elements that can /// be rendered. /// </summary> public abstract class MarkupNode { /// <summary> /// Gets a fallback version of this node for when the renderer /// doesn't know how to render this node's type. Null is /// returned if no reasonable fallback can be provided. /// </summary> /// <returns>The node's fallback version, or <c>null</c>.</returns> public abstract MarkupNode Fallback { get; } /// <summary> /// Applies a mapping to this markup node's children and returns /// a new instance of this node's type that contains the modified /// children. /// </summary> /// <param name="mapping">A mapping function.</param> /// <returns>A new markup node.</returns> public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping); } }
using System; using Pixie.Markup; namespace Pixie { /// <summary> /// A base class for markup nodes: composable elements that can /// be rendered. /// </summary> public abstract class MarkupNode { /// <summary> /// Gets a fallback version of this node for when the renderer /// doesn't know how to render this node's type. Null is /// returned if no reasonable fallback can be provided. /// </summary> /// <returns>The node's fallback version, or <c>null</c>.</returns> public abstract MarkupNode Fallback { get; } /// <summary> /// Applies a mapping to this markup node's children and returns /// a new instance of this node's type that contains the modified /// children. /// </summary> /// <param name="mapping">A mapping function.</param> /// <returns>A new markup node.</returns> public abstract MarkupNode Map(Func<MarkupNode, MarkupNode> mapping); /// <summary> /// Creates a text markup node from a string of characters. /// </summary> /// <param name="text"> /// The text to wrap in a text markup node. /// </param> public static implicit operator MarkupNode(string text) { return new Text(text); } } }
Define an implicit conversion from strings to markup nodes
Define an implicit conversion from strings to markup nodes
C#
mit
jonathanvdc/Pixie,jonathanvdc/Pixie
4688f63632324d54c8f7e2b471f795babb050e60
src/Avalonia.Styling/ClassBindingManager.cs
src/Avalonia.Styling/ClassBindingManager.cs
using System; using System.Collections.Generic; using Avalonia.Data; namespace Avalonia { internal static class ClassBindingManager { private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties = new Dictionary<string, AvaloniaProperty>(); public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor) { if (!s_RegisteredProperties.TryGetValue(className, out var prop)) s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className); return target.Bind(prop, source, anchor); } private static AvaloniaProperty RegisterClassProxyProperty(string className) { var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className); prop.Changed.Subscribe(args => { var enable = args.NewValue.GetValueOrDefault(); var classes = ((IStyledElement)args.Sender).Classes; if (enable) { if (!classes.Contains(className)) classes.Add(className); } else classes.Remove(className); }); return prop; } } }
using System; using System.Collections.Generic; using Avalonia.Data; namespace Avalonia { internal static class ClassBindingManager { private static readonly Dictionary<string, AvaloniaProperty> s_RegisteredProperties = new Dictionary<string, AvaloniaProperty>(); public static IDisposable Bind(IStyledElement target, string className, IBinding source, object anchor) { if (!s_RegisteredProperties.TryGetValue(className, out var prop)) s_RegisteredProperties[className] = prop = RegisterClassProxyProperty(className); return target.Bind(prop, source, anchor); } private static AvaloniaProperty RegisterClassProxyProperty(string className) { var prop = AvaloniaProperty.Register<StyledElement, bool>("__AvaloniaReserved::Classes::" + className); prop.Changed.Subscribe(args => { var classes = ((IStyledElement)args.Sender).Classes; classes.Set(className, args.NewValue.GetValueOrDefault()); }); return prop; } } }
Simplify the code a bit
Simplify the code a bit
C#
mit
SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex
605f9d62a16a536f3ddfcdfac0a654983d2b6e7b
src/Snowflake.Framework.Tests/Scraping/ScraperIntegrationTests.cs
src/Snowflake.Framework.Tests/Scraping/ScraperIntegrationTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Plugin.Scraping.TheGamesDb; using Snowflake.Scraping; using Snowflake.Scraping.Extensibility; using Xunit; namespace Snowflake.Scraping.Tests { public class ScraperIntegrationTests { [Fact] public async Task TGDBScraping_Test() { var tgdb = new TheGamesDbScraper(); var scrapeJob = new ScrapeJob(new SeedContent[] { ("platform", "NINTENDO_NES"), ("search_title", "Super Mario Bros."), }, new[] { tgdb }, new ICuller[] { }); while (await scrapeJob.Proceed()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Plugin.Scraping.TheGamesDb; using Snowflake.Scraping; using Snowflake.Scraping.Extensibility; using Xunit; namespace Snowflake.Scraping.Tests { public class ScraperIntegrationTests { // [Fact] // public async Task TGDBScraping_Test() // { // var tgdb = new TheGamesDbScraper(); // var scrapeJob = new ScrapeJob(new SeedContent[] { // ("platform", "NINTENDO_NES"), // ("search_title", "Super Mario Bros."), // }, new[] { tgdb }, new ICuller[] { }); // while (await scrapeJob.Proceed()); // } } }
Disable TGDB Tests for now
Tests: Disable TGDB Tests for now
C#
mpl-2.0
RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake
848c32ca77fa46aa0efb8d49c413a191777dcdc9
alert-roster.web/Migrations/Configuration.cs
alert-roster.web/Migrations/Configuration.cs
namespace alert_roster.web.Migrations { using alert_roster.web.Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = false; ContextKey = "alert_roster.web.Models.AlertRosterDbContext"; } protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context) { // This method will be called after migrating to the latest version. //context.Messages.AddOrUpdate( // m => m.Content, // new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" } // ); } } }
namespace alert_roster.web.Migrations { using alert_roster.web.Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<alert_roster.web.Models.AlertRosterDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "alert_roster.web.Models.AlertRosterDbContext"; } protected override void Seed(alert_roster.web.Models.AlertRosterDbContext context) { // This method will be called after migrating to the latest version. //context.Messages.AddOrUpdate( // m => m.Content, // new Message { PostedDate = DateTime.UtcNow, Content = "This is the initial, test message posting" } // ); } } }
Allow dataloss... shouldn't be necesssary?
Allow dataloss... shouldn't be necesssary?
C#
mit
mattgwagner/alert-roster
0140a714de533083de1972e65bbb7f615d30e57e
VersionOne.Bugzilla.BugzillaAPI.Testss/BugTests.cs
VersionOne.Bugzilla.BugzillaAPI.Testss/BugTests.cs
using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace VersionOne.Bugzilla.BugzillaAPI.Testss { [TestClass()] public class given_a_Bug { private IBug _bug; private string _expectedReassignToPayload; [TestInitialize()] public void SetContext() { _bug = new Bug(); _expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}"; } [TestMethod] public void it_should_give_appropriate_reassigneto_payloads() { var integrationUser = "terry.densmore@versionone.com"; _bug.AssignedTo = "denise@denise.com"; Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace VersionOne.Bugzilla.BugzillaAPI.Testss { [TestClass()] public class given_a_Bug { private IBug _bug; private string _expectedReassignToPayload; [TestInitialize()] public void SetContext() { _bug = new Bug(); _expectedReassignToPayload = "{\r\n \"assigned_to\": \"denise@denise.com\",\r\n \"status\": \"CONFIRMED\",\r\n \"token\": \"terry.densmore@versionone.com\"\r\n}"; } [TestMethod] public void it_should_give_appropriate_reassigneto_payloads() { var integrationUser = "terry.densmore@versionone.com"; _bug.AssignedTo = "denise@denise.com"; Assert.IsTrue(_expectedReassignToPayload == _bug.GetReassignBugPayload(integrationUser)); } } }
Remove no longer needed usings
S-51801: Remove no longer needed usings
C#
bsd-3-clause
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
cfc31fdcec61207af14c3b46130dcf6a7dfc22d0
src/Glimpse.Common/Internal/Messaging/DefaultMessageTypeProcessor.cs
src/Glimpse.Common/Internal/Messaging/DefaultMessageTypeProcessor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Glimpse.Extensions; namespace Glimpse.Internal { public class DefaultMessageTypeProcessor : IMessageTypeProcessor { private readonly static Type[] _exclusions = { typeof(object) }; public virtual IEnumerable<string> Derive(object payload) { var typeInfo = payload.GetType().GetTypeInfo(); return typeInfo.BaseTypes(true) .Concat(typeInfo.ImplementedInterfaces) .Except(_exclusions) .Select(t => t.KebabCase()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Glimpse.Extensions; namespace Glimpse.Internal { public class DefaultMessageTypeProcessor : IMessageTypeProcessor { private readonly static Type[] _exclusions = { typeof(object) }; public virtual IEnumerable<string> Derive(object payload) { var typeInfo = payload.GetType().GetTypeInfo(); return typeInfo.BaseTypes(true) .Concat(typeInfo.ImplementedInterfaces) .Except(_exclusions) .Select(t => { var result = t.KebabCase(); if (result.EndsWith("-message")) return result.Substring(0, result.Length - 8); return result; }); } } }
Drop "-message" from all message names
Drop "-message" from all message names
C#
mit
mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype
aff981020ece51a678a8589891cfa2916543d538
src/SFA.DAS.EmployerUsers.Web/Views/Login/AuthorizeResponse.cshtml
src/SFA.DAS.EmployerUsers.Web/Views/Login/AuthorizeResponse.cshtml
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Please wait"; ViewBag.HideSigninLink = "true"; Layout = "~/Views/Shared/_Layout-NoBanner.cshtml"; } <h1 class="heading-xlarge">You've logged in</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Please wait"; ViewBag.HideSigninLink = "true"; Layout = "~/Views/Shared/_Layout-NoBanner.cshtml"; } <h1 class="heading-xlarge">@ViewBag.Title</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
Use the viewBag Title rather than the hard coded one.
Use the viewBag Title rather than the hard coded one.
C#
mit
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
a8704d78f49810d7c2addf886cb2d49ae07cca6c
ThinMvvm.WindowsPhone.SampleApp/App.cs
ThinMvvm.WindowsPhone.SampleApp/App.cs
// Copyright (c) Solal Pirelli 2014 // See License.txt file for more details using ThinMvvm.WindowsPhone.SampleApp.Resources; using ThinMvvm.WindowsPhone.SampleApp.ViewModels; namespace ThinMvvm.WindowsPhone.SampleApp { public sealed class App : AppBase { protected override string Language { get { return AppResources.ResourceLanguage; } } protected override string FlowDirection { get { return AppResources.ResourceFlowDirection; } } public App() { Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>(); Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>(); Container.Bind<ISettings, Settings>(); } protected override void Start( AppDependencies dependencies, AppArguments arguments ) { // simple app, no additional dependencies or arguments dependencies.NavigationService.Bind<MainViewModel>( "/Views/MainView.xaml" ); dependencies.NavigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" ); dependencies.NavigationService.NavigateTo<MainViewModel, int>( 42 ); } } }
// Copyright (c) Solal Pirelli 2014 // See License.txt file for more details using ThinMvvm.WindowsPhone.SampleApp.Resources; using ThinMvvm.WindowsPhone.SampleApp.ViewModels; namespace ThinMvvm.WindowsPhone.SampleApp { public sealed class App : AppBase { private readonly IWindowsPhoneNavigationService _navigationService; protected override string Language { get { return AppResources.ResourceLanguage; } } protected override string FlowDirection { get { return AppResources.ResourceFlowDirection; } } public App() { _navigationService = Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>(); Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>(); Container.Bind<ISettings, Settings>(); } protected override void Start( AppArguments arguments ) { // simple app, no additional dependencies or arguments _navigationService.Bind<MainViewModel>( "/Views/MainView.xaml" ); _navigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" ); _navigationService.NavigateTo<MainViewModel, int>( 42 ); } } }
Fix the sample app following previous changes.
Fix the sample app following previous changes.
C#
mit
SolalPirelli/ThinMvvm
59bfb4148adf810ccb61acdceac42d10e104d2fb
src/Bakery/Security/RandomExtensions.cs
src/Bakery/Security/RandomExtensions.cs
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } } }
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } public static UInt64 GetUInt64(this IRandom random) { return BitConverter.ToUInt64(random.GetBytes(8), 0); } } }
Add extension method for IRandom to get an unsigned 64-bit integer.
Add extension method for IRandom to get an unsigned 64-bit integer.
C#
mit
brendanjbaker/Bakery
d33ee612e59400706d3cd623ae35a508bf13c810
tests/Magick.NET.Tests/Shared/MagickImageTests/TheAddNoiseMethod.cs
tests/Magick.NET.Tests/Shared/MagickImageTests/TheAddNoiseMethod.cs
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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 ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 100, 100)) { imageA.AddNoise(NoiseType.Random); using (var imageB = new MagickImage(MagickColors.Black, 100, 100)) { imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // 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 ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 10, 10)) { using (var imageB = new MagickImage(MagickColors.Black, 10, 10)) { imageA.AddNoise(NoiseType.Random); imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
Revert changes to the test.
Revert changes to the test.
C#
apache-2.0
dlemstra/Magick.NET,dlemstra/Magick.NET
584b31d5c8874d96bf8c538b859b254a6d37e21b
IntegrationEngine.Tests/Api/Controllers/CronTriggerControllerTest.cs
IntegrationEngine.Tests/Api/Controllers/CronTriggerControllerTest.cs
using IntegrationEngine.Api.Controllers; using IntegrationEngine.Core.Storage; using IntegrationEngine.Model; using IntegrationEngine.Scheduler; using Moq; using NUnit.Framework; namespace IntegrationEngine.Tests.Api.Controllers { public class CronTriggerControllerTest { [Test] public void ShouldScheduleJobWhenCronTriggerIsCreated() { var subject = new CronTriggerController(); var cronExpression = "0 6 * * 1-5"; var jobType = "MyProject.MyIntegrationJob"; var expected = new CronTrigger() { JobType = jobType, CronExpressionString = cronExpression }; var engineScheduler = new Mock<IEngineScheduler>(); engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected)); subject.EngineScheduler = engineScheduler.Object; var esRepository = new Mock<ESRepository<CronTrigger>>(); esRepository.Setup(x => x.Insert(expected)).Returns(expected); subject.Repository = esRepository.Object; subject.PostCronTrigger(expected); engineScheduler.Verify(x => x .ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType && y.CronExpressionString == cronExpression)), Times.Once); } } }
using IntegrationEngine.Api.Controllers; using IntegrationEngine.Core.Storage; using IntegrationEngine.Model; using IntegrationEngine.Scheduler; using Moq; using NUnit.Framework; namespace IntegrationEngine.Tests.Api.Controllers { public class CronTriggerControllerTest { [Test] public void ShouldScheduleJobWhenCronTriggerIsCreatedWithValidCronExpression() { var subject = new CronTriggerController(); var cronExpression = "0 6 * * 1-5 ?"; var jobType = "MyProject.MyIntegrationJob"; var expected = new CronTrigger() { JobType = jobType, CronExpressionString = cronExpression }; var engineScheduler = new Mock<IEngineScheduler>(); engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected)); subject.EngineScheduler = engineScheduler.Object; var esRepository = new Mock<ESRepository<CronTrigger>>(); esRepository.Setup(x => x.Insert(expected)).Returns(expected); subject.Repository = esRepository.Object; subject.PostCronTrigger(expected); engineScheduler.Verify(x => x .ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType && y.CronExpressionString == cronExpression)), Times.Once); } } }
Add valid cron expression to test
Add valid cron expression to test
C#
mit
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
a6d664d629f516737ddc1024a61ff9cdfaed035b
Examples/TestHttpCompositionConsoleApp/Program.cs
Examples/TestHttpCompositionConsoleApp/Program.cs
 namespace TestHttpCompositionConsoleApp { using Serviceable.Objects.Remote.Composition.Host; using Serviceable.Objects.Remote.Composition.Host.Commands; class Program { static void Main(string[] args) { /* * Principles: * * Testable * Composable * Configurable * Instrumentable * Scalable * Updatable TODO * */ new ApplicationHost(args).Execute(new RunAndBlock()); } } }
 namespace TestHttpCompositionConsoleApp { using Serviceable.Objects.Remote.Composition.Host; using Serviceable.Objects.Remote.Composition.Host.Commands; class Program { static void Main(string[] args) { /* * Principles: * * Testable * Composable * Configurable * Instrumentable * Scalable * Updatable TODO * */ // Sample host should minimal like that. // Override templates or data from args before reaching the host execution new ApplicationHost(args).Execute(new RunAndBlock()); } } }
Add some comments for the host process
Add some comments for the host process
C#
mit
phaetto/serviceable-objects
357f1aa1661ee6e8acbe0232687b4ee20107e063
src/Orchard.Web/Modules/Orchard.Blogs/Views/Content-Blog.Edit.cshtml
src/Orchard.Web/Modules/Orchard.Blogs/Views/Content-Blog.Edit.cshtml
@using Orchard.Mvc.Html; @{ Layout.Title = T("New Blog"); } <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
@using Orchard.Mvc.Html; <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
Fix incorrect title on edit page
Fix incorrect title on edit page Fixes #7142
C#
bsd-3-clause
Serlead/Orchard,Lombiq/Orchard,Serlead/Orchard,li0803/Orchard,rtpHarry/Orchard,aaronamm/Orchard,jersiovic/Orchard,aaronamm/Orchard,abhishekluv/Orchard,OrchardCMS/Orchard,Dolphinsimon/Orchard,tobydodds/folklife,Codinlab/Orchard,bedegaming-aleksej/Orchard,aaronamm/Orchard,jimasp/Orchard,jimasp/Orchard,abhishekluv/Orchard,AdvantageCS/Orchard,Fogolan/OrchardForWork,li0803/Orchard,IDeliverable/Orchard,ehe888/Orchard,yersans/Orchard,li0803/Orchard,LaserSrl/Orchard,fassetar/Orchard,gcsuk/Orchard,jersiovic/Orchard,grapto/Orchard.CloudBust,gcsuk/Orchard,tobydodds/folklife,yersans/Orchard,gcsuk/Orchard,jersiovic/Orchard,fassetar/Orchard,hbulzy/Orchard,OrchardCMS/Orchard,jimasp/Orchard,Dolphinsimon/Orchard,tobydodds/folklife,grapto/Orchard.CloudBust,gcsuk/Orchard,Codinlab/Orchard,omidnasri/Orchard,li0803/Orchard,IDeliverable/Orchard,AdvantageCS/Orchard,IDeliverable/Orchard,OrchardCMS/Orchard,ehe888/Orchard,rtpHarry/Orchard,abhishekluv/Orchard,yersans/Orchard,tobydodds/folklife,OrchardCMS/Orchard,omidnasri/Orchard,omidnasri/Orchard,jersiovic/Orchard,Codinlab/Orchard,yersans/Orchard,hbulzy/Orchard,fassetar/Orchard,omidnasri/Orchard,grapto/Orchard.CloudBust,Fogolan/OrchardForWork,grapto/Orchard.CloudBust,bedegaming-aleksej/Orchard,OrchardCMS/Orchard,hbulzy/Orchard,jimasp/Orchard,Fogolan/OrchardForWork,Serlead/Orchard,abhishekluv/Orchard,Codinlab/Orchard,Serlead/Orchard,Codinlab/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,Dolphinsimon/Orchard,li0803/Orchard,Fogolan/OrchardForWork,LaserSrl/Orchard,Dolphinsimon/Orchard,abhishekluv/Orchard,omidnasri/Orchard,rtpHarry/Orchard,IDeliverable/Orchard,hbulzy/Orchard,grapto/Orchard.CloudBust,rtpHarry/Orchard,jersiovic/Orchard,Lombiq/Orchard,aaronamm/Orchard,bedegaming-aleksej/Orchard,omidnasri/Orchard,Dolphinsimon/Orchard,tobydodds/folklife,Lombiq/Orchard,grapto/Orchard.CloudBust,Fogolan/OrchardForWork,yersans/Orchard,AdvantageCS/Orchard,ehe888/Orchard,rtpHarry/Orchard,tobydodds/folklife,jimasp/Orchard,aaronamm/Orchard,bedegaming-aleksej/Orchard,fassetar/Orchard,hbulzy/Orchard,omidnasri/Orchard,LaserSrl/Orchard,bedegaming-aleksej/Orchard,gcsuk/Orchard,ehe888/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,IDeliverable/Orchard,LaserSrl/Orchard,abhishekluv/Orchard,fassetar/Orchard,LaserSrl/Orchard,ehe888/Orchard,Lombiq/Orchard,Lombiq/Orchard,Serlead/Orchard
1e6d29eac62406acbea55e4a222222a09c3d9f9c
SurveyMonkey/Helpers/RequestSettingsHelper.cs
SurveyMonkey/Helpers/RequestSettingsHelper.cs
using System; using System.Reflection; using SurveyMonkey.RequestSettings; namespace SurveyMonkey.Helpers { internal class RequestSettingsHelper { internal static RequestData GetPopulatedProperties(object obj) { var output = new RequestData(); foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (property.GetValue(obj, null) != null) { Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(property.PropertyType) : property.PropertyType; if (underlyingType.IsEnum) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString())); } else if (underlyingType == typeof(DateTime)) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s")); } else { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null)); } } } return output; } } }
using System; using System.Reflection; using SurveyMonkey.RequestSettings; namespace SurveyMonkey.Helpers { internal class RequestSettingsHelper { internal static RequestData GetPopulatedProperties(object obj) { var output = new RequestData(); foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (property.GetValue(obj, null) != null) { Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(property.PropertyType) : property.PropertyType; if (underlyingType.IsEnum) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString())); } else if (underlyingType == typeof(DateTime)) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s") + "+00:00"); } else { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null)); } } } return output; } } }
Format dates properly for the api
Format dates properly for the api
C#
mit
bcemmett/SurveyMonkeyApi-v3,davek17/SurveyMonkeyApi-v3
d46f8165a9eb6c7fe6f9f292ef04cd65be24e6e6
src/Raven.Bundles.Contrib.IndexedAttachments/Properties/AssemblyInfo.cs
src/Raven.Bundles.Contrib.IndexedAttachments/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")] [assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")] [assembly: AssemblyVersion("2.0.2.0")] [assembly: AssemblyFileVersion("2.0.2.0")]
using System.Reflection; [assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")] [assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")] [assembly: AssemblyVersion("2.0.3.0")] [assembly: AssemblyFileVersion("2.0.3.0")]
Set IndexedAttachments to version 2.0.3.0
Set IndexedAttachments to version 2.0.3.0
C#
mit
ravendb/ravendb.contrib
6539c204aa30b79c8eecd11c1c069847c7a23e9e
src/Konsola/Metadata/ObjectMetadata.cs
src/Konsola/Metadata/ObjectMetadata.cs
using System; using System.Collections.Generic; namespace Konsola.Metadata { public class ObjectMetadata { public ObjectMetadata( Type type, IEnumerable<PropertyMetadata> properties, IEnumerable<AttributeMetadata> attributes) { Type = type; Properties = properties; Attributes = attributes; } public Type Type { get; private set; } public virtual IEnumerable<PropertyMetadata> Properties { get; private set; } public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; } } }
using System; using System.Linq; using System.Collections.Generic; namespace Konsola.Metadata { public class ObjectMetadata { public ObjectMetadata( Type type, IEnumerable<PropertyMetadata> properties, IEnumerable<AttributeMetadata> attributes) { Type = type; Properties = properties; Attributes = attributes; } public Type Type { get; private set; } public virtual IEnumerable<PropertyMetadata> Properties { get; private set; } public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; } public IEnumerable<T> AttributesOfType<T>() { return Attributes .Select(a => a.Attribute) .OfType<T>(); } public T AttributeOfType<T>() { return AttributesOfType<T>() .FirstOrDefault(); } } }
Add helpers for finding attributes
Add helpers for finding attributes
C#
mit
mrahhal/Konsola
8541a994600580ecf9eb498c95d8bfacdde84d61
bigquery/data-transfer/api/QuickStart/QuickStart.cs
bigquery/data-transfer/api/QuickStart/QuickStart.cs
/* * Copyright (c) 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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. */ // [START bigquery_data_transfer_quickstart] using System; using Google.Api.Gax; using Google.Cloud.BigQuery.DataTransfer.V1; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Instantiates a client DataTransferServiceClient client = DataTransferServiceClient.Create(); // Your Google Cloud Platform project ID string projectId = "YOUR-PROJECT-ID"; ProjectName project = new ProjectName(projectId); var sources = client.ListDataSources(ParentNameOneof.From(project)); Console.WriteLine("Supported Data Sources:"); foreach (DataSource source in sources) { Console.WriteLine( $"{source.DataSourceId}: " + $"{source.DisplayName} ({source.Description})"); } } } } // [END bigquery_data_transfer_quickstart]
/* * Copyright (c) 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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. */ // [START bigquerydatatransfer_quickstart] using System; using Google.Api.Gax; using Google.Cloud.BigQuery.DataTransfer.V1; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Instantiates a client DataTransferServiceClient client = DataTransferServiceClient.Create(); // Your Google Cloud Platform project ID string projectId = "YOUR-PROJECT-ID"; ProjectName project = new ProjectName(projectId); var sources = client.ListDataSources(ParentNameOneof.From(project)); Console.WriteLine("Supported Data Sources:"); foreach (DataSource source in sources) { Console.WriteLine( $"{source.DataSourceId}: " + $"{source.DisplayName} ({source.Description})"); } } } } // [END bigquerydatatransfer_quickstart]
Use bigquerydatatransfer instead of bigquery_data_transfer in region tags
Use bigquerydatatransfer instead of bigquery_data_transfer in region tags We are treating BigQuery Data Transfer Service as its own product in the samples tracker.
C#
apache-2.0
jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples
fe778f576de801ad1a69879393ae82c99610d733
src/LiberisLabs.CompaniesHouse/CompaniesHouseCompanyProfileClient.cs
src/LiberisLabs.CompaniesHouse/CompaniesHouseCompanyProfileClient.cs
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using LiberisLabs.CompaniesHouse.Response.CompanyProfile; using LiberisLabs.CompaniesHouse.UriBuilders; namespace LiberisLabs.CompaniesHouse { public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient { private readonly IHttpClientFactory _httpClientFactory; private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder; public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder) { _httpClientFactory = httpClientFactory; _companyProfileUriBuilder = companyProfileUriBuilder; } public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken)) { using (var httpClient = _httpClientFactory.CreateHttpClient()) { var requestUri = _companyProfileUriBuilder.Build(companyNumber); var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false); CompanyProfile result = response.IsSuccessStatusCode ? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false) : null; return new CompaniesHouseClientResponse<CompanyProfile>(result); } } } }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using LiberisLabs.CompaniesHouse.Response.CompanyProfile; using LiberisLabs.CompaniesHouse.UriBuilders; namespace LiberisLabs.CompaniesHouse { public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient { private readonly IHttpClientFactory _httpClientFactory; private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder; public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder) { _httpClientFactory = httpClientFactory; _companyProfileUriBuilder = companyProfileUriBuilder; } public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken)) { using (var httpClient = _httpClientFactory.CreateHttpClient()) { var requestUri = _companyProfileUriBuilder.Build(companyNumber); var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false); // Return a null profile on 404s, but raise exception for all other error codes if (response.StatusCode != System.Net.HttpStatusCode.NotFound) response.EnsureSuccessStatusCode(); CompanyProfile result = response.IsSuccessStatusCode ? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false) : null; return new CompaniesHouseClientResponse<CompanyProfile>(result); } } } }
Raise exceptions on non-404 error codes
Raise exceptions on non-404 error codes
C#
mit
kevbite/CompaniesHouse.NET,LiberisLabs/CompaniesHouse.NET
a1b92810641ad47859919cd521e7922061639112
BundlerTestSite/Startup.cs
BundlerTestSite/Startup.cs
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using BundlerMiddleware; [assembly: OwinStartup(typeof(BundlerTestSite.Startup))] namespace BundlerTestSite { public class Startup { public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable(); public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable(); public void Configuration(IAppBuilder app) { app.UseBundlerMiddlewareForIIS(); app.UseBundlerMarkdown(MarkdownRoutes); app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate); } } }
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using BundlerMiddleware; [assembly: OwinStartup(typeof(BundlerTestSite.Startup))] namespace BundlerTestSite { public class Startup { public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable(); public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable(); public void Configuration(IAppBuilder app) { app.UseBundlerMiddlewareForIIS(); app.UseBundlerMarkdown(MarkdownRoutes); app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate); } } }
Fix tabs/spaces in test site startup
Fix tabs/spaces in test site startup
C#
mit
msarchet/Bundler,msarchet/Bundler
13d6a501ff247dfa84d67de912468c3585084794
CorrugatedIron.Tests.Live/RiakDtTests.cs
CorrugatedIron.Tests.Live/RiakDtTests.cs
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // // This file is provided 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 CorrugatedIron.Tests.Live.LiveRiakConnectionTests; using NUnit.Framework; namespace CorrugatedIron.Tests.Live { [TestFixture] public class RiakDtTests : LiveRiakConnectionTestBase { private const string Bucket = "riak_dt_bucket"; [TearDown] public void TearDown() { Client.DeleteBucket(Bucket); } } }
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // // This file is provided 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 CorrugatedIron.Tests.Live.LiveRiakConnectionTests; using NUnit.Framework; namespace CorrugatedIron.Tests.Live { [TestFixture] public class RiakDtTests : LiveRiakConnectionTestBase { private const string Bucket = "riak_dt_bucket"; /// <summary> /// The tearing of the down, it is done here. /// </summary> [TearDown] public void TearDown() { Client.DeleteBucket(Bucket); } } }
Test commit of new line endings
Test commit of new line endings Former-commit-id: 26984ece764e524a7745bc91497effde699d4879
C#
apache-2.0
rob-somerville/riak-dotnet-client,basho/riak-dotnet-client,basho/riak-dotnet-client,rob-somerville/riak-dotnet-client
a459f10eea1f72c6d17b750eda87bee6831cc3a5
Mindscape.Raygun4Net/RaygunClientBase.cs
Mindscape.Raygun4Net/RaygunClientBase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunClientBase { protected internal const string SentKey = "AlreadySentByRaygun"; protected bool CanSend(Exception exception) { return exception == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]); } protected void FlagAsSent(Exception exception) { if (exception != null) { exception.Data[SentKey] = true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunClientBase { protected internal const string SentKey = "AlreadySentByRaygun"; protected bool CanSend(Exception exception) { return exception == null || exception.Data == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]); } protected void FlagAsSent(Exception exception) { if (exception != null && exception.Data != null) { try { Type[] genericTypes = exception.Data.GetType().GetGenericArguments(); if (genericTypes.Length > 0 && genericTypes[0].IsAssignableFrom(typeof(string))) { exception.Data[SentKey] = true; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(String.Format("Failed to flag exception as sent: {0}", ex.Message)); } } } } }
Check that Data dictionary accepts string keys.
Check that Data dictionary accepts string keys.
C#
mit
tdiehl/raygun4net,nelsonsar/raygun4net,ddunkin/raygun4net,MindscapeHQ/raygun4net,articulate/raygun4net,articulate/raygun4net,tdiehl/raygun4net,ddunkin/raygun4net,MindscapeHQ/raygun4net,nelsonsar/raygun4net,MindscapeHQ/raygun4net
bdfeb55dec5614b535737fb22df80c59627973a4
osu.Game.Tests/Visual/Multiplayer/TestSceneRoomStatus.cs
osu.Game.Tests/Visual/Multiplayer/TestSceneRoomStatus.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Online.Multiplayer.RoomStatuses; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneRoomStatus : OsuTestScene { public TestSceneRoomStatus() { Child = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Width = 0.5f, Children = new Drawable[] { new DrawableRoom(new Room { Name = { Value = "Room 1" }, Status = { Value = new RoomStatusOpen() } }), new DrawableRoom(new Room { Name = { Value = "Room 2" }, Status = { Value = new RoomStatusPlaying() } }), new DrawableRoom(new Room { Name = { Value = "Room 3" }, Status = { Value = new RoomStatusEnded() } }), } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Online.Multiplayer; using osu.Game.Online.Multiplayer.RoomStatuses; using osu.Game.Screens.Multi.Lounge.Components; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneRoomStatus : OsuTestScene { public TestSceneRoomStatus() { Child = new FillFlowContainer { RelativeSizeAxes = Axes.Both, Width = 0.5f, Children = new Drawable[] { new DrawableRoom(new Room { Name = { Value = "Room 1" }, Status = { Value = new RoomStatusOpen() }, EndDate = { Value = DateTimeOffset.Now.AddDays(1) } }) { MatchingFilter = true }, new DrawableRoom(new Room { Name = { Value = "Room 2" }, Status = { Value = new RoomStatusPlaying() }, EndDate = { Value = DateTimeOffset.Now.AddDays(1) } }) { MatchingFilter = true }, new DrawableRoom(new Room { Name = { Value = "Room 3" }, Status = { Value = new RoomStatusEnded() }, EndDate = { Value = DateTimeOffset.Now } }) { MatchingFilter = true }, } }; } } }
Fix room status test scene not working
Fix room status test scene not working
C#
mit
UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu
65d71b94424ab46a3fa307784a8637334d75f172
osu.Game/Online/API/Requests/GetBeatmapRequest.cs
osu.Game/Online/API/Requests/GetBeatmapRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path ?? string.Empty)}"; } }
Fix beatmap lookups failing for beatmaps with no local path
Fix beatmap lookups failing for beatmaps with no local path Turns out the underlying EscapeUriString doesn't like nulls
C#
mit
UselessToucan/osu,2yangk23/osu,smoogipoo/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu
d4051d7d89e5fef4de5117d4708e39e4515377e1
Test/AdventureWorksFunctionalModel/Helpers.cs
Test/AdventureWorksFunctionalModel/Helpers.cs
using System.Linq; using NakedFunctions; namespace AW { public static class Helpers { /// <summary> /// Returns a random instance from the set of all instance of type T /// </summary> public static T Random<T>(IContext context) where T : class { //The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip //which in turn is needed because LINQ to Entities doesn't support .ElementAt(x) var instances = context.Instances<T>().OrderBy(n => ""); return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault(); } } }
using System; using System.Linq; using NakedFunctions; namespace AW { public static class Helpers { /// <summary> /// Returns a random instance from the set of all instance of type T /// </summary> public static T Random<T>(IContext context) where T : class { //The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip //which in turn is needed because LINQ to Entities doesn't support .ElementAt(x) var instances = context.Instances<T>().OrderBy(n => ""); return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault(); } //TODO: Temporary DUMMY extension method, pending native new method on IContext. public static IContext WithFunction(this IContext context, Func<IContext, IContext> func) => context.WithInformUser($"Registered function {func.ToString()} NOT called."); //TODO: Temporary DUMMY extension method, pending native new method on IContext. public static IContext WithDeleted(this IContext context, object toDelete) => context.WithInformUser($"object {toDelete} scheduled for deletion."); } }
Add temp dummy impl of IContext.WithDeleted and WithFunction
Add temp dummy impl of IContext.WithDeleted and WithFunction
C#
apache-2.0
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
b06294083f4e62a5eb0d4a91b2d4867e2840aa38
src/Arkivverket.Arkade.GUI/Util/ArkadeProcessingAreaLocationSetting.cs
src/Arkivverket.Arkade.GUI/Util/ArkadeProcessingAreaLocationSetting.cs
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } }
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } }
Make sure ProcessAreaLocationSetting is set on first start-up
Make sure ProcessAreaLocationSetting is set on first start-up ARKADE-451
C#
agpl-3.0
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
5310388b0c3813ce214583980b77187fdd6a4b70
MathSample/RandomWalkConsole/Program.cs
MathSample/RandomWalkConsole/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RandomWalkConsole { class Program { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace RandomWalkConsole { class Program { static void Main(string[] args) { var unfinished = Enumerable.Range(0, 1000) .Select(_ => Walk2()) .Aggregate(0, (u, t) => u + (t.HasValue ? 0 : 1)); Console.WriteLine(unfinished); } static readonly Random random = new Random(); static readonly Int32Vector3[] Directions2 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis }; static int? Walk2() { var current = Int32Vector3.Zero; for (var i = 1; i <= 1000000; i++) { current += Directions2[random.Next(0, Directions2.Length)]; if (current == Int32Vector3.Zero) return i; } Console.WriteLine(current); return null; } } }
Implement random walk for 2D
Implement random walk for 2D
C#
mit
sakapon/Samples-2016,sakapon/Samples-2016
32fcb95d67710f9130a9fa1f43d3b1d5d50a6893
Dashboard/App_Start/RouteConfig.cs
Dashboard/App_Start/RouteConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Dashboard { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Dashboard { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.LowercaseUrls = true; routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
Switch to lower case URLs
Switch to lower case URLs
C#
apache-2.0
jaredpar/jenkins,jaredpar/jenkins,jaredpar/jenkins
4d2f17c2220c4db0ddccddf266948b293933aaf2
MonoGameUtils/Drawing/Utilities.cs
MonoGameUtils/Drawing/Utilities.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.Drawing { /// <summary> /// Various useful utility methods that don't obviously go elsewhere. /// </summary> public static class Utilities { /// <summary> /// Draw the provided model in the world, given the provided matrices. /// </summary> /// <param name="model">The model to draw.</param> /// <param name="world">The world matrix that the model should be drawn in.</param> /// <param name="view">The view matrix that the model should be drawn in.</param> /// <param name="projection">The projection matrix that the model should be drawn in.</param> private static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.Drawing { /// <summary> /// Various useful utility methods that don't obviously go elsewhere. /// </summary> public static class Utilities { /// <summary> /// Draw the provided model in the world, given the provided matrices. /// </summary> /// <param name="model">The model to draw.</param> /// <param name="world">The world matrix that the model should be drawn in.</param> /// <param name="view">The view matrix that the model should be drawn in.</param> /// <param name="projection">The projection matrix that the model should be drawn in.</param> public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } }
Make public a method which was accidentally committed as private.
Make public a method which was accidentally committed as private.
C#
mit
dneelyep/MonoGameUtils
b31faabff41bb98c8d208d01f2010657edf73e3b
Modules/AppBrix.Events.Schedule/Impl/PriorityQueueItem.cs
Modules/AppBrix.Events.Schedule/Impl/PriorityQueueItem.cs
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; using System.Linq; namespace AppBrix.Events.Schedule.Impl { internal abstract class PriorityQueueItem { #region Construction public PriorityQueueItem(object scheduledEvent) { this.ScheduledEvent = scheduledEvent; } #endregion #region Properties public object ScheduledEvent { get; } public DateTime Occurrence { get; protected set; } #endregion #region Public and overriden methods public abstract void Execute(); public abstract void MoveToNextOccurrence(DateTime now); #endregion } internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent { #region Construction public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent) : base(scheduledEvent) { this.app = app; this.scheduledEvent = scheduledEvent; } #endregion #region Public and overriden methods public override void Execute() { try { this.app.GetEventHub().Raise(this.scheduledEvent.Event); } catch (Exception) { } } public override void MoveToNextOccurrence(DateTime now) { this.Occurrence = ((IScheduledEvent<T>)this.ScheduledEvent).GetNextOccurrence(now); } #endregion #region Private fields and constants private readonly IApp app; private readonly IScheduledEvent<T> scheduledEvent; #endregion } }
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; using System.Linq; namespace AppBrix.Events.Schedule.Impl { internal abstract class PriorityQueueItem { #region Properties public abstract object ScheduledEvent { get; } public DateTime Occurrence { get; protected set; } #endregion #region Public and overriden methods public abstract void Execute(); public abstract void MoveToNextOccurrence(DateTime now); #endregion } internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent { #region Construction public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent) { this.app = app; this.scheduledEvent = scheduledEvent; } #endregion #region Properties public override object ScheduledEvent => this.scheduledEvent; #endregion #region Public and overriden methods public override void Execute() { try { this.app.GetEventHub().Raise(this.scheduledEvent.Event); } catch (Exception) { } } public override void MoveToNextOccurrence(DateTime now) { this.Occurrence = this.scheduledEvent.GetNextOccurrence(now); } #endregion #region Private fields and constants private readonly IApp app; private readonly IScheduledEvent<T> scheduledEvent; #endregion } }
Remove unnecessary reference to IScheduledEvent
Remove unnecessary reference to IScheduledEvent
C#
mit
MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore
6908fb27ba3521937837bc0bf32769561f018d8e
RightpointLabs.Pourcast.Web/Controllers/HomeController.cs
RightpointLabs.Pourcast.Web/Controllers/HomeController.cs
using System.Web.Mvc; namespace RightpointLabs.Pourcast.Web.Controllers { using RightpointLabs.Pourcast.Application.Orchestrators.Abstract; public class HomeController : Controller { private readonly ITapOrchestrator _tapOrchestrator; private readonly IIdentityOrchestrator _identityOrchestrator; public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator) { _tapOrchestrator = tapOrchestrator; _identityOrchestrator = identityOrchestrator; } // // GET: /Home/ public ActionResult Index() { // Replace this with a Mock so it doesn't blow up the app //_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01); // TODO : remove this so users aren't added to admin automatically! var roleName = "Administrators"; var username = Request.LogonUserIdentity.Name; if (!_identityOrchestrator.UserExists(username)) { _identityOrchestrator.CreateUser(username); } if (!_identityOrchestrator.RoleExists(roleName)) { _identityOrchestrator.CreateRole(roleName); } if (!_identityOrchestrator.IsUserInRole(username, roleName)) { _identityOrchestrator.AddUserToRole(username, roleName); } return View(); } } }
using System.Web.Mvc; namespace RightpointLabs.Pourcast.Web.Controllers { using RightpointLabs.Pourcast.Application.Orchestrators.Abstract; public class HomeController : Controller { private readonly ITapOrchestrator _tapOrchestrator; private readonly IIdentityOrchestrator _identityOrchestrator; public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator) { _tapOrchestrator = tapOrchestrator; _identityOrchestrator = identityOrchestrator; } // // GET: /Home/ public ActionResult Index() { // Replace this with a Mock so it doesn't blow up the app //_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01); #if DEBUG // TODO : remove this so users aren't added to admin automatically! var roleName = "Administrators"; var username = Request.LogonUserIdentity.Name; if (!_identityOrchestrator.UserExists(username)) { _identityOrchestrator.CreateUser(username); } if (!_identityOrchestrator.RoleExists(roleName)) { _identityOrchestrator.CreateRole(roleName); } if (!_identityOrchestrator.IsUserInRole(username, roleName)) { _identityOrchestrator.AddUserToRole(username, roleName); } #endif return View(); } } }
Kill auto user insertion in non-debug
Kill auto user insertion in non-debug
C#
mit
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
ab84a734e672c2e3400b815b3284b0bef067fe30
Verdeler/MultipleConcurrencyLimiter.cs
Verdeler/MultipleConcurrencyLimiter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Verdeler { internal class MultipleConcurrencyLimiter<TSubject> { private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters = new List<ConcurrencyLimiter<TSubject>>(); public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number) { _concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number)); } public async Task Do(Func<Task> asyncFunc, TSubject subject) { //NOTE: This cannot be replaced with a Linq .ForEach foreach (var cl in _concurrencyLimiters) { await cl.WaitFor(subject).ConfigureAwait(false); } try { await asyncFunc().ConfigureAwait(false); } finally { //Release in the reverse order to prevent deadlocks _concurrencyLimiters .AsEnumerable().Reverse().ToList() .ForEach(l => l.Release(subject)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Verdeler { internal class MultipleConcurrencyLimiter<TSubject> { private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters = new List<ConcurrencyLimiter<TSubject>>(); public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number) { _concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number)); } public async Task Do(Func<Task> asyncFunc, TSubject subject) { //We must obtain locks in order to prevent cycles from forming. foreach (var concurrencyLimiter in _concurrencyLimiters) { await concurrencyLimiter.WaitFor(subject).ConfigureAwait(false); } try { await asyncFunc().ConfigureAwait(false); } finally { //Release in reverse order _concurrencyLimiters .AsEnumerable().Reverse().ToList() .ForEach(l => l.Release(subject)); } } } }
Update comments & variable name
Update comments & variable name
C#
mit
justinjstark/Verdeler,justinjstark/Delivered
077d87ffbbbaa90f9f71f2d6e24ba057dc8ac3a1
src/Proto.Remote/RemotingSystem.cs
src/Proto.Remote/RemotingSystem.cs
// ----------------------------------------------------------------------- // <copyright file="RemotingSystem.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using Grpc.Core; namespace Proto.Remote { public static class RemotingSystem { private static Server _server; public static PID EndpointManagerPid { get; private set; } public static void Start(string host, int port) { var addr = host + ":" + port; ProcessRegistry.Instance.Address = addr; ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid)); _server = new Server { Services = {Remoting.BindService(new EndpointReader())}, Ports = {new ServerPort(host, port, ServerCredentials.Insecure)} }; _server.Start(); var emProps = Actor.FromProducer(() => new EndpointManager()); EndpointManagerPid = Actor.Spawn(emProps); Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}"); } } }
// ----------------------------------------------------------------------- // <copyright file="RemotingSystem.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Linq; using Grpc.Core; namespace Proto.Remote { public static class RemotingSystem { private static Server _server; public static PID EndpointManagerPid { get; private set; } public static void Start(string host, int port) { ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid)); _server = new Server { Services = {Remoting.BindService(new EndpointReader())}, Ports = {new ServerPort(host, port, ServerCredentials.Insecure)} }; _server.Start(); var boundPort = _server.Ports.Single().BoundPort; var addr = host + ":" + boundPort; ProcessRegistry.Instance.Address = addr; var props = Actor.FromProducer(() => new EndpointManager()); EndpointManagerPid = Actor.Spawn(props); Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}"); } } }
Support port 0 in remoting
Support port 0 in remoting
C#
apache-2.0
raskolnikoov/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,AsynkronIT/protoactor-dotnet,tomliversidge/protoactor-dotnet,tomliversidge/protoactor-dotnet,masteryee/protoactor-dotnet,cpx86/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,raskolnikoov/protoactor-dotnet,masteryee/protoactor-dotnet,cpx86/protoactor-dotnet
d89ad7f1acaaf2a12243ffefd8b523ea4c4163f3
GreekNakamaTorrentUpload/WinClass/Helper/Helper.cs
GreekNakamaTorrentUpload/WinClass/Helper/Helper.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GreekNakamaTorrentUpload.WinClass.Helper { static class Helper { static public void BrowseFiles(TextBox txt_torrent, Label lbl_file) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Torrent files|*.torrent"; ofd.Multiselect = false; ofd.Title = "Browse the torrent file..."; DialogResult DL = ofd.ShowDialog(); if (DL == DialogResult.OK) { txt_torrent.Text = ofd.FileName; lbl_file.Text = "File Name : " + ofd.SafeFileName; } } } static public void SaveToJson(string content) { string contentForSave = JsonConvert.SerializeObject(content, Formatting.Indented); File.WriteAllText("settings.json", contentForSave); } static public void SaveToJson(string[] contents) { string contentForSave = JsonConvert.SerializeObject(contents.ToArray(), Formatting.Indented); File.WriteAllText("settings.json", contentForSave); } static public string LoadFromJson() { string loadedContents; try { loadedContents = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText("settings.json")); } catch (Exception) { return "0x01"; } return loadedContents; } } }
using Newtonsoft.Json; using System; using System.IO; using System.Windows.Forms; namespace GreekNakamaTorrentUpload.WinClass.Helper { static class Helper { static public Exception LoadedError = new Exception("Error while load the file. Error code: 0x01."); static public void BrowseFiles(TextBox txt_torrent, Label lbl_file) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Torrent files|*.torrent"; ofd.Multiselect = false; ofd.Title = "Browse the torrent file..."; DialogResult DL = ofd.ShowDialog(); if (DL == DialogResult.OK) { txt_torrent.Text = ofd.FileName; lbl_file.Text = ofd.SafeFileName; } } } static public void SaveToJson(string content) { string contentForSave = JsonConvert.SerializeObject(content, Formatting.Indented); File.WriteAllText("settings.json", contentForSave); } static public void SaveToJson(Credentials credentials) { string contentForSave = JsonConvert.SerializeObject(credentials, Formatting.Indented); File.WriteAllText("settings.json", contentForSave); } static public Credentials LoadFromJson() { Credentials loadedContents; loadedContents = JsonConvert.DeserializeObject<Credentials>(System.IO.File.ReadAllText("settings.json")); return loadedContents; } } }
Update the Load & Save Methods with new.
Update the Load & Save Methods with new.
C#
mit
HaruTzuki/Greek-Nakama-Upload-System,HaruTzuki/Greek-Nakama-Upload-System
7d301a351c618f5ed107c6a9f5f1bc2836cdec8f
PalasoUIWindowsForms.Tests/WritingSystems/UITests.cs
PalasoUIWindowsForms.Tests/WritingSystems/UITests.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using NUnit.Framework; using Palaso.TestUtilities; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture] public class UITests { [Test, Ignore("By hand only")] public void WritingSystemSetupDialog() { using (var folder = new TemporaryFolder("WS-Test")) { new WritingSystemSetupDialog(folder.Path).ShowDialog(); } } [Test, Ignore("By hand only")] public void WritingSystemSetupViewWithComboAttached() { using (var folder = new TemporaryFolder("WS-Test")) { var f = new Form(); f.Size=new Size(800,600); var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path)); var v = new WritingSystemSetupView(model); var combo = new WSPickerUsingComboBox(model); f.Controls.Add(combo); f.Controls.Add(v); f.ShowDialog(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using NUnit.Framework; using Palaso.TestUtilities; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.UI.WindowsForms.WritingSystems.WSTree; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture] public class UITests { [Test, Ignore("By hand only")] public void WritingSystemSetupDialog() { using (var folder = new TemporaryFolder("WS-Test")) { var dlg = new WritingSystemSetupDialog(folder.Path); dlg.WritingSystemSuggestor.SuggestVoice = true; dlg.ShowDialog(); } } [Test, Ignore("By hand only")] public void WritingSystemSetupViewWithComboAttached() { using (var folder = new TemporaryFolder("WS-Test")) { var f = new Form(); f.Size=new Size(800,600); var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path)); var v = new WritingSystemSetupView(model); var combo = new WSPickerUsingComboBox(model); f.Controls.Add(combo); f.Controls.Add(v); f.ShowDialog(); } } } }
Add voice option to ui test
Add voice option to ui test
C#
mit
glasseyes/libpalaso,marksvc/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,marksvc/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,ddaspit/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,darcywong00/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,hatton/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,hatton/libpalaso,JohnThomson/libpalaso
0d39ef7c94484f266c7fbee1ae263247f72a0b1e
Framework/Lokad.Cqrs.Portable/Core.Inbox/Events/FailedToAccessStorage.cs
Framework/Lokad.Cqrs.Portable/Core.Inbox/Events/FailedToAccessStorage.cs
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; namespace Lokad.Cqrs.Core.Inbox.Events { public sealed class FailedToAccessStorage : ISystemEvent { public Exception Exception { get; private set; } public string QueueName { get; private set; } public string MessageId { get; private set; } public FailedToAccessStorage(Exception exception, string queueName, string messageId) { Exception = exception; QueueName = queueName; MessageId = messageId; } } }
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; namespace Lokad.Cqrs.Core.Inbox.Events { public sealed class FailedToAccessStorage : ISystemEvent { public Exception Exception { get; private set; } public string QueueName { get; private set; } public string MessageId { get; private set; } public FailedToAccessStorage(Exception exception, string queueName, string messageId) { Exception = exception; QueueName = queueName; MessageId = messageId; } public override string ToString() { return string.Format("Failed to read '{0}' from '{1}': {2}", MessageId, QueueName, Exception.Message); } } }
Access storage failure is readable.
Access storage failure is readable.
C#
bsd-3-clause
modulexcite/lokad-cqrs
b511126a775d068e1727c1b56615e52a80195a8d
src/Galaxy/WebEnd/Models/DeploymentListModel.cs
src/Galaxy/WebEnd/Models/DeploymentListModel.cs
using System; using System.Collections.Generic; using System.Linq; using Codestellation.Galaxy.Domain; using Codestellation.Quarks.Collections; using Nejdb.Bson; namespace Codestellation.Galaxy.WebEnd.Models { public class DeploymentListModel { public readonly DeploymentModel[] Deployments; public readonly KeyValuePair<ObjectId, string>[] AllFeeds; public DeploymentListModel(DashBoard dashBoard) { AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count); Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count); Groups = Deployments.Select(GetGroup).Distinct().ToArray(); } public string[] Groups { get; set; } public int Count { get { return Deployments.Length; } } public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup) { var modelsByGroup = Deployments .Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal)) .OrderBy(x => x.ServiceFullName); return modelsByGroup; } private static string GetGroup(DeploymentModel model) { return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group; } } }
using System; using System.Collections.Generic; using System.Linq; using Codestellation.Galaxy.Domain; using Codestellation.Quarks.Collections; using Nejdb.Bson; namespace Codestellation.Galaxy.WebEnd.Models { public class DeploymentListModel { public readonly DeploymentModel[] Deployments; public readonly KeyValuePair<ObjectId, string>[] AllFeeds; public DeploymentListModel(DashBoard dashBoard) { AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count); Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count); Groups = Deployments.Select(GetGroup).Distinct().OrderBy(x => x).ToArray(); } public string[] Groups { get; set; } public int Count { get { return Deployments.Length; } } public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup) { var modelsByGroup = Deployments .Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal)) .OrderBy(x => x.ServiceFullName); return modelsByGroup; } private static string GetGroup(DeploymentModel model) { return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group; } } }
Sort deployment groups in deployment list
Sort deployment groups in deployment list
C#
apache-2.0
Codestellation/Galaxy,Codestellation/Galaxy,Codestellation/Galaxy
3a30117b89160cd5ae287fa2c44650e03d12e5ac
api-example-csharp/Inventory.cs
api-example-csharp/Inventory.cs
using System.Collections.Generic; namespace ApiTest.InventoryApi { public class UnitOfMeasure { public int id { get; set; } public string code { get; set; } } public sealed class InventoryStatus { public static string Active = "active"; public static string OnHold = "onhold"; public static string Inactive = "inactive"; } public sealed class InventoryType { public static string Normal = "normal"; public static string NonPhysical = "nonPhysical"; public static string Manufactured = "manufactured"; public static string Kitted = "kitted"; public static string RawMaterial = "rawMaterial"; } public class Inventory { public int id { get; set; } public string partNo { get; set; } public string whse { get; set; } public string description { get; set; } public string type { get; set; } public string status { get; set; } public decimal onHandQty { get; set; } public decimal committedQty { get; set; } public decimal backorderQty { get; set; } public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; } } public class InventoryClient : BaseObjectClient<Inventory> { public InventoryClient(ApiClient client) : base(client) { } public override string Resource { get { return "inventory/items/"; } } } }
using System.Collections.Generic; namespace ApiTest.InventoryApi { public class UnitOfMeasure { public int id { get; set; } public string code { get; set; } } public sealed class InventoryStatus { public static string Active = 0; public static string OnHold = 1; public static string Inactive = 2; } public sealed class InventoryType { public static string Normal = "N"; public static string NonPhysical = "V"; public static string Manufactured = "M"; public static string Kitted = "K"; public static string RawMaterial = "R"; } public class Inventory { public int id { get; set; } public string partNo { get; set; } public string whse { get; set; } public string description { get; set; } public string type { get; set; } public string status { get; set; } public decimal onHandQty { get; set; } public decimal committedQty { get; set; } public decimal backorderQty { get; set; } public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; } } public class InventoryClient : BaseObjectClient<Inventory> { public InventoryClient(ApiClient client) : base(client) { } public override string Resource { get { return "inventory/items/"; } } } }
Update inventory type and status mappings
Update inventory type and status mappings
C#
mit
spiresystems/spire-api-example-csharp
ad6f418d98d0476892504501074d0ddb78e4c2c5
Tests/IntegrationTests.Shared/NotificationTests.cs
Tests/IntegrationTests.Shared/NotificationTests.cs
using System; using NUnit.Framework; using Realms; using System.Threading; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; private void WriteOnDifferentThread(Action<Realm> action) { var thread = new Thread(() => { var r = Realm.GetInstance(_databasePath); r.Write(() => action(r)); r.Close(); }); thread.Start(); thread.Join(); } [Test] public void SimpleTest() { // Arrange // Act } } }
using System; using NUnit.Framework; using Realms; using System.Threading; using System.IO; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; private void WriteOnDifferentThread(Action<Realm> action) { var thread = new Thread(() => { var r = Realm.GetInstance(_databasePath); r.Write(() => action(r)); r.Close(); }); thread.Start(); thread.Join(); } [SetUp] private void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [Test] public void ShouldTriggerRealmChangedEvent() { // Arrange var wasNotified = false; _realm.RealmChanged += (sender, e) => { wasNotified = true; }; // Act WriteOnDifferentThread((realm) => { realm.CreateObject<Person>(); }); // Assert Assert.That(wasNotified, "RealmChanged notification was not triggered"); } } }
Add the simples notification test
Add the simples notification test
C#
apache-2.0
Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet
f3824da64b2596b49fe317fe784b30d831c9cc19
src/backend/SO115App.FakePersistenceJSon/GestioneIntervento/GetMaxCodice.cs
src/backend/SO115App.FakePersistenceJSon/GestioneIntervento/GetMaxCodice.cs
using Newtonsoft.Json; using SO115App.API.Models.Classi.Soccorso; using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SO115App.FakePersistenceJSon.GestioneIntervento { public class GetMaxCodice : IGetMaxCodice { public int GetMax() { int MaxIdSintesi; string filepath = "Fake/ListaRichiesteAssistenza.json"; string json; using (StreamReader r = new StreamReader(filepath)) { json = r.ReadToEnd(); } List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json); if (ListaRichieste != null) MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]); else MaxIdSintesi = 1; return MaxIdSintesi; } } }
using Newtonsoft.Json; using SO115App.API.Models.Classi.Soccorso; using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SO115App.FakePersistenceJSon.GestioneIntervento { public class GetMaxCodice : IGetMaxCodice { public int GetMax() { int MaxIdSintesi; string filepath = "Fake/ListaRichiesteAssistenza.json"; string json; using (StreamReader r = new StreamReader(filepath)) { json = r.ReadToEnd(); } List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json); if (ListaRichieste != null) MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]); else MaxIdSintesi = 0; return MaxIdSintesi; } } }
Fix - Corretto reperimento codice chiamata
Fix - Corretto reperimento codice chiamata
C#
agpl-3.0
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
356f37e4fd7cf32b2f596e685d0ce987ebb38bfc
Assetts/Classes/GGProduction/LetterStorm/Data/Collections/LessonBookTests.cs
Assetts/Classes/GGProduction/LetterStorm/Data/Collections/LessonBookTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using GGProductions.LetterStorm.Data.Collections; namespace Test.GGProductions.LetterStorm.Data.Collections { [TestClass] public class LessonBookTests { [TestMethod] public void CreateSampleLessonTest() { // Create a lesson book with a sample lesson LessonBook lessonBook = new LessonBook(); lessonBook.CreateSampleLesson(); // Verify a lesson was created and that it has the correct name Assert.AreEqual(1, lessonBook.Lessons.Count); Assert.AreEqual("Sample Lesson", lessonBook.Lessons[0].Name); // Verify the lesson's words were created Assert.AreEqual(4, lessonBook.Lessons[0].Words.Count); Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text); Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text); Assert.AreEqual("fish", lessonBook.Lessons[0].Words[2].Text); Assert.AreEqual("horse", lessonBook.Lessons[0].Words[3].Text); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using GGProductions.LetterStorm.Data.Collections; namespace Test.GGProductions.LetterStorm.Data.Collections { [TestClass] public class LessonBookTests { [TestMethod] public void CreateSampleLessonTest() { // Create a lesson book with a sample lesson LessonBook lessonBook = new LessonBook(); lessonBook.CreateSampleLessons(); // Verify a lesson was created and that it has the correct name Assert.AreEqual(5, lessonBook.Lessons.Count); Assert.AreEqual("K5 Sample", lessonBook.Lessons[0].Name); // Verify the lesson's words were created Assert.AreEqual(5, lessonBook.Lessons[0].Words.Count); Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text); Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text); Assert.AreEqual("bug", lessonBook.Lessons[0].Words[2].Text); Assert.AreEqual("fish", lessonBook.Lessons[0].Words[3].Text); Assert.AreEqual("horse", lessonBook.Lessons[0].Words[4].Text); } } }
Update text case for CreateSampleLesson
Update text case for CreateSampleLesson
C#
mit
GGProductions/LetterStormUnitTests
5603be33edd2521541c5cffffc0bb5d9f7b07be0
DesktopWidgets/Widgets/Note/Settings.cs
DesktopWidgets/Widgets/Note/Settings.cs
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Width = 160; Height = 200; } [DisplayName("Saved Text")] public string Text { get; set; } } }
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Width = 160; Height = 132; } [DisplayName("Saved Text")] public string Text { get; set; } } }
Change "Note" widget default height
Change "Note" widget default height
C#
apache-2.0
danielchalmers/DesktopWidgets
990ed090f91ac08d096b4f8d918732214d5bf81e
KataPotter/KataPotterPriceCalculator.cs
KataPotter/KataPotterPriceCalculator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KataPotter { public class KataPotterPriceCalculator { private static readonly double BOOK_UNIT_PRICE = 8; public double Calculate(Dictionary<string, int> booksToBuy) { var totalCount = booksToBuy.Sum(i => i.Value); var totalPrice = totalCount * BOOK_UNIT_PRICE; return totalPrice; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KataPotter { public class KataPotterPriceCalculator { private static readonly double BOOK_UNIT_PRICE = 8; private static readonly double TWO_BOOKS_DISCOUNT_RATE = 0.95; public double Calculate(Dictionary<string, int> booksToBuy) { var totalCount = booksToBuy.Sum(i => i.Value); var totalPrice = totalCount * BOOK_UNIT_PRICE; if (totalCount > 1) { totalPrice = totalPrice * TWO_BOOKS_DISCOUNT_RATE; } return totalPrice; } } }
Add two book discount scenario
Add two book discount scenario
C#
mit
kirkchen/KataPotter.CSharp
f6f1a4359287e94961eb766e744653121a23c266
src/backend/SO115App.SignalR/Sender/GestioneRuoli/NotificationDeleteRuolo.cs
src/backend/SO115App.SignalR/Sender/GestioneRuoli/NotificationDeleteRuolo.cs
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneRuoli { public class NotificationDeleteRuolo : INotifyDeleteRuolo { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteRuoliUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false); await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false); } } }
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneRuoli { public class NotificationDeleteRuolo : INotifyDeleteRuolo { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteRuoliUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); //await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false); await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false); } } }
Fix - Corretta notifica delete utente
Fix - Corretta notifica delete utente
C#
agpl-3.0
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
b6eb1456b9258bcd462a877b97f58f3687f8fc99
Oogstplanner.Web/App_Start/IocConfig.cs
Oogstplanner.Web/App_Start/IocConfig.cs
using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Oogstplanner.Models; using Oogstplanner.Data; using Oogstplanner.Services; namespace Oogstplanner.Web { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<OogstplannerUnitOfWork>() .As<IOogstplannerUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<OogstplannerContext>() .As<IOogstplannerContext>() .InstancePerRequest(); var repositoryInstances = new RepositoryFactories(); builder.RegisterInstance(repositoryInstances) .As<RepositoryFactories>() .SingleInstance(); builder.RegisterType<RepositoryProvider>() .As<IRepositoryProvider>() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly) .AsImplementedInterfaces() .Except<UserService>() .Except<AnonymousUserService>(); builder.RegisterType<AnonymousUserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Oogstplanner.Models; using Oogstplanner.Data; using Oogstplanner.Services; namespace Oogstplanner.Web { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<OogstplannerUnitOfWork>() .As<IOogstplannerUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<OogstplannerContext>() .As<IOogstplannerContext>() .InstancePerRequest(); var repositoryFactories = new RepositoryFactories(); builder.RegisterInstance(repositoryFactories) .As<RepositoryFactories>() .SingleInstance(); builder.RegisterType<RepositoryProvider>() .As<IRepositoryProvider>() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly) .AsImplementedInterfaces() .Except<UserService>() .Except<AnonymousUserService>() .InstancePerRequest(); builder.RegisterType<AnonymousUserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous) .InstancePerRequest(); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated) .InstancePerRequest(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
Set lifetime scope of services to instance per request
Set lifetime scope of services to instance per request
C#
mit
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
88bfa0dab7ba9794ea7b7803a123215c82473e57
src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlLanguageServerClient.cs
src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlLanguageServerClient.cs
// 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; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { [ContentType(ContentTypeNames.XamlContentType)] [DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere [Export(typeof(ILanguageClient))] internal class XamlLanguageServerClient : AbstractLanguageServerClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider) : base(languageServerProtocol, workspace, diagnosticService, listenerProvider, solutionProvider, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public override string Name => Resources.Xaml_Language_Server_Client; } }
// 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; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { [ContentType(ContentTypeNames.XamlContentType)] [DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere [Export(typeof(ILanguageClient))] internal class XamlLanguageServerClient : AbstractLanguageServerClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider) : base(languageServerProtocol, workspace, listenerProvider, solutionProvider, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public override string Name => Resources.Xaml_Language_Server_Client; } }
Remove unnecessary fields/methods for lsp push diagnostics
Remove unnecessary fields/methods for lsp push diagnostics
C#
mit
mavasani/roslyn,gafter/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,KevinRansom/roslyn,wvdd007/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,AmadeusW/roslyn,physhi/roslyn,wvdd007/roslyn,AmadeusW/roslyn,stephentoub/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,dotnet/roslyn,gafter/roslyn,panopticoncentral/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,tmat/roslyn,panopticoncentral/roslyn,weltkante/roslyn,stephentoub/roslyn,tannergooding/roslyn,diryboy/roslyn,heejaechang/roslyn,mavasani/roslyn,eriawan/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,tmat/roslyn,KevinRansom/roslyn,diryboy/roslyn,bartdesmet/roslyn,physhi/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,mavasani/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,dotnet/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,tannergooding/roslyn,physhi/roslyn,jasonmalinowski/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,AlekseyTs/roslyn,eriawan/roslyn,tannergooding/roslyn
451eac594d35fc681e4431e093a0d985e2359626
src/StreamDeckSharp/Internals/Throttle.cs
src/StreamDeckSharp/Internals/Throttle.cs
using System; using System.Diagnostics; using System.Threading; namespace StreamDeckSharp.Internals { internal class Throttle { private readonly Stopwatch stopwatch = Stopwatch.StartNew(); private long sumBytesInWindow = 0; public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity; public void MeasureAndBlock(int bytes) { sumBytesInWindow += bytes; var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit; if (elapsedSeconds < estimatedSeconds) { var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000)); Thread.Sleep(delta); } if (elapsedSeconds >= 1) { stopwatch.Restart(); sumBytesInWindow = 0; } } } }
using System; using System.Diagnostics; using System.Threading; namespace StreamDeckSharp.Internals { internal class Throttle { private readonly Stopwatch stopwatch = Stopwatch.StartNew(); private long sumBytesInWindow = 0; private int sleepCount = 0; public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity; public void MeasureAndBlock(int bytes) { sumBytesInWindow += bytes; var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit; if (elapsedSeconds < estimatedSeconds) { var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000)); Thread.Sleep(delta); sleepCount++; } if (elapsedSeconds >= 1) { if (sleepCount > 1) { Debug.WriteLine($"[Throttle] {sumBytesInWindow / elapsedSeconds}"); } stopwatch.Restart(); sumBytesInWindow = 0; sleepCount = 0; } } } }
Debug output on throttled throughput
Debug output on throttled throughput
C#
mit
OpenStreamDeck/StreamDeckSharp
d5403032a94a956c8d91b934e4f4ef19894960c4
src/Symbooglix/Solver/CVC4SMTLIBSolver.cs
src/Symbooglix/Solver/CVC4SMTLIBSolver.cs
using System; using Symbooglix.Solver; namespace Symbooglix { namespace Solver { public class CVC4SMTLIBSolver : SimpleSMTLIBSolver { SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) : base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags { } // HACK: public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) : this(useNamedAttributes, pathToSolver, persistentProcess) { LogicToUse = logic; } protected override void SetSolverOptions() { Printer.PrintSetLogic(LogicToUse); } } } }
using System; using Symbooglix.Solver; namespace Symbooglix { namespace Solver { public class CVC4SMTLIBSolver : SimpleSMTLIBSolver { SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) : base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags { } // HACK: public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) : this(useNamedAttributes, pathToSolver, persistentProcess) { // We should not use DO_NOT_SET because CVC4 complains if no // logic is set which causes a SolverErrorException to be raised. if (logic != SMTLIBQueryPrinter.Logic.DO_NOT_SET) LogicToUse = logic; } protected override void SetSolverOptions() { Printer.PrintSetLogic(LogicToUse); } } } }
Fix CVC4 support (requires a new version that supports the reset command).
Fix CVC4 support (requires a new version that supports the reset command).
C#
bsd-2-clause
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
06ffc916f97dab59ba0aa6c322e805e9b1b0dd93
Utility.cs
Utility.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Cipher { class Utility { public static string directory = @"c:\code\cypher_files"; /// <summary> /// Allows user to choose to display the password on the screen as is being typed. /// </summary> /// <param name="displayPassword"> /// Indicates whether or not password displays on the screen. /// </param> /// <returns> /// A password string. /// </returns> public static string GetPassword(string displayPassword) { string password = ""; if (displayPassword == "y" || displayPassword == "") { password = Console.ReadLine(); } if (displayPassword == "n") { while (true) { var pressedKey = System.Console.ReadKey(true); // Get all typed keys until 'Enter' is pressed. if (pressedKey.Key == ConsoleKey.Enter) { Console.WriteLine(""); break; } password += pressedKey.KeyChar; } } return password; } public static void SaveFileToDisk(string fileName, byte[] fileContents) { File.WriteAllBytes(fileName, fileContents); } } }
using System; using System.IO; namespace Cipher { class Utility { public static string directory = "/Users/emiranda/Documents/code/c#/cipher_files/"; /// <summary> /// Allows user to choose to display the password on the screen as is being typed. /// </summary> /// <param name="displayPassword"> /// Indicates whether or not password displays on the screen. /// </param> /// <returns> /// A password string. /// </returns> public static string GetPassword(string displayPassword) { string password = ""; if (displayPassword == "y" || displayPassword == "") { password = Console.ReadLine(); } if (displayPassword == "n") { while (true) { var pressedKey = System.Console.ReadKey(true); // Get all typed keys until 'Enter' is pressed. if (pressedKey.Key == ConsoleKey.Enter) { Console.WriteLine(""); break; } password += pressedKey.KeyChar; } } return password; } public static void SaveFileToDisk(string fileName, byte[] fileContents) { File.WriteAllBytes(fileName, fileContents); } } }
Remove unused code and updated directory location.
Remove unused code and updated directory location.
C#
mit
emiranda04/aes
bab16971ae3fe0d117154ab2697b25b5b2056657
src/Microsoft.AspNetCore.Authentication.Abstractions/IClaimsTransformation.cs
src/Microsoft.AspNetCore.Authentication.Abstractions/IClaimsTransformation.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Used by the <see cref="IAuthenticationService"/> for claims transformation. /// </summary> public interface IClaimsTransformation { /// <summary> /// Provides a central transformation point to change the specified principal. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param> /// <returns>The transformed principal.</returns> Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Used by the <see cref="IAuthenticationService"/> for claims transformation. /// </summary> public interface IClaimsTransformation { /// <summary> /// Provides a central transformation point to change the specified principal. /// Note: this will be run on each AuthenticateAsync call, so its safer to /// return a new ClaimsPrincipal if your transformation is not idempotent. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param> /// <returns>The transformed principal.</returns> Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal); } }
Add comment for claims transform
Add comment for claims transform
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
e7ce6a307e1bdc36b1aff0f72e556e6d369c5cd0
src/Umbraco.Core/Persistence/Repositories/Implement/UpgradeCheckRepository.cs
src/Umbraco.Core/Persistence/Repositories/Implement/UpgradeCheckRepository.cs
using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using Semver; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories.Implement { internal class UpgradeCheckRepository : IUpgradeCheckRepository { private static HttpClient _httpClient; private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade"; public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version) { try { if (_httpClient == null) _httpClient = new HttpClient(); var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter()); var result = await task.Content.ReadAsAsync<UpgradeResult>(); return result ?? new UpgradeResult("None", "", ""); } catch (HttpRequestException) { // this occurs if the server for Our is down or cannot be reached return new UpgradeResult("None", "", ""); } } private class CheckUpgradeDto { public CheckUpgradeDto(SemVersion version) { VersionMajor = version.Major; VersionMinor = version.Minor; VersionPatch = version.Patch; VersionComment = version.Prerelease; } public int VersionMajor { get; } public int VersionMinor { get; } public int VersionPatch { get; } public string VersionComment { get; } } } }
using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using Semver; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories.Implement { internal class UpgradeCheckRepository : IUpgradeCheckRepository { private static HttpClient _httpClient; private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade"; public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version) { try { if (_httpClient == null) _httpClient = new HttpClient(); var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter()); var result = await task.Content.ReadAsAsync<UpgradeResult>(); return result ?? new UpgradeResult("None", "", ""); } catch (UnsupportedMediaTypeException) { // this occurs if the server for Our is up but doesn't return a valid result (ex. content type) return new UpgradeResult("None", "", ""); } catch (HttpRequestException) { // this occurs if the server for Our is down or cannot be reached return new UpgradeResult("None", "", ""); } } private class CheckUpgradeDto { public CheckUpgradeDto(SemVersion version) { VersionMajor = version.Major; VersionMinor = version.Minor; VersionPatch = version.Patch; VersionComment = version.Prerelease; } public int VersionMajor { get; } public int VersionMinor { get; } public int VersionPatch { get; } public string VersionComment { get; } } } }
Handle Invalid format for Upgrade check
Handle Invalid format for Upgrade check
C#
mit
madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS
1a761239cbf4f52666327e5b2ce7e62a4cc0f43d
Hello_MultiScreen_iPhone/AppDelegate.cs
Hello_MultiScreen_iPhone/AppDelegate.cs
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Hello_MultiScreen_iPhone { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { //---- declarations UIWindow window; UINavigationController rootNavigationController; // This method is invoked when the application has loaded its UI and it is ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { this.window = new UIWindow (UIScreen.MainScreen.Bounds); //---- instantiate a new navigation controller this.rootNavigationController = new UINavigationController(); //---- instantiate a new home screen HomeScreen homeScreen = new HomeScreen(); //---- add the home screen to the navigation controller (it'll be the top most screen) this.rootNavigationController.PushViewController(homeScreen, false); //---- set the root view controller on the window. the nav controller will handle the rest this.window.RootViewController = this.rootNavigationController; this.window.MakeKeyAndVisible (); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Hello_MultiScreen_iPhone { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { //---- declarations UIWindow window; // This method is invoked when the application has loaded its UI and it is ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { this.window = new UIWindow (UIScreen.MainScreen.Bounds); //---- instantiate a new navigation controller var rootNavigationController = new UINavigationController(); //---- instantiate a new home screen HomeScreen homeScreen = new HomeScreen(); //---- add the home screen to the navigation controller (it'll be the top most screen) rootNavigationController.PushViewController(homeScreen, false); //---- set the root view controller on the window. the nav controller will handle the rest this.window.RootViewController = rootNavigationController; this.window.MakeKeyAndVisible (); return true; } } }
Remove class variable declaration for UINavigationController
Remove class variable declaration for UINavigationController
C#
mit
iFreedive/monotouch-samples,iFreedive/monotouch-samples,robinlaide/monotouch-samples,W3SS/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,peteryule/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,hongnguyenpro/monotouch-samples,robinlaide/monotouch-samples,a9upam/monotouch-samples,nelzomal/monotouch-samples,a9upam/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,hongnguyenpro/monotouch-samples,hongnguyenpro/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,a9upam/monotouch-samples,haithemaraissia/monotouch-samples,kingyond/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,nervevau2/monotouch-samples,albertoms/monotouch-samples,markradacz/monotouch-samples,andypaul/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,albertoms/monotouch-samples,albertoms/monotouch-samples,kingyond/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,xamarin/monotouch-samples,labdogg1003/monotouch-samples,YOTOV-LIMITED/monotouch-samples,xamarin/monotouch-samples
03f61e240cd512d69f9248dcb9c475c62430ff48
LogicalShift.Reason/BasicUnification.cs
LogicalShift.Reason/BasicUnification.cs
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program) { var simpleUnifier = new SimpleUnifier(); var traceUnifier = new TraceUnifier(simpleUnifier); // Run the unifier try { Console.WriteLine(query); traceUnifier.QueryUnifier.Compile(query); simpleUnifier.PrepareToRunProgram(); Console.WriteLine(program); traceUnifier.ProgramUnifier.Compile(program); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way yield break; } // Retrieve the unified value for the program // TODO: eventually we'll need to use a unification key var result = simpleUnifier.UnifiedValue(program.UnificationKey ?? program); // If the result was valid, return as the one value from this function if (result != null) { yield return result; } } } }
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program) { var simpleUnifier = new SimpleUnifier(); // Run the unifier try { simpleUnifier.QueryUnifier.Compile(query); simpleUnifier.PrepareToRunProgram(); simpleUnifier.ProgramUnifier.Compile(program); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way yield break; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { yield return result; } } } }
Remove tracing from the unifier
Remove tracing from the unifier
C#
apache-2.0
Logicalshift/Reason
d20a79c3f992261665b41203207621be9aee9100
TGS.Interface.Bridge/DreamDaemonBridge.cs
TGS.Interface.Bridge/DreamDaemonBridge.cs
using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using TGS.Interface; using TGS.Interface.Components; namespace TGS.Interface.Bridge { /// <summary> /// Holds the proc that DD calls to access <see cref="ITGInterop"/> /// </summary> public static class DreamDaemonBridge { /// <summary> /// The proc that DD calls to access <see cref="ITGInterop"/> /// </summary> /// <param name="argc">The number of arguments passed</param> /// <param name="args">The arguments passed</param> /// <returns>0</returns> [DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)] public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args) { try { var parsedArgs = new List<string>(); parsedArgs.AddRange(args); var instance = parsedArgs[0]; parsedArgs.RemoveAt(0); using (var I = new ServerInterface()) if(I.ConnectToInstance(instance, true).HasFlag(ConnectivityLevel.Connected)) I.GetComponent<ITGInterop>().InteropMessage(String.Join(" ", parsedArgs)); } catch { } return 0; } } }
using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace TGS.Interface.Bridge { /// <summary> /// Holds the proc that DD calls to access <see cref="ITGInterop"/> /// </summary> public static class DreamDaemonBridge { /// <summary> /// The proc that DD calls to access <see cref="ITGInterop"/> /// </summary> /// <param name="argc">The number of arguments passed</param> /// <param name="args">The arguments passed</param> /// <returns>0</returns> [DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)] public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args) { try { var parsedArgs = new List<string>(); parsedArgs.AddRange(args); var instance = parsedArgs[0]; parsedArgs.RemoveAt(0); using (var I = new ServerInterface()) I.Server.GetInstance(instance).Interop.InteropMessage(String.Join(" ", parsedArgs)); } catch { } return 0; } } }
Update bridge to use new interface
Update bridge to use new interface
C#
agpl-3.0
Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server
6493a4c7d1438c2c2decbd002bc0d28c73db9a86
OdeToFood/Controllers/HomeController.cs
OdeToFood/Controllers/HomeController.cs
using System.Linq; using Microsoft.AspNetCore.Mvc; using OdeToFood.Entities; using OdeToFood.Services; using OdeToFood.ViewModels; namespace OdeToFood.Controllers { public class HomeController : Controller { private IRestaurantData _restaurantData; private IGreeter _greeter; public HomeController(IRestaurantData restaurantData, IGreeter greeter) { _restaurantData = restaurantData; _greeter = greeter; } public IActionResult Index() { var model = new HomePageViewModel() { Message = _greeter.GetGreeting(), Restaurants = _restaurantData.GetAll() }; return View(model); } public IActionResult Details(int id) { var model = _restaurantData.Get(id); if (model == null) { return RedirectToAction(nameof(Index)); } return View(model); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(RestaurantEditViewModel model) { var restaurant = new Restaurant() { Name = model.Name, Cuisine = model.Cuisine }; restaurant = _restaurantData.Add(restaurant); return View(nameof(Details), restaurant); } } }
using Microsoft.AspNetCore.Mvc; using OdeToFood.Entities; using OdeToFood.Services; using OdeToFood.ViewModels; namespace OdeToFood.Controllers { public class HomeController : Controller { private IRestaurantData _restaurantData; private IGreeter _greeter; public HomeController(IRestaurantData restaurantData, IGreeter greeter) { _restaurantData = restaurantData; _greeter = greeter; } public IActionResult Index() { var model = new HomePageViewModel() { Message = _greeter.GetGreeting(), Restaurants = _restaurantData.GetAll() }; return View(model); } public IActionResult Details(int id) { var model = _restaurantData.Get(id); if (model == null) { return RedirectToAction(nameof(Index)); } return View(model); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(RestaurantEditViewModel model) { var restaurant = new Restaurant() { Name = model.Name, Cuisine = model.Cuisine }; restaurant = _restaurantData.Add(restaurant); return RedirectToAction(nameof(Details), new { Id = restaurant.Id }); } } }
Add POST REDIRECT GET Pattern to controller
Add POST REDIRECT GET Pattern to controller
C#
mit
IliaAnastassov/OdeToFood,IliaAnastassov/OdeToFood
acfd4352b5d9a3611666f2f9768526156e27103b
src/NodaTime/Calendars/NamespaceDoc.cs
src/NodaTime/Calendars/NamespaceDoc.cs
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // 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. #endregion using System.Runtime.CompilerServices; namespace NodaTime.Calendars { /// <summary> /// <para> /// The NodaTime.Calendar namespace contains types related to calendars beyond the /// <see cref="CalendarSystem"/> type in the core NodaTime namespace. /// </para> /// </summary> [CompilerGenerated] internal class NamespaceDoc { // No actual code here - it's just for the sake of documenting the namespace. } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // 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. #endregion using System.Runtime.CompilerServices; namespace NodaTime.Calendars { /// <summary> /// <para> /// The NodaTime.Calendars namespace contains types related to calendars beyond the /// <see cref="CalendarSystem"/> type in the core NodaTime namespace. /// </para> /// </summary> [CompilerGenerated] internal class NamespaceDoc { // No actual code here - it's just for the sake of documenting the namespace. } }
Fix a typo in the NodaTime.Calendars namespace summary.
Fix a typo in the NodaTime.Calendars namespace summary.
C#
apache-2.0
zaccharles/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,nodatime/nodatime,malcolmr/nodatime,nodatime/nodatime,zaccharles/nodatime,jskeet/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,jskeet/nodatime
ce603fc99ec9c2b9cc5d233f14878d61930634d0
build.cake
build.cake
var configuration = Argument("configuration", "Debug"); Task("Clean") .Does(() => { CleanDirectory("./artifacts/"); }); Task("Restore") .Does(() => { DotNetCoreRestore(); }); Task("Build") .Does(() => { DotNetCoreBuild("./src/**/project.json", new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Pack") .Does(() => { new List<string> { "Stormpath.Owin.Abstractions", "Stormpath.Owin.Middleware", "Stormpath.Owin.Views.Precompiled" }.ForEach(name => { DotNetCorePack("./src/" + name + "/project.json", new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = "./artifacts/" }); }); }); Task("Test") .IsDependentOn("Restore") .IsDependentOn("Build") .Does(() => { new List<string> { "Stormpath.Owin.UnitTest" }.ForEach(name => { DotNetCoreTest("./test/" + name + "/project.json"); }); }); Task("Default") .IsDependentOn("Clean") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Pack"); var target = Argument("target", "Default"); RunTarget(target);
var configuration = Argument("configuration", "Debug"); Task("Clean") .Does(() => { CleanDirectory("./artifacts/"); }); Task("Restore") .Does(() => { DotNetCoreRestore(); }); Task("Build") .Does(() => { DotNetCoreBuild("./src/**/*.csproj", new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Pack") .Does(() => { new List<string> { "Stormpath.Owin.Abstractions", "Stormpath.Owin.Middleware", "Stormpath.Owin.Views.Precompiled" }.ForEach(name => { DotNetCorePack("./src/" + name + ".csproj", new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = "./artifacts/" }); }); }); Task("Test") .IsDependentOn("Restore") .IsDependentOn("Build") .Does(() => { new List<string> { "Stormpath.Owin.UnitTest" }.ForEach(name => { DotNetCoreTest("./test/" + name + ".csproj"); }); }); Task("Default") .IsDependentOn("Clean") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Pack"); var target = Argument("target", "Default"); RunTarget(target);
Update cake script to csproj
Update cake script to csproj
C#
apache-2.0
stormpath/stormpath-dotnet-owin-middleware
015f71f35881e721b3d0f6964926fafccd65ea4d
Types/Properties/AssemblyInfo.cs
Types/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyTitle("NuGetPackageExplorer.Types")] [assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyTitle("NuGetPackageExplorer.Types")] [assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.7.0.0")] [assembly: AssemblyFileVersion("3.7.0.0")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]
Update assembly version of Types.dll to 3.7
Update assembly version of Types.dll to 3.7
C#
mit
NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer,dsplaisted/NuGetPackageExplorer
c0803ee8f0df48412564af36d5c7d56702b3bf19
Tests/CSF.Screenplay.Reporting.Tests/JsonReportRendererTests.cs
Tests/CSF.Screenplay.Reporting.Tests/JsonReportRendererTests.cs
using System.IO; using System.Text; using CSF.Screenplay.Reporting.Tests; using CSF.Screenplay.Reporting.Tests.Autofixture; using CSF.Screenplay.ReportModel; using NUnit.Framework; namespace CSF.Screenplay.Reporting.Tests { [TestFixture] public class JsonReportRendererTests { [Test,AutoMoqData] public void Write_can_create_a_document_without_crashing([RandomReport] Report report) { // Arrange using(var writer = GetReportOutput()) { var sut = new JsonReportRenderer(writer); // Act & assert Assert.DoesNotThrow(() => sut.Render(report)); } } TextWriter GetReportOutput() { // Uncomment this line to write the report to a file instead of a throwaway string return new StreamWriter("JsonReportRendererTests.json"); //var sb = new StringBuilder(); //return new StringWriter(sb); } } }
using System.IO; using System.Text; using CSF.Screenplay.Reporting.Tests; using CSF.Screenplay.Reporting.Tests.Autofixture; using CSF.Screenplay.ReportModel; using NUnit.Framework; namespace CSF.Screenplay.Reporting.Tests { [TestFixture] public class JsonReportRendererTests { [Test,AutoMoqData] public void Write_can_create_a_document_without_crashing([RandomReport] Report report) { // Arrange using(var writer = GetReportOutput()) { var sut = new JsonReportRenderer(writer); // Act & assert Assert.DoesNotThrow(() => sut.Render(report)); } } TextWriter GetReportOutput() { // Uncomment this line to write the report to a file instead of a throwaway string //return new StreamWriter("JsonReportRendererTests.json"); var sb = new StringBuilder(); return new StringWriter(sb); } } }
Change test back to using a string builder
Change test back to using a string builder
C#
mit
csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay
b6d25ed5d740381f4fc2870d13eabcd12096c7fe
Source/EasyNetQ.Hosepipe/QueueRetrieval.cs
Source/EasyNetQ.Hosepipe/QueueRetrieval.cs
using System; using System.Collections.Generic; using System.Text; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe { public interface IQueueRetreival { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetreival : IQueueRetreival { public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var channel = connection.CreateModel()) { try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (++count < parameters.NumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName); yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info); } } } } }
using System; using System.Collections.Generic; using System.Text; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe { public interface IQueueRetreival { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetreival : IQueueRetreival { public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var channel = connection.CreateModel()) { try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (count++ < parameters.NumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName); yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info); } } } } }
Fix number of messages retrieved. Used to be n-1
Fix number of messages retrieved. Used to be n-1
C#
mit
chinaboard/EasyNetQ,Ascendon/EasyNetQ,fpommerening/EasyNetQ,lukasz-lysik/EasyNetQ,ar7z1/EasyNetQ,sanjaysingh/EasyNetQ,nicklv/EasyNetQ,EasyNetQ/EasyNetQ,mleenhardt/EasyNetQ,scratch-net/EasyNetQ,zidad/EasyNetQ,Ascendon/EasyNetQ,fpommerening/EasyNetQ,Pliner/EasyNetQ,EIrwin/EasyNetQ,micdenny/EasyNetQ,tkirill/EasyNetQ,reisenberger/EasyNetQ,scratch-net/EasyNetQ,reisenberger/EasyNetQ,maverix/EasyNetQ,ar7z1/EasyNetQ,alexwiese/EasyNetQ,alexwiese/EasyNetQ,lukasz-lysik/EasyNetQ,chinaboard/EasyNetQ,danbarua/EasyNetQ,EIrwin/EasyNetQ,sanjaysingh/EasyNetQ,maverix/EasyNetQ,blackcow02/EasyNetQ,Pliner/EasyNetQ,alexwiese/EasyNetQ,mleenhardt/EasyNetQ,danbarua/EasyNetQ,GeckoInformasjonssystemerAS/EasyNetQ,nicklv/EasyNetQ,zidad/EasyNetQ,blackcow02/EasyNetQ,tkirill/EasyNetQ,GeckoInformasjonssystemerAS/EasyNetQ
182cf2f51700643d9d9e7547d3bd079b7b5b6eb5
src/Abp.EntityFrameworkCore/EntityFrameworkCore/ValueConverters/AbpDateTimeValueConverter.cs
src/Abp.EntityFrameworkCore/EntityFrameworkCore/ValueConverters/AbpDateTimeValueConverter.cs
using System; using System.Linq.Expressions; using Abp.Timing; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Abp.EntityFrameworkCore.ValueConverters { public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?> { public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = default) : base(Normalize, Normalize, mappingHints) { } private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x => x.HasValue ? Clock.Normalize(x.Value) : x; } }
using System; using System.Linq.Expressions; using Abp.Timing; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Abp.EntityFrameworkCore.ValueConverters { public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?> { public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = null) : base(Normalize, Normalize, mappingHints) { } private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x => x.HasValue ? Clock.Normalize(x.Value) : x; } }
Change the default value of the parameter initialization method.
Change the default value of the parameter initialization method.
C#
mit
luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate
f72a968ae1808814f49cb3a9cf2c6426be7e7848
Knapcode.StandardSerializer/Properties/AssemblyInfo.cs
Knapcode.StandardSerializer/Properties/AssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")] [assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-9c82a0d-dirty")] [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")] [assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-base")] [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
Change the assembly version to "base"
Change the assembly version to "base"
C#
unlicense
joelverhagen/StandardSerializer
354e57418a5cd18e173384eece261b71e8c20b95
Anlab.Mvc/Views/Admin/ListClients.cshtml
Anlab.Mvc/Views/Admin/ListClients.cshtml
@model IList<User> @{ ViewData["Title"] = "List Non Admin Users"; } <div class="col"> <table id="table"> <thead> <tr> <th></th> <th>Name</th> <th>Email</th> <th>Client Id</th> <th>Phone</th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td> <a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a> </td> <td>@user.Name</td> <td>@user.Email</td> <td>@user.ClientId</td> <td>@user.Phone</td> </tr> } </tbody> </table> </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function () { $("#table").dataTable({ "sorting": [[2, "desc"]], "pageLength": 100, }); }); </script> }
@model IList<User> @{ ViewData["Title"] = "List Non Admin Users"; } <div class="col"> <table id="table"> <thead> <tr> <th></th> <th>Name</th> <th>Email</th> <th>Client Id</th> <th>Phone</th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td> <a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a> </td> <td>@user.Name</td> <td>@user.Email</td> <td>@user.ClientId</td> <td>@user.Phone</td> </tr> } </tbody> </table> </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function () { $("#table").dataTable({ "sorting": [[2, "desc"]], "pageLength": 100, "columnDefs": [ { "orderable": false, "targets": [0] }, { "searchable":false, "targets": 0 } ] }); }); </script> }
Fix sorting and searching on table
Fix sorting and searching on table
C#
mit
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
7e826ebd9b914fb8b46bec946c127db4e9b2768f
src/CGO.Web/Views/Shared/_Layout.cshtml
src/CGO.Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/themes/base/css", "~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/themes/base/css", "~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
Set the document language to English
Set the document language to English
C#
mit
alastairs/cgowebsite,alastairs/cgowebsite
d6a5743d1b04da99e6e2ae62ee6b6cd2c4201405
osu.Framework/Platform/Linux/Sdl/SdlClipboard.cs
osu.Framework/Platform/Linux/Sdl/SdlClipboard.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern IntPtr SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { IntPtr ptrToText = SDL_GetClipboardText(); string text = Marshal.PtrToStringAnsi(ptrToText); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); /// <returns>Returns the clipboard text on success or <see cref="IntPtr.Zero"/> on failure. </returns> [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern IntPtr SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { IntPtr ptrToText = SDL_GetClipboardText(); string text = Marshal.PtrToStringAnsi(ptrToText); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
Add doc for what happens when getting clipboard text fails (SDL)
Add doc for what happens when getting clipboard text fails (SDL)
C#
mit
peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework
d030dea1b1b9760c918d1da46aac9dffeb7340e1
src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs
src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs
using Hangfire.Mongo.Database; using MongoDB.Driver; using System; using Hangfire.Mongo.Helpers; using MongoDB.Bson; namespace Hangfire.Mongo.MongoUtils { /// <summary> /// Helper utilities to work with Mongo database /// </summary> public static class MongoExtensions { /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="database">Mongo database</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this IMongoDatabase database) { try { dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1))); return ((DateTime)serverStatus.localTime).ToUniversalTime(); } catch (MongoException) { return DateTime.UtcNow; } } /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="dbContext">Hangfire database context</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext) { return GetServerTimeUtc(dbContext.Database); } } }
using Hangfire.Mongo.Database; using MongoDB.Driver; using System; using System.Collections.Generic; using Hangfire.Mongo.Helpers; using MongoDB.Bson; namespace Hangfire.Mongo.MongoUtils { /// <summary> /// Helper utilities to work with Mongo database /// </summary> public static class MongoExtensions { /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="database">Mongo database</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this IMongoDatabase database) { dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1))); object localTime; if (((IDictionary<string, object>)serverStatus).TryGetValue("localTime", out localTime)) { return ((DateTime)localTime).ToUniversalTime(); } return DateTime.UtcNow; } /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="dbContext">Hangfire database context</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext) { return GetServerTimeUtc(dbContext.Database); } } }
Optimize query for server time. (not throwing exception)
Optimize query for server time. (not throwing exception)
C#
mit
sergeyzwezdin/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,persi12/Hangfire.Mongo,sergun/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,sergun/Hangfire.Mongo,persi12/Hangfire.Mongo
cd86a29695a8d6afc48d736890cd74211d01f620
Nilgiri.Tests/Examples/Should/NotBeOk.cs
Nilgiri.Tests/Examples/Should/NotBeOk.cs
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ExpectStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ShouldStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
Fix the using. Sometimes atom can be...
Fix the using. Sometimes atom can be...
C#
mit
brycekbargar/Nilgiri,brycekbargar/Nilgiri
15411d9c6d3e8aacb9485d4a0af8b19eeae49fe3
ProjectTrackercs/PTWpf/RolesEdit.xaml.cs
ProjectTrackercs/PTWpf/RolesEdit.xaml.cs
using System; using System.Collections.Generic; 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; using ProjectTracker.Library.Admin; namespace PTWpf { /// <summary> /// Interaction logic for RolesEdit.xaml /// </summary> public partial class RolesEdit : EditForm { public RolesEdit() { InitializeComponent(); Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider; dp.DataChanged += new EventHandler(base.DataChanged); } protected override void ApplyAuthorization() { this.AuthPanel.Refresh(); if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles))) { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"]; } else { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"]; ((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel(); } } } }
using System; using System.Collections.Generic; 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; using ProjectTracker.Library.Admin; namespace PTWpf { /// <summary> /// Interaction logic for RolesEdit.xaml /// </summary> public partial class RolesEdit : EditForm { public RolesEdit() { InitializeComponent(); Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider; dp.DataChanged += new EventHandler(base.DataChanged); } protected override void ApplyAuthorization() { if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles))) { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"]; } else { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"]; ((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel(); } } } }
Use the new Delete command support in CslaDataProvider.
Use the new Delete command support in CslaDataProvider.
C#
mit
JasonBock/csla,JasonBock/csla,jonnybee/csla,BrettJaner/csla,rockfordlhotka/csla,ronnymgm/csla-light,MarimerLLC/csla,BrettJaner/csla,ronnymgm/csla-light,BrettJaner/csla,JasonBock/csla,MarimerLLC/csla,jonnybee/csla,MarimerLLC/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,rockfordlhotka/csla
f06576a15685a9a6417a950aab2980b9829e1435
nuserv/Utility/HttpRouteDataResolver.cs
nuserv/Utility/HttpRouteDataResolver.cs
namespace nuserv.Utility { using System.Net.Http; using System.Web; using System.Web.Http.Routing; public class HttpRouteDataResolver : IHttpRouteDataResolver { #region Public Methods and Operators public IHttpRouteData Resolve() { if (HttpContext.Current != null) { var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage; return requestMessage.GetRouteData(); } return null; } #endregion } }
namespace nuserv.Utility { #region Usings using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http.Routing; #endregion public class HttpRouteDataResolver : IHttpRouteDataResolver { #region Public Methods and Operators public IHttpRouteData Resolve() { if (HttpContext.Current != null) { if (HttpContext.Current.Items.Contains("")) { var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage; if (requestMessage != null) { return requestMessage.GetRouteData(); } } else { return new RouteData(HttpContext.Current.Request.RequestContext.RouteData); } } return null; } #endregion private class RouteData : IHttpRouteData { #region Fields private readonly System.Web.Routing.RouteData originalRouteData; #endregion #region Constructors and Destructors public RouteData(System.Web.Routing.RouteData routeData) { if (routeData == null) { throw new ArgumentNullException("routeData"); } this.originalRouteData = routeData; this.Route = null; } #endregion #region Public Properties public IHttpRoute Route { get; private set; } public IDictionary<string, object> Values { get { return this.originalRouteData.Values; } } #endregion } } }
Implement RouteData resolvement while in wcf context
Implement RouteData resolvement while in wcf context
C#
mit
baseclass/nuserv,baseclass/nuserv,baseclass/nuserv
256ea0920292077a1547be795cfd1d5507064cb3
src/SqlPersistence/SqlPersistence.cs
src/SqlPersistence/SqlPersistence.cs
namespace NServiceBus { using Settings; using Features; using Persistence; using Persistence.Sql; /// <summary> /// The <see cref="PersistenceDefinition"/> for the SQL Persistence. /// </summary> public class SqlPersistence : PersistenceDefinition { /// <summary> /// Initializes a new instance of <see cref="SqlPersistence"/>. /// </summary> public SqlPersistence() { Supports<StorageType.Outbox>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlOutboxFeature>(); }); Supports<StorageType.Timeouts>(s => { s.EnableFeatureByDefault<SqlTimeoutFeature>(); }); Supports<StorageType.Sagas>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlSagaFeature>(); s.AddUnrecoverableException(typeof(SerializationException)); }); Supports<StorageType.Subscriptions>(s => { s.EnableFeatureByDefault<SqlSubscriptionFeature>(); }); Defaults(s => { var dialect = s.GetSqlDialect(); var diagnostics = dialect.GetCustomDialectDiagnosticsInfo(); s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new { Name = dialect.Name, CustomDiagnostics = diagnostics }); s.EnableFeatureByDefault<InstallerFeature>(); }); } static void EnableSession(SettingsHolder s) { s.EnableFeatureByDefault<StorageSessionFeature>(); } } }
namespace NServiceBus { using Settings; using Features; using Persistence; using Persistence.Sql; /// <summary> /// The <see cref="PersistenceDefinition"/> for the SQL Persistence. /// </summary> public class SqlPersistence : PersistenceDefinition { /// <summary> /// Initializes a new instance of <see cref="SqlPersistence"/>. /// </summary> public SqlPersistence() { Supports<StorageType.Outbox>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlOutboxFeature>(); }); Supports<StorageType.Timeouts>(s => { s.EnableFeatureByDefault<SqlTimeoutFeature>(); }); Supports<StorageType.Sagas>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlSagaFeature>(); s.AddUnrecoverableException(typeof(SerializationException)); }); Supports<StorageType.Subscriptions>(s => { s.EnableFeatureByDefault<SqlSubscriptionFeature>(); }); Defaults(s => { var defaultsAppliedSettingsKey = "NServiceBus.Persistence.Sql.DefaultApplied"; if (s.HasSetting(defaultsAppliedSettingsKey)) { return; } var dialect = s.GetSqlDialect(); var diagnostics = dialect.GetCustomDialectDiagnosticsInfo(); s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new { Name = dialect.Name, CustomDiagnostics = diagnostics }); s.EnableFeatureByDefault<InstallerFeature>(); s.Set(defaultsAppliedSettingsKey, true); }); } static void EnableSession(SettingsHolder s) { s.EnableFeatureByDefault<StorageSessionFeature>(); } } }
Make sure to only invoke defaults once
Make sure to only invoke defaults once
C#
mit
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
545c0585e0697190da6b023d5310e17588745c8a
ExpressRunner/TestItem.cs
ExpressRunner/TestItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using ExpressRunner.Api; namespace ExpressRunner { public class TestItem : PropertyChangedBase, IRunnableTest { public string Name { get { return Test.Name; } } private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>(); public IObservableCollection<TestRun> Runs { get { return runs; } } private TestStatus status = TestStatus.NotRun; public TestStatus Status { get { return status; } private set { if (status != value) { status = value; NotifyOfPropertyChange("Status"); } } } private readonly Test test; public Test Test { get { return test; } } public TestItem(Test test) { if (test == null) throw new ArgumentNullException("test"); this.test = test; } public void RecordRun(TestRun run) { runs.Add(run); UpdateStatus(run); } private void UpdateStatus(TestRun run) { if (run.Status == TestStatus.Failed) Status = TestStatus.Failed; else if (Status == TestStatus.NotRun) Status = run.Status; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using ExpressRunner.Api; namespace ExpressRunner { public class TestItem : PropertyChangedBase, IRunnableTest { public string Name { get { return Test.Name; } } private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>(); public IObservableCollection<TestRun> Runs { get { return runs; } } private TestStatus status = TestStatus.NotRun; public TestStatus Status { get { return status; } private set { if (status != value) { status = value; NotifyOfPropertyChange("Status"); } } } private readonly Test test; public Test Test { get { return test; } } public TestItem(Test test) { if (test == null) throw new ArgumentNullException("test"); this.test = test; } public void RecordRun(TestRun run) { UpdateStatus(run); runs.Add(run); } private void UpdateStatus(TestRun run) { if (run.Status == TestStatus.Failed) Status = TestStatus.Failed; else if (Status == TestStatus.NotRun) Status = run.Status; } } }
Change order of update operation in RecordRun
Change order of update operation in RecordRun
C#
mit
lpatalas/ExpressRunner
7527730eb521d8c9375eacb8d7257ef7c49c3a61
src/Fixie/Execution/MethodDiscoverer.cs
src/Fixie/Execution/MethodDiscoverer.cs
namespace Fixie.Execution { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class MethodDiscoverer { readonly Filter filter; readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions; public MethodDiscoverer(Filter filter, Convention convention) { this.filter = filter; testMethodConditions = convention.Config.TestMethodConditions; } public IReadOnlyList<MethodInfo> TestMethods(Type testClass) { try { bool testClassIsDisposable = IsDisposable(testClass); return testClass .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(method => method.DeclaringType != typeof(object)) .Where(method => !(testClassIsDisposable && HasDisposeSignature(method))) .Where(IsMatch) .Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method))) .ToArray(); } catch (Exception exception) { throw new Exception( "Exception thrown while attempting to run a custom method-discovery predicate. " + "Check the inner exception for more details.", exception); } } bool IsMatch(MethodInfo candidate) => testMethodConditions.All(condition => condition(candidate)); static bool IsDisposable(Type type) => type.GetInterfaces().Any(interfaceType => interfaceType == typeof(IDisposable)); static bool HasDisposeSignature(MethodInfo method) => method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0; } }
namespace Fixie.Execution { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class MethodDiscoverer { readonly Filter filter; readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions; public MethodDiscoverer(Filter filter, Convention convention) { this.filter = filter; testMethodConditions = convention.Config.TestMethodConditions; } public IReadOnlyList<MethodInfo> TestMethods(Type testClass) { try { bool testClassIsDisposable = IsDisposable(testClass); return testClass .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(method => method.DeclaringType != typeof(object)) .Where(method => !(testClassIsDisposable && HasDisposeSignature(method))) .Where(IsMatch) .Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method))) .ToArray(); } catch (Exception exception) { throw new Exception( "Exception thrown while attempting to run a custom method-discovery predicate. " + "Check the inner exception for more details.", exception); } } bool IsMatch(MethodInfo candidate) => testMethodConditions.All(condition => condition(candidate)); static bool IsDisposable(Type type) => type.GetInterfaces().Contains(typeof(IDisposable)); static bool HasDisposeSignature(MethodInfo method) => method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0; } }
Optimize the detection of IDisposable test classes. Array.Contains performs fewer allocations than the LINQ Any extension method.
Optimize the detection of IDisposable test classes. Array.Contains performs fewer allocations than the LINQ Any extension method.
C#
mit
fixie/fixie
bd68ab67e2574353f6fc4486a07b7744dbac72ec
projects/AlertSample/source/AlertSample.App/Program.cs
projects/AlertSample/source/AlertSample.App/Program.cs
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AlertSample { using System; internal sealed class Program { private static void Main(string[] args) { Alert alert = new Alert("AlertSample", 5.0d, 10.0d); try { alert.Start(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e); throw; } finally { alert.Stop(); } } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AlertSample { using System; internal sealed class Program { private static int Main(string[] args) { if (args.Length == 0) { return RunParent(); } else if (args.Length == 1) { return RunChild(args[0]); } else { Console.WriteLine("Invalid arguments."); return 1; } } private static int RunParent() { Alert alert = new Alert("AlertSample", 5.0d, 10.0d); try { alert.Start(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e); throw; } finally { alert.Stop(); } return 0; } private static int RunChild(string name) { Console.WriteLine("TODO: " + name); return 0; } } }
Add parent and child app skeleton
Add parent and child app skeleton
C#
unlicense
brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync
fbcc612fbdef66a614cb211dccbabf40736ddde6
TfsHipChat/Program.cs
TfsHipChat/Program.cs
using System.ServiceModel; namespace TfsHipChat { class Program { static void Main() { using (var host = new ServiceHost(typeof(CheckinEventService))) { host.Open(); } } } }
using System; using System.ServiceModel; namespace TfsHipChat { class Program { static void Main() { using (var host = new ServiceHost(typeof(CheckinEventService))) { host.Open(); Console.WriteLine("TfsHipChat started!"); Console.ReadLine(); } } } }
Add blocking statement to ensure service remains alive
Add blocking statement to ensure service remains alive
C#
mit
timclipsham/tfs-hipchat
d5df48be378f9223170106938be75bf04d531b74
src/Cake.Core/Polyfill/ProcessHelper.cs
src/Cake.Core/Polyfill/ProcessHelper.cs
using System.Diagnostics; namespace Cake.Core.Polyfill { internal static class ProcessHelper { public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value) { #if NETCORE info.Environment[key] = value; #else info.EnvironmentVariables[key] = value; #endif } } }
using System; using System.Diagnostics; using System.Linq; namespace Cake.Core.Polyfill { internal static class ProcessHelper { public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value) { #if NETCORE var envKey = info.Environment.Keys.FirstOrDefault(exisitingKey => StringComparer.OrdinalIgnoreCase.Equals(exisitingKey, key)) ?? key; info.Environment[envKey] = value; #else var envKey = info.EnvironmentVariables.Keys.Cast<string>().FirstOrDefault(existingKey => StringComparer.OrdinalIgnoreCase.Equals(existingKey, key)) ?? key; info.EnvironmentVariables[key] = value; #endif } } }
Address ProcessStartInfo envvar case sensitivite issue
Address ProcessStartInfo envvar case sensitivite issue * Fixes #1326
C#
mit
mholo65/cake,ferventcoder/cake,daveaglick/cake,daveaglick/cake,Julien-Mialon/cake,devlead/cake,mholo65/cake,Sam13/cake,RehanSaeed/cake,DixonD-git/cake,phenixdotnet/cake,patriksvensson/cake,thomaslevesque/cake,phrusher/cake,phenixdotnet/cake,ferventcoder/cake,gep13/cake,robgha01/cake,vlesierse/cake,Julien-Mialon/cake,cake-build/cake,thomaslevesque/cake,phrusher/cake,vlesierse/cake,Sam13/cake,patriksvensson/cake,cake-build/cake,adamhathcock/cake,robgha01/cake,gep13/cake,adamhathcock/cake,RehanSaeed/cake,devlead/cake
2638f5dddb08f12655b24dad74a2b0a615031069
client/BlueMonkey/BlueMonkey/App.xaml.cs
client/BlueMonkey/BlueMonkey/App.xaml.cs
using BlueMonkey.ExpenceServices; using BlueMonkey.ExpenceServices.Local; using BlueMonkey.Model; using Prism.Unity; using BlueMonkey.Views; using Xamarin.Forms; using Microsoft.Practices.Unity; namespace BlueMonkey { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("NavigationPage/MainPage"); } protected override void RegisterTypes() { Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager()); Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<MainPage>(); Container.RegisterTypeForNavigation<AddExpensePage>(); Container.RegisterTypeForNavigation<ExpenseListPage>(); Container.RegisterTypeForNavigation<ChartPage>(); Container.RegisterTypeForNavigation<ReportPage>(); Container.RegisterTypeForNavigation<ReceiptPage>(); Container.RegisterTypeForNavigation<AddReportPage>(); Container.RegisterTypeForNavigation<ReportListPage>(); Container.RegisterTypeForNavigation<ExpenseSelectionPage>(); Container.RegisterTypeForNavigation<LoginPage>(); } } }
using BlueMonkey.ExpenceServices; using BlueMonkey.ExpenceServices.Local; using BlueMonkey.Model; using Prism.Unity; using BlueMonkey.Views; using Xamarin.Forms; using Microsoft.Practices.Unity; namespace BlueMonkey { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("LoginPage"); } protected override void RegisterTypes() { Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager()); Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<MainPage>(); Container.RegisterTypeForNavigation<AddExpensePage>(); Container.RegisterTypeForNavigation<ExpenseListPage>(); Container.RegisterTypeForNavigation<ChartPage>(); Container.RegisterTypeForNavigation<ReportPage>(); Container.RegisterTypeForNavigation<ReceiptPage>(); Container.RegisterTypeForNavigation<AddReportPage>(); Container.RegisterTypeForNavigation<ReportListPage>(); Container.RegisterTypeForNavigation<ExpenseSelectionPage>(); Container.RegisterTypeForNavigation<LoginPage>(); } } }
Set initial page to LoginPage
Set initial page to LoginPage
C#
mit
ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey
fb5bf5e62b76688b93cb8892ac9cc31bbb5ca3b5
src/ResourceManager/AzureBatch/Commands.Batch/Locations/GetBatchLocationQuotasCommand.cs
src/ResourceManager/AzureBatch/Commands.Batch/Locations/GetBatchLocationQuotasCommand.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Batch.Models; using System.Management.Automation; using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants; namespace Microsoft.Azure.Commands.Batch { [Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))] [Alias("Get-AzureRmBatchSubscriptionQuotas")] public class GetBatchLocationQuotasCommand : BatchCmdletBase { [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")] [ValidateNotNullOrEmpty] public string Location { get; set; } public override void ExecuteCmdlet() { PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location); WriteObject(quotas); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Batch.Models; using System.Management.Automation; using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants; namespace Microsoft.Azure.Commands.Batch { [Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))] // This alias was added in 10/2016 for backwards compatibility [Alias("Get-AzureRmBatchSubscriptionQuotas")] public class GetBatchLocationQuotasCommand : BatchCmdletBase { [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")] [ValidateNotNullOrEmpty] public string Location { get; set; } public override void ExecuteCmdlet() { PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location); WriteObject(quotas); } } }
Add comment to backwards compat alias
Add comment to backwards compat alias
C#
apache-2.0
hungmai-msft/azure-powershell,krkhan/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,zhencui/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,AzureRT/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,AzureRT/azure-powershell,yoavrubin/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,jtlibing/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,alfantp/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,zhencui/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,alfantp/azure-powershell,krkhan/azure-powershell,zhencui/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,AzureRT/azure-powershell,devigned/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,zhencui/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,jtlibing/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,AzureRT/azure-powershell,pankajsn/azure-powershell,zhencui/azure-powershell
c0533d2f7623075a1dd5c8a1ab6801af0c16ceed
TicketTimer.Jira/Services/DefaultJiraService.cs
TicketTimer.Jira/Services/DefaultJiraService.cs
using Atlassian.Jira; using TicketTimer.Core.Infrastructure; using TicketTimer.Jira.Extensions; namespace TicketTimer.Jira.Services { public class DefaultJiraService : JiraService { private readonly WorkItemStore _workItemStore; // TODO Insert correct parameters public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword"); public DefaultJiraService(WorkItemStore workItemStore) { _workItemStore = workItemStore; } public void WriteEntireArchive() { var archive = _workItemStore.GetState().WorkItemArchive; foreach (var workItem in archive) { // TODO Check if work item is jira-item. TrackTime(workItem); } } private void TrackTime(WorkItem workItem) { var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment); JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog); } } }
using Atlassian.Jira; using TicketTimer.Core.Infrastructure; using TicketTimer.Jira.Extensions; namespace TicketTimer.Jira.Services { public class DefaultJiraService : JiraService { private readonly WorkItemStore _workItemStore; // TODO Insert correct parameters public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword"); public DefaultJiraService(WorkItemStore workItemStore) { _workItemStore = workItemStore; } public async void WriteEntireArchive() { var archive = _workItemStore.GetState().WorkItemArchive; foreach (var workItem in archive) { var jiraIssue = await JiraClient.Issues.GetIssueAsync(workItem.TicketNumber); if (jiraIssue != null) { TrackTime(workItem); } } } private void TrackTime(WorkItem workItem) { var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment); JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog); } } }
Check if the workitem if a jira issue, before logging time.
[master] Check if the workitem if a jira issue, before logging time.
C#
mit
n-develop/tickettimer