Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make sure to assign concatted value to variable | using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, new string[] { ".git", ".hg" })
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static FileInfo[] GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
var files = directory.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (var nestedDirectory in directory.GetDirectories())
{
if (excludedDirectories.Contains(nestedDirectory.Name))
{
continue;
}
files.Concat(GetFiles(nestedDirectory, excludedDirectories));
}
return files;
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, new string[] { ".git", ".hg" })
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static FileInfo[] GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
var files = directory.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (var nestedDirectory in directory.GetDirectories())
{
if (excludedDirectories.Contains(nestedDirectory.Name))
{
continue;
}
files = files.Concat(GetFiles(nestedDirectory, excludedDirectories));
}
return files;
}
}
}
|
Remove startup delay from project template. | using Windows.UI.Xaml;
using System.Threading.Tasks;
using TraktApiSharp.Example.UWP.Services.SettingsServices;
using Windows.ApplicationModel.Activation;
using Template10.Controls;
using Template10.Common;
using System;
using System.Linq;
using Windows.UI.Xaml.Data;
namespace TraktApiSharp.Example.UWP
{
/// Documentation on APIs used in this page:
/// https://github.com/Windows-XAML/Template10/wiki
[Bindable]
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
SplashFactory = (e) => new Views.Splash(e);
#region App settings
var _settings = SettingsService.Instance;
RequestedTheme = _settings.AppTheme;
CacheMaxDuration = _settings.CacheMaxDuration;
ShowShellBackButton = _settings.UseShellBackButton;
#endregion
}
public override async Task OnInitializeAsync(IActivatedEventArgs args)
{
if (Window.Current.Content as ModalDialog == null)
{
// create a new frame
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
// create modal root
Window.Current.Content = new ModalDialog
{
DisableBackButtonWhenModal = true,
Content = new Views.Shell(nav),
ModalContent = new Views.Busy(),
};
}
await Task.CompletedTask;
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
// long-running startup tasks go here
await Task.Delay(5000);
NavigationService.Navigate(typeof(Views.MainPage));
await Task.CompletedTask;
}
}
}
| using System.Threading.Tasks;
using Template10.Controls;
using TraktApiSharp.Example.UWP.Services.SettingsServices;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace TraktApiSharp.Example.UWP
{
/// Documentation on APIs used in this page:
/// https://github.com/Windows-XAML/Template10/wiki
[Bindable]
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
SplashFactory = (e) => new Views.Splash(e);
var settings = SettingsService.Instance;
RequestedTheme = settings.AppTheme;
CacheMaxDuration = settings.CacheMaxDuration;
ShowShellBackButton = settings.UseShellBackButton;
}
public override async Task OnInitializeAsync(IActivatedEventArgs args)
{
if (Window.Current.Content as ModalDialog == null)
{
// create a new frame
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
// create modal root
Window.Current.Content = new ModalDialog
{
DisableBackButtonWhenModal = true,
Content = new Views.Shell(nav),
ModalContent = new Views.Busy(),
};
}
await Task.CompletedTask;
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
await Task.CompletedTask;
}
}
}
|
Add skipCertVerify back to options | using CommandLine;
using CommandLine.Text;
namespace Builder
{
public enum OptionBool
{
False,
True
}
public class Options
{
[Option("buildDir", Required = true)]
public string BuildDir { get; set; }
[Option("buildArtifactsCacheDir", Required = false)]
public string BuildArtifactsCacheDir { get; set; }
[Option("buildpackOrder", Required = false)]
public string BuildpackOrder { get; set; }
[Option("buildpacksDir", Required = false)]
public string BuildpacksDir { get; set; }
[Option("outputBuildArtifactsCache", Required = false)]
public string OutputBuildArtifactsCache { get; set; }
[Option("outputDroplet", Required = true)]
public string OutputDroplet { get; set; }
[Option("outputMetadata", Required = true)]
public string OutputMetadata { get; set; }
[Option("skipDetect", Required = false, DefaultValue = OptionBool.False)]
public OptionBool SkipDetect { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
| using CommandLine;
using CommandLine.Text;
namespace Builder
{
public enum OptionBool
{
False,
True
}
public class Options
{
[Option("buildDir", Required = true)]
public string BuildDir { get; set; }
[Option("buildArtifactsCacheDir", Required = false)]
public string BuildArtifactsCacheDir { get; set; }
[Option("buildpackOrder", Required = false)]
public string BuildpackOrder { get; set; }
[Option("buildpacksDir", Required = false)]
public string BuildpacksDir { get; set; }
[Option("outputBuildArtifactsCache", Required = false)]
public string OutputBuildArtifactsCache { get; set; }
[Option("outputDroplet", Required = true)]
public string OutputDroplet { get; set; }
[Option("outputMetadata", Required = true)]
public string OutputMetadata { get; set; }
[Option("skipDetect", Required = false, DefaultValue = OptionBool.False)]
public OptionBool SkipDetect { get; set; }
[Option("skipCertVerify", Required = false)]
public OptionBool SkipCertVerify { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
|
Update change user, don't update if same val. | using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class ProfileKeys {
public static string login_count = "login_count";
}
public class Profile : DataObject {
public virtual int login_count {
get {
return Get<int>(ProfileKeys.login_count);
}
set {
Set(ProfileKeys.login_count, value);
}
}
public virtual string username {
get {
return Get<string>(BaseDataObjectKeys.username);
}
set {
Set(BaseDataObjectKeys.username, value);
}
}
public virtual string uuid {
get {
//string val = Get<string>(BaseDataObjectKeys.uuid);
//if(string.IsNullOrEmpty(val)) {
// val = UniqueUtil.Instance.CreateUUID4();
// Set(BaseDataObjectKeys.uuid, val);
//}
return Get<string>(BaseDataObjectKeys.uuid,
UniqueUtil.Instance.CreateUUID4());
}
set {
Set(BaseDataObjectKeys.uuid, value);
}
}
public Profile() {
Reset();
}
public void ChangeUser(string name) {
Reset();
username = name;
}
public void ChangeUserNoReset(string name) {
username = name;
}
public override void Reset() {
base.Reset();
username = "Player";
uuid = "";
}
} | using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class ProfileKeys {
public static string login_count = "login_count";
}
public class Profile : DataObject {
public virtual int login_count {
get {
return Get<int>(ProfileKeys.login_count);
}
set {
Set(ProfileKeys.login_count, value);
}
}
public virtual string username {
get {
return Get<string>(BaseDataObjectKeys.username);
}
set {
Set(BaseDataObjectKeys.username, value);
}
}
public virtual string uuid {
get {
//string val = Get<string>(BaseDataObjectKeys.uuid);
//if(string.IsNullOrEmpty(val)) {
// val = UniqueUtil.Instance.CreateUUID4();
// Set(BaseDataObjectKeys.uuid, val);
//}
return Get<string>(BaseDataObjectKeys.uuid,
UniqueUtil.Instance.CreateUUID4());
}
set {
Set(BaseDataObjectKeys.uuid, value);
}
}
public Profile() {
Reset();
}
public void ChangeUser(string name) {
if(name == username) {
return;
}
Reset();
username = name;
}
public void ChangeUserNoReset(string name) {
username = name;
}
public override void Reset() {
base.Reset();
username = "Player";
uuid = "";
}
} |
Use Array.Empty instead of list. | using System;
using System.Collections.Generic;
using Avalonia.Native.Interop;
using Avalonia.Platform;
namespace Avalonia.Native
{
class ScreenImpl : IScreenImpl, IDisposable
{
private IAvnScreens _native;
public ScreenImpl(IAvnScreens native)
{
_native = native;
}
public int ScreenCount => _native.GetScreenCount();
public IReadOnlyList<Screen> AllScreens
{
get
{
if (_native != null)
{
var count = ScreenCount;
var result = new Screen[count];
for (int i = 0; i < count; i++)
{
var screen = _native.GetScreen(i);
result[i] = new Screen(
screen.PixelDensity,
screen.Bounds.ToAvaloniaPixelRect(),
screen.WorkingArea.ToAvaloniaPixelRect(),
screen.Primary);
}
return result;
}
return new List<Screen>();
}
}
public void Dispose ()
{
_native?.Dispose();
_native = null;
}
}
}
| using System;
using System.Collections.Generic;
using Avalonia.Native.Interop;
using Avalonia.Platform;
namespace Avalonia.Native
{
class ScreenImpl : IScreenImpl, IDisposable
{
private IAvnScreens _native;
public ScreenImpl(IAvnScreens native)
{
_native = native;
}
public int ScreenCount => _native.GetScreenCount();
public IReadOnlyList<Screen> AllScreens
{
get
{
if (_native != null)
{
var count = ScreenCount;
var result = new Screen[count];
for (int i = 0; i < count; i++)
{
var screen = _native.GetScreen(i);
result[i] = new Screen(
screen.PixelDensity,
screen.Bounds.ToAvaloniaPixelRect(),
screen.WorkingArea.ToAvaloniaPixelRect(),
screen.Primary);
}
return result;
}
return Array.Empty<Screen>();
}
}
public void Dispose ()
{
_native?.Dispose();
_native = null;
}
}
}
|
Update test utility class for new ILibrary interface. | using System.IO;
using CppSharp.Generators;
namespace CppSharp.Utils
{
public abstract class LibraryTest : ILibrary
{
readonly string name;
readonly LanguageGeneratorKind kind;
public LibraryTest(string name, LanguageGeneratorKind kind)
{
this.name = name;
this.kind = kind;
}
public virtual void Setup(DriverOptions options)
{
options.LibraryName = name + ".Native";
options.GeneratorKind = kind;
options.OutputDir = "../gen/" + name;
options.GenerateLibraryNamespace = false;
var path = "../../../tests/" + name;
options.IncludeDirs.Add(path);
var files = Directory.EnumerateFiles(path, "*.h");
foreach(var file in files)
options.Headers.Add(Path.GetFileName(file));
}
public virtual void Preprocess(Library lib)
{
}
public virtual void Postprocess(Library lib)
{
}
public virtual void SetupPasses(Driver driver, PassBuilder passes)
{
}
public virtual void GenerateStart(TextTemplate template)
{
}
public virtual void GenerateAfterNamespaces(TextTemplate template)
{
}
}
}
| using System.IO;
using CppSharp.Generators;
namespace CppSharp.Utils
{
public abstract class LibraryTest : ILibrary
{
readonly string name;
readonly LanguageGeneratorKind kind;
public LibraryTest(string name, LanguageGeneratorKind kind)
{
this.name = name;
this.kind = kind;
}
public virtual void Setup(Driver driver)
{
var options = driver.Options;
options.LibraryName = name + ".Native";
options.GeneratorKind = kind;
options.OutputDir = "../gen/" + name;
options.GenerateLibraryNamespace = false;
var path = "../../../tests/" + name;
options.IncludeDirs.Add(path);
var files = Directory.EnumerateFiles(path, "*.h");
foreach(var file in files)
options.Headers.Add(Path.GetFileName(file));
}
public virtual void Preprocess(Driver driver, Library lib)
{
}
public virtual void Postprocess(Library lib)
{
}
public virtual void SetupPasses(Driver driver, PassBuilder passes)
{
}
public virtual void GenerateStart(TextTemplate template)
{
}
public virtual void GenerateAfterNamespaces(TextTemplate template)
{
}
}
}
|
Set compatibility version to 2.2 in simple API test project | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
app.UseMvc();
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Mvc;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddFluentActions()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
app.UseMvc();
}
}
}
|
Remove refs to "ShowPager" that isn't relevant any more | @model PagedMemberListViewModel
@using GiveCRM.Web.Models.Members
@using PagedList.Mvc
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/ViewScripts/MemberList.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
MemberList.Initialise();
});
</script>
@if (Model != null && Model.Count > 0)
{
<table>
@{ Html.RenderPartial("_TableOfMembers", Model); }
<tr>
<td colspan="7" style="text-align: center">
<style type="text/css">
.PagedList-pager ul li
{
display: inline;
margin: 0 5px;
}
.PagedList-currentPage { font-weight: bold; }
.PagedList-currentPage a { color: Black; }
</style>
@* what's a "ShowPager"? - caused an error if (Model.ShowPager) { *@
@Html.PagedListPager(Model, Model.PagingFunction, PagedListRenderOptions.OnlyShowFivePagesAtATime)
</td>
</tr>
</table>
}
else
{
<p>Your search returned no results.</p>
}
| @model PagedMemberListViewModel
@using GiveCRM.Web.Models.Members
@using PagedList.Mvc
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/ViewScripts/MemberList.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
MemberList.Initialise();
});
</script>
@if (Model != null && Model.Count > 0)
{
<table>
@{ Html.RenderPartial("_TableOfMembers", Model); }
<tr>
<td colspan="7" style="text-align: center">
<style type="text/css">
.PagedList-pager ul li
{
display: inline;
margin: 0 5px;
}
.PagedList-currentPage { font-weight: bold; }
.PagedList-currentPage a { color: Black; }
</style>
@Html.PagedListPager(Model, Model.PagingFunction, PagedListRenderOptions.OnlyShowFivePagesAtATime)
</td>
</tr>
</table>
}
else
{
<p>Your search returned no results.</p>
}
|
Add - Aggiunta la registrazione nella composition root della ricerca della richiesta di assistenza | using Microsoft.Extensions.Configuration;
using Persistence.MongoDB;
using SimpleInjector;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using SO115App.Persistence.MongoDB;
namespace SO115App.CompositionRoot
{
internal static class PersistenceServicesConfigurator_MongoDB
{
internal static void Configure(Container container, IConfiguration configuration)
{
var connectionString = configuration.GetSection("ConnectionString").Value;
var databaseName = configuration.GetSection("DatabaseName").Value;
container.Register<DbContext>(() =>
new DbContext(connectionString, databaseName), Lifestyle.Singleton);
container.Register<ISaveRichiestaAssistenza, SaveRichiesta>();
container.Register<IUpDateRichiestaAssistenza, UpDateRichiesta>();
}
}
}
| using Microsoft.Extensions.Configuration;
using Persistence.MongoDB;
using SimpleInjector;
using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso;
using SO115App.Models.Servizi.Infrastruttura.GestioneSoccorso;
using SO115App.Persistence.MongoDB;
namespace SO115App.CompositionRoot
{
internal static class PersistenceServicesConfigurator_MongoDB
{
internal static void Configure(Container container, IConfiguration configuration)
{
var connectionString = configuration.GetSection("ConnectionString").Value;
var databaseName = configuration.GetSection("DatabaseName").Value;
container.Register<DbContext>(() =>
new DbContext(connectionString, databaseName), Lifestyle.Singleton);
#region Gestione richiesta di assistenza
container.Register<ISaveRichiestaAssistenza, SaveRichiesta>();
container.Register<IUpDateRichiestaAssistenza, UpDateRichiesta>();
container.Register<IGetRichiestaById, GetRichiesta>();
container.Register<IGetListaSintesi, GetRichiesta>();
#endregion Gestione richiesta di assistenza
}
}
}
|
Switch Conduit to use rift.lol | using System;
using System.IO;
namespace Conduit
{
class Program
{
public static string APP_NAME = "Mimic Conduit";
public static string VERSION = "2.0.0";
public static string HUB_WS = "ws://127.0.0.1:51001/conduit";
public static string HUB = "http://127.0.0.1:51001";
private static App _instance;
[STAThread]
public static void Main()
{
// Start the application.
_instance = new App();
_instance.InitializeComponent();
_instance.Run();
}
}
}
| using System;
using System.IO;
namespace Conduit
{
class Program
{
public static string APP_NAME = "Mimic Conduit";
public static string VERSION = "2.0.0";
public static string HUB_WS = "ws://rift.mimic.lol/conduit";
public static string HUB = "https://rift.mimic.lol";
private static App _instance;
[STAThread]
public static void Main()
{
// Start the application.
_instance = new App();
_instance.InitializeComponent();
_instance.Run();
}
}
}
|
Enable shutdown and set reset period. | using Topshelf;
using Topshelf.HostConfigurators;
namespace Cogito.Components.Server
{
public static class Program
{
/// <summary>
/// Main application entry point.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static int Main(string[] args)
{
return (int)BuildHost(args).Run();
}
/// <summary>
/// Builds a new <see cref="Host"/>.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static Host BuildHost(string[] args)
{
return HostFactory.New(x => ConfigureHostFactory(args, x));
}
/// <summary>
/// Applies the configuration to the given <see cref="HostConfigurator"/>.
/// </summary>
/// <param name="args"></param>
/// <param name="x"></param>
public static void ConfigureHostFactory(string[] args, HostConfigurator x)
{
x.Service<ServiceHost>(() => new ServiceHost());
x.SetServiceName("Cogito.Components.Server");
x.StartAutomatically();
x.EnableServiceRecovery(c => c.RestartService(5));
x.RunAsNetworkService();
}
}
}
| using Topshelf;
using Topshelf.HostConfigurators;
namespace Cogito.Components.Server
{
public static class Program
{
/// <summary>
/// Main application entry point.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static int Main(string[] args)
{
return (int)BuildHost(args).Run();
}
/// <summary>
/// Builds a new <see cref="Host"/>.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static Host BuildHost(string[] args)
{
return HostFactory.New(x => ConfigureHostFactory(args, x));
}
/// <summary>
/// Applies the configuration to the given <see cref="HostConfigurator"/>.
/// </summary>
/// <param name="args"></param>
/// <param name="x"></param>
public static void ConfigureHostFactory(string[] args, HostConfigurator x)
{
x.Service<ServiceHost>(() => new ServiceHost());
x.SetServiceName("Cogito.Components.Server");
x.StartAutomatically();
x.EnableServiceRecovery(c => c.RestartService(5).SetResetPeriod(0));
x.EnableShutdown();
x.RunAsNetworkService();
}
}
}
|
Create the log file if it doesn't already exist | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UKParliData.BPTweets
{
public class TweetLog : ITweetLog
{
private string filename;
public TweetLog(string filename)
{
this.filename = filename;
}
public ISet<string> GetTweetedIDs()
{
return new HashSet<string>(File.ReadAllLines(filename));
}
public void LogTweetedID(string id)
{
File.AppendAllLines(filename, new string[] { id });
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UKParliData.BPTweets
{
public class TweetLog : ITweetLog
{
private string filename;
public TweetLog(string filename)
{
this.filename = filename;
if (!File.Exists(this.filename))
{
using (var f = File.Create(this.filename)) { }
}
}
public ISet<string> GetTweetedIDs()
{
return new HashSet<string>(File.ReadAllLines(filename));
}
public void LogTweetedID(string id)
{
File.AppendAllLines(filename, new string[] { id });
}
}
}
|
Use using() for Ninject kernel. | using System;
using System.Linq;
using CommandLine;
using Ninject;
using P2E.ExtensionMethods;
using P2E.Interfaces.AppLogic;
using P2E.Interfaces.CommandLine;
namespace P2EApp
{
internal static class Program
{
static void Main(string[] args)
{
try
{
var kernel = new StandardKernel();
Bootstrapper.ConfigureContainer(kernel);
var options = kernel.Get<IConsoleOptions>();
if (Parser.Default.ParseArguments(args, options) == false)
{
Console.WriteLine(options.GetUsage());
return;
}
kernel.Get<IMainLogic>().RunAsync().Wait();
}
catch (AggregateException ae)
{
var messages = ae.Flatten().InnerExceptions
.ToList()
.Select(e => e.GetInnermostException())
.Select(e => (object)e.Message)
.ToArray();
Console.WriteLine("Oops, you did something I didn't think of:\n{0}", messages);
}
catch (Exception ex)
{
Console.WriteLine("Oops, you did something I didn't think of:\n{0}", ex.Message);
}
finally
{
// todo - remove the whole finally block
Console.ReadLine();
}
}
}
}
| using System;
using System.Linq;
using CommandLine;
using Ninject;
using P2E.ExtensionMethods;
using P2E.Interfaces.AppLogic;
using P2E.Interfaces.CommandLine;
namespace P2EApp
{
internal static class Program
{
static void Main(string[] args)
{
try
{
// FYI: Disposable objects bound in InSingletonScope are disposed when the kernel is disposed.
using (var kernel = new StandardKernel())
{
Bootstrapper.ConfigureContainer(kernel);
var options = kernel.Get<IConsoleOptions>();
if (Parser.Default.ParseArguments(args, options) == false)
{
Console.WriteLine(options.GetUsage());
return;
}
kernel.Get<IMainLogic>().RunAsync().Wait();
}
}
catch (AggregateException ae)
{
var messages = ae.Flatten().InnerExceptions
.ToList()
.Select(e => e.GetInnermostException())
.Select(e => (object)e.Message)
.ToArray();
Console.WriteLine("Oops, you did something I didn't think of:\n{0}", messages);
}
catch (Exception ex)
{
Console.WriteLine("Oops, you did something I didn't think of:\n{0}", ex.Message);
}
finally
{
// todo - remove the whole finally block
Console.ReadLine();
}
}
}
}
|
Fix threading issue on initialisation | using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace AlloyDemoKit.Business.Channels
{
/// <summary>
/// Base class for all resolution definitions
/// </summary>
public abstract class DisplayResolutionBase : IDisplayResolution
{
private Injected<LocalizationService> LocalizationService { get; set; }
protected DisplayResolutionBase(string name, int width, int height)
{
Id = GetType().FullName;
Name = Translate(name);
Width = width;
Height = height;
}
/// <summary>
/// Gets the unique ID for this resolution
/// </summary>
public string Id { get; protected set; }
/// <summary>
/// Gets the name of resolution
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets the resolution width in pixels
/// </summary>
public int Width { get; protected set; }
/// <summary>
/// Gets the resolution height in pixels
/// </summary>
public int Height { get; protected set; }
private string Translate(string resurceKey)
{
string value;
if(!LocalizationService.Service.TryGetString(resurceKey, out value))
{
value = resurceKey;
}
return value;
}
}
}
| using System;
using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using EPiServer.Web;
namespace AlloyDemoKit.Business.Channels
{
/// <summary>
/// Base class for all resolution definitions
/// </summary>
public abstract class DisplayResolutionBase : IDisplayResolution
{
private Injected<LocalizationService> LocalizationService { get; set; }
private static object syncLock = new Object();
protected DisplayResolutionBase(string name, int width, int height)
{
Id = GetType().FullName;
Name = Translate(name);
Width = width;
Height = height;
}
/// <summary>
/// Gets the unique ID for this resolution
/// </summary>
public string Id { get; protected set; }
/// <summary>
/// Gets the name of resolution
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets the resolution width in pixels
/// </summary>
public int Width { get; protected set; }
/// <summary>
/// Gets the resolution height in pixels
/// </summary>
public int Height { get; protected set; }
private string Translate(string resurceKey)
{
string value;
lock (syncLock)
{
if (!LocalizationService.Service.TryGetString(resurceKey, out value))
{
value = resurceKey;
}
}
return value;
}
}
}
|
Add missing RotateZ helper function. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ModGL.Numerics
{
public static class MatrixExtensions
{
public static Matrix4f Translate(this Matrix4f mat, Vector3f offset)
{
return MatrixHelper.Translate(offset).Multiply(mat);
}
public static Matrix4f Translate(this Matrix4f mat, float x, float y, float z)
{
return MatrixHelper.Translate(x, y, z).Multiply(mat);
}
public static Matrix4f Scale(this Matrix4f mat, Vector3f scale)
{
return MatrixHelper.Scale(scale).Multiply(mat);
}
public static Matrix4f Scale(this Matrix4f mat, float x, float y, float z)
{
return MatrixHelper.Scale(x, y, z).Multiply(mat);
}
public static Matrix4f RotateX(this Matrix4f mat, float angleInRadians)
{
return MatrixHelper.RotateX(angleInRadians).Multiply(mat);
}
public static Matrix4f RotateY(this Matrix4f mat, float angleInRadians)
{
return MatrixHelper.RotateY(angleInRadians).Multiply(mat);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ModGL.Numerics
{
public static class MatrixExtensions
{
public static Matrix4f Translate(this Matrix4f mat, Vector3f offset)
{
return MatrixHelper.Translate(offset).Multiply(mat);
}
public static Matrix4f Translate(this Matrix4f mat, float x, float y, float z)
{
return MatrixHelper.Translate(x, y, z).Multiply(mat);
}
public static Matrix4f Scale(this Matrix4f mat, Vector3f scale)
{
return MatrixHelper.Scale(scale).Multiply(mat);
}
public static Matrix4f Scale(this Matrix4f mat, float x, float y, float z)
{
return MatrixHelper.Scale(x, y, z).Multiply(mat);
}
public static Matrix4f RotateX(this Matrix4f mat, float angleInRadians)
{
return MatrixHelper.RotateX(angleInRadians).Multiply(mat);
}
public static Matrix4f RotateY(this Matrix4f mat, float angleInRadians)
{
return MatrixHelper.RotateY(angleInRadians).Multiply(mat);
}
public static Matrix4f RotateZ(this Matrix4f mat, float angleInRadians)
{
return MatrixHelper.RotateZ(angleInRadians).Multiply(mat);
}
}
}
|
Add help text when incorrect args passed in | namespace Sitecore.Courier.Runner
{
using Sitecore.Update;
using Sitecore.Update.Engine;
using System;
/// <summary>
/// Defines the program class.
/// </summary>
internal class Program
{
/// <summary>
/// Mains the specified args.
/// </summary>
/// <param name="args">The arguments.</param>
public static void Main(string[] args)
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
Console.WriteLine("Source: {0}", options.Source);
Console.WriteLine("Target: {0}", options.Target);
Console.WriteLine("Output: {0}", options.Output);
var diff = new DiffInfo(
DiffGenerator.GetDiffCommands(options.Source, options.Target),
"Sitecore Courier Package",
string.Empty,
string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target));
PackageGenerator.GeneratePackage(diff, string.Empty, options.Output);
}
}
}
}
| namespace Sitecore.Courier.Runner
{
using Sitecore.Update;
using Sitecore.Update.Engine;
using System;
/// <summary>
/// Defines the program class.
/// </summary>
internal class Program
{
/// <summary>
/// Mains the specified args.
/// </summary>
/// <param name="args">The arguments.</param>
public static void Main(string[] args)
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
Console.WriteLine("Source: {0}", options.Source);
Console.WriteLine("Target: {0}", options.Target);
Console.WriteLine("Output: {0}", options.Output);
var diff = new DiffInfo(
DiffGenerator.GetDiffCommands(options.Source, options.Target),
"Sitecore Courier Package",
string.Empty,
string.Format("Diff between serialization folders '{0}' and '{1}'.", options.Source, options.Target));
PackageGenerator.GeneratePackage(diff, string.Empty, options.Output);
}
else
{
Console.WriteLine(options.GetUsage());
}
}
}
}
|
Apply a ReadTimeout/WriteTimeout to serialport stream | using System;
using System.IO.Ports;
using MYCroes.ATCommands;
using MYCroes.ATCommands.Forwarding;
namespace SupportManager.Control
{
public class ATHelper : IDisposable
{
private readonly SerialPort serialPort;
public ATHelper(string port)
{
serialPort = new SerialPort(port);
serialPort.Open();
}
public void ForwardTo(string phoneNumberWithInternationalAccessCode)
{
var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration,
phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode,
ForwardingClass.Voice);
Execute(cmd);
}
public string GetForwardedPhoneNumber()
{
var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional);
var res = Execute(cmd);
return ForwardingStatus.Parse(res[0]).Number;
}
private string[] Execute(ATCommand command)
{
var stream = serialPort.BaseStream;
return command.Execute(stream);
}
public void Dispose()
{
if (serialPort.IsOpen) serialPort.Close();
serialPort.Dispose();
}
}
} | using System;
using System.IO.Ports;
using MYCroes.ATCommands;
using MYCroes.ATCommands.Forwarding;
namespace SupportManager.Control
{
public class ATHelper : IDisposable
{
private readonly SerialPort serialPort;
public ATHelper(string port)
{
serialPort = new SerialPort(port);
serialPort.Open();
}
public void ForwardTo(string phoneNumberWithInternationalAccessCode)
{
var cmd = ForwardingStatus.Set(ForwardingReason.Unconditional, ForwardingMode.Registration,
phoneNumberWithInternationalAccessCode, ForwardingPhoneNumberType.WithInternationalAccessCode,
ForwardingClass.Voice);
Execute(cmd);
}
public string GetForwardedPhoneNumber()
{
var cmd = ForwardingStatus.Query(ForwardingReason.Unconditional);
var res = Execute(cmd);
return ForwardingStatus.Parse(res[0]).Number;
}
private string[] Execute(ATCommand command)
{
var stream = serialPort.BaseStream;
stream.ReadTimeout = 10000;
stream.WriteTimeout = 10000;
return command.Execute(stream);
}
public void Dispose()
{
if (serialPort.IsOpen) serialPort.Close();
serialPort.Dispose();
}
}
} |
Test that a non thrown exception produces a report | using Bugsnag.Payload;
using Xunit;
namespace Bugsnag.Tests
{
public class ReportTests
{
[Fact]
public void BasicTest()
{
System.Exception exception = null;
var configuration = new Configuration("123456");
try
{
throw new System.Exception("test");
}
catch (System.Exception caughtException)
{
exception = caughtException;
}
var report = new Report(configuration, exception, Bugsnag.Payload.Severity.ForHandledException(), new Breadcrumb[] { new Breadcrumb("test", BreadcrumbType.Manual) }, new Session(), new Request());
Assert.NotNull(report);
}
}
}
| using Bugsnag.Payload;
using Xunit;
namespace Bugsnag.Tests
{
public class ReportTests
{
[Fact]
public void BasicTest()
{
System.Exception exception = null;
var configuration = new Configuration("123456");
try
{
throw new System.Exception("test");
}
catch (System.Exception caughtException)
{
exception = caughtException;
}
var report = new Report(configuration, exception, Bugsnag.Payload.Severity.ForHandledException(), new Breadcrumb[] { new Breadcrumb("test", BreadcrumbType.Manual) }, new Session(), new Request());
Assert.NotNull(report);
}
[Fact]
public void NonThrownException()
{
System.Exception exception = new System.Exception("test");
var configuration = new Configuration("123456");
var report = new Report(configuration, exception, Bugsnag.Payload.Severity.ForHandledException(), new Breadcrumb[] { new Breadcrumb("test", BreadcrumbType.Manual) }, new Session(), new Request());
Assert.NotNull(report);
}
}
}
|
Fix CppCodegen build break and hook up CppCodegen to TFS build | // 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 ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
public sealed class CppCodegenNodeFactory : NodeFactory
{
public CppCodegenNodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, MetadataManager metadataManager, NameMangler nameMangler, new LazyGenericsDisabledPolicy())
: base(context, compilationModuleGroup, metadataManager, nameMangler)
{
}
public override bool IsCppCodegenTemporaryWorkaround => true;
protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method)
{
if (CompilationModuleGroup.ContainsMethod(method))
{
return new CppMethodCodeNode(method);
}
else
{
return new ExternMethodSymbolNode(this, method);
}
}
protected override IMethodNode CreateUnboxingStubNode(MethodDesc method)
{
// TODO: this is wrong: this returns an assembly stub node
return new UnboxingStubNode(method);
}
protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall)
{
// TODO: this is wrong: this returns an assembly stub node
return new ReadyToRunHelperNode(this, helperCall.HelperId, helperCall.Target);
}
}
}
| // 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 ILCompiler.DependencyAnalysisFramework;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
public sealed class CppCodegenNodeFactory : NodeFactory
{
public CppCodegenNodeFactory(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, MetadataManager metadataManager, NameMangler nameMangler)
: base(context, compilationModuleGroup, metadataManager, nameMangler, new LazyGenericsDisabledPolicy())
{
}
public override bool IsCppCodegenTemporaryWorkaround => true;
protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method)
{
if (CompilationModuleGroup.ContainsMethod(method))
{
return new CppMethodCodeNode(method);
}
else
{
return new ExternMethodSymbolNode(this, method);
}
}
protected override IMethodNode CreateUnboxingStubNode(MethodDesc method)
{
// TODO: this is wrong: this returns an assembly stub node
return new UnboxingStubNode(method);
}
protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall)
{
// TODO: this is wrong: this returns an assembly stub node
return new ReadyToRunHelperNode(this, helperCall.HelperId, helperCall.Target);
}
}
}
|
Fix huge oops in test scene (we actually want ConfigureAwait(true) here) | // 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.Threading;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneSynchronizationContext : FrameworkTestScene
{
private AsyncPerformingBox box;
[Test]
public void TestAsyncPerformingBox()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox());
AddAssert("not spun", () => box.Rotation == 0);
AddStep("trigger", () => box.Trigger());
AddUntilStep("has spun", () => box.Rotation == 180);
}
public class AsyncPerformingBox : Box
{
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public AsyncPerformingBox()
{
Size = new Vector2(100);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override async void LoadComplete()
{
base.LoadComplete();
await waiter.WaitAsync().ConfigureAwait(false);
this.RotateTo(180, 500);
}
public void Trigger()
{
waiter.Release();
}
}
}
}
| // 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.Threading;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osuTK;
namespace osu.Framework.Tests.Visual.Drawables
{
public class TestSceneSynchronizationContext : FrameworkTestScene
{
private AsyncPerformingBox box;
[Test]
public void TestAsyncPerformingBox()
{
AddStep("add box", () => Child = box = new AsyncPerformingBox());
AddAssert("not spun", () => box.Rotation == 0);
AddStep("trigger", () => box.Trigger());
AddUntilStep("has spun", () => box.Rotation == 180);
}
public class AsyncPerformingBox : Box
{
private readonly SemaphoreSlim waiter = new SemaphoreSlim(0);
public AsyncPerformingBox()
{
Size = new Vector2(100);
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
protected override async void LoadComplete()
{
base.LoadComplete();
await waiter.WaitAsync().ConfigureAwait(true);
this.RotateTo(180, 500);
}
public void Trigger()
{
waiter.Release();
}
}
}
}
|
Add extension method with environment string | //
// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Steeltoe.Extensions.Configuration.ConfigServer;
namespace Steeltoe.Extensions.Configuration
{
public static class ConfigServerConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder configurationBuilder, ConfigServerClientSettings settings, ILoggerFactory logFactory = null)
{
if (configurationBuilder == null)
{
throw new ArgumentNullException(nameof(configurationBuilder));
}
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
configurationBuilder.Add(new ConfigServerConfigurationProvider(settings, logFactory));
return configurationBuilder;
}
}
}
| //
// Copyright 2017 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Steeltoe.Extensions.Configuration.ConfigServer;
namespace Steeltoe.Extensions.Configuration
{
public static class ConfigServerConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder configurationBuilder, string environment, ILoggerFactory logFactory = null) =>
configurationBuilder.AddConfigServer(new ConfigServerClientSettings() { Environment = environment }, logFactory);
public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder configurationBuilder, ConfigServerClientSettings defaultSettings, ILoggerFactory logFactory = null)
{
if (configurationBuilder == null)
{
throw new ArgumentNullException(nameof(configurationBuilder));
}
if (defaultSettings == null)
{
throw new ArgumentNullException(nameof(defaultSettings));
}
configurationBuilder.Add(new ConfigServerConfigurationProvider(defaultSettings, logFactory));
return configurationBuilder;
}
}
}
|
Add support for ctm model format | // // //-------------------------------------------------------------------------------------------------
// // // <copyright file="ModelFormats.cs" company="Microsoft Corporation">
// // // Copyright (c) Microsoft Corporation. All rights reserved.
// // // </copyright>
// // //-------------------------------------------------------------------------------------------------
namespace CubeServer.DataAccess
{
public enum ModelFormats
{
Unknown = 0,
Obj = 1,
Ebo = 2
}
} | // // //-------------------------------------------------------------------------------------------------
// // // <copyright file="ModelFormats.cs" company="Microsoft Corporation">
// // // Copyright (c) Microsoft Corporation. All rights reserved.
// // // </copyright>
// // //-------------------------------------------------------------------------------------------------
namespace CubeServer.DataAccess
{
public enum ModelFormats
{
Unknown = 0,
Obj = 1,
Ebo = 2,
Ctm = 3
}
} |
Use informational attribute for version | using System;
using System.Deployment.Application;
using System.Globalization;
using System.Windows;
using System.Windows.Documents;
using StringResources = PackageExplorer.Resources.Resources;
namespace PackageExplorer
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
public partial class AboutWindow : StandardDialog
{
public AboutWindow()
{
InitializeComponent();
ProductTitle.Text = String.Format(
CultureInfo.CurrentCulture,
"{0} ({1})",
StringResources.Dialog_Title,
GetApplicationVersion());
}
private static Version GetApplicationVersion()
{
if (ApplicationDeployment.IsNetworkDeployed)
{
return ApplicationDeployment.CurrentDeployment.CurrentVersion;
}
else
{
return typeof(MainWindow).Assembly.GetName().Version;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
var link = (Hyperlink) sender;
UriHelper.OpenExternalLink(link.NavigateUri);
}
}
} | using System;
using System.Deployment.Application;
using System.Globalization;
using System.Reflection;
using System.Windows;
using System.Windows.Documents;
using StringResources = PackageExplorer.Resources.Resources;
namespace PackageExplorer
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
public partial class AboutWindow : StandardDialog
{
public AboutWindow()
{
InitializeComponent();
ProductTitle.Text = $"{StringResources.Dialog_Title} ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion})";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
var link = (Hyperlink) sender;
UriHelper.OpenExternalLink(link.NavigateUri);
}
}
} |
Test 1st commit from explorer to GitHub. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NativeWiFiApi_TestWinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
NativeWiFiApi.wifi wifiApi = new NativeWiFiApi.wifi();
wifiApi.EnumerateNICs();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NativeWiFiApi_TestWinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//
NativeWiFiApi.wifi wifiApi = new NativeWiFiApi.wifi();
wifiApi.EnumerateNICs();
}
}
}
|
Enforce an exception when the ETL has failed | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SqlServer.Dts.Runtime;
namespace NBi.Core.Etl.IntegrationService
{
abstract class EtlRunner: IEtlRunner
{
public IEtl Etl { get; private set; }
public EtlRunner(IEtl etl)
{
Etl = etl;
}
public abstract IExecutionResult Run();
public void Execute()
{
Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SqlServer.Dts.Runtime;
namespace NBi.Core.Etl.IntegrationService
{
abstract class EtlRunner: IEtlRunner
{
public IEtl Etl { get; private set; }
public EtlRunner(IEtl etl)
{
Etl = etl;
}
public abstract IExecutionResult Run();
public void Execute()
{
var result = Run();
if (result.IsFailure)
throw new Exception(result.Message);
}
}
}
|
Allow passing fields to next/previous page filters | using ShopifySharp.Filters;
using ShopifySharp.Infrastructure;
using System.Collections.Generic;
using System.Linq;
namespace ShopifySharp.Lists
{
public class ListResult<T>
{
public IEnumerable<T> Items { get; }
public LinkHeaderParseResult<T> LinkHeader { get; }
public bool HasNextPage => LinkHeader?.NextLink != null;
public bool HasPreviousPage => LinkHeader?.PreviousLink != null;
public ListFilter<T> GetNextPageFilter(int? limit = null)
{
return LinkHeader?.NextLink?.GetFollowingPageFilter(limit);
}
public ListFilter<T> GetPreviousPageFilter(int? limit = null)
{
return LinkHeader?.PreviousLink?.GetFollowingPageFilter(limit);
}
public ListResult(IEnumerable<T> items, LinkHeaderParseResult<T> linkHeader)
{
Items = items;
LinkHeader = linkHeader;
}
}
} | using ShopifySharp.Filters;
using ShopifySharp.Infrastructure;
using System.Collections.Generic;
using System.Linq;
namespace ShopifySharp.Lists
{
public class ListResult<T>
{
public IEnumerable<T> Items { get; }
public LinkHeaderParseResult<T> LinkHeader { get; }
public bool HasNextPage => LinkHeader?.NextLink != null;
public bool HasPreviousPage => LinkHeader?.PreviousLink != null;
public ListFilter<T> GetNextPageFilter(int? limit = null, string fields = null)
{
return LinkHeader?.NextLink?.GetFollowingPageFilter(limit, fields);
}
public ListFilter<T> GetPreviousPageFilter(int? limit = null, string fields = null)
{
return LinkHeader?.PreviousLink?.GetFollowingPageFilter(limit, fields);
}
public ListResult(IEnumerable<T> items, LinkHeaderParseResult<T> linkHeader)
{
Items = items;
LinkHeader = linkHeader;
}
}
} |
Fix Dialoguer using a deprecated Unity feature | using UnityEngine;
using UnityEditor;
using System.Collections;
using DialoguerEditor;
public class DialogueEditorAssetModificationProcessor : UnityEditor.AssetModificationProcessor {
public static string[] OnWillSaveAssets(string[] paths){
//DialogueEditorWindow window = (DialogueEditorWindow)EditorWindow.GetWindow(typeof(DialogueEditorWindow));
if(EditorWindow.focusedWindow != null){
if(EditorWindow.focusedWindow.title == "Dialogue Editor" || EditorWindow.focusedWindow.title == "Variable Editor" || EditorWindow.focusedWindow.title == "Theme Editor"){
DialogueEditorDataManager.save();
DialoguerEnumGenerator.GenerateDialoguesEnum();
}
}
return paths;
}
}
| using UnityEngine;
using UnityEditor;
using System.Collections;
using DialoguerEditor;
public class DialogueEditorAssetModificationProcessor : UnityEditor.AssetModificationProcessor {
public static string[] OnWillSaveAssets(string[] paths){
//DialogueEditorWindow window = (DialogueEditorWindow)EditorWindow.GetWindow(typeof(DialogueEditorWindow));
if(EditorWindow.focusedWindow != null){
if (EditorWindow.focusedWindow.titleContent.text == "Dialogue Editor" || EditorWindow.focusedWindow.titleContent.text == "Variable Editor" || EditorWindow.focusedWindow.titleContent.text == "Theme Editor")
{
DialogueEditorDataManager.save();
DialoguerEnumGenerator.GenerateDialoguesEnum();
}
}
return paths;
}
}
|
Add simulate call to robot | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Halodi.Physics.Interfaces
{
public abstract class IPhysicsEngine : MonoBehaviour
{
public abstract IRevoluteJointPhysics AddRevoluteJoint(ArticulationRevoluteJoint joint);
public abstract IPrismaticJointPhysics AddPrismaticJoint(ArticulationPrismaticJoint joint);
public abstract IFixedJointPhysics AddFixedJoint(ArticulationFixedJoint joint);
public abstract IFloatingJointPhysics AddFloatingJoint(ArticulationFloatingJoint joint);
public abstract void Simulate(float step);
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Halodi.Physics.Interfaces
{
public abstract class IPhysicsEngine : MonoBehaviour
{
public abstract IRevoluteJointPhysics AddRevoluteJoint(ArticulationRevoluteJoint joint);
public abstract IPrismaticJointPhysics AddPrismaticJoint(ArticulationPrismaticJoint joint);
public abstract IFixedJointPhysics AddFixedJoint(ArticulationFixedJoint joint);
public abstract IFloatingJointPhysics AddFloatingJoint(ArticulationFloatingJoint joint);
}
} |
Use the new extension method | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Bugsnag.Sample.AspNet35
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AspNet.Client.Current.Breadcrumbs.Leave("Page_Load");
}
protected void Unhandled(object sender, EventArgs e)
{
throw new NotImplementedException();
}
protected void Handled(object sender, EventArgs e)
{
try
{
throw new Exception("This could be bad");
}
catch (Exception exception)
{
AspNet.Client.Current.Notify(exception);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Bugsnag.AspNet;
namespace Bugsnag.Sample.AspNet35
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AspNet.Client.Current.Breadcrumbs.Leave("Page_Load");
}
protected void Unhandled(object sender, EventArgs e)
{
throw new NotImplementedException();
}
protected void Handled(object sender, EventArgs e)
{
try
{
throw new Exception("This could be bad");
}
catch (Exception exception)
{
AspNet.Client.Current.NotifyWithHttpContext(exception);
}
}
}
}
|
Add missing property, needed in web | using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.Gen;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
[DataMember]
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
using PS.Mothership.Core.Common.Template.App;
using PS.Mothership.Core.Common.Template.Gen;
namespace PS.Mothership.Core.Common.Dto.Application
{
[DataContract]
public class ApplicationDetailsMetadataDto
{
[DataMember]
public IList<GenBusinessLegalType> BusinessLegalTypes { get; set; }
[DataMember]
public IList<AppAdvertisingFlags> AdvertisingTypes { get; set; }
}
}
|
Update linux HD serial number to pull a real value | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using AutomaticTypeMapper;
namespace EOLib
{
#if LINUX
[AutoMappedType]
public class HDSerialNumberServiceLinux : IHDSerialNumberService
{
public string GetHDSerialNumber()
{
return "12345"; // Just like my luggage
}
}
#endif
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using AutomaticTypeMapper;
namespace EOLib
{
#if LINUX
[AutoMappedType]
public class HDSerialNumberServiceLinux : IHDSerialNumberService
{
public string GetHDSerialNumber()
{
// use lsblk --nodeps -o serial to get serial number
try
{
var serialNumber = "";
var p = new ProcessStartInfo
{
Arguments = "--nodeps -o serial",
CreateNoWindow = true,
FileName = "lsblk",
RedirectStandardOutput = true,
UseShellExecute = false
};
using (var process = Process.Start(p))
{
process.WaitForExit();
if (process.ExitCode == 0)
{
var output = process.StandardOutput.ReadToEnd();
serialNumber = output.Split('\n').Skip(1).Where(x => !string.IsNullOrEmpty(x)).First();
}
}
// remove non-numeric characters so eoserv can handle it
serialNumber = Regex.Replace(serialNumber, @"\D", string.Empty);
// make the serial number shorted so eoserv can handle it
while (ulong.TryParse(serialNumber, out var sn) && sn > uint.MaxValue)
serialNumber = serialNumber.Substring(0, serialNumber.Length - 1);
return serialNumber;
}
catch
{
// if this fails for ANY reason, just give a dummy value.
// this isn't important enough to be worth crashing or notifying the user.
return "12345"; // Just like my luggage
}
}
}
#endif
}
|
Set geoip webservice to port 4000 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using GeoIP.Models;
using GeoIP.Executers;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace GeoIP.Controllers
{
[Route("api/[controller]")]
public class IP2LocationController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public IP2LocationController(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
// GET api/ip2location?ipaddress=123.123.123.123
[HttpGet]
public string GetGeoLocation([FromQuery]string ipAddress)
{
var dataSource = "http://localhost:3000/ip2location";
var geolocation = new IP2LocationQuery().Query(ipAddress, dataSource);
return geolocation.Result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using GeoIP.Models;
using GeoIP.Executers;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace GeoIP.Controllers
{
[Route("api/[controller]")]
public class IP2LocationController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public IP2LocationController(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
// GET api/ip2location?ipaddress=123.123.123.123
[HttpGet]
public string GetGeoLocation([FromQuery]string ipAddress)
{
var dataSource = "http://localhost:4000/ip2location";
var geolocation = new IP2LocationQuery().Query(ipAddress, dataSource);
return geolocation.Result;
}
}
}
|
Add vector scaling method to vector3 | namespace DynamixelServo.Quadruped
{
public struct Vector3
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
public override string ToString()
{
return $"[{X:f3}; {Y:f3}; {Z:f3}]";
}
}
}
| namespace DynamixelServo.Quadruped
{
public struct Vector3
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator *(Vector3 vector, float multiplier)
{
return new Vector3(vector.X * multiplier, vector.Y * multiplier, vector.Z * multiplier);
}
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
}
public static Vector3 operator -(Vector3 a, Vector3 b)
{
return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
}
public override string ToString()
{
return $"[{X:f3}; {Y:f3}; {Z:f3}]";
}
}
}
|
Define unused instance of Table | using System;
using Table;
public class Hangman {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
| using System;
using Table;
public class Hangman {
public static void Main(string[] args) {
Table.Table t = new Table.Table();
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
|
Add EagerStaticConstructorOrder.ReflectionExecution, fix the typo EagerStaticConstructorOrder.TypeLoaderEnvirnoment -> TypeLoaderEnvironment | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Runtime.CompilerServices
{
// When applied to a type this custom attribute will cause it's cctor to be executed during startup
// rather being deferred.'order' define the order of execution relative to other cctor's marked with the same attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)]
sealed public class EagerOrderedStaticConstructorAttribute : Attribute
{
private EagerStaticConstructorOrder _order;
public EagerOrderedStaticConstructorAttribute(EagerStaticConstructorOrder order)
{
_order = order;
}
public EagerStaticConstructorOrder Order { get { return _order; } }
}
// Defines all the types which require eager cctor execution ,defined order is the order of execution.The enum is
// grouped by Modules and then by types.
public enum EagerStaticConstructorOrder : int
{
// System.Private.TypeLoader
RuntimeTypeHandleEqualityComparer,
TypeLoaderEnvirnoment,
SystemRuntimeTypeLoaderExports,
// System.Private.CoreLib
SystemString,
SystemPreallocatedOutOfMemoryException,
SystemEnvironment, // ClassConstructorRunner.Cctor.GetCctor use Lock which inturn use current threadID , so System.Environment
// should come before CompilerServicesClassConstructorRunnerCctor
CompilerServicesClassConstructorRunnerCctor,
CompilerServicesClassConstructorRunner,
// Interop
InteropHeap,
VtableIUnknown,
McgModuleManager
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Runtime.CompilerServices
{
// When applied to a type this custom attribute will cause it's cctor to be executed during startup
// rather being deferred.'order' define the order of execution relative to other cctor's marked with the same attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)]
sealed public class EagerOrderedStaticConstructorAttribute : Attribute
{
private EagerStaticConstructorOrder _order;
public EagerOrderedStaticConstructorAttribute(EagerStaticConstructorOrder order)
{
_order = order;
}
public EagerStaticConstructorOrder Order { get { return _order; } }
}
// Defines all the types which require eager cctor execution ,defined order is the order of execution.The enum is
// grouped by Modules and then by types.
public enum EagerStaticConstructorOrder : int
{
// System.Private.TypeLoader
RuntimeTypeHandleEqualityComparer,
TypeLoaderEnvironment,
SystemRuntimeTypeLoaderExports,
// System.Private.CoreLib
SystemString,
SystemPreallocatedOutOfMemoryException,
SystemEnvironment, // ClassConstructorRunner.Cctor.GetCctor use Lock which inturn use current threadID , so System.Environment
// should come before CompilerServicesClassConstructorRunnerCctor
CompilerServicesClassConstructorRunnerCctor,
CompilerServicesClassConstructorRunner,
// System.Private.Reflection.Execution
ReflectionExecution,
// Interop
InteropHeap,
VtableIUnknown,
McgModuleManager
}
}
|
Add support for obsolete collection initializers. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.AddObsoleteAttribute;
using Microsoft.CodeAnalysis.CodeFixes;
namespace Microsoft.CodeAnalysis.CSharp.AddObsoleteAttribute
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpAddObsoleteAttributeCodeFixProvider)), Shared]
internal class CSharpAddObsoleteAttributeCodeFixProvider
: AbstractAddObsoleteAttributeCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(
"CS0612", // 'C' is obsolete
"CS0618", // 'C' is obsolete (msg)
"CS0672" // Member 'D.F()' overrides obsolete member 'C.F()'
);
public CSharpAddObsoleteAttributeCodeFixProvider()
: base(CSharpSyntaxFactsService.Instance, CSharpFeaturesResources.Add_Obsolete)
{
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.AddObsoleteAttribute;
using Microsoft.CodeAnalysis.CodeFixes;
namespace Microsoft.CodeAnalysis.CSharp.AddObsoleteAttribute
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpAddObsoleteAttributeCodeFixProvider)), Shared]
internal class CSharpAddObsoleteAttributeCodeFixProvider
: AbstractAddObsoleteAttributeCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(
"CS0612", // 'C' is obsolete
"CS0618", // 'C' is obsolete (msg)
"CS0672", // Member 'D.F()' overrides obsolete member 'C.F()'
"CS1062", // The best overloaded Add method 'MyCollection.Add(int)' for the collection initializer element is obsolete. (msg)
"CS1064" // The best overloaded Add method 'MyCollection.Add(int)' for the collection initializer element is obsolete"
);
public CSharpAddObsoleteAttributeCodeFixProvider()
: base(CSharpSyntaxFactsService.Instance, CSharpFeaturesResources.Add_Obsolete)
{
}
}
}
|
Add more default usings to new scripts. | using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Mapset;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
| using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Mapset;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
|
Fix for changes to default fileversion (00000). | using System.Diagnostics;
using Cuemon.Extensions.Xunit;
using Xunit;
using Xunit.Abstractions;
namespace Cuemon.Extensions.Diagnostics
{
public class FileVersionInfoExtensionsTest : Test
{
public FileVersionInfoExtensionsTest(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ToProductVersion_ShouldConvertFileVersionInfoToVersionResult()
{
var sut1 = FileVersionInfo.GetVersionInfo(typeof(FileVersionInfoExtensions).Assembly.Location);
var sut2 = sut1.ToProductVersion();
TestOutput.WriteLine(sut1.ToString());
TestOutput.WriteLine(sut2.ToString());
Assert.True(sut2.HasAlphanumericVersion);
Assert.True(sut2.IsSemanticVersion());
Assert.Equal(sut2.AlphanumericVersion, sut1.ProductVersion);
Assert.Equal(sut2.ToString(), sut1.ProductVersion);
}
[Fact]
public void ToFileVersion_ShouldConvertFileVersionInfoToVersionResult()
{
var sut1 = FileVersionInfo.GetVersionInfo(typeof(FileVersionInfoExtensions).Assembly.Location);
var sut2 = sut1.ToFileVersion();
TestOutput.WriteLine(sut1.ToString());
TestOutput.WriteLine(sut2.ToString());
Assert.False(sut2.HasAlphanumericVersion);
Assert.False(sut2.IsSemanticVersion());
Assert.NotEqual(sut2.AlphanumericVersion, sut1.FileVersion);
Assert.Equal(sut2.ToString(), sut1.FileVersion);
}
}
} | using System.Diagnostics;
using Cuemon.Extensions.Xunit;
using Xunit;
using Xunit.Abstractions;
namespace Cuemon.Extensions.Diagnostics
{
public class FileVersionInfoExtensionsTest : Test
{
public FileVersionInfoExtensionsTest(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ToProductVersion_ShouldConvertFileVersionInfoToVersionResult()
{
var sut1 = FileVersionInfo.GetVersionInfo(typeof(FileVersionInfoExtensions).Assembly.Location);
var sut2 = sut1.ToProductVersion();
TestOutput.WriteLine(sut1.ToString());
TestOutput.WriteLine(sut2.ToString());
Assert.True(sut2.HasAlphanumericVersion);
Assert.True(sut2.IsSemanticVersion());
Assert.Equal(sut2.AlphanumericVersion, sut1.ProductVersion);
Assert.Equal(sut2.ToString(), sut1.ProductVersion);
}
[Fact]
public void ToFileVersion_ShouldConvertFileVersionInfoToVersionResult()
{
var sut1 = FileVersionInfo.GetVersionInfo(typeof(FileVersionInfoExtensions).Assembly.Location);
var sut2 = sut1.ToFileVersion();
TestOutput.WriteLine(sut1.ToString());
TestOutput.WriteLine(sut2.ToString());
Assert.True(sut2.HasAlphanumericVersion);
Assert.False(sut2.IsSemanticVersion());
Assert.Equal(sut2.AlphanumericVersion, sut1.FileVersion);
Assert.Equal(sut2.ToString(), sut1.FileVersion);
}
}
} |
Add property to use to determine the queue name to be used, and applied QueueName attribute to the property | using System;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Messages;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Data;
using SFA.DAS.Messaging;
namespace SFA.DAS.EmployerApprenticeshipsService.Application.Commands.CreateEmployerAccount
{
public class CreateAccountCommandHandler : AsyncRequestHandler<CreateAccountCommand>
{
private readonly IAccountRepository _accountRepository;
private readonly IMessagePublisher _messagePublisher;
private readonly CreateAccountCommandValidator _validator;
public CreateAccountCommandHandler(IAccountRepository accountRepository, IMessagePublisher messagePublisher)
{
if (accountRepository == null)
throw new ArgumentNullException(nameof(accountRepository));
if (messagePublisher == null)
throw new ArgumentNullException(nameof(messagePublisher));
_accountRepository = accountRepository;
_messagePublisher = messagePublisher;
_validator = new CreateAccountCommandValidator();
}
protected override async Task HandleCore(CreateAccountCommand message)
{
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid())
throw new InvalidRequestException(validationResult.ValidationDictionary);
var accountId = await _accountRepository.CreateAccount(message.UserId, message.CompanyNumber, message.CompanyName, message.EmployerRef);
await _messagePublisher.PublishAsync(new EmployerRefreshLevyQueueMessage
{
AccountId = accountId
});
}
}
} | using System;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerApprenticeshipsService.Application.Messages;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Attributes;
using SFA.DAS.EmployerApprenticeshipsService.Domain.Data;
using SFA.DAS.Messaging;
namespace SFA.DAS.EmployerApprenticeshipsService.Application.Commands.CreateEmployerAccount
{
public class CreateAccountCommandHandler : AsyncRequestHandler<CreateAccountCommand>
{
[QueueName]
private string das_at_eas_get_employer_levy { get; set; }
private readonly IAccountRepository _accountRepository;
private readonly IMessagePublisher _messagePublisher;
private readonly CreateAccountCommandValidator _validator;
public CreateAccountCommandHandler(IAccountRepository accountRepository, IMessagePublisher messagePublisher)
{
if (accountRepository == null)
throw new ArgumentNullException(nameof(accountRepository));
if (messagePublisher == null)
throw new ArgumentNullException(nameof(messagePublisher));
_accountRepository = accountRepository;
_messagePublisher = messagePublisher;
_validator = new CreateAccountCommandValidator();
}
protected override async Task HandleCore(CreateAccountCommand message)
{
var validationResult = _validator.Validate(message);
if (!validationResult.IsValid())
throw new InvalidRequestException(validationResult.ValidationDictionary);
var accountId = await _accountRepository.CreateAccount(message.UserId, message.CompanyNumber, message.CompanyName, message.EmployerRef);
await _messagePublisher.PublishAsync(new EmployerRefreshLevyQueueMessage
{
AccountId = accountId
});
}
}
} |
Add a link to "about trac" on the trac version number at the end | <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <strong>Trac <?cs var:trac.version ?></strong><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
| <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs
var:trac.version ?></strong></a><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
|
Add a link to "about trac" on the trac version number at the end | <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <strong>Trac <?cs var:trac.version ?></strong><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
| <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs
var:trac.version ?></strong></a><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
|
Add new payment sources (e.g. paynow etc) | using System.Runtime.Serialization;
namespace Omise.Models
{
public enum OffsiteTypes
{
[EnumMember(Value = null)]
None,
[EnumMember(Value = "internet_banking_scb")]
InternetBankingSCB,
[EnumMember(Value = "internet_banking_bbl")]
InternetBankingBBL,
[EnumMember(Value = "internet_banking_ktb")]
InternetBankingKTB,
[EnumMember(Value = "internet_banking_bay")]
InternetBankingBAY,
[EnumMember(Value = "alipay")]
AlipayOnline,
[EnumMember(Value = "installment_bay")]
InstallmentBAY,
[EnumMember(Value = "installment_kbank")]
InstallmentKBank,
[EnumMember(Value = "bill_payment_tesco_lotus")]
BillPaymentTescoLotus,
[EnumMember(Value = "barcode_alipay")]
BarcodeAlipay
}
}
| using System.Runtime.Serialization;
namespace Omise.Models
{
public enum OffsiteTypes
{
[EnumMember(Value = null)]
None,
[EnumMember(Value = "internet_banking_scb")]
InternetBankingSCB,
[EnumMember(Value = "internet_banking_bbl")]
InternetBankingBBL,
[EnumMember(Value = "internet_banking_ktb")]
InternetBankingKTB,
[EnumMember(Value = "internet_banking_bay")]
InternetBankingBAY,
[EnumMember(Value = "alipay")]
AlipayOnline,
[EnumMember(Value = "installment_bay")]
InstallmentBAY,
[EnumMember(Value = "installment_kbank")]
InstallmentKBank,
[EnumMember(Value = "bill_payment_tesco_lotus")]
BillPaymentTescoLotus,
[EnumMember(Value = "barcode_alipay")]
BarcodeAlipay,
[EnumMember(Value = "paynow")]
Paynow,
[EnumMember(Value = "points_citi")]
PointsCiti,
[EnumMember(Value = "truemoney")]
TrueMoney
}
}
|
Remove unnecessary check and throw (already throws) | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[256];
}
public FileHeader GetFileHeader(string file)
{
if (!System.IO.File.Exists(file))
{
throw new Exception("File was not found on path " + file);
}
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, 256);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true);
}
}
} | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[256];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, 256);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer) == true);
}
}
} |
Fix null-ref exception when doing get request | // 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.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
public partial class ServiceModelHttpMessageHandler : DelegatingHandler
{
public DecompressionMethods AutomaticDecompression
{
get { return _innerHandler.AutomaticDecompression; }
set { _innerHandler.AutomaticDecompression = value; }
}
public bool PreAuthenticate
{
get { return _innerHandler.PreAuthenticate; }
set { _innerHandler.PreAuthenticate = value; }
}
public CookieContainer CookieContainer
{
get { return _innerHandler.CookieContainer; }
set { _innerHandler.CookieContainer = value; }
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var content = request.Content as MessageContent;
var responseMessage = await base.SendAsync(request, cancellationToken);
await content.WriteCompletionTask;
return responseMessage;
}
}
}
| // 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.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
public partial class ServiceModelHttpMessageHandler : DelegatingHandler
{
public DecompressionMethods AutomaticDecompression
{
get { return _innerHandler.AutomaticDecompression; }
set { _innerHandler.AutomaticDecompression = value; }
}
public bool PreAuthenticate
{
get { return _innerHandler.PreAuthenticate; }
set { _innerHandler.PreAuthenticate = value; }
}
public CookieContainer CookieContainer
{
get { return _innerHandler.CookieContainer; }
set { _innerHandler.CookieContainer = value; }
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var content = request.Content as MessageContent;
var responseMessage = await base.SendAsync(request, cancellationToken);
if (content != null)
{
await content.WriteCompletionTask;
}
return responseMessage;
}
}
}
|
Fix uri templates in episode requests. | namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Episodes
{
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Episodes;
using System.Collections.Generic;
internal class TraktEpisodeCommentsRequest : TraktGetByIdEpisodeRequest<TraktPaginationListResult<TraktEpisodeComment>, TraktEpisodeComment>
{
internal TraktEpisodeCommentsRequest(TraktClient client) : base(client) { }
internal TraktCommentSortOrder? Sorting { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
uriParams.Add("sorting", Sorting.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/{id}/seasons/{season}/episodes/{episode}/comments/{sorting}";
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Episodes
{
using Enums;
using Objects.Basic;
using Objects.Get.Shows.Episodes;
using System.Collections.Generic;
internal class TraktEpisodeCommentsRequest : TraktGetByIdEpisodeRequest<TraktPaginationListResult<TraktEpisodeComment>, TraktEpisodeComment>
{
internal TraktEpisodeCommentsRequest(TraktClient client) : base(client) { }
internal TraktCommentSortOrder? Sorting { get; set; }
protected override IDictionary<string, object> GetUriPathParameters()
{
var uriParams = base.GetUriPathParameters();
if (Sorting.HasValue && Sorting.Value != TraktCommentSortOrder.Unspecified)
uriParams.Add("sorting", Sorting.Value.AsString());
return uriParams;
}
protected override string UriTemplate => "shows/{id}/seasons/{season}/episodes/{episode}/comments{/sorting}";
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Rename local variable for accuracy. | using System;
using System.Diagnostics;
namespace Fixie.Behaviors
{
public class ExecuteCases : InstanceBehavior
{
public void Execute(Fixture fixture)
{
foreach (var @case in fixture.Cases)
{
var result = @case.Execution;
using (var console = new RedirectedConsole())
{
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
fixture.CaseExecutionBehavior.Execute(@case, fixture.Instance);
}
catch (Exception exception)
{
@case.Fail(exception);
}
stopwatch.Stop();
result.Duration = stopwatch.Elapsed;
result.Output = console.Output;
}
Console.Write(result.Output);
}
}
}
} | using System;
using System.Diagnostics;
namespace Fixie.Behaviors
{
public class ExecuteCases : InstanceBehavior
{
public void Execute(Fixture fixture)
{
foreach (var @case in fixture.Cases)
{
var execution = @case.Execution;
using (var console = new RedirectedConsole())
{
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
fixture.CaseExecutionBehavior.Execute(@case, fixture.Instance);
}
catch (Exception exception)
{
@case.Fail(exception);
}
stopwatch.Stop();
execution.Duration = stopwatch.Elapsed;
execution.Output = console.Output;
}
Console.Write(execution.Output);
}
}
}
} |
Test that the initial nonce is set. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace CertManager.Test.AcmeTests
{
[TestFixture]
public class WhenInitializing : WithAcmeClient
{
public override async Task BecauseOf()
{
await ClassUnderTest.Initialize();
}
[Test]
public void DirectoryShouldBePopulated()
{
Assert.That(ClassUnderTest.Directory, Is.Not.Null);
}
[Test]
public void NewRegIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewReg, Is.Not.Null);
}
[Test]
public void NewCertIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewCert, Is.Not.Null);
}
[Test]
public void NewAuthzIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewAuthz, Is.Not.Null);
}
[Test]
public void RecoverRegIsPopulated()
{
Assert.That(ClassUnderTest.Directory.RecoverReg, Is.Not.Null);
}
[Test]
public void RevokeCertIsNotNull()
{
Assert.That(ClassUnderTest.Directory.RevokeCert, Is.Not.Null);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace CertManager.Test.AcmeTests
{
[TestFixture]
public class WhenInitializing : WithAcmeClient
{
public override async Task BecauseOf()
{
await ClassUnderTest.Initialize();
}
[Test]
public void DirectoryShouldBePopulated()
{
Assert.That(ClassUnderTest.Directory, Is.Not.Null);
}
[Test]
public void NewRegIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewReg, Is.Not.Null);
}
[Test]
public void NewCertIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewCert, Is.Not.Null);
}
[Test]
public void NewAuthzIsPopulated()
{
Assert.That(ClassUnderTest.Directory.NewAuthz, Is.Not.Null);
}
[Test]
public void RecoverRegIsPopulated()
{
Assert.That(ClassUnderTest.Directory.RecoverReg, Is.Not.Null);
}
[Test]
public void RevokeCertIsNotNull()
{
Assert.That(ClassUnderTest.Directory.RevokeCert, Is.Not.Null);
}
[Test]
public void InitialNonceIsSet()
{
Assert.That(ClassUnderTest.LastNonce, Is.Not.Null);
}
}
}
|
Change verb from get to post | using System;
using DrClockwork.Domain.Logic;
using DrClockwork.Domain.Models;
using DrClockwork.Nancy.ViewModels;
using Microsoft.AspNet.SignalR;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Validation;
using Raven.Client;
namespace DrClockwork.Nancy.Modules
{
public class AskModule : NancyModule
{
public AskModule(IDocumentSession documentSession, IHubContext hubContext)
: base("Ask")
{
Get["/"] = _ =>
{
try
{
var model = this.Bind<AskViewModel>();
var pathToAiml = System.Web.HttpContext.Current.Server.MapPath(@"~/aiml");
var drClockwork = new DoctorClockwork(pathToAiml);
var answer = drClockwork.AskMeAnything(model.From, model.Content);
ClockworkSMS.Send(model.From, answer);
var question = new Question
{
ToPhoneNumber = model.To,
FromPhoneNumber = model.From,
DateAsked = DateTime.Now,
Content = model.Content,
MessageId = model.Msg_Id,
Keyword = model.Keyword,
Answer = answer
};
documentSession.Store(question);
documentSession.SaveChanges();
hubContext.Clients.All.broadcastAnswer(model.Content, answer);
return null;
}
catch (Exception ex)
{
return string.Format("Message: {0}\r\nDetail {1}", ex.Message, ex.StackTrace);
}
};
}
}
} | using System;
using DrClockwork.Domain.Logic;
using DrClockwork.Domain.Models;
using DrClockwork.Nancy.ViewModels;
using Microsoft.AspNet.SignalR;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Validation;
using Raven.Client;
namespace DrClockwork.Nancy.Modules
{
public class AskModule : NancyModule
{
public AskModule(IDocumentSession documentSession, IHubContext hubContext)
: base("Ask")
{
Post["/"] = _ =>
{
try
{
var model = this.Bind<AskViewModel>();
var pathToAiml = System.Web.HttpContext.Current.Server.MapPath(@"~/aiml");
var drClockwork = new DoctorClockwork(pathToAiml);
var answer = drClockwork.AskMeAnything(model.From, model.Content);
ClockworkSMS.Send(model.From, answer);
var question = new Question
{
ToPhoneNumber = model.To,
FromPhoneNumber = model.From,
DateAsked = DateTime.Now,
Content = model.Content,
MessageId = model.Msg_Id,
Keyword = model.Keyword,
Answer = answer
};
documentSession.Store(question);
documentSession.SaveChanges();
hubContext.Clients.All.broadcastAnswer(model.Content, answer);
return null;
}
catch (Exception ex)
{
return string.Format("Message: {0}\r\nDetail {1}", ex.Message, ex.StackTrace);
}
};
}
}
} |
Use ConditionalFact to not run tests on xplat | // 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.Threading.Tasks;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.Precompilation
{
public class SimpleAppDesktopOnlyTest : IClassFixture<SimpleAppDesktopOnlyTest.SimpleAppDesktopOnlyTestFixture>
{
public SimpleAppDesktopOnlyTest(SimpleAppDesktopOnlyTestFixture fixture)
{
Fixture = fixture;
}
public ApplicationTestFixture Fixture { get; }
[Fact]
[OSSkipConditionAttribute(OperatingSystems.Linux)]
[OSSkipConditionAttribute(OperatingSystems.Windows)]
public async Task Precompilation_WorksForSimpleApps()
{
// Arrange
using (var deployer = Fixture.CreateDeployment(RuntimeFlavor.Clr))
{
var deploymentResult = deployer.Deploy();
// Act
var response = await Fixture.HttpClient.GetStringWithRetryAsync(
deploymentResult.ApplicationBaseUri,
Fixture.Logger);
// Assert
TestEmbeddedResource.AssertContent("SimpleAppDesktopOnly.Home.Index.txt", response);
}
}
public class SimpleAppDesktopOnlyTestFixture : ApplicationTestFixture
{
public SimpleAppDesktopOnlyTestFixture()
: base("SimpleAppDesktopOnly")
{
}
}
}
}
| // 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.Threading.Tasks;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.Precompilation
{
public class SimpleAppDesktopOnlyTest : IClassFixture<SimpleAppDesktopOnlyTest.SimpleAppDesktopOnlyTestFixture>
{
public SimpleAppDesktopOnlyTest(SimpleAppDesktopOnlyTestFixture fixture)
{
Fixture = fixture;
}
public ApplicationTestFixture Fixture { get; }
[ConditionalFact]
[OSSkipConditionAttribute(OperatingSystems.Linux)]
[OSSkipConditionAttribute(OperatingSystems.Windows)]
public async Task Precompilation_WorksForSimpleApps()
{
// Arrange
using (var deployer = Fixture.CreateDeployment(RuntimeFlavor.Clr))
{
var deploymentResult = deployer.Deploy();
// Act
var response = await Fixture.HttpClient.GetStringWithRetryAsync(
deploymentResult.ApplicationBaseUri,
Fixture.Logger);
// Assert
TestEmbeddedResource.AssertContent("SimpleAppDesktopOnly.Home.Index.txt", response);
}
}
public class SimpleAppDesktopOnlyTestFixture : ApplicationTestFixture
{
public SimpleAppDesktopOnlyTestFixture()
: base("SimpleAppDesktopOnly")
{
}
}
}
}
|
Fix incorrect alive criteria causing clicking future objects to be too greedy | // 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.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Screens.Edit;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints
{
public abstract class OsuSelectionBlueprint<T> : HitObjectSelectionBlueprint<T>
where T : OsuHitObject
{
[Resolved]
private EditorClock editorClock { get; set; }
protected new DrawableOsuHitObject DrawableObject => (DrawableOsuHitObject)base.DrawableObject;
protected override bool AlwaysShowWhenSelected => true;
protected override bool ShouldBeAlive => base.ShouldBeAlive || editorClock.CurrentTime - Item.GetEndTime() < HitCircleOverlapMarker.FADE_OUT_EXTENSION;
protected OsuSelectionBlueprint(T hitObject)
: base(hitObject)
{
}
}
}
| // 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.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Screens.Edit;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints
{
public abstract class OsuSelectionBlueprint<T> : HitObjectSelectionBlueprint<T>
where T : OsuHitObject
{
[Resolved]
private EditorClock editorClock { get; set; }
protected new DrawableOsuHitObject DrawableObject => (DrawableOsuHitObject)base.DrawableObject;
protected override bool AlwaysShowWhenSelected => true;
protected override bool ShouldBeAlive => base.ShouldBeAlive
|| (editorClock.CurrentTime >= Item.StartTime && editorClock.CurrentTime - Item.GetEndTime() < HitCircleOverlapMarker.FADE_OUT_EXTENSION);
protected OsuSelectionBlueprint(T hitObject)
: base(hitObject)
{
}
}
}
|
Fix server not starting on correct URL | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Yio.Utilities;
namespace Yio
{
public class Program
{
private static int _port { get; set; }
public static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan);
if (!File.Exists("appsettings.json")) {
StartupUtilities.WriteFailure("configuration is missing");
Environment.Exit(1);
}
StartupUtilities.WriteInfo("setting port");
if(args == null || args.Length == 0)
{
_port = 5100;
StartupUtilities.WriteSuccess("port set to " + _port + " (default)");
}
else
{
_port = args[0] == null ? 5100 : Int32.Parse(args[0]);
StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)");
}
StartupUtilities.WriteInfo("starting App");
BuildWebHost(args).Run();
Console.ResetColor();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Yio.Utilities;
namespace Yio
{
public class Program
{
private static int _port { get; set; }
public static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
StartupUtilities.WriteStartupMessage(StartupUtilities.GetRelease(), ConsoleColor.Cyan);
if (!File.Exists("appsettings.json")) {
StartupUtilities.WriteFailure("configuration is missing");
Environment.Exit(1);
}
StartupUtilities.WriteInfo("setting port");
if(args == null || args.Length == 0)
{
_port = 5100;
StartupUtilities.WriteSuccess("port set to " + _port + " (default)");
}
else
{
_port = args[0] == null ? 5100 : Int32.Parse(args[0]);
StartupUtilities.WriteSuccess("port set to " + _port + " (user defined)");
}
StartupUtilities.WriteInfo("starting App");
BuildWebHost(args).Run();
Console.ResetColor();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://0.0.0.0:" + _port.ToString() + "/")
.UseStartup<Startup>()
.Build();
}
}
|
Test for petapoco to stay internal | using System;
using System.Linq;
using FluentAssertions;
using NSaga;
using Xunit;
namespace Tests
{
public class NamespaceTests
{
[Fact]
public void NSaga_Contains_Only_One_Namespace()
{
//Arrange
var assembly = typeof(ISagaMediator).Assembly;
// Act
var namespaces = assembly.GetTypes()
.Where(t => t.IsPublic)
.Select(t => t.Namespace)
.Distinct()
.ToList();
// Assert
var names = String.Join(", ", namespaces);
namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'");
}
[Fact]
public void PetaPoco_Stays_Internal()
{
//Arrange
var petapocoTypes = typeof(SqlSagaRepository).Assembly
.GetTypes()
.Where(t => !String.IsNullOrEmpty(t.Namespace))
.Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase))
.Where(t => t.IsPublic)
.ToList();
petapocoTypes.Should().BeEmpty();
}
[Fact]
public void TinyIoc_Stays_Internal()
{
typeof(TinyIoCContainer).IsPublic.Should().BeFalse();
}
}
}
| using System;
using System.Linq;
using FluentAssertions;
using NSaga;
using PetaPoco;
using Xunit;
namespace Tests
{
public class NamespaceTests
{
[Fact]
public void NSaga_Contains_Only_One_Namespace()
{
//Arrange
var assembly = typeof(ISagaMediator).Assembly;
// Act
var namespaces = assembly.GetTypes()
.Where(t => t.IsPublic)
.Select(t => t.Namespace)
.Distinct()
.ToList();
// Assert
var names = String.Join(", ", namespaces);
namespaces.Should().HaveCount(1, $"Should only contain 'NSaga' namespace, but found '{names}'");
}
[Fact]
public void PetaPocoNamespace_Stays_Internal()
{
//Arrange
var petapocoTypes = typeof(SqlSagaRepository).Assembly
.GetTypes()
.Where(t => !String.IsNullOrEmpty(t.Namespace))
.Where(t => t.Namespace.StartsWith("PetaPoco", StringComparison.OrdinalIgnoreCase))
.Where(t => t.IsPublic)
.ToList();
petapocoTypes.Should().BeEmpty();
}
[Fact]
public void TinyIoc_Stays_Internal()
{
typeof(TinyIoCContainer).IsPublic.Should().BeFalse();
}
[Fact]
public void PetaPoco_Stays_Internal()
{
typeof(Database).IsPublic.Should().BeFalse();
}
}
}
|
Add base method for testing conversion in other direction | // 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 System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets;
namespace osu.Game.Tests.Beatmaps
{
/// <summary>
/// Base class for tests of converting <see cref="LegacyMods"/> enumeration flags to ruleset mod instances.
/// </summary>
public abstract class LegacyModConversionTest
{
/// <summary>
/// Creates the <see cref="Ruleset"/> whose legacy mod conversion is to be tested.
/// </summary>
/// <returns></returns>
protected abstract Ruleset CreateRuleset();
protected void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods)
{
var ruleset = CreateRuleset();
var mods = ruleset.ConvertFromLegacyMods(legacyMods).ToList();
Assert.AreEqual(expectedMods.Length, mods.Count);
foreach (var modType in expectedMods)
{
Assert.IsNotNull(mods.SingleOrDefault(mod => mod.GetType() == modType));
}
}
}
}
| // 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 System.Linq;
using NUnit.Framework;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets;
namespace osu.Game.Tests.Beatmaps
{
/// <summary>
/// Base class for tests of converting <see cref="LegacyMods"/> enumeration flags to ruleset mod instances.
/// </summary>
public abstract class LegacyModConversionTest
{
/// <summary>
/// Creates the <see cref="Ruleset"/> whose legacy mod conversion is to be tested.
/// </summary>
/// <returns></returns>
protected abstract Ruleset CreateRuleset();
protected void TestFromLegacy(LegacyMods legacyMods, Type[] expectedMods)
{
var ruleset = CreateRuleset();
var mods = ruleset.ConvertFromLegacyMods(legacyMods).ToList();
Assert.AreEqual(expectedMods.Length, mods.Count);
foreach (var modType in expectedMods)
{
Assert.IsNotNull(mods.SingleOrDefault(mod => mod.GetType() == modType));
}
}
protected void TestToLegacy(LegacyMods expectedLegacyMods, Type[] providedModTypes)
{
var ruleset = CreateRuleset();
var modInstances = ruleset.GetAllMods()
.Where(mod => providedModTypes.Contains(mod.GetType()))
.ToArray();
var actualLegacyMods = ruleset.ConvertToLegacyMods(modInstances);
Assert.AreEqual(expectedLegacyMods, actualLegacyMods);
}
}
}
|
Update field name change that got missed | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class FixedRequestAuthorizerProvider : IRequestAuthorizerProvider
{
public FixedRequestAuthorizerProvider()
: this(Enumerable.Empty<IRequestAuthorizer>())
{
}
public FixedRequestAuthorizerProvider(IEnumerable<IRequestAuthorizer> controllerTypes)
{
Policies = new List<IRequestAuthorizer>(controllerTypes);
}
public IList<IRequestAuthorizer> Policies { get; }
IEnumerable<IRequestAuthorizer> IRequestAuthorizerProvider.Authorizers => Policies;
}
} | using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Web
{
public class FixedRequestAuthorizerProvider : IRequestAuthorizerProvider
{
public FixedRequestAuthorizerProvider()
: this(Enumerable.Empty<IRequestAuthorizer>())
{
}
public FixedRequestAuthorizerProvider(IEnumerable<IRequestAuthorizer> controllerTypes)
{
Authorizers = new List<IRequestAuthorizer>(controllerTypes);
}
public IList<IRequestAuthorizer> Authorizers { get; }
IEnumerable<IRequestAuthorizer> IRequestAuthorizerProvider.Authorizers => Authorizers;
}
} |
Remove IClientPublisher service as it doesn't exist before | using Glimpse.Agent;
using Microsoft.Framework.DependencyInjection;
using Glimpse.Server.Web;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
//
// Store
//
services.AddSingleton<IStorage, InMemoryStorage>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IRequestAuthorizer>, DefaultExtensionProvider<IRequestAuthorizer>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddTransient<IResourceManager, ResourceManager>();
services.AddTransient<IClientBroker, MessageStreamResource>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
} | using Glimpse.Agent;
using Microsoft.Framework.DependencyInjection;
using Glimpse.Server.Web;
using Microsoft.Framework.OptionsModel;
namespace Glimpse
{
public class GlimpseServerWebServices
{
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IServerBroker, DefaultServerBroker>();
//
// Store
//
services.AddSingleton<IStorage, InMemoryStorage>();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseServerWebOptions>, GlimpseServerWebOptionsSetup>();
services.AddTransient<IExtensionProvider<IRequestAuthorizer>, DefaultExtensionProvider<IRequestAuthorizer>>();
services.AddTransient<IExtensionProvider<IResource>, DefaultExtensionProvider<IResource>>();
services.AddTransient<IExtensionProvider<IResourceStartup>, DefaultExtensionProvider<IResourceStartup>>();
services.AddSingleton<IAllowRemoteProvider, DefaultAllowRemoteProvider>();
services.AddTransient<IResourceManager, ResourceManager>();
return services;
}
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IMessagePublisher, InProcessChannel>();
return services;
}
}
} |
Add more tests to ensure secure properties are kept secure | using System;
using NUnit.Framework;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Common
{
[TestFixture]
public class TorrentEditorTests
{
[Test]
public void EditingCreatesCopy ()
{
var d = Create ("comment", "a");
var editor = new TorrentEditor (d);
editor.Comment = "b";
Assert.AreEqual ("a", d ["comment"].ToString (), "#1");
}
[Test]
public void EditComment ()
{
var d = Create ("comment", "a");
var editor = new TorrentEditor (d);
editor.Comment = "b";
d = editor.ToDictionary ();
Assert.AreEqual ("b", d ["comment"].ToString (), "#1");
}
BEncodedDictionary Create (string key, string value)
{
var d = new BEncodedDictionary ();
d.Add (key, (BEncodedString) value);
return d;
}
}
}
| using System;
using NUnit.Framework;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Common
{
[TestFixture]
public class TorrentEditorTests
{
[Test]
public void EditingCreatesCopy ()
{
var d = Create ("comment", "a");
var editor = new TorrentEditor (d);
editor.Comment = "b";
Assert.AreEqual ("a", d ["comment"].ToString (), "#1");
}
[Test]
public void EditComment ()
{
var d = Create ("comment", "a");
var editor = new TorrentEditor (d);
editor.Comment = "b";
d = editor.ToDictionary ();
Assert.AreEqual ("b", d ["comment"].ToString (), "#1");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void ReplaceInfoDict ()
{
var editor = new TorrentEditor (new BEncodedDictionary ()) { CanEditSecureMetadata = false };
editor.SetCustom ("info", new BEncodedDictionary ());
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void EditProtectedProperty_NotAllowed ()
{
var editor = new TorrentEditor (new BEncodedDictionary ()) { CanEditSecureMetadata = false };
editor.PieceLength = 16;
}
BEncodedDictionary Create (string key, string value)
{
var d = new BEncodedDictionary ();
d.Add (key, (BEncodedString) value);
return d;
}
}
}
|
Add - Aggiunto controller adibito alla gestione dei dati del Personale | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace SO115.ApiGateway.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonaleController : ControllerBase
{
/// <summary>
/// Controller che si occuperà di gestire tutte le informazioni riguardanti il Personale
/// mettendo insieme le informaizoni reperite dalle API Servizi e IdentityManagement e
/// restituendole al FrontEnd
/// </summary>
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SO115App.ApiGateway.Classi;
using SO115App.ApiGateway.Servizi;
namespace SO115.ApiGateway.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonaleController : ControllerBase
{
private readonly PersonaleService prsonaleService;
/// <summary>
/// Controller che si occuperà di gestire tutte le informazioni riguardanti il Personale
/// mettendo insieme le informaizoni reperite dalle API Servizi e IdentityManagement e
/// restituendole al FrontEnd
/// </summary>
public PersonaleController(PersonaleService prsonaleService)
{
this.prsonaleService = prsonaleService;
}
[HttpGet]
public async Task<List<SquadreNelTurno>> GetSquadreNelTurno(string codiceSede, string codiceTurno)
{
List<SquadreNelTurno> Turno = await prsonaleService.GetSquadreNelTurno(codiceSede, codiceTurno);
return Turno;
}
[HttpGet]
public async Task<List<SquadreNelTurno>> GetSquadreBySede(string codiceSede)
{
List<SquadreNelTurno> Turno = await prsonaleService.GetSquadreBySede(codiceSede);
return Turno;
}
}
}
|
Fix ordering of license header. | using System.Collections.Generic;
using osu.Framework.Input;
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Replays;
namespace osu.Game.Rulesets.Mania.Replays
{
internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler
{
public ManiaFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override List<InputState> GetPendingStates()
{
var actions = new List<ManiaAction>();
int activeColumns = (int)(CurrentFrame.MouseX ?? 0);
int counter = 0;
while (activeColumns > 0)
{
if ((activeColumns & 1) > 0)
actions.Add(ManiaAction.Key1 + counter);
counter++;
activeColumns >>= 1;
}
return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } };
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Input;
using osu.Game.Rulesets.Replays;
namespace osu.Game.Rulesets.Mania.Replays
{
internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler
{
public ManiaFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override List<InputState> GetPendingStates()
{
var actions = new List<ManiaAction>();
int activeColumns = (int)(CurrentFrame.MouseX ?? 0);
int counter = 0;
while (activeColumns > 0)
{
if ((activeColumns & 1) > 0)
actions.Add(ManiaAction.Key1 + counter);
counter++;
activeColumns >>= 1;
}
return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } };
}
}
}
|
Change The Detail of the ajax Search | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MMLibrarySystem.Models;
namespace MMLibrarySystem.Controllers
{
public class BookListController : Controller
{
public ActionResult Index(string searchTerm = null)
{
List<Book> books = new List<Book>();
using (var dbContext = new BookLibraryContext())
{
var tempBooks = dbContext.Books.Include("BookInfo");
if (string.IsNullOrEmpty(searchTerm))
{
books.AddRange(tempBooks.ToList());
}
else
{
books.AddRange(tempBooks.Where(b => b.BookInfo.Title.Contains(searchTerm) || b.BookInfo.Description.Contains(searchTerm)));
}
}
if (Request.IsAjaxRequest())
{
PartialView("_BookList", books);
}
return View(books);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MMLibrarySystem.Models;
namespace MMLibrarySystem.Controllers
{
public class BookListController : Controller
{
public ActionResult Index(string searchTerm = null)
{
List<Book> books = new List<Book>();
using (var dbContext = new BookLibraryContext())
{
var tempBooks = dbContext.Books.Include("BookInfo");
if (string.IsNullOrEmpty(searchTerm))
{
books.AddRange(tempBooks.ToList());
}
else
{
books.AddRange(tempBooks.Where(b => b.BookInfo.Title.Contains(searchTerm) || b.BookInfo.Description.Contains(searchTerm)));
}
}
if (Request.IsAjaxRequest())
{
return PartialView("_BookList", books);
}
return View(books);
}
}
}
|
Set base path to current directory if ContentRootPath is null on hosting environment. This path is where AI would look for appsettings.json file for ikey, endpoint etc. | namespace Microsoft.AspNetCore.Hosting
{
using System.Diagnostics;
using System.Globalization;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
/// <summary>
/// <see cref="IConfigureOptions<ApplicationInsightsServiceOptions>"/> implemetation that reads options from 'appsettings.json',
/// environment variables and sets developer mode based on debugger state.
/// </summary>
internal class DefaultApplicationInsightsServiceConfigureOptions : IConfigureOptions<ApplicationInsightsServiceOptions>
{
private readonly IHostingEnvironment hostingEnvironment;
/// <summary>
/// Creates a new instance of <see cref="DefaultApplicationInsightsServiceConfigureOptions"/>
/// </summary>
/// <param name="hostingEnvironment"><see cref="IHostingEnvironment"/> to use for retreiving ContentRootPath</param>
public DefaultApplicationInsightsServiceConfigureOptions(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
/// <inheritdoc />
public void Configure(ApplicationInsightsServiceOptions options)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(this.hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true)
.AddJsonFile(string.Format(CultureInfo.InvariantCulture,"appsettings.{0}.json", hostingEnvironment.EnvironmentName), true)
.AddEnvironmentVariables();
ApplicationInsightsExtensions.AddTelemetryConfiguration(configBuilder.Build(), options);
if (Debugger.IsAttached)
{
options.DeveloperMode = true;
}
}
}
} | namespace Microsoft.AspNetCore.Hosting
{
using System.Diagnostics;
using System.Globalization;
using System.IO;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
/// <summary>
/// <see cref="IConfigureOptions<ApplicationInsightsServiceOptions>"/> implemetation that reads options from 'appsettings.json',
/// environment variables and sets developer mode based on debugger state.
/// </summary>
internal class DefaultApplicationInsightsServiceConfigureOptions : IConfigureOptions<ApplicationInsightsServiceOptions>
{
private readonly IHostingEnvironment hostingEnvironment;
/// <summary>
/// Creates a new instance of <see cref="DefaultApplicationInsightsServiceConfigureOptions"/>
/// </summary>
/// <param name="hostingEnvironment"><see cref="IHostingEnvironment"/> to use for retreiving ContentRootPath</param>
public DefaultApplicationInsightsServiceConfigureOptions(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
/// <inheritdoc />
public void Configure(ApplicationInsightsServiceOptions options)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(this.hostingEnvironment.ContentRootPath??Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true)
.AddJsonFile(string.Format(CultureInfo.InvariantCulture,"appsettings.{0}.json", hostingEnvironment.EnvironmentName), true)
.AddEnvironmentVariables();
ApplicationInsightsExtensions.AddTelemetryConfiguration(configBuilder.Build(), options);
if (Debugger.IsAttached)
{
options.DeveloperMode = true;
}
}
}
} |
Add general JWK to JWK (RSA) conversion | using System;
using System.Security.Cryptography;
namespace THNETII.Security.JOSE
{
public static class JsonWebRsaExtensions
{
public static JsonRsaWebKey ExportJsonWebKey(this RSA rsa, bool includePrivateParameters)
{
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
var param = rsa.ExportParameters(includePrivateParameters);
var jwk = new JsonRsaWebKey
{
N = param.Modulus,
E = param.Exponent
};
if (param.D != null)
jwk.D = param.D;
if (param.P != null)
jwk.P = param.P;
if (param.Q != null)
jwk.Q = param.Q;
if (param.DP != null)
jwk.DP = param.DP;
if (param.DQ != null)
jwk.DQ = param.DQ;
if (param.InverseQ != null)
jwk.QI = param.InverseQ;
return jwk;
}
}
}
| using Newtonsoft.Json;
using System;
using System.Security.Cryptography;
namespace THNETII.Security.JOSE
{
public static class JsonWebRsaExtensions
{
public static JsonRsaWebKey ExportJsonWebKey(this RSA rsa, bool includePrivateParameters)
{
if (rsa == null)
throw new ArgumentNullException(nameof(rsa));
var param = rsa.ExportParameters(includePrivateParameters);
var jwk = new JsonRsaWebKey
{
N = param.Modulus,
E = param.Exponent
};
if (param.D != null)
jwk.D = param.D;
if (param.P != null)
jwk.P = param.P;
if (param.Q != null)
jwk.Q = param.Q;
if (param.DP != null)
jwk.DP = param.DP;
if (param.DQ != null)
jwk.DQ = param.DQ;
if (param.InverseQ != null)
jwk.QI = param.InverseQ;
return jwk;
}
public static JsonRsaWebKey ToRsaWebKey(this JsonWebKey jwk_general)
{
if (jwk_general == null)
return null;
else if (jwk_general is JsonRsaWebKey jwk_rsa)
return jwk_rsa;
else
{
var jwk_json = JsonConvert.SerializeObject(jwk_general);
return JsonConvert.DeserializeObject<JsonRsaWebKey>(jwk_json);
}
}
}
}
|
Replace by other icon (temporary) | using System.ComponentModel.Composition;
using Microsoft.VisualStudio.ProjectSystem;
namespace Cosmos.VS.ProjectSystem
{
[Export(typeof(IProjectTreePropertiesProvider))]
[AppliesTo(ProjectCapability.Cosmos)]
[Order(Order.OverrideManaged)]
internal class ProjectTreePropertiesProvider : IProjectTreePropertiesProvider
{
public void CalculatePropertyValues(
IProjectTreeCustomizablePropertyContext propertyContext,
IProjectTreeCustomizablePropertyValues propertyValues)
{
if (propertyValues.Flags.Contains(ProjectTreeFlags.Common.ProjectRoot))
{
propertyValues.Icon = CosmosImagesMonikers.ProjectRootIcon.ToProjectSystemType();
}
}
}
}
| using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.ProjectSystem;
namespace Cosmos.VS.ProjectSystem
{
[Export(typeof(IProjectTreePropertiesProvider))]
[AppliesTo(ProjectCapability.Cosmos)]
[Order(Order.OverrideManaged)]
internal class ProjectTreePropertiesProvider : IProjectTreePropertiesProvider
{
public void CalculatePropertyValues(
IProjectTreeCustomizablePropertyContext propertyContext,
IProjectTreeCustomizablePropertyValues propertyValues)
{
if (propertyValues.Flags.Contains(ProjectTreeFlags.Common.ProjectRoot))
{
//propertyValues.Icon = CosmosImagesMonikers.ProjectRootIcon.ToProjectSystemType();
propertyValues.Icon = KnownMonikers.StatusOK.ToProjectSystemType();
}
}
}
}
|
Add HOTP key URI implementation | namespace Albireo.Otp
{
using System;
using System.Diagnostics.Contracts;
public static class Hotp
{
public static int GetCode(string secret, long counter, int digits = Otp.DefaultDigits)
{
Contract.Requires<ArgumentNullException>(secret != null);
Contract.Requires<ArgumentOutOfRangeException>(counter >= 0);
Contract.Requires<ArgumentOutOfRangeException>(digits > 0);
Contract.Ensures(Contract.Result<int>() > 0);
Contract.Ensures(Contract.Result<int>() < Math.Pow(10, digits));
return Otp.GetCode(secret, counter, digits);
}
}
}
| namespace Albireo.Otp
{
using System;
using System.Diagnostics.Contracts;
public static class Hotp
{
public static int GetCode(string secret, long counter, int digits = Otp.DefaultDigits)
{
Contract.Requires<ArgumentNullException>(secret != null);
Contract.Requires<ArgumentOutOfRangeException>(counter >= 0);
Contract.Requires<ArgumentOutOfRangeException>(digits > 0);
Contract.Ensures(Contract.Result<int>() > 0);
Contract.Ensures(Contract.Result<int>() < Math.Pow(10, digits));
return Otp.GetCode(secret, counter, digits);
}
public static string GetKeyUri(
string issuer,
string account,
byte[] secret,
long counter,
int digits = Otp.DefaultDigits)
{
Contract.Requires<ArgumentNullException>(issuer != null);
Contract.Requires<ArgumentOutOfRangeException>(!string.IsNullOrWhiteSpace(issuer));
Contract.Requires<ArgumentNullException>(account != null);
Contract.Requires<ArgumentOutOfRangeException>(!string.IsNullOrWhiteSpace(account));
Contract.Requires<ArgumentNullException>(secret != null);
Contract.Requires<ArgumentException>(secret.Length > 0);
Contract.Requires<ArgumentOutOfRangeException>(digits > 0);
Contract.Requires<ArgumentOutOfRangeException>(counter >= 0);
Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result<string>()));
return
Otp.GetKeyUri(
OtpType.Hotp,
issuer,
account,
secret,
HashAlgorithm.Sha1,
digits,
counter,
0);
}
}
}
|
Use full type name to allow multiple toggles with same name but different namespace. | using System;
using System.Collections.Generic;
using System.Linq;
namespace SimpleToggle
{
public class Toggle
{
public class Config
{
static Config()
{
NoToggleBehaviour = DefaultNoToggleBehaviour;
}
private static bool DefaultNoToggleBehaviour(string toggle)
{
throw new KeyNotFoundException(string.Format("Toggle {0} could not be found in any of the {1} ToggleStateProviders", toggle, Providers.Count));
}
public static readonly IList<IToggleStateProvider> Providers = new List<IToggleStateProvider>();
public static Func<string, bool> NoToggleBehaviour { get; set; }
public static void Default()
{
Providers.Clear();
NoToggleBehaviour = DefaultNoToggleBehaviour;
}
}
public static string NameFor<T>()
{
return typeof(T).Name;
}
public static bool Enabled<T>()
{
return Enabled(NameFor<T>());
}
public static bool Enabled(string toggle)
{
var provider = Config.Providers
.FirstOrDefault(p => p.HasValue(toggle));
return provider == null ? Config.NoToggleBehaviour(toggle) : provider.IsEnabled(toggle);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace SimpleToggle
{
public class Toggle
{
public class Config
{
static Config()
{
NoToggleBehaviour = DefaultNoToggleBehaviour;
}
private static bool DefaultNoToggleBehaviour(string toggle)
{
throw new KeyNotFoundException(string.Format("Toggle {0} could not be found in any of the {1} ToggleStateProviders", toggle, Providers.Count));
}
public static readonly IList<IToggleStateProvider> Providers = new List<IToggleStateProvider>();
public static Func<string, bool> NoToggleBehaviour { get; set; }
public static void Default()
{
Providers.Clear();
NoToggleBehaviour = DefaultNoToggleBehaviour;
}
}
public static string NameFor<T>()
{
return typeof(T).FullName;
}
public static bool Enabled<T>()
{
return Enabled(NameFor<T>());
}
public static bool Enabled(string toggle)
{
var provider = Config.Providers
.FirstOrDefault(p => p.HasValue(toggle));
return provider == null ? Config.NoToggleBehaviour(toggle) : provider.IsEnabled(toggle);
}
}
} |
Mark class [Serializable] to address warning | using System;
namespace LiteDB.Shell
{
internal class ShellException : Exception
{
public ShellException(string message)
: base(message)
{
}
public static ShellException NoDatabase()
{
return new ShellException("No open database");
}
}
} | using System;
namespace LiteDB.Shell
{
[Serializable]
internal class ShellException : Exception
{
public ShellException(string message)
: base(message)
{
}
public static ShellException NoDatabase()
{
return new ShellException("No open database");
}
}
}
|
Disable echo effect on double click copy | using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
namespace clipman.Views
{
/// <summary>
/// Interaction logic for ClipList.xaml
/// </summary>
public partial class ClipList : UserControl
{
public ClipList()
{
InitializeComponent();
}
private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Utility.Logging.Log("Double-click copy");
var viewModel = (ViewModels.ClipViewModel)(sender as ListBoxItem).DataContext;
viewModel.Clip.Copy();
Echo(sender as ListBoxItem);
}
private void Echo(ListBoxItem control)
{
var echoAnim = FindResource("Echo") as Storyboard;
echoAnim.Begin(control, control.Template);
}
private void OnClearButtonClick(object sender, System.Windows.RoutedEventArgs e)
{
var viewModel = (ViewModels.ClipListViewModel)DataContext;
viewModel.Clips.Clear();
}
}
}
| using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
namespace clipman.Views
{
/// <summary>
/// Interaction logic for ClipList.xaml
/// </summary>
public partial class ClipList : UserControl
{
public ClipList()
{
InitializeComponent();
}
private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Utility.Logging.Log("Double-click copy");
var viewModel = (ViewModels.ClipViewModel)(sender as ListBoxItem).DataContext;
viewModel.Clip.Copy();
//Echo(sender as ListBoxItem);
}
private void Echo(ListBoxItem control)
{
var echoAnim = FindResource("Echo") as Storyboard;
echoAnim.Begin(control, control.Template);
}
private void OnClearButtonClick(object sender, System.Windows.RoutedEventArgs e)
{
var viewModel = (ViewModels.ClipListViewModel)DataContext;
viewModel.Clips.Clear();
}
}
}
|
Apply transaction in same thread | using System;
using System.Threading.Tasks;
namespace Marcello.Transactions
{
internal class Transaction
{
Marcello Session { get; set; }
internal bool Running { get; set; }
internal bool IsCommitting { get; set; }
int Enlisted { get; set; }
internal Transaction(Marcello session)
{
this.Session = session;
this.Running = true;
this.IsCommitting = false;
this.Apply(); //apply to be sure
}
internal void Enlist()
{
if (this.IsCommitting)
return;
this.Enlisted++;
}
internal void Leave()
{
if (this.IsCommitting)
return;
this.Enlisted--;
if (this.Enlisted == 0)
{
this.Commit();
this.Running = false;
}
}
internal void Rollback()
{
Session.Journal.ClearUncommitted();
this.Running = false;
}
internal void Commit()
{
this.IsCommitting = true;
Session.Journal.Commit();
this.IsCommitting = false;
this.ApplyAsync();
}
void Apply()
{
lock (this.Session.SyncLock)
{
Session.Journal.Apply();
}
}
void ApplyAsync()
{
Task.Run (() => {
Apply();
});
}
}
}
| using System;
using System.Threading.Tasks;
namespace Marcello.Transactions
{
internal class Transaction
{
Marcello Session { get; set; }
internal bool Running { get; set; }
internal bool IsCommitting { get; set; }
int Enlisted { get; set; }
internal Transaction(Marcello session)
{
this.Session = session;
this.Running = true;
this.IsCommitting = false;
this.Apply(); //apply to be sure
}
internal void Enlist()
{
if (this.IsCommitting)
return;
this.Enlisted++;
}
internal void Leave()
{
if (this.IsCommitting)
return;
this.Enlisted--;
if (this.Enlisted == 0)
{
this.Commit();
this.Running = false;
}
}
internal void Rollback()
{
Session.Journal.ClearUncommitted();
this.Running = false;
}
internal void Commit()
{
this.IsCommitting = true;
Session.Journal.Commit();
this.IsCommitting = false;
this.TryApply();
}
void Apply()
{
lock (this.Session.SyncLock)
{
Session.Journal.Apply();
}
}
void TryApply()
{
try{
Apply();
}catch(Exception){}
}
}
}
|
Change Pad-Tileset behavior to be similar to Pad-Palettes. | using LibPixelPet;
using System;
namespace PixelPet.CLI.Commands {
internal class PadTilesetCmd : CliCommand {
public PadTilesetCmd()
: base("Pad-Tileset",
new Parameter(true, new ParameterValue("width"))
) { }
public override void Run(Workbench workbench, ILogger logger) {
int width = FindUnnamedParameter(0).Values[0].ToInt32();
if (width < 1) {
logger?.Log("Invalid tileset width.", LogLevel.Error);
return;
}
int tw = workbench.Tileset.TileWidth;
int th = workbench.Tileset.TileHeight;
int addedTiles = 0;
while (workbench.Tileset.Count % width != 0) {
workbench.Tileset.AddTile(new Tile(tw, th), false, false);
addedTiles++;
}
logger?.Log("Padded tileset to width " + width + " (added " + addedTiles + " tiles).", LogLevel.Information);
}
}
}
| using LibPixelPet;
using System;
namespace PixelPet.CLI.Commands {
internal class PadTilesetCmd : CliCommand {
public PadTilesetCmd()
: base("Pad-Tileset",
new Parameter(true, new ParameterValue("width"))
) { }
public override void Run(Workbench workbench, ILogger logger) {
int width = FindUnnamedParameter(0).Values[0].ToInt32();
if (width < 1) {
logger?.Log("Invalid tileset width.", LogLevel.Error);
return;
}
int tw = workbench.Tileset.TileWidth;
int th = workbench.Tileset.TileHeight;
int addedTiles = 0;
while (workbench.Tileset.Count < width) {
workbench.Tileset.AddTile(new Tile(tw, th), false, false);
addedTiles++;
}
logger?.Log("Padded tileset to width " + width + " (added " + addedTiles + " tiles).", LogLevel.Information);
}
}
}
|
Add an option to provide a template name | using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IdunnSql.Console
{
[Verb("generate", HelpText = "Generate a file")]
public class GenerateOptions
{
[Option('s', "source", Required = true,
HelpText = "Name of the file containing information about the permissions to check")]
public string Source { get; set; }
[Option('d', "destination", Required = true,
HelpText = "Name of the file to be generated.")]
public string Destination { get; set; }
[Option('p', "principal", Required = false,
HelpText = "Name of the principal to impersonate.")]
public string Principal { get; set; }
}
}
| using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IdunnSql.Console
{
[Verb("generate", HelpText = "Generate a file")]
public class GenerateOptions
{
[Option('s', "source", Required = true,
HelpText = "Name of the file containing information about the permissions to check")]
public string Source { get; set; }
[Option('t', "template", Required = false,
HelpText = "Name of the file containing the template")]
public string Template { get; set; }
[Option('d', "destination", Required = true,
HelpText = "Name of the file to be generated.")]
public string Destination { get; set; }
[Option('p', "principal", Required = false,
HelpText = "Name of the principal to impersonate.")]
public string Principal { get; set; }
}
}
|
Fix typo for LateUpdate calls | using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace IllusionInjector
{
class PluginComponent : MonoBehaviour
{
private CompositePlugin plugins;
private bool freshlyLoaded = false;
void Awake()
{
DontDestroyOnLoad(this);
if (Environment.CommandLine.Contains("--verbose") && !Screen.fullScreen)
{
Windows.GuiConsole.CreateConsole();
}
plugins = new CompositePlugin(PluginManager.LoadPlugins());
plugins.OnApplicationStart();
}
void Start()
{
OnLevelWasLoaded(Application.loadedLevel);
}
void Update()
{
if (freshlyLoaded)
{
freshlyLoaded = false;
plugins.OnLevelWasInitialized(Application.loadedLevel);
}
plugins.OnUpdate();
}
void FixedUpdate()
{
plugins.OnFixedUpdate();
}
void OnDestroy()
{
plugins.OnApplicationQuit();
}
void OnLevelWasLoaded(int level)
{
plugins.OnLevelWasLoaded(level);
freshlyLoaded = true;
}
void OnLateUpdate()
{
plugins.OnLateUpdate();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace IllusionInjector
{
class PluginComponent : MonoBehaviour
{
private CompositePlugin plugins;
private bool freshlyLoaded = false;
void Awake()
{
DontDestroyOnLoad(this);
if (Environment.CommandLine.Contains("--verbose") && !Screen.fullScreen)
{
Windows.GuiConsole.CreateConsole();
}
plugins = new CompositePlugin(PluginManager.LoadPlugins());
plugins.OnApplicationStart();
}
void Start()
{
OnLevelWasLoaded(Application.loadedLevel);
}
void Update()
{
if (freshlyLoaded)
{
freshlyLoaded = false;
plugins.OnLevelWasInitialized(Application.loadedLevel);
}
plugins.OnUpdate();
}
void LateUpdate()
{
plugins.OnLateUpdate();
}
void FixedUpdate()
{
plugins.OnFixedUpdate();
}
void OnDestroy()
{
plugins.OnApplicationQuit();
}
void OnLevelWasLoaded(int level)
{
plugins.OnLevelWasLoaded(level);
freshlyLoaded = true;
}
}
}
|
Fix issues with specifying manual resolve paths and with-application shipped fluidsynth libraries | using System;
using System.Runtime.InteropServices;
namespace NFluidsynth.Native
{
internal static partial class LibFluidsynth
{
public const string LibraryName = "fluidsynth";
public const int FluidOk = 0;
public const int FluidFailed = -1;
#if NETCOREAPP
static LibFluidsynth()
{
NativeLibrary.SetDllImportResolver(typeof(LibFluidsynth).Assembly, (name, assembly, path) =>
{
if (name == LibraryName)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Assumption here is that this binds against whatever API .2 is,
// but will try the general name anyway just in case.
try
{
return NativeLibrary.Load("libfluidsynth.so.2");
}
catch (Exception ex)
{
}
return NativeLibrary.Load("libfluidsynth.so");
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return NativeLibrary.Load("libfluidsynth.dylib");
}
}
return IntPtr.Zero;
});
}
#endif
}
}
| using System;
using System.Runtime.InteropServices;
namespace NFluidsynth.Native
{
internal static partial class LibFluidsynth
{
public const string LibraryName = "fluidsynth";
public const int FluidOk = 0;
public const int FluidFailed = -1;
#if NETCOREAPP
static LibFluidsynth()
{
try
{
NativeLibrary.SetDllImportResolver(typeof(LibFluidsynth).Assembly, (name, assembly, path) =>
{
IntPtr handle;
if (name == LibraryName)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// Assumption here is that this binds against whatever API .2 is,
// but will try the general name anyway just in case.
if (NativeLibrary.TryLoad("libfluidsynth.so.2", assembly, path, out handle))
return handle;
if (NativeLibrary.TryLoad("libfluidsynth.so", assembly, path, out handle))
return handle;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (NativeLibrary.TryLoad("libfluidsynth.dylib", assembly, path, out handle))
return handle;
}
}
return IntPtr.Zero;
});
}
catch (Exception)
{
// An exception can be thrown in the above call if someone has already set a DllImportResolver.
// (Can occur if the application wants to override behaviour.)
// This does not throw away failures to resolve.
}
}
#endif
}
}
|
Fix benchmarks not running due to unoptimised nunit | // 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 BenchmarkDotNet.Running;
namespace osu.Framework.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args);
}
}
}
| // 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 BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
namespace osu.Framework.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true));
}
}
}
|
Add cancel/handle for value changed eventargs | using System;
using System.Collections.Generic;
using System.Text;
namespace SadConsole
{
/// <summary>
/// The old value and the value it changed to.
/// </summary>
public class ValueChangedEventArgs<T> : EventArgs
{
/// <summary>
/// The previous object.
/// </summary>
public readonly T OldValue;
/// <summary>
/// The new object.
/// </summary>
public readonly T NewValue;
/// <summary>
/// Creates a new instance of this object with the specified old and new value.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
public ValueChangedEventArgs(T oldValue, T newValue) =>
(OldValue, NewValue) = (oldValue, newValue);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace SadConsole
{
/// <summary>
/// The old value and the value it changed to.
/// </summary>
public class ValueChangedEventArgs<T> : EventArgs
{
/// <summary>
/// The previous object.
/// </summary>
public readonly T OldValue;
/// <summary>
/// The new object.
/// </summary>
public readonly T NewValue;
/// <summary>
/// When <see langword="true"/>, indicates this value change can be cancelled; otherwise <see langword="false"/>.
/// </summary>
public readonly bool SupportsCancel;
/// <summary>
/// When <see langword="true"/>, indicates this value change can be flagged as handled and stop further event handlers; otherwise <see langword="false"/>.
/// </summary>
public readonly bool SupportsHandled;
/// <summary>
/// When <see cref="SupportsCancel"/> is <see langword="true"/>, setting this property to <see langword="true"/> causes the value change to be cancelled and to stop processing further event handlers.
/// </summary>
public bool IsCancelled { get; set; }
/// <summary>
/// When <see cref="SupportsHandled"/> is <see langword="true"/>, setting this property to <see langword="true"/> flags this change as handled and to stop processing further event handlers.
/// </summary>
public bool IsHandled { get; set; }
/// <summary>
/// Creates a new instance of this object with the specified old and new value.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <param name="supportsCancel">When <see langword="true"/>, indicates this value change can be cancelled.</param>
/// <param name="supportsHandled">When <see langword="true"/>, indicates this value change can be flagged as handled and stop further event handlers.</param>
public ValueChangedEventArgs(T oldValue, T newValue, bool supportsCancel = false, bool supportsHandled = false) =>
(OldValue, NewValue, SupportsCancel, SupportsHandled) = (oldValue, newValue, supportsCancel, supportsCancel);
}
}
|
Remove old testing code in instance controller | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KenticoInspector.Core.Models;
using KenticoInspector.Core.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace KenticoInspector.WebApplication.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InstancesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<InstanceConfiguration>> Get()
{
var db = new DatabaseConfiguration();
db.User = "Me";
db.ServerName = $"S-{DateTime.Now.Millisecond}";
var admin = new AdministrationConfiguration("http://localhost", "C:\\inetpub\\");
var instance = new InstanceConfiguration(db, admin);
var fsics = new FileSystemInstanceConfigurationService();
//fsics.Upsert(instance);
return fsics.GetItems();
}
[HttpGet("{guid}")]
public ActionResult<InstanceConfiguration> Get(Guid guid)
{
var fsics = new FileSystemInstanceConfigurationService();
return fsics.GetItem(guid);
}
[HttpDelete("{guid}")]
public void Delete(Guid guid)
{
var fsics = new FileSystemInstanceConfigurationService();
fsics.Delete(guid);
}
[HttpPost]
public void Post([FromBody] InstanceConfiguration instanceConfiguration)
{
var fsics = new FileSystemInstanceConfigurationService();
fsics.Upsert(instanceConfiguration);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KenticoInspector.Core.Models;
using KenticoInspector.Core.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace KenticoInspector.WebApplication.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InstancesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<InstanceConfiguration>> Get()
{
var fsics = new FileSystemInstanceConfigurationService();
return fsics.GetItems();
}
[HttpGet("{guid}")]
public ActionResult<InstanceConfiguration> Get(Guid guid)
{
var fsics = new FileSystemInstanceConfigurationService();
return fsics.GetItem(guid);
}
[HttpDelete("{guid}")]
public void Delete(Guid guid)
{
var fsics = new FileSystemInstanceConfigurationService();
fsics.Delete(guid);
}
[HttpPost]
public Guid Post([FromBody] InstanceConfiguration instanceConfiguration)
{
var fsics = new FileSystemInstanceConfigurationService();
return fsics.Upsert(instanceConfiguration);
}
}
} |
Remove the usage of Parallel to run the populators | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Examine;
namespace Umbraco.Examine
{
/// <summary>
/// Utility to rebuild all indexes ensuring minimal data queries
/// </summary>
public class IndexRebuilder
{
private readonly IEnumerable<IIndexPopulator> _populators;
public IExamineManager ExamineManager { get; }
public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
{
_populators = populators;
ExamineManager = examineManager;
}
public bool CanRebuild(IIndex index)
{
return _populators.Any(x => x.IsRegistered(index));
}
public void RebuildIndex(string indexName)
{
if (!ExamineManager.TryGetIndex(indexName, out var index))
throw new InvalidOperationException($"No index found with name {indexName}");
index.CreateIndex(); // clear the index
foreach (var populator in _populators)
{
populator.Populate(index);
}
}
public void RebuildIndexes(bool onlyEmptyIndexes)
{
var indexes = (onlyEmptyIndexes
? ExamineManager.Indexes.Where(x => !x.IndexExists())
: ExamineManager.Indexes).ToArray();
if (indexes.Length == 0) return;
foreach (var index in indexes)
{
index.CreateIndex(); // clear the index
}
//run the populators in parallel against all indexes
Parallel.ForEach(_populators, populator => populator.Populate(indexes));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Examine;
namespace Umbraco.Examine
{
/// <summary>
/// Utility to rebuild all indexes ensuring minimal data queries
/// </summary>
public class IndexRebuilder
{
private readonly IEnumerable<IIndexPopulator> _populators;
public IExamineManager ExamineManager { get; }
public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
{
_populators = populators;
ExamineManager = examineManager;
}
public bool CanRebuild(IIndex index)
{
return _populators.Any(x => x.IsRegistered(index));
}
public void RebuildIndex(string indexName)
{
if (!ExamineManager.TryGetIndex(indexName, out var index))
throw new InvalidOperationException($"No index found with name {indexName}");
index.CreateIndex(); // clear the index
foreach (var populator in _populators)
{
populator.Populate(index);
}
}
public void RebuildIndexes(bool onlyEmptyIndexes)
{
var indexes = (onlyEmptyIndexes
? ExamineManager.Indexes.Where(x => !x.IndexExists())
: ExamineManager.Indexes).ToArray();
if (indexes.Length == 0) return;
foreach (var index in indexes)
{
index.CreateIndex(); // clear the index
}
// run each populator over the indexes
foreach(var populator in _populators)
{
populator.Populate(indexes);
}
}
}
}
|
Add VS2017 and VS2019 as known versions |
namespace Xunit
{
/// <summary>
/// Suggested values for the Visual Studio Version to run tests against.
/// </summary>
public static class VisualStudioVersion
{
/// <summary>
/// Specifies that the test should be run against all installed
/// Visual Studio versions that have a corresponding VSSDK installed.
/// </summary>
public const string All = "All";
/// <summary>
/// Specifies that the test should be run against the currently running
/// VS version (or the latest if not run within an IDE integrated runner).
/// </summary>
public const string Current = "Current";
/// <summary>
/// Specifies that the test should be run against the latest installed
/// VS version (even if different from the current version when run
/// from within an IDE integrated runner).
/// </summary>
public const string Latest = "Latest";
/// <summary>
/// Visual Studio 2012.
/// </summary>
public const string VS2012 = "11.0";
/// <summary>
/// Visual Studio 2013.
/// </summary>
public const string VS2013 = "12.0";
/// <summary>
/// Visual Studio 2015.
/// </summary>
public const string VS2015 = "14.0";
}
}
|
namespace Xunit
{
/// <summary>
/// Suggested values for the Visual Studio Version to run tests against.
/// </summary>
public static class VisualStudioVersion
{
/// <summary>
/// Specifies that the test should be run against all installed
/// Visual Studio versions that have a corresponding VSSDK installed.
/// </summary>
public const string All = "All";
/// <summary>
/// Specifies that the test should be run against the currently running
/// VS version (or the latest if not run within an IDE integrated runner).
/// </summary>
public const string Current = "Current";
/// <summary>
/// Specifies that the test should be run against the latest installed
/// VS version (even if different from the current version when run
/// from within an IDE integrated runner).
/// </summary>
public const string Latest = "Latest";
/// <summary>
/// Visual Studio 2012.
/// </summary>
public const string VS2012 = "11.0";
/// <summary>
/// Visual Studio 2013.
/// </summary>
public const string VS2013 = "12.0";
/// <summary>
/// Visual Studio 2015.
/// </summary>
public const string VS2015 = "14.0";
/// <summary>
/// Visual Studio 2017.
/// </summary>
public const string VS2017 = "15.0";
/// <summary>
/// Visual Studio 2019.
/// </summary>
public const string VS2019 = "16.0";
}
}
|
Rewrite message serialization to fix PlaySound missing flag | using Antagonists;
using UnityEngine;
namespace Messages.Server.LocalGuiMessages
{
public class AntagBannerMessage: ServerMessage
{
public string AntagName;
public string AntagSound;
public Color TextColor;
public Color BackgroundColor;
private bool playSound;
public static AntagBannerMessage Send(
GameObject player,
string antagName,
string antagSound,
Color textColor,
Color backgroundColor,
bool playSound)
{
AntagBannerMessage msg = new AntagBannerMessage
{
AntagName = antagName,
AntagSound = antagSound,
TextColor = textColor,
BackgroundColor = backgroundColor,
playSound = playSound
};
msg.SendTo(player);
return msg;
}
public override void Process()
{
UIManager.Instance.antagBanner.Show(AntagName, TextColor, BackgroundColor);
if (playSound)
{
SoundManager.Play(AntagSound);
}
}
}
} | using Antagonists;
using Audio.Managers;
using Mirror;
using UnityEngine;
namespace Messages.Server.LocalGuiMessages
{
public class AntagBannerMessage: ServerMessage
{
public string AntagName;
public string AntagSound;
public Color TextColor;
public Color BackgroundColor;
private bool PlaySound;
public static AntagBannerMessage Send(
GameObject player,
string antagName,
string antagSound,
Color textColor,
Color backgroundColor,
bool playSound)
{
AntagBannerMessage msg = new AntagBannerMessage
{
AntagName = antagName,
AntagSound = antagSound,
TextColor = textColor,
BackgroundColor = backgroundColor,
PlaySound = playSound
};
msg.SendTo(player);
return msg;
}
public override void Serialize(NetworkWriter writer)
{
base.Serialize(writer);
writer.WriteString(AntagName);
writer.WriteString(AntagSound);
writer.WriteColor(TextColor);
writer.WriteColor(BackgroundColor);
writer.WriteBoolean(PlaySound);
}
public override void Deserialize(NetworkReader reader)
{
base.Deserialize(reader);
AntagName = reader.ReadString();
AntagSound = reader.ReadString();
TextColor = reader.ReadColor();
BackgroundColor = reader.ReadColor();
PlaySound = reader.ReadBoolean();
}
public override void Process()
{
UIManager.Instance.antagBanner.Show(AntagName, TextColor, BackgroundColor);
if (PlaySound)
{
// make sure that all sound is disabled
SoundAmbientManager.StopAllAudio();
//play the spawn sound
SoundAmbientManager.PlayAudio(AntagSound);
}
}
}
} |
Remove Contact Page from Menu Seed | using Portal.CMS.Entities.Entities;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Entities.Seed
{
public static class MenuSeed
{
public static void Seed(PortalEntityModel context)
{
if (!context.Menus.Any(x => x.MenuName == "Main Menu"))
{
var menuItems = new List<MenuItem>();
menuItems.Add(new MenuItem { LinkText = "Home", LinkURL = "/Home/Index", LinkIcon = "fa-home" });
menuItems.Add(new MenuItem { LinkText = "Blog", LinkURL = "/Blog/Index", LinkIcon = "fa-book" });
menuItems.Add(new MenuItem { LinkText = "Contact", LinkURL = "/Contact/Index", LinkIcon = "fa-envelope" });
context.Menus.Add(new MenuSystem { MenuName = "Main Menu", MenuItems = menuItems });
}
}
}
} | using Portal.CMS.Entities.Entities;
using System.Collections.Generic;
using System.Linq;
namespace Portal.CMS.Entities.Seed
{
public static class MenuSeed
{
public static void Seed(PortalEntityModel context)
{
if (!context.Menus.Any(x => x.MenuName == "Main Menu"))
{
var menuItems = new List<MenuItem>();
menuItems.Add(new MenuItem { LinkText = "Home", LinkURL = "/Home/Index", LinkIcon = "fa-home" });
menuItems.Add(new MenuItem { LinkText = "Blog", LinkURL = "/Blog/Index", LinkIcon = "fa-book" });
context.Menus.Add(new MenuSystem { MenuName = "Main Menu", MenuItems = menuItems });
}
}
}
} |
Test if ExportCodeFixProviderAttribute is applied correctly - adjusted/corrected | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StyleCop.Analyzers.ReadabilityRules;
namespace StyleCop.Analyzers.Test
{
[TestClass]
public class ExportCodeFixProviderAttributeNameTest
{
[TestMethod]
public void Test()
{
var issues = new List<string>();
var codeFixProviders = typeof(SA1110OpeningParenthesisMustBeOnDeclarationLine)
.Assembly
.GetExportedTypes()
.Where(t => typeof(CodeFixProvider).IsAssignableFrom(t))
.ToList();
foreach (var codeFixProvider in codeFixProviders)
{
var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes(false)
.OfType<ExportCodeFixProviderAttribute>()
.FirstOrDefault();
if (exportCodeFixProviderAttribute == null)
{
issues.Add(string.Format("{0} should have ExportCodeFixProviderAttribute attribute", codeFixProvider.Name));
continue;
}
if (!string.Equals(exportCodeFixProviderAttribute.Name, codeFixProvider.Name,
StringComparison.InvariantCulture))
{
issues.Add(string.Format("Name parameter of ExportCodeFixProviderAttribute applied on {0} should be set to {0}", codeFixProvider.Name));
}
}
if (issues.Any())
{
Assert.Fail(string.Join("\r\t", issues));
}
}
}
} | namespace StyleCop.Analyzers.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using StyleCop.Analyzers.ReadabilityRules;
using Xunit;
public class ExportCodeFixProviderAttributeNameTest
{
public static IEnumerable<object[]> CodeFixProviderTypeData
{
get
{
var codeFixProviders = typeof(SA1110OpeningParenthesisMustBeOnDeclarationLine)
.Assembly
.GetTypes()
.Where(t => typeof(CodeFixProvider).IsAssignableFrom(t));
return codeFixProviders.Select(x => new[] { x });
}
}
[Theory]
[MemberData(nameof(CodeFixProviderTypeData))]
public void Test(Type codeFixProvider)
{
var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault();
Assert.NotNull(exportCodeFixProviderAttribute);
Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name);
Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length);
Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]);
}
}
} |
Implement the simplest possible 'Hello World' DAE | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventLogDataSource
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EventLogDataSource
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Console.WriteLine("beginDSInfo");
Console.WriteLine("endDSInfo");
Console.WriteLine("beginData");
Console.WriteLine("hello, world");
Console.WriteLine("endData");
}
}
}
|
Revert "Revert "AI detects when player is close"" | using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float speed = 6.0F;
private Animator animator;
private Vector3 moveDirection = Vector3.zero;
public float lookSpeed = 10;
private Vector3 curLoc;
private Vector3 prevLoc;
void Start(){
animator = GetComponent<Animator>();
}
void Update() {
InputCheck();
if(Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0){
animator.SetBool("isWalking", true);
}
else{
animator.SetBool("isWalking", false);
}
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - prevLoc), Time.fixedDeltaTime * lookSpeed);
}
private void InputCheck()
{
prevLoc = curLoc;
curLoc = transform.position;
if(Input.GetAxis("Horizontal") != 0)
curLoc.x += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
if(Input.GetAxis("Vertical") != 0)
curLoc.z += Input.GetAxis("Vertical") * speed * Time.deltaTime;
transform.position = curLoc;
}
}
| using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public float speed = 6.0F;
private Animator animator;
private Vector3 moveDirection = Vector3.zero;
public float lookSpeed = 10;
private Vector3 curLoc;
private Vector3 prevLoc;
void Start(){
animator = GetComponent<Animator>();
}
void Update() {
InputCheck();
if(Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0){
animator.SetBool("isWalking", true);
}
else{
animator.SetBool("isWalking", false);
}
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - prevLoc), Time.fixedDeltaTime * lookSpeed);
}
private void InputCheck()
{
prevLoc = curLoc;
curLoc = transform.position;
if(Input.GetAxis("Horizontal") != 0)
curLoc.x += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
if(Input.GetAxis("Vertical") != 0)
curLoc.z += Input.GetAxis("Vertical") * speed * Time.deltaTime;
transform.position = curLoc;
}
public void Tether(GameObject sprite){
}
}
|
Add VNDB as possible search site | using System;
using IvionWebSoft;
public class Site
{
public readonly Uri SiteUrl;
public readonly int DisplayMax;
public string GoogleSiteDeclaration
{
get { return "site:" + SiteUrl.Host; }
}
public static readonly Site None;
public static readonly Site YouTube;
public static readonly Site MyAnimeList;
public static readonly Site AniDb;
public static readonly Site MangaUpdates;
static Site()
{
None = new Site();
YouTube = new Site("https://www.youtube.com/", 3);
MyAnimeList = new Site("http://myanimelist.net/", 2);
AniDb = new Site("https://anidb.net/", 2);
MangaUpdates = new Site("https://www.mangaupdates.com/", 2);
}
Site(string url, int displayMax) : this(new Uri(url), displayMax) {}
public Site(Uri url, int displayMax)
{
SiteUrl = url;
DisplayMax = displayMax;
}
public Site()
{
SiteUrl = null;
DisplayMax = 3;
}
public SearchResults Search(string searchQuery)
{
string finalQuery;
if (SiteUrl == null)
finalQuery = searchQuery;
else
finalQuery = GoogleSiteDeclaration + " " + searchQuery;
return GoogleTools.Search(finalQuery);
}
} | using System;
using IvionWebSoft;
public class Site
{
public readonly Uri SiteUrl;
public readonly int DisplayMax;
public string GoogleSiteDeclaration
{
get { return "site:" + SiteUrl.Host; }
}
public static readonly Site None;
public static readonly Site YouTube;
public static readonly Site MyAnimeList;
public static readonly Site AniDb;
public static readonly Site MangaUpdates;
public static readonly Site VnDb;
static Site()
{
None = new Site();
YouTube = new Site("https://www.youtube.com/", 3);
MyAnimeList = new Site("http://myanimelist.net/", 2);
AniDb = new Site("https://anidb.net/", 2);
MangaUpdates = new Site("https://www.mangaupdates.com/", 2);
VnDb = new Site("https://vndb.org/", 2);
}
Site(string url, int displayMax) : this(new Uri(url), displayMax) {}
public Site(Uri url, int displayMax)
{
SiteUrl = url;
DisplayMax = displayMax;
}
public Site()
{
SiteUrl = null;
DisplayMax = 3;
}
public SearchResults Search(string searchQuery)
{
string finalQuery;
if (SiteUrl == null)
finalQuery = searchQuery;
else
finalQuery = GoogleSiteDeclaration + " " + searchQuery;
return GoogleTools.Search(finalQuery);
}
} |
Add local popover container to editor screens | // 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.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Screens.Edit
{
/// <summary>
/// TODO: eventually make this inherit Screen and add a local screen stack inside the Editor.
/// </summary>
public abstract class EditorScreen : VisibilityContainer
{
[Resolved]
protected EditorBeatmap EditorBeatmap { get; private set; }
protected override Container<Drawable> Content => content;
private readonly Container content;
public readonly EditorScreenMode Type;
protected EditorScreen(EditorScreenMode type)
{
Type = type;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = content = new Container { RelativeSizeAxes = Axes.Both };
}
protected override void PopIn()
{
this.ScaleTo(1f, 200, Easing.OutQuint)
.FadeIn(200, Easing.OutQuint);
}
protected override void PopOut()
{
this.ScaleTo(0.98f, 200, Easing.OutQuint)
.FadeOut(200, Easing.OutQuint);
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
namespace osu.Game.Screens.Edit
{
/// <summary>
/// TODO: eventually make this inherit Screen and add a local screen stack inside the Editor.
/// </summary>
public abstract class EditorScreen : VisibilityContainer
{
[Resolved]
protected EditorBeatmap EditorBeatmap { get; private set; }
protected override Container<Drawable> Content => content;
private readonly Container content;
public readonly EditorScreenMode Type;
protected EditorScreen(EditorScreenMode type)
{
Type = type;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
InternalChild = content = new PopoverContainer { RelativeSizeAxes = Axes.Both };
}
protected override void PopIn()
{
this.ScaleTo(1f, 200, Easing.OutQuint)
.FadeIn(200, Easing.OutQuint);
}
protected override void PopOut()
{
this.ScaleTo(0.98f, 200, Easing.OutQuint)
.FadeOut(200, Easing.OutQuint);
}
}
}
|
Add test data to mock view-model | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpressRunner.DesignerMocks
{
public class TestExplorerViewModel
{
private readonly TestGroup selectedTestGroup;
public TestGroup SelectedTestGroup
{
get { return selectedTestGroup; }
}
public TestExplorerViewModel()
{
selectedTestGroup = new TestGroup("Tests");
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("First test", "tests", "1")));
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("Second test", "tests", "2")));
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("Third test", "tests", "3")));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpressRunner.DesignerMocks
{
public class TestExplorerViewModel
{
private readonly TestGroup selectedTestGroup;
public TestGroup SelectedTestGroup
{
get { return selectedTestGroup; }
}
private readonly IEnumerable<TestGroup> testGroups;
public IEnumerable<TestGroup> TestGroups
{
get { return testGroups; }
}
public TestExplorerViewModel()
{
selectedTestGroup = new TestGroup("Tests");
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("First test", "tests", "1")));
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("Second test", "tests", "2")));
selectedTestGroup.Tests.Add(new TestItem(new Api.Test("Third test", "tests", "3")));
var rootGroup = new TestGroup("Root");
rootGroup.SubGroups.Add(new TestGroup("First"));
rootGroup.SubGroups.Add(new TestGroup("Second"));
rootGroup.SubGroups.Add(new TestGroup("Third"));
testGroups = Enumerable.Repeat(rootGroup, 1);
}
}
}
|
Order the throughput data by newest to oldest. | using System;
using System.Linq;
using System.Threading.Tasks;
using CommandLine;
using VstsMetrics.Abstractions;
using VstsMetrics.Extensions;
using VstsMetrics.Renderers;
namespace VstsMetrics.Commands.Throughput
{
public class ThroughputCommand : Command
{
[Option('d', "doneState", DefaultValue = "Done", HelpText = "The work item state you project is using to indicate a work item is 'Done'.")]
public string DoneState { get; set; }
[Option('s', "since", Required = false, DefaultValue = null, HelpText = "Only calculate throuput for work items that entered the done state on or after this date.")]
public DateTime? Since { get; set; }
public override async Task Execute()
{
var workItemClient = WorkItemClientFactory.Create(ProjectCollectionUrl, PatToken);
var workItemReferences = await workItemClient.QueryWorkItemsAsync(ProjectName, Query);
var calculator = new WorkItemDoneDateAggregator(workItemClient, DoneState);
var workItemDoneDates = await calculator.AggregateAsync(workItemReferences);
var weeklyThroughput =
workItemDoneDates
.GroupBy(t => t.DoneDate.StartOfWeek(DayOfWeek.Monday))
.OrderBy(t => t.Key)
.Select(g => new {WeekBeginning = g.Key, Throughput = g.Count()});
OutputRendererFactory.Create(OutputFormat).Render(weeklyThroughput);
}
public ThroughputCommand(IWorkItemClientFactory workItemClientFactory, IOutputRendererFactory outputRendererFactory)
: base(workItemClientFactory, outputRendererFactory)
{
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using CommandLine;
using VstsMetrics.Abstractions;
using VstsMetrics.Extensions;
using VstsMetrics.Renderers;
namespace VstsMetrics.Commands.Throughput
{
public class ThroughputCommand : Command
{
[Option('d', "doneState", DefaultValue = "Done", HelpText = "The work item state you project is using to indicate a work item is 'Done'.")]
public string DoneState { get; set; }
[Option('s', "since", Required = false, DefaultValue = null, HelpText = "Only calculate throuput for work items that entered the done state on or after this date.")]
public DateTime? Since { get; set; }
public override async Task Execute()
{
var workItemClient = WorkItemClientFactory.Create(ProjectCollectionUrl, PatToken);
var workItemReferences = await workItemClient.QueryWorkItemsAsync(ProjectName, Query);
var calculator = new WorkItemDoneDateAggregator(workItemClient, DoneState);
var workItemDoneDates = await calculator.AggregateAsync(workItemReferences);
var weeklyThroughput =
workItemDoneDates
.GroupBy(t => t.DoneDate.StartOfWeek(DayOfWeek.Monday))
.OrderByDescending(t => t.Key)
.Select(g => new {WeekBeginning = g.Key, Throughput = g.Count()});
OutputRendererFactory.Create(OutputFormat).Render(weeklyThroughput);
}
public ThroughputCommand(IWorkItemClientFactory workItemClientFactory, IOutputRendererFactory outputRendererFactory)
: base(workItemClientFactory, outputRendererFactory)
{
}
}
} |
Set the same delivery time for Reprints Desk as for Subito | using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;
namespace Chalmers.ILL.Providers
{
public class ProviderService : IProviderService
{
IOrderItemSearcher _orderItemsSearcher;
public ProviderService(IOrderItemSearcher orderItemsSearcher)
{
_orderItemsSearcher = orderItemsSearcher;
}
public IEnumerable<String> FetchAndCreateListOfUsedProviders()
{
return _orderItemsSearcher.AggregatedProviders();
}
public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
{
int res = 168;
if (!String.IsNullOrWhiteSpace(providerName) && providerName.ToLower().Contains("subito"))
{
res = 24;
}
return res;
}
}
} | using Chalmers.ILL.Models;
using Examine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chalmers.ILL.Extensions;
using Chalmers.ILL.OrderItems;
namespace Chalmers.ILL.Providers
{
public class ProviderService : IProviderService
{
IOrderItemSearcher _orderItemsSearcher;
public ProviderService(IOrderItemSearcher orderItemsSearcher)
{
_orderItemsSearcher = orderItemsSearcher;
}
public IEnumerable<String> FetchAndCreateListOfUsedProviders()
{
return _orderItemsSearcher.AggregatedProviders();
}
public int GetSuggestedDeliveryTimeInHoursForProvider(string providerName)
{
int res = 168;
if (!String.IsNullOrWhiteSpace(providerName) && (providerName.ToLower().Contains("subito") || providerName.ToLower().Contains("reprints desk")))
{
res = 24;
}
return res;
}
}
} |
Tidy up class xmldoc and naming | // 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.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
using osu.Framework.Graphics.Primitives;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ITextureUpload
{
public AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrame;
public ReadOnlySpan<Rgba32> Data => ReadOnlySpan<Rgba32>.Empty;
public int Level => 0;
public RectangleI Bounds { get; set; }
public PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame cotaining the data to be uploaded
/// </summary>
/// <param name="frame">The libav frame to upload.</param>
/// <param name="free">A function to free the frame on disposal.</param>
public VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate free)
{
Frame = frame;
freeFrame = free;
}
#region IDisposable Support
public void Dispose()
{
fixed (AVFrame** ptr = &Frame)
freeFrame(ptr);
}
#endregion
}
}
| // 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.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
using osu.Framework.Graphics.Primitives;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ITextureUpload
{
public readonly AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate;
public ReadOnlySpan<Rgba32> Data => ReadOnlySpan<Rgba32>.Empty;
public int Level => 0;
public RectangleI Bounds { get; set; }
public PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame containing the data to be uploaded.
/// </summary>
/// <param name="frame">The frame to upload.</param>
/// <param name="freeFrameDelegate">A function to free the frame on disposal.</param>
public VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate)
{
Frame = frame;
this.freeFrameDelegate = freeFrameDelegate;
}
#region IDisposable Support
public void Dispose()
{
fixed (AVFrame** ptr = &Frame)
freeFrameDelegate(ptr);
}
#endregion
}
}
|
Improve error messages for invalid Guids in ItemData | using System;
using Sitecore.Data;
namespace AutoSitecore
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class ItemDataAttribute : Attribute
{
public static readonly ItemDataAttribute Null = new ItemDataAttribute();
public ItemDataAttribute(string name=null, string id = null, string templateId= null)
{
this.Name = name;
ID result;
if (ID.TryParse(templateId, out result))
{
TemplateId = result;
}
else
{
TemplateId = ID.Null;
}
ID result2;
if (ID.TryParse(id, out result2))
{
ItemId = result2;
}
else
{
ItemId = ID.Undefined;
}
}
public string Name { get; }
public ID TemplateId { get; }
public ID ItemId { get; }
}
} | using System;
using Sitecore.Data;
namespace AutoSitecore
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class ItemDataAttribute : Attribute
{
public static readonly ItemDataAttribute Null = new ItemDataAttribute();
public ItemDataAttribute(string name=null, string itemId = null, string templateId= null)
{
Name = name;
ItemId = ID.Parse(itemId, ID.Undefined);
TemplateId = ID.Parse(templateId, ID.Undefined);
}
public string Name { get; }
public ID TemplateId { get; }
public ID ItemId { get; }
}
} |
Remove PasswordMode and PasswordChar from interface definition | namespace Internal.ReadLine.Abstractions
{
internal interface IConsole
{
int CursorLeft { get; }
int CursorTop { get; }
int BufferWidth { get; }
int BufferHeight { get; }
bool PasswordMode { get; set; }
char PasswordChar { get; set; }
void SetCursorPosition(int left, int top);
void SetBufferSize(int width, int height);
void Write(string value);
void WriteLine(string value);
}
} | namespace Internal.ReadLine.Abstractions
{
internal interface IConsole
{
int CursorLeft { get; }
int CursorTop { get; }
int BufferWidth { get; }
int BufferHeight { get; }
void SetCursorPosition(int left, int top);
void SetBufferSize(int width, int height);
void Write(string value);
void WriteLine(string value);
}
} |
Add dbus-sharp-glib to friend assemblies | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
|
Add CompetitionPlatformUser to Identity models. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompetitionPlatform.Models
{
public class AuthenticateModel
{
public string FullName { get; set; }
public string Password { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompetitionPlatform.Models
{
public class AuthenticateModel
{
public string FullName { get; set; }
public string Password { get; set; }
}
public class CompetitionPlatformUser
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetFullName()
{
return FirstName + " " + LastName;
}
}
}
|
Add PATCH to http verbs enumeration | // IPAddressType.cs
// Script#/Libraries/Node/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace NodeApi.Network {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptConstants(UseNames = true)]
public enum HttpVerb {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS
}
}
| // IPAddressType.cs
// Script#/Libraries/Node/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace NodeApi.Network {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptConstants(UseNames = true)]
public enum HttpVerb {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
PATCH
}
}
|
Add new test for NotNull with provided message. | using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNull
{
[TestFixture]
public class When_argument_is_null
{
[Test]
public void Should_throw_argumentnullexception ()
{
Assert.Throws<ArgumentNullException> (() => Guard.NotNull (null, null));
}
[Test]
public void Should_include_argument_name_in_exception_message ()
{
object what = null;
Assert.Throws<ArgumentNullException> (() => Guard.NotNull (what, "what"), "what");
}
}
}
| using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Guard.For_NotNull
{
[TestFixture]
public class When_argument_is_null
{
[Test]
public void Should_throw_argumentnullexception ()
{
Assert.Throws<ArgumentNullException> (() => Guard.NotNull (null, null));
}
[Test]
public void Should_include_argument_name_in_exception_message ()
{
object what = null;
Assert.Throws<ArgumentNullException> (() => Guard.NotNull (what, "what"), "what");
}
[Test]
public void Should_include_message_if_provided ()
{
object what = null;
Assert.IsTrue (
Assert.Throws<ArgumentNullException> (() => Guard.NotNull (what, "what", "the real deal"))
.Message.Contains("the real deal")
);
}
}
}
|
Add test for invalid range | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CSharp.Functional.Tests
{
public class RangeTests
{
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerable(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable>(result);
}
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerableOfIntegers(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable<int>>(result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeBeginssAtStartValue(int start, int end)
{
var result = F.Range(start, end).First();
Assert.Equal(start, result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeTerminatesAtEndValue(int start, int end)
{
var result = F.Range(start, end).Last();
Assert.Equal(end, result);
}
}
} | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CSharp.Functional.Tests
{
public class RangeTests
{
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerable(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable>(result);
}
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerableOfIntegers(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable<int>>(result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeBeginssAtStartValue(int start, int end)
{
var result = F.Range(start, end).First();
Assert.Equal(start, result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeTerminatesAtEndValue(int start, int end)
{
var result = F.Range(start, end).Last();
Assert.Equal(end, result);
}
[Theory]
[InlineData(0, -3)]
[InlineData(5, 2)]
public void RangeReturnsEmptyEnumerableOnInvalidRanges(int start, int end)
{
var result = F.Range(start, end).ToList();
Assert.Equal(0, result.Count);
}
}
} |
Simplify login docs region & only show action | // Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
namespace GoogleCloudSamples.Controllers
{
// [START login]
public class SessionController : Controller
{
public void Login()
{
// Redirect to the Google OAuth 2.0 user consent screen
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
"Google"
);
}
// ...
// [END login]
// [START logout]
public ActionResult Logout()
{
Request.GetOwinContext().Authentication.SignOut();
return Redirect("/");
}
// [END logout]
}
}
| // Copyright(c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
namespace GoogleCloudSamples.Controllers
{
public class SessionController : Controller
{
// [START login]
public void Login()
{
// Redirect to the Google OAuth 2.0 user consent screen
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
"Google"
);
}
// [END login]
// [START logout]
public ActionResult Logout()
{
Request.GetOwinContext().Authentication.SignOut();
return Redirect("/");
}
// [END logout]
}
}
|
Use type inference in type definition | using MyDocs.Common.Contract.Service;
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using MyDocs.WindowsStore.Storage;
using System;
using System.Threading.Tasks;
using Windows.Media.Capture;
namespace MyDocs.WindowsStore.Service
{
public class CameraService : ICameraService
{
public async Task<Photo> CapturePhotoAsync()
{
CameraCaptureUI camera = new CameraCaptureUI();
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file == null) {
return null;
}
return new Photo(DateTime.Now.ToString("G"), new WindowsStoreFile(file));
}
}
}
| using MyDocs.Common.Contract.Service;
using MyDocs.Common.Contract.Storage;
using MyDocs.Common.Model;
using MyDocs.WindowsStore.Storage;
using System;
using System.Threading.Tasks;
using Windows.Media.Capture;
namespace MyDocs.WindowsStore.Service
{
public class CameraService : ICameraService
{
public async Task<Photo> CapturePhotoAsync()
{
var camera = new CameraCaptureUI();
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file == null) {
return null;
}
return new Photo(DateTime.Now.ToString("G"), new WindowsStoreFile(file));
}
}
}
|
Refactor test to use AutoCommandData | using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Xunit;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
private readonly IFixture _fixture;
public CreateCommandTest()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
}
[Fact]
public void ShouldCreateApplication()
{
var client = _fixture.Freeze<Mock<IAppHarborClient>>();
var command = _fixture.CreateAnonymous<CreateCommand>();
command.Execute(new string[] { "foo", "var" });
client.Verify(x => x.CreateApplication("bar", "baz"), Times.Once());
}
}
}
| using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
private readonly IFixture _fixture;
public CreateCommandTest()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
}
[Theory, AutoCommandData]
public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command)
{
command.Execute(new string[] { "foo", "bar" });
client.Verify(x => x.CreateApplication("foo", "bar"), Times.Once());
}
}
}
|
Change DestinationFilenamePrefix to be a required field | using System.ComponentModel.DataAnnotations;
using API.WindowsService.Validators;
using Contract;
using FluentValidation.Attributes;
namespace API.WindowsService.Models
{
[Validator(typeof(AudioRequestValidator))]
public class AudioJobRequestModel : JobRequestModel
{
[Required]
public AudioDestinationFormat[] Targets { get; set; }
public string DestinationFilenamePrefix { get; set; }
[Required]
public string SourceFilename { get; set; }
}
} | using System.ComponentModel.DataAnnotations;
using API.WindowsService.Validators;
using Contract;
using FluentValidation.Attributes;
namespace API.WindowsService.Models
{
[Validator(typeof(AudioRequestValidator))]
public class AudioJobRequestModel : JobRequestModel
{
[Required]
public AudioDestinationFormat[] Targets { get; set; }
[Required]
public string DestinationFilenamePrefix { get; set; }
[Required]
public string SourceFilename { get; set; }
}
} |
Add keyword "delay" to hold-to-confirm activation time setting | // 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.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.UserInterface
{
public class GeneralSettings : SettingsSubsection
{
protected override LocalisableString Header => UserInterfaceStrings.GeneralHeader;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = UserInterfaceStrings.CursorRotation,
Current = config.GetBindable<bool>(OsuSetting.CursorRotation)
},
new SettingsSlider<float, SizeSlider>
{
LabelText = UserInterfaceStrings.MenuCursorSize,
Current = config.GetBindable<float>(OsuSetting.MenuCursorSize),
KeyboardStep = 0.01f
},
new SettingsCheckbox
{
LabelText = UserInterfaceStrings.Parallax,
Current = config.GetBindable<bool>(OsuSetting.MenuParallax)
},
new SettingsSlider<double, TimeSlider>
{
LabelText = UserInterfaceStrings.HoldToConfirmActivationTime,
Current = config.GetBindable<double>(OsuSetting.UIHoldActivationDelay),
KeyboardStep = 50
},
};
}
}
}
| // 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.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
namespace osu.Game.Overlays.Settings.Sections.UserInterface
{
public class GeneralSettings : SettingsSubsection
{
protected override LocalisableString Header => UserInterfaceStrings.GeneralHeader;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = UserInterfaceStrings.CursorRotation,
Current = config.GetBindable<bool>(OsuSetting.CursorRotation)
},
new SettingsSlider<float, SizeSlider>
{
LabelText = UserInterfaceStrings.MenuCursorSize,
Current = config.GetBindable<float>(OsuSetting.MenuCursorSize),
KeyboardStep = 0.01f
},
new SettingsCheckbox
{
LabelText = UserInterfaceStrings.Parallax,
Current = config.GetBindable<bool>(OsuSetting.MenuParallax)
},
new SettingsSlider<double, TimeSlider>
{
LabelText = UserInterfaceStrings.HoldToConfirmActivationTime,
Current = config.GetBindable<double>(OsuSetting.UIHoldActivationDelay),
Keywords = new[] { @"delay" },
KeyboardStep = 50
},
};
}
}
}
|
Refactor to build on Visual Studio 2013 | using System;
using System.Windows.Input;
namespace OutlookMatters.Settings
{
public class SaveCommand : ICommand
{
private readonly ISettingsSaveService _saveService;
private readonly IClosableWindow _window;
public SaveCommand(ISettingsSaveService saveService, IClosableWindow window)
{
_saveService = saveService;
_window = window;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var viewModel = parameter as SettingsViewModel;
if (viewModel == null)
{
throw new ArgumentException(@"Invalid ViewModel", nameof(parameter));
}
var settings = new Settings(
viewModel.MattermostUrl,
viewModel.TeamId,
viewModel.ChannelId,
viewModel.Username,
Properties.Settings.Default.ChannelsMap
);
_saveService.Save(settings);
_window.Close();
}
public event EventHandler CanExecuteChanged;
}
} | using System;
using System.Windows.Input;
namespace OutlookMatters.Settings
{
public class SaveCommand : ICommand
{
private readonly ISettingsSaveService _saveService;
private readonly IClosableWindow _window;
public SaveCommand(ISettingsSaveService saveService, IClosableWindow window)
{
_saveService = saveService;
_window = window;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var viewModel = parameter as SettingsViewModel;
if (viewModel == null)
{
throw new ArgumentException(@"Invalid ViewModel ", "parameter");
}
var settings = new Settings(
viewModel.MattermostUrl,
viewModel.TeamId,
viewModel.ChannelId,
viewModel.Username,
Properties.Settings.Default.ChannelsMap
);
_saveService.Save(settings);
_window.Close();
}
public event EventHandler CanExecuteChanged;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.