Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix that the flag prevents serialization.
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; namespace MsgPack.Rpc { internal sealed class ExceptionModifiers { public static readonly ExceptionModifiers IsMatrioshkaInner = new ExceptionModifiers(); private ExceptionModifiers() { } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; namespace MsgPack.Rpc { internal static class ExceptionModifiers { public static readonly object IsMatrioshkaInner = String.Intern( typeof( ExceptionModifiers ).FullName + ".IsMatrioshkaInner" ); } }
Cover ALL forward/back navigation cases
#region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserRequestHandler : IRequestHandler { #region Public Methods public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm, string scheme, ref string username, ref string password) { // Let the Chromium web browser handle the event return false; } public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) { // Let the Chromium web browser handle the event return null; } public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) { // Disable browser forward/back navigation with keyboard keys if(request.TransitionType == (TransitionType.Explicit | TransitionType.ForwardBack)) { return true; } // Let the Chromium web browser handle the event return false; } public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) { // Let the Chromium web browser handle the event return false; } public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) { // Let the Chromium web browser handle the event return false; } public void OnPluginCrashed(IWebBrowser browser, string pluginPath) { // No implementation required } public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) { // No implementation required } #endregion } }
#region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserRequestHandler : IRequestHandler { #region Public Methods public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm, string scheme, ref string username, ref string password) { // Let the Chromium web browser handle the event return false; } public ResourceHandler GetResourceHandler(IWebBrowser browser, IRequest request) { // Let the Chromium web browser handle the event return null; } public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, bool isRedirect) { // Disable browser forward/back navigation with keyboard keys if((request.TransitionType & TransitionType.ForwardBack) != 0) { return true; } // Let the Chromium web browser handle the event return false; } public bool OnBeforePluginLoad(IWebBrowser browser, string url, string policyUrl, IWebPluginInfo info) { // Let the Chromium web browser handle the event return false; } public bool OnBeforeResourceLoad(IWebBrowser browser, IRequest request, IResponse response) { // Let the Chromium web browser handle the event return false; } public void OnPluginCrashed(IWebBrowser browser, string pluginPath) { // No implementation required } public void OnRenderProcessTerminated(IWebBrowser browser, CefTerminationStatus status) { // No implementation required } #endregion } }
Rename Email struct as EmailAddress; refactor as appropriate
using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct EmailAddress { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<EmailAddress> _emailAddresses; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<EmailAddress> emailAddresses) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emailAddresses = emailAddresses; } #endregion } }
Make internals visible to Newtonsoft.Json
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("StripeTests")]
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Newtonsoft.Json")] [assembly: InternalsVisibleTo("StripeTests")]
Use default error messages in demo app.
using Dolstagis.Web; using Dolstagis.Web.Sessions; namespace WebApp { public class HomeModule : Module { public HomeModule() { Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>(); AddStaticFiles("~/content"); AddViews("~/views"); AddViews("~/errors"); AddHandler<Index>(); } } }
using Dolstagis.Web; using Dolstagis.Web.Sessions; namespace WebApp { public class HomeModule : Module { public HomeModule() { Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>(); AddStaticFiles("~/content"); AddViews("~/views"); // Uncomment the following line to use custom error messages. // AddViews("~/errors"); AddHandler<Index>(); } } }
Add more tests for enums
using System; using System.Linq.Expressions; using Xunit; namespace DelegateDecompiler.Tests { public class EnumTests : DecompilerTestsBase { public enum TestEnum { Foo, Bar } [Fact] public void TestEnumParameterEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar; Func<TestEnum, bool> compiled = x => x == TestEnum.Bar; Test(expected, compiled); } [Fact] public void TestEnumConstantEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x; Func<TestEnum, bool> compiled = x => TestEnum.Bar == x; Test(expected, compiled); } } }
using System; using System.Linq.Expressions; using Xunit; namespace DelegateDecompiler.Tests { public class EnumTests : DecompilerTestsBase { public enum TestEnum { Foo, Bar } [Fact] public void TestEnumParameterEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x == TestEnum.Bar; Func<TestEnum, bool> compiled = x => x == TestEnum.Bar; Test(expected, compiled); } [Fact] public void TestEnumConstantEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar == x; Func<TestEnum, bool> compiled = x => TestEnum.Bar == x; Test(expected, compiled); } [Fact] public void TestEnumParametersEqual() { Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x == y; Func<TestEnum, TestEnum, bool> compiled = (x, y) => x == y; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumParameterNotEqualsEnumConstant() { Expression<Func<TestEnum, bool>> expected = x => x != TestEnum.Bar; Func<TestEnum, bool> compiled = x => x != TestEnum.Bar; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumConstantNotEqualsEnumParameter() { Expression<Func<TestEnum, bool>> expected = x => TestEnum.Bar != x; Func<TestEnum, bool> compiled = x => TestEnum.Bar != x; Test(expected, compiled); } [Fact(Skip = "Needs optimization")] public void TestEnumParametersNotEqual() { Expression<Func<TestEnum, TestEnum, bool>> expected = (x, y) => x != y; Func<TestEnum, TestEnum, bool> compiled = (x, y) => x != y; Test(expected, compiled); } } }
Improve tests with theory test cases
using Ardalis.GuardClauses; using System; using Xunit; namespace GuardClauses.UnitTests { public class GuardAgainsOutOfRange { [Fact] public void DoesNothingGivenInRangeValueUsingShortcutMethod() { Guard.AgainsOutOfRange(2, "index", 1, 5); } [Fact] public void DoesNothingGivenInRangeValueUsingExtensionMethod() { Guard.Against.OutOfRange(2, "index", 1, 5); } [Fact] public void ThrowsGivenOutOfRangeValueUsingShortcutMethod() { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(5, "index", 1, 4)); } [Fact] public void ThrowsGivenOutOfRangeValueUsingExtensionMethod() { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(5, "index", 1, 4)); } } }
using Ardalis.GuardClauses; using System; using Xunit; namespace GuardClauses.UnitTests { public class GuardAgainsOutOfRange { [Theory] [InlineData(1, 1, 5)] [InlineData(2, 1, 5)] [InlineData(3, 1, 5)] public void DoesNothingGivenInRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo) { Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo); } [Theory] [InlineData(1, 1, 5)] [InlineData(2, 1, 5)] [InlineData(3, 1, 5)] public void DoesNothingGivenInRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo) { Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo); } [Theory] [InlineData(-1, 1, 5)] [InlineData(0, 1, 5)] [InlineData(6, 1, 5)] public void ThrowsGivenOutOfRangeValueUsingShortcutMethod(int input, int rangeFrom, int rangeTo) { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.AgainsOutOfRange(input, "index", rangeFrom, rangeTo)); } [Theory] [InlineData(-1, 1, 5)] [InlineData(0, 1, 5)] [InlineData(6, 1, 5)] public void ThrowsGivenOutOfRangeValueUsingExtensionMethod(int input, int rangeFrom, int rangeTo) { Assert.Throws<ArgumentOutOfRangeException>(() => Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo)); } } }
Exclude AppBuilder test from running on Mono.
namespace Nancy.Owin.Tests { using System; using global::Owin; using Microsoft.Owin.Testing; using Nancy.Testing; using Xunit; public class AppBuilderExtensionsFixture { /*[Fact] public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() { // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>()); using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) { // When var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result; // Then Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); } }*/ public class TestModule : NancyModule { public TestModule() { Get["/"] = _ => HttpStatusCode.OK; } } } }
namespace Nancy.Owin.Tests { using System; using global::Owin; using Microsoft.Owin.Testing; using Nancy.Testing; using Xunit; public class AppBuilderExtensionsFixture { #if !__MonoCS__ [Fact] public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() { // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>()); using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) { // When var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result; // Then Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); } } #endif public class TestModule : NancyModule { public TestModule() { Get["/"] = _ => HttpStatusCode.OK; } } } }
Validate Username and ApiKey from appSettings.
using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { // ReSharper disable once InconsistentNaming private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings(); private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public static AppSettingsLibratoSettings Settings { get { return settings; } } public string Username { get { return ConfigurationManager.AppSettings["Librato.Username"]; } } public string ApiKey { get { return ConfigurationManager.AppSettings["Librato.ApiKey"]; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }
using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { // ReSharper disable once InconsistentNaming private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings(); private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public static AppSettingsLibratoSettings Settings { get { return settings; } } public string Username { get { var username = ConfigurationManager.AppSettings["Librato.Username"]; if (string.IsNullOrEmpty(username)) { throw new ConfigurationErrorsException("Librato.Username is required and cannot be empty"); } return username; } } public string ApiKey { get { var apiKey = ConfigurationManager.AppSettings["Librato.ApiKey"]; if (string.IsNullOrEmpty(apiKey)) { throw new ConfigurationErrorsException("Librato.ApiKey is required and cannot be empty"); } return apiKey; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }
Fix issue where ratio was always returning "1"
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return Width / Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
Change InitializeStackTrace helper to store trace in Data
// 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. namespace System.Diagnostics { /// <summary>Provides a set of static methods for working with Exceptions.</summary> internal static class ExceptionHelpers { public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception { Debug.Assert(e != null); Debug.Assert(e.StackTrace == null); try { throw e; } catch { return e; } } } }
// 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. namespace System.Diagnostics { /// <summary>Provides a set of static methods for working with Exceptions.</summary> internal static class ExceptionHelpers { public static TException InitializeStackTrace<TException>(this TException e) where TException : Exception { Debug.Assert(e != null); // Ideally we'd be able to populate e.StackTrace with the current stack trace. // We could throw the exception and catch it, but the populated StackTrace would // not extend beyond this frame. Instead, we grab a stack trace and store it into // the exception's data dictionary, at least making the info available for debugging, // albeit not part of the string returned by e.ToString() or e.StackTrace. e.Data["StackTrace"] = Environment.StackTrace; return e; } } }
Fix imports on admin logs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.IO; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { // Admin Tasks: // Add/Remove Users // Backup SQLite Db // Scrub Soldier Data private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Logs() { byte[] data; using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd()); } return File(data, "text/plain"); } } }
Use CRLF instead of LF.
// 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; namespace osu.Game.Audio { public class SampleInfoList : List<SampleInfo> { public SampleInfoList() { } public SampleInfoList(IEnumerable<SampleInfo> elements) { AddRange(elements); } } }
// 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; namespace osu.Game.Audio { public class SampleInfoList : List<SampleInfo> { public SampleInfoList() { } public SampleInfoList(IEnumerable<SampleInfo> elements) { AddRange(elements); } } }
Update Error Layout to Standardise Against Standard Layout
@model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel @{ ViewBag.Title = "Error"; Layout = ""; } <!DOCTYPE html> <html lang="en-gb"> <head> <title>Portal CMS: @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Framework") <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script> <script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script> @RenderSection("HEADScripts", false) </head> <body> <nav class="navbar navbar-inverse"><div class="container-fluid"><div class="navbar-header"><a class="navbar-brand" href="@Url.Action("Index", "Home", new { area = "" })">Portal CMS</a></div></div></nav> @RenderBody() @RenderSection("DOMScripts", false) @Scripts.Render("~/Resources/JavaScript/Bootstrap") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation") @Scripts.Render("~/Resources/JavaScript/Bootstrap/Modal") @Scripts.Render("~/Resources/JavaScript/Framework/Global") </body> </html>
@model Portal.CMS.Web.Areas.Builder.ViewModels.Build.CustomViewModel @{ ViewBag.Title = "Error"; Layout = ""; } <!DOCTYPE html> <html lang="en-gb"> <head> <title>Portal CMS: @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Framework") @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body class="page-builder"> <nav class="navbar navbar-inverse"><div class="container-fluid"><div class="navbar-header"><a class="navbar-brand" href="@Url.Action("Index", "Home", new { area = "" })">Portal CMS</a></div></div></nav> @Html.Partial("_NavBar") @RenderBody() @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>
Destroy NetworkController when going back to menu
using UnityEngine; using System.Collections; public class BackToMenu : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Escape)){ Application.LoadLevel(0); GameObject GUI; GUI = GameObject.Find("GUISYSTEM"); Destroy(GUI); } } }
using UnityEngine; using System.Collections; public class BackToMenu : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Escape)){ Application.LoadLevel(0); GameObject guiSys; guiSys = GameObject.Find("GUISYSTEM"); Destroy(guiSys); GameObject networkC; networkC = GameObject.Find("NetworkController"); Destroy(networkC); } } }
Fix NUGET_PACKAGES folder when running tests.
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", RepoInfo.PackagesPath); return command; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.NET.TestFramework.Commands { public class MSBuildTest { public static readonly MSBuildTest Stage0MSBuild = new MSBuildTest(RepoInfo.DotNetHostPath); private string DotNetHostPath { get; } public MSBuildTest(string dotNetHostPath) { DotNetHostPath = dotNetHostPath; } public ICommand CreateCommandForTarget(string target, params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"/t:{target}"); return CreateCommand(newArgs.ToArray()); } private ICommand CreateCommand(params string[] args) { var newArgs = args.ToList(); newArgs.Insert(0, $"msbuild"); ICommand command = Command.Create(DotNetHostPath, newArgs); // Set NUGET_PACKAGES environment variable to match value from build.ps1 command = command.EnvironmentVariable("NUGET_PACKAGES", Path.Combine(RepoInfo.RepoRoot, "packages")); return command; } } }
Split the commit message into the subject line and the body
using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format("{0}{1}", Environment.NewLine, body); arguments += "\""; } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } }
using System; using System.Threading; namespace GitHub.Unity { class GitCommitTask : ProcessTask<string> { private const string TaskName = "git commit"; private readonly string arguments; public GitCommitTask(string message, string body, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(message, "message"); Name = TaskName; arguments = "commit "; arguments += String.Format(" -m \"{0}\"", message); if (!String.IsNullOrEmpty(body)) arguments += String.Format(" -m \"{0}\"", body); } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } }
Add dynamic left margin for line parts
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); line.Add(part); usedSpace += part.Length; } return String.Join("", line); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
using System; using System.Collections.Generic; namespace Hangman { public class Row { public Cell[] Cells; private int Width; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; Width = width; return String.Join("\n", Lines()); } private string[] Lines() { var lines = new List<string>(); for (var i = 0; i < MaxCellDepth(); i++) { var line = LineAtIndex(i); lines.Add(String.Join("", line)); } return lines.ToArray(); } private string LineAtIndex(int index) { var line = new List<string>(); int usedSpace = 0; foreach (var cell in Cells) { var part = cell.LineAtIndex(index); var spacing = SpacingFor(cell); line.Add(spacing + part); usedSpace += part.Length; } return String.Join("", line); } private string SpacingFor(Cell cell) { return new String(' ', 4); } private int MaxCellDepth() { int max = 0; foreach (var cell in Cells) { max = Math.Max(max, cell.Depth()); } return max; } } }
Use IsAssignableTo instead of IsAssignableFrom
using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } var fallbackTypeInfo = fallbackType.GetTypeInfo(); var serviceTypeInfo = ServiceType.GetTypeInfo(); if (!serviceTypeInfo.IsAssignableFrom(fallbackTypeInfo)) { throw new InvalidOperationException($@"Type ""{fallbackTypeInfo.FullName}"" is not assignable to ""${serviceTypeInfo.FullName}""."); } yield return ServiceType; } } }
using System; using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; namespace Scrutor { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ServiceDescriptorAttribute : Attribute { public ServiceDescriptorAttribute() : this(null) { } public ServiceDescriptorAttribute(Type serviceType) : this(serviceType, ServiceLifetime.Transient) { } public ServiceDescriptorAttribute(Type serviceType, ServiceLifetime lifetime) { ServiceType = serviceType; Lifetime = lifetime; } public Type ServiceType { get; } public ServiceLifetime Lifetime { get; } public IEnumerable<Type> GetServiceTypes(Type fallbackType) { if (ServiceType == null) { yield return fallbackType; var fallbackTypes = fallbackType.GetBaseTypes(); foreach (var type in fallbackTypes) { if (type == typeof(object)) { continue; } yield return type; } yield break; } if (!fallbackType.IsAssignableTo(ServiceType)) { throw new InvalidOperationException($@"Type ""{fallbackType.FullName}"" is not assignable to ""${ServiceType.FullName}""."); } yield return ServiceType; } } }
Fix issue where Get-AzureRmContext does not allow user to silently continue
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Profile.Models; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Common; using System.Management.Automation; namespace Microsoft.Azure.Commands.Profile { /// <summary> /// Cmdlet to get current context. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmContext")] [OutputType(typeof(PSAzureContext))] public class GetAzureRMContextCommand : AzureRMCmdlet { /// <summary> /// Gets the current default context. /// </summary> protected override AzureContext DefaultContext { get { if (DefaultProfile == null || DefaultProfile.Context == null) { WriteError(new ErrorRecord( new PSInvalidOperationException("Run Login-AzureRmAccount to login."), string.Empty, ErrorCategory.AuthenticationError, null)); } return DefaultProfile.Context; } } public override void ExecuteCmdlet() { WriteObject((PSAzureContext)AzureRmProfileProvider.Instance.Profile.Context); } } }
Refactor NHibernate module for clarity
using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { // Configuration builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); }) .SingleInstance(); // ISessionFactory builder .Register((ctx, parameters) => { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); }) .SingleInstance(); // ISession builder .Register((ctx, parameters) => { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); }) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } } }
using System; using Agiil.Data; using Agiil.Domain; using Autofac; using NHibernate; using NHibernate.Cfg; namespace Agiil.Bootstrap.Data { public class NHibernateModule : Module { protected override void Load(ContainerBuilder builder) { builder .Register(BuildNHibernateConfiguration) .SingleInstance(); builder .Register(BuildSessionFactory) .SingleInstance(); builder .Register(BuildSession) .InstancePerMatchingLifetimeScope(ComponentScope.ApplicationConnection); } Configuration BuildNHibernateConfiguration(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactoryFactory>(); return factory.GetConfiguration(); } ISessionFactory BuildSessionFactory(IComponentContext ctx) { var config = ctx.Resolve<Configuration>(); return config.BuildSessionFactory(); } ISession BuildSession(IComponentContext ctx) { var factory = ctx.Resolve<ISessionFactory>(); return factory.OpenSession(); } } }
Add InternalsVisibleTo for T4 Tests
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.0.0")] [assembly: AssemblyFileVersionAttribute("1.0.*")]
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Vipr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Vipr")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("ViprCliUnitTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: AssemblyCompanyAttribute("Microsoft")] [assembly: AssemblyVersionAttribute("1.0.*")] [assembly: AssemblyFileVersionAttribute("1.0.*")] [assembly: InternalsVisibleTo("T4TemplateWriterTests")]
Move conditional compilation around namespace.
namespace Cassette.Views { #if NET35 public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } #endif }
#if NET35 namespace Cassette.Views { public interface IHtmlString { string ToHtmlString(); } public class HtmlString : IHtmlString { string _htmlString; public HtmlString(string htmlString) { this._htmlString = htmlString; } public string ToHtmlString() { return _htmlString; } public override string ToString() { return this._htmlString; } } } #endif
Update tests with new behaviour
// 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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = "invariant"; private const string current_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(current_culture, true, current_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; case current_culture: expectedCulture = CultureInfo.CurrentCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } }
// 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.Globalization; using NUnit.Framework; using osu.Framework.Localisation; namespace osu.Framework.Tests.Localisation { [TestFixture] public class CultureInfoHelperTest { private const string invariant_culture = ""; [TestCase("en-US", true, "en-US")] [TestCase("invalid name", false, invariant_culture)] [TestCase(invariant_culture, true, invariant_culture)] [TestCase("ko_KR", false, invariant_culture)] public void TestTryGetCultureInfo(string name, bool expectedReturnValue, string expectedCultureName) { CultureInfo expectedCulture; switch (expectedCultureName) { case invariant_culture: expectedCulture = CultureInfo.InvariantCulture; break; default: expectedCulture = CultureInfo.GetCultureInfo(expectedCultureName); break; } bool retVal = CultureInfoHelper.TryGetCultureInfo(name, out var culture); Assert.That(retVal, Is.EqualTo(expectedReturnValue)); Assert.That(culture, Is.EqualTo(expectedCulture)); } } }
Update the exception to be more developer friendly
using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base($"{permissions} permission(s) are required.") { Permissions = permissions; } } }
using System; using System.Collections.Generic; using System.Text; using Plugin.Permissions.Abstractions; namespace Plugin.Media.Abstractions { /// <summary> /// Permission exception. /// </summary> public class MediaPermissionException : Exception { /// <summary> /// Permission required that is missing /// </summary> public Permission[] Permissions { get; } /// <summary> /// Creates a media permission exception /// </summary> /// <param name="permissions"></param> public MediaPermissionException(params Permission[] permissions) : base() { Permissions = permissions; } /// <summary> /// Gets a message that describes current exception /// </summary> /// <value>The message.</value> public override string Message { get { string missingPermissions = string.Join(", ", Permissions); return $"{missingPermissions} permission(s) are required."; } } } }
Modify trace injector to http injector
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ITraceInjector<HttpHeaders> _injector; private readonly string _serviceName; public TracingHandler(ITraceInjector<HttpHeaders> injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Criteo.Profiling.Tracing.Transport; namespace Criteo.Profiling.Tracing.Middleware { public class TracingHandler : DelegatingHandler { private readonly ZipkinHttpTraceInjector _injector; private readonly string _serviceName; public TracingHandler(string serviceName) : this(new ZipkinHttpTraceInjector(), serviceName) {} internal TracingHandler(ZipkinHttpTraceInjector injector, string serviceName) { _injector = injector; _serviceName = serviceName; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var trace = Trace.Current; if (trace != null) { trace = trace.Child(); _injector.Inject(trace, request.Headers); } trace.Record(Annotations.ClientSend()); trace.Record(Annotations.ServiceName(_serviceName)); trace.Record(Annotations.Rpc(request.Method.ToString())); return base.SendAsync(request, cancellationToken) .ContinueWith(t => { trace.Record(Annotations.ClientRecv()); return t.Result; }); } } }
Fix master server auto-update with /nightly flag
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.ApiLatestGithubReleaseUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
using LmpGlobal; using LmpUpdater.Appveyor.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Net; namespace LmpUpdater.Appveyor { public class AppveyorUpdateChecker { public static RootObject LatestBuild { get { try { using (var wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var json = wc.DownloadString(RepoConstants.AppveyorUrl); return JsonConvert.DeserializeObject<RootObject>(JObject.Parse(json).ToString()); } } catch (Exception) { //Ignore as either we don't have internet connection or something like that... } return null; } } public static Version GetLatestVersion() { var versionComponents = LatestBuild?.build.version.Split('.'); return versionComponents != null && versionComponents.Length >= 3 ? new Version(int.Parse(versionComponents[0]), int.Parse(versionComponents[1]), int.Parse(versionComponents[2])) : new Version("0.0.0"); } } }
Write data to OBJ and MTL
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String outputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); File.WriteAllText(outputName, mesh.ToString()); // Show the user it worked MessageBox.Show(outputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
using System; using System.IO; using System.Windows.Forms; namespace JPMeshConverter { public partial class Form1 : Form { private ModelFileDialog fileDialog; public Form1() { InitializeComponent(); fileDialog = new ModelFileDialog(System.AppDomain.CurrentDomain.BaseDirectory); } private void OnConvert(object sender, EventArgs e) { // Show the user a file dialog if (!fileDialog.Open()) { return; } // Parse the model data D3DReader reader = new D3DReader(fileDialog.FileName); // If the model couldn't be parsed correctly, error and return Mesh mesh = reader.MeshData; if (reader.MeshData == null) { MessageBox.Show("ERROR: Model could not be parsed.","Export failed!"); return; } // Output the mesh data to a Wavefront OBJ String meshOutputName = fileDialog.FileName.Replace(".d3dmesh", ".obj"); String mtlOutputName = meshOutputName.Replace(".obj",".mtl"); String mtlName = mtlOutputName.Substring(mtlOutputName.LastIndexOf("\\")+1); File.WriteAllText(meshOutputName, mesh.GetObjData(mtlName)); File.WriteAllText(mtlOutputName,mesh.GetMtlData()); // Show the user it worked MessageBox.Show(meshOutputName+"\n\nProcessed "+mesh.Chunks.Count+" chunks.\n"+mesh.Vertices.Count + " vertices exported.", "Export successful!"); } } }
Fix for balance null ref
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account).Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Cash_Flow_Projection.Models { public static class Balance { public static Decimal CurrentBalance(this IEnumerable<Entry> entries, Account account = Account.Cash) { return GetLastBalanceEntry(entries, account)?.Amount ?? Decimal.Zero; } public static IEnumerable<Entry> SinceBalance(this IEnumerable<Entry> entries, DateTime end) { // Includes the last balance entry var last_balance = GetLastBalanceEntry(entries)?.Date; return entries .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date < end) .OrderBy(entry => entry.Date); } public static Entry GetLastBalanceEntry(this IEnumerable<Entry> entries, Account account = Account.Cash) { return entries .Where(entry => entry.Account == account) .Where(entry => entry.IsBalance) .OrderByDescending(entry => entry.Date) .FirstOrDefault(); } public static Decimal GetBalanceOn(this IEnumerable<Entry> entries, DateTime asOf, Account account = Account.Cash) { var last_balance = GetLastBalanceEntry(entries, account)?.Date; var delta_since_last_balance = entries .Where(entry => entry.Account == account) .Where(entry => !entry.IsBalance) .Where(entry => entry.Date >= last_balance) .Where(entry => entry.Date <= asOf) .Sum(entry => entry.Amount); return CurrentBalance(entries, account) + delta_since_last_balance; } } }
Fix unity call in another thread
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData) || !System.PartSyncSystemReady) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
using LunaClient.Base; using LunaClient.Base.Interface; using LunaClient.VesselUtilities; using LunaCommon.Message.Data.Vessel; using LunaCommon.Message.Interface; using System.Collections.Concurrent; namespace LunaClient.Systems.VesselPartModuleSyncSys { public class VesselPartModuleSyncMessageHandler : SubSystem<VesselPartModuleSyncSystem>, IMessageHandler { public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>(); public void HandleMessage(IServerMessageBase msg) { if (!(msg.Data is VesselPartSyncMsgData msgData)) return; //We received a msg for our own controlled/updated vessel so ignore it if (!VesselCommon.DoVesselChecks(msgData.VesselId)) return; if (!System.VesselPartsSyncs.ContainsKey(msgData.VesselId)) { System.VesselPartsSyncs.TryAdd(msgData.VesselId, new VesselPartSyncQueue()); } if (System.VesselPartsSyncs.TryGetValue(msgData.VesselId, out var queue)) { if (queue.TryPeek(out var resource) && resource.GameTime > msgData.GameTime) { //A user reverted, so clear his message queue and start from scratch queue.Clear(); } queue.Enqueue(msgData); } } } }
Work around faulty StatusStrip implementations
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST && (int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls { public class StatusStripCustom : StatusStrip { public const int WM_NCHITTEST = 0x84; public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONUP = 0xA2; public const int HT_CLIENT = 0x1; public const int HT_BOTTOMRIGHT = 0x11; public const int HT_TRANSPARENT = -1; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_NCHITTEST) { if ((int)m.Result == HT_BOTTOMRIGHT) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } else if ((int)m.Result == HT_CLIENT) { // Work around the implementation returning HT_CLIENT instead of HT_BOTTOMRIGHT int x = unchecked((short)((uint)m.LParam & 0xFFFF)); int y = unchecked((short)((uint)m.LParam >> 16)); Point p = PointToClient(new Point(x, y)); if (p.X >= this.ClientSize.Width - this.ClientSize.Height) { // Tell the system to test the parent m.Result = (IntPtr)HT_TRANSPARENT; } } } } } }
Fix for null values when stripping characters in feeds.
/* Copyright 2017 James Craig 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. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and"); } } }
/* Copyright 2017 James Craig 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. */ namespace FileCurator.Formats.RSS.Data { /// <summary> /// Utility class used by RSS classes. /// </summary> public static class Utils { /// <summary> /// Strips illegal characters from RSS items /// </summary> /// <param name="original">Original text</param> /// <returns>string stripped of certain characters.</returns> public static string StripIllegalCharacters(string original) { return original?.Replace("&nbsp;", " ") .Replace("&#160;", string.Empty) .Trim() .Replace("&", "and") ?? ""; } } }
Add button to access first run setup on demand
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new LanguageSettings(), new UpdateSettings(), }; } } }
// 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.Sprites; using osu.Framework.Localisation; using osu.Game.Localisation; using osu.Game.Overlays.Settings.Sections.General; namespace osu.Game.Overlays.Settings.Sections { public class GeneralSection : SettingsSection { [Resolved(CanBeNull = true)] private FirstRunSetupOverlay firstRunSetupOverlay { get; set; } public override LocalisableString Header => GeneralSettingsStrings.GeneralSectionHeader; public override Drawable CreateIcon() => new SpriteIcon { Icon = FontAwesome.Solid.Cog }; public GeneralSection() { Children = new Drawable[] { new SettingsButton { Text = "Run setup wizard", Action = () => firstRunSetupOverlay?.Show(), }, new LanguageSettings(), new UpdateSettings(), }; } } }
Add calc method for disposible income
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType : byte { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> [Display(Name = "Percent of Gross Pay")] PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> [Display(Name = "Percent of Net Pay")] PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> [Display(Name = "Fixed Amount")] FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> [Display(Name = "Fixed Hourly Amount")] FixedHourlyAmount = 4, /// <summary> /// Deduction is taken as a percentage of the disposible income (gross pay - payroll taxes) /// </summary> PercentOfDisposibleIncome } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; yield return CalculationType.PercentOfDisposibleIncome; } } }
Support invalid certificates (e.g. if Fiddler is in use) and more security protocols (adds Tls1.1 and Tls1.2)
using System; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } }
using System; using System.Net; using System.Windows.Forms; namespace DrawShip.Viewer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var applicationContext = new ApplicationContext(); var runMode = applicationContext.GetRunMode(); runMode.Run(applicationContext); } } }
Split out package equality comparer
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System.Collections.Generic; namespace Microsoft.NodejsTools.Npm { public class PackageComparer : IComparer<IPackage> { public int Compare(IPackage x, IPackage y) { if (x == y) { return 0; } else if (null == x) { return -1; } else if (null == y) { return 1; } // TODO: should take into account versions! return x.Name.CompareTo(y.Name); } } public class PackageEqualityComparer : EqualityComparer<IPackage> { public override bool Equals(IPackage p1, IPackage p2) { return p1.Name == p2.Name && p1.Version == p2.Version && p1.IsBundledDependency == p2.IsBundledDependency && p1.IsDevDependency == p2.IsDevDependency && p1.IsListedInParentPackageJson == p2.IsListedInParentPackageJson && p1.IsMissing == p2.IsMissing && p1.IsOptionalDependency == p2.IsOptionalDependency; } public override int GetHashCode(IPackage obj) { if (obj.Name == null || obj.Version == null) return obj.GetHashCode(); return obj.Name.GetHashCode() ^ obj.Version.GetHashCode(); } } }
Remove trailing .exe in process name.
using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } }
using System; using System.Diagnostics; namespace IronAHK.Rusty { partial class Core { #region Disk static string[] Glob(string pattern) { return new string[] { }; } #endregion #region Process static Process FindProcess(string name) { int id; if (int.TryParse(name, out id)) return System.Diagnostics.Process.GetProcessById(id); const string exe = ".exe"; if (name.EndsWith(exe, StringComparison.OrdinalIgnoreCase)) name = name.Substring(0, name.Length - exe.Length); var prc = System.Diagnostics.Process.GetProcessesByName(name); return prc.Length > 0 ? prc[0] : null; } #endregion #region Text static string NormaliseEol(string text, string eol = null) { const string CR = "\r", LF = "\n", CRLF = "\r\n"; eol = eol ?? Environment.NewLine; switch (eol) { case CR: return text.Replace(CRLF, CR).Replace(LF, CR); case LF: return text.Replace(CRLF, LF).Replace(CR, LF); case CRLF: return text.Replace(CR, string.Empty).Replace(LF, CRLF); } return text; } #endregion } }
Use the term response instead of request.
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS response.", "It works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS response.", "It works only from www.bigfont.ca AND from the same origin." }; } } }
Fix spurious 404 response when deep linking to a client route
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace WebPackAngular2TypeScript.Routing { public class DeepLinkingMiddleware { public DeepLinkingMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, ILoggerFactory loggerFactory, DeepLinkingOptions options) { this.next = next; this.options = options; staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory); } public async Task Invoke(HttpContext context) { // try to resolve the request with default static file middleware await staticFileMiddleware.Invoke(context); if (context.Response.StatusCode == 404) { var redirectUrlPath = FindRedirection(context); if (redirectUrlPath != unresolvedPath) { context.Request.Path = redirectUrlPath; await staticFileMiddleware.Invoke(context); } } } protected virtual PathString FindRedirection(HttpContext context) { // route to root path when request was not resolved return options.RedirectUrlPath; } protected readonly DeepLinkingOptions options; protected readonly RequestDelegate next; protected readonly StaticFileMiddleware staticFileMiddleware; protected readonly PathString unresolvedPath = null; } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace WebPackAngular2TypeScript.Routing { public class DeepLinkingMiddleware { public DeepLinkingMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, ILoggerFactory loggerFactory, DeepLinkingOptions options) { this.next = next; this.options = options; staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv, options.FileServerOptions.StaticFileOptions, loggerFactory); } public async Task Invoke(HttpContext context) { // try to resolve the request with default static file middleware await staticFileMiddleware.Invoke(context); if (context.Response.StatusCode == StatusCodes.Status404NotFound) { var redirectUrlPath = FindRedirection(context); if (redirectUrlPath != unresolvedPath) { // if resolved, reset response as successful context.Response.StatusCode = StatusCodes.Status200OK; context.Request.Path = redirectUrlPath; await staticFileMiddleware.Invoke(context); } } } protected virtual PathString FindRedirection(HttpContext context) { // route to root path when request was not resolved return options.RedirectUrlPath; } protected readonly DeepLinkingOptions options; protected readonly RequestDelegate next; protected readonly StaticFileMiddleware staticFileMiddleware; protected readonly PathString unresolvedPath = null; } }
Fix connectionStrings section attribute in BadConfig doc page
@using Dashboard @using Microsoft.WindowsAzure.Jobs @{ ViewBag.Title = "Configuration Error"; } <h2>Bad Config</h2> <p> The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard. In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like: </p> <pre> &lt;add name="@JobHost.LoggingConnectionStringName" value="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" /&gt; </pre> <p> This is the storage account that your user functions will bind against. This is also where logging will be stored. </p> <p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>
@using Dashboard @using Microsoft.WindowsAzure.Jobs @{ ViewBag.Title = "Configuration Error"; } <h2>Bad Config</h2> <p> The configuration is not properly set for the Windows Azure Web Jobs SDK Dashboard. In your configuration (such as web.config), you must set a connection string named <i>@JobHost.LoggingConnectionStringName</i> that points to the account connection string where the sb logs are being stored. EG, under "connectionStrings" in Web.config, add a value like: </p> <pre> &lt;add name="@JobHost.LoggingConnectionStringName" connectionString="DefaultEndpointsProtocol=https;AccountName=<b>NAME</b>;AccountKey=<b>KEY</b>" /&gt; </pre> <p> This is the storage account that your user functions will bind against. This is also where logging will be stored. </p> <p class="alert alert-danger">@SimpleBatchStuff.BadInitErrorMessage</p>
Enhance the Mac command reference text a bit
using System; using System.Text; using System.Collections.Generic; using System.Linq; namespace RepoZ.UI.Mac.Story { public class StringCommandHandler { private Dictionary<string, Action> _commands = new Dictionary<string, Action>(); private StringBuilder _helpBuilder = new StringBuilder(); internal bool IsCommand(string value) { return value?.StartsWith(":") == true; } internal bool Handle(string command) { if (_commands.TryGetValue(CleanCommand(command), out Action commandAction)) { commandAction.Invoke(); return true; } return false; } internal void Define(string[] commands, Action commandAction, string helpText) { foreach (var command in commands) _commands[CleanCommand(command)] = commandAction; if (_helpBuilder.Length > 0) _helpBuilder.AppendLine(""); _helpBuilder.AppendLine(string.Join(", ", commands.OrderBy(c => c))); _helpBuilder.AppendLine("\t"+ helpText); } private string CleanCommand(string command) { command = command?.Trim().ToLower() ?? ""; return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command; } internal string GetHelpText() => _helpBuilder.ToString(); } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; namespace RepoZ.UI.Mac.Story { public class StringCommandHandler { private Dictionary<string, Action> _commands = new Dictionary<string, Action>(); private StringBuilder _helpBuilder = new StringBuilder(); internal bool IsCommand(string value) { return value?.StartsWith(":") == true; } internal bool Handle(string command) { if (_commands.TryGetValue(CleanCommand(command), out Action commandAction)) { commandAction.Invoke(); return true; } return false; } internal void Define(string[] commands, Action commandAction, string helpText) { foreach (var command in commands) _commands[CleanCommand(command)] = commandAction; if (_helpBuilder.Length == 0) { _helpBuilder.AppendLine("To execute a command instead of filtering the list of repositories, simply begin with a colon (:)."); _helpBuilder.AppendLine(""); _helpBuilder.AppendLine("Command reference:"); } _helpBuilder.AppendLine(""); _helpBuilder.AppendLine("\t:" + string.Join(" or :", commands.OrderBy(c => c))); _helpBuilder.AppendLine("\t\t"+ helpText); } private string CleanCommand(string command) { command = command?.Trim().ToLower() ?? ""; return command.StartsWith(":", StringComparison.OrdinalIgnoreCase) ? command.Substring(1) : command; } internal string GetHelpText() => _helpBuilder.ToString(); } }
Use site title in email subject for exception handler.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ActionMailer.Net.Mvc; using RationalVote.Models; using System.Configuration; namespace RationalVote.Controllers { public class MailController : MailerBase { public static string GetFromEmail( string purpose ) { return String.Format( "\"{0} {1}\" <{2}>", ConfigurationManager.AppSettings.Get("siteTitle"), purpose, ConfigurationManager.AppSettings.Get("emailFrom") ); } public EmailResult VerificationEmail( User model, EmailVerificationToken token ) { To.Add( model.Email ); From = GetFromEmail( "Verification" ); Subject = "Please verify your account"; ViewBag.Token = token.Token; return Email( "VerificationEmail" ); } public EmailResult ExceptionEmail( HttpException e, string message ) { To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) ); From = GetFromEmail( "Exception" ); Subject = "Site exception - " + message; ViewBag.Exception = e.ToString(); return Email( "ExceptionEmail" ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ActionMailer.Net.Mvc; using RationalVote.Models; using System.Configuration; namespace RationalVote.Controllers { public class MailController : MailerBase { public static string GetFromEmail( string purpose ) { return String.Format( "\"{0} {1}\" <{2}>", ConfigurationManager.AppSettings.Get("siteTitle"), purpose, ConfigurationManager.AppSettings.Get("emailFrom") ); } public EmailResult VerificationEmail( User model, EmailVerificationToken token ) { To.Add( model.Email ); From = GetFromEmail( "Verification" ); Subject = "Please verify your account"; ViewBag.Token = token.Token; return Email( "VerificationEmail" ); } public EmailResult ExceptionEmail( HttpException e, string message ) { To.Add( ConfigurationManager.AppSettings.Get( "ServerAdmin" ) ); From = GetFromEmail( "Exception" ); Subject = ConfigurationManager.AppSettings.Get("siteTitle") + " exception - " + message; ViewBag.Exception = e.ToString(); return Email( "ExceptionEmail" ); } } }
Use SequenceEqual instead of operator== for comparison of arrays in 'Can_perform_query_with_max_length' test
namespace InfoCarrier.Core.EFCore.FunctionalTests { using Microsoft.EntityFrameworkCore.Specification.Tests; using Xunit; public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture> { public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture) : base(fixture) { } [Fact] public virtual void Can_perform_query_with_ansi_strings() { this.Can_perform_query_with_ansi_strings(supportsAnsi: false); } } }
namespace InfoCarrier.Core.EFCore.FunctionalTests { using System.Linq; using Microsoft.EntityFrameworkCore.Specification.Tests; using Xunit; public class BuiltInDataTypesInfoCarrierTest : BuiltInDataTypesTestBase<BuiltInDataTypesInfoCarrierFixture> { public BuiltInDataTypesInfoCarrierTest(BuiltInDataTypesInfoCarrierFixture fixture) : base(fixture) { } [Fact] public virtual void Can_perform_query_with_ansi_strings() { this.Can_perform_query_with_ansi_strings(supportsAnsi: false); } [Fact] public override void Can_perform_query_with_max_length() { // UGLY: this is a complete copy-n-paste of // https://github.com/aspnet/EntityFramework/blob/rel/1.1.0/src/Microsoft.EntityFrameworkCore.Specification.Tests/BuiltInDataTypesTestBase.cs#L25 // We only use SequenceEqual instead of operator== for comparison of arrays. var shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; var longString = new string('X', 9000); var longBinary = new byte[9000]; for (var i = 0; i < longBinary.Length; i++) { longBinary[i] = (byte)i; } using (var context = this.CreateContext()) { context.Set<MaxLengthDataTypes>().Add( new MaxLengthDataTypes { Id = 799, String3 = shortString, ByteArray5 = shortBinary, String9000 = longString, ByteArray9000 = longBinary }); Assert.Equal(1, context.SaveChanges()); } using (var context = this.CreateContext()) { Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String3 == shortString)); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray5.SequenceEqual(shortBinary))); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.String9000 == longString)); Assert.NotNull(context.Set<MaxLengthDataTypes>().SingleOrDefault(e => e.Id == 799 && e.ByteArray9000.SequenceEqual(longBinary))); } } } }
Return JSON object from Values controller
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebAPIApplication.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet] [Route("ping")] public string Ping() { return "All good. You don't need to be authenticated to call this."; } [Authorize] [HttpGet] [Route("secured/ping")] public string PingSecured() { return "All good. You only get this message if you are authenticated."; } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebAPIApplication.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { [HttpGet] [Route("ping")] public dynamic Ping() { return new { message = "All good. You don't need to be authenticated to call this." }; } [Authorize] [HttpGet] [Route("secured/ping")] public object PingSecured() { return new { message = "All good. You only get this message if you are authenticated." }; } } }
Make sure a capture will not leave the TemplateContext in an unbalanced state if an exception occurs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("capture statement", "capture <variable> ... end")] public class ScriptCaptureStatement : ScriptStatement { public ScriptExpression Target { get; set; } public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { // unit test: 230-capture-statement.txt context.PushOutput(); { context.Evaluate(Body); } var result = context.PopOutput(); context.SetValue(Target, result); return null; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("capture statement", "capture <variable> ... end")] public class ScriptCaptureStatement : ScriptStatement { public ScriptExpression Target { get; set; } public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { // unit test: 230-capture-statement.txt context.PushOutput(); try { context.Evaluate(Body); } finally { var result = context.PopOutput(); context.SetValue(Target, result); } return null; } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Mvc")]
Rename app setting for finance api audiences
using System.Configuration; using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using SFA.DAS.EmployerFinance.Api; [assembly: OwinStartup(typeof(Startup))] namespace SFA.DAS.EmployerFinance.Api { public class Startup { public void Configuration(IAppBuilder app) { _ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdentifierUri"].ToString().Split(',') } }); } } }
using System.Configuration; using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using SFA.DAS.EmployerFinance.Api; [assembly: OwinStartup(typeof(Startup))] namespace SFA.DAS.EmployerFinance.Api { public class Startup { public void Configuration(IAppBuilder app) { _ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudiences = ConfigurationManager.AppSettings["FinanceApiIdaAudience"].ToString().Split(',') } }); } } }
Fix answer 28 to include square roots in prime test
using System; using System.Linq; namespace Abc.NCrafts.Quizz.Performance.Questions._028 { [CorrectAnswer(Difficulty = Difficulty.Medium)] public class Answer1 { public static void Run() { // begin var primes = Enumerable.Range(0, 10 * 1000) .Where(IsPrime) .ToList(); // end Logger.Log("Primes: {0}", primes.Count); } private static bool IsPrime(int number) { if (number == 0 || number == 1) return false; if (number == 2) return true; for (var divisor = 2; divisor < (int)Math.Sqrt(number); divisor++) { if (number % divisor == 0) return false; } return true; } } }
using System; using System.Linq; namespace Abc.NCrafts.Quizz.Performance.Questions._028 { [CorrectAnswer(Difficulty = Difficulty.Medium)] public class Answer1 { public static void Run() { // begin var primes = Enumerable.Range(0, 10 * 1000) .Where(IsPrime) .ToList(); // end Logger.Log("Primes: {0}", primes.Count); } private static bool IsPrime(int number) { if (number == 0 || number == 1) return false; if (number == 2) return true; for (var divisor = 2; divisor <= (int)Math.Sqrt(number); divisor++) { if (number % divisor == 0) return false; } return true; } } }
Add base uri to tests
using System; using System.Diagnostics; using Microsoft.Extensions.Configuration; using Xunit; using SocksSharp; using SocksSharp.Proxy; namespace SocksSharp.Tests { public class ProxyClientTests { private ProxySettings proxySettings; private void GatherTestConfiguration() { var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail."; var builder = new ConfigurationBuilder() .AddJsonFile("proxysettings.json") .Build(); proxySettings = new ProxySettings(); var host = builder["host"]; if (String.IsNullOrEmpty(host)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host))); } else { proxySettings.Host = host; } var port = builder["port"]; if (String.IsNullOrEmpty(port)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port))); } else { proxySettings.Port = Int32.Parse(port); } //TODO: Setup manualy var username = builder["username"]; var password = builder["password"]; } private ProxyClientHandler<Socks5> CreateNewSocks5Client() { if(proxySettings.Host == null || proxySettings.Port == 0) { throw new Exception("Please add your proxy settings to proxysettings.json!"); } return new ProxyClientHandler<Socks5>(proxySettings); } [Fact] public void Test1() { } } }
using System; using System.Diagnostics; using Microsoft.Extensions.Configuration; using Xunit; using SocksSharp; using SocksSharp.Proxy; namespace SocksSharp.Tests { public class ProxyClientTests { private Uri baseUri = new Uri("http://httpbin.org/"); private ProxySettings proxySettings; private void GatherTestConfiguration() { var appConfigMsgWarning = "{0} not configured in proxysettings.json! Some tests may fail."; var builder = new ConfigurationBuilder() .AddJsonFile("proxysettings.json") .Build(); proxySettings = new ProxySettings(); var host = builder["host"]; if (String.IsNullOrEmpty(host)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(host))); } else { proxySettings.Host = host; } var port = builder["port"]; if (String.IsNullOrEmpty(port)) { Debug.WriteLine(String.Format(appConfigMsgWarning, nameof(port))); } else { proxySettings.Port = Int32.Parse(port); } //TODO: Setup manualy var username = builder["username"]; var password = builder["password"]; } private ProxyClientHandler<Socks5> CreateNewSocks5Client() { if(proxySettings.Host == null || proxySettings.Port == 0) { throw new Exception("Please add your proxy settings to proxysettings.json!"); } return new ProxyClientHandler<Socks5>(proxySettings); } [Fact] public void Test1() { } } }
Check Azure configuration more carefully. Add contracts for some base classes. Fix ExportOrder.
using System; using System.ComponentModel.Composition; namespace Cogito.Composition { /// <summary> /// Attaches an Order metadata property to the export. /// </summary> [MetadataAttribute] public class ExportOrderAttribute : Attribute { readonly int order; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="order"></param> /// <returns></returns> public ExportOrderAttribute(int order) { Priority = order; } public int Priority { get; set; } } }
using System; using System.ComponentModel.Composition; namespace Cogito.Composition { /// <summary> /// Attaches an Order metadata property to the export. /// </summary> [MetadataAttribute] public class ExportOrderAttribute : Attribute, IOrderedExportMetadata { /// <summary> /// Initializes a new instance. /// </summary> /// <param name="order"></param> /// <returns></returns> public ExportOrderAttribute(int order) { Order = order; } public int Order { get; set; } } }
Add unit test for empty timezone
namespace DarkSky.UnitTests.Extensions { using System; using NodaTime; using Xunit; using static DarkSky.Extensions.LongExtensions; public class LongExtensionsUnitTests { public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets() { yield return new object[] { DateTimeOffset.MinValue, "UTC" }; yield return new object[] { DateTimeOffset.MaxValue, "UTC" }; yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" }; } [Theory] [MemberData(nameof(GetDateTimeOffsets))] public void CorrectConversionTest(DateTimeOffset date, string timezone) { // Truncate milliseconds since we don't use them for the UNIX timestamps. var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond)); var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone); Assert.Equal(dateTimeOffset, convertedDate); } } }
namespace DarkSky.UnitTests.Extensions { using System; using NodaTime; using Xunit; using static DarkSky.Extensions.LongExtensions; public class LongExtensionsUnitTests { public static System.Collections.Generic.IEnumerable<object[]> GetDateTimeOffsets() { yield return new object[] { DateTimeOffset.MinValue, "UTC" }; yield return new object[] { DateTimeOffset.MaxValue, "UTC" }; yield return new object[] { new DateTimeOffset(2017, 1, 1, 1, 0, 0, new TimeSpan(0)), "UTC" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), "America/New_York" }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), string.Empty }; yield return new object[] { new ZonedDateTime(Instant.FromUnixTimeSeconds(1499435235), DateTimeZoneProviders.Tzdb["America/New_York"]).ToDateTimeOffset(), null }; } [Theory] [MemberData(nameof(GetDateTimeOffsets))] public void CorrectConversionTest(DateTimeOffset date, string timezone) { // Truncate milliseconds since we don't use them for the UNIX timestamps. var dateTimeOffset = date.AddTicks(-(date.Ticks % TimeSpan.TicksPerSecond)); var convertedDate = dateTimeOffset.ToUnixTimeSeconds().ToDateTimeOffsetFromUnixTimestamp(timezone); Assert.Equal(dateTimeOffset, convertedDate); } } }
Add basic setup for song select screen
// 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. namespace osu.Game.Screens.Edit.Setup { public class SetupScreen : EditorScreen { public SetupScreen() { Child = new ScreenWhiteBox.UnderConstructionMessage("Setup mode"); } } }
// 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.Shapes; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterfaceV2; using osuTK; namespace osu.Game.Screens.Edit.Setup { public class SetupScreen : EditorScreen { [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { Colour = colours.Gray0, RelativeSizeAxes = Axes.Both, }, new OsuScrollContainer { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding(50), Child = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(20), Direction = FillDirection.Vertical, Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.X, Height = 250, Masking = true, CornerRadius = 50, Child = new BeatmapBackgroundSprite(Beatmap.Value) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, }, }, new OsuSpriteText { Text = "Beatmap metadata" }, new LabelledTextBox { Label = "Artist", Current = { Value = Beatmap.Value.Metadata.Artist } }, new LabelledTextBox { Label = "Title", Current = { Value = Beatmap.Value.Metadata.Title } }, new LabelledTextBox { Label = "Creator", Current = { Value = Beatmap.Value.Metadata.AuthorString } }, new LabelledTextBox { Label = "Difficulty Name", Current = { Value = Beatmap.Value.BeatmapInfo.Version } }, } }, }, }; } } }
Fix type mapping for IPubFileProvider
// 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; using EOLib.IO.Pub; namespace EOLib.IO.Repositories { [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)] public class PubFileRepository : IPubFileRepository, IPubFileProvider { public IPubFile<EIFRecord> EIFFile { get; set; } public IPubFile<ENFRecord> ENFFile { get; set; } public IPubFile<ESFRecord> ESFFile { get; set; } public IPubFile<ECFRecord> ECFFile { get; set; } } }
// 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; using EOLib.IO.Pub; namespace EOLib.IO.Repositories { [MappedType(BaseType = typeof(IPubFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IPubFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IEIFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IENFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IESFFileProvider), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileRepository), IsSingleton = true)] [MappedType(BaseType = typeof(IECFFileProvider), IsSingleton = true)] public class PubFileRepository : IPubFileRepository, IPubFileProvider { public IPubFile<EIFRecord> EIFFile { get; set; } public IPubFile<ENFRecord> ENFFile { get; set; } public IPubFile<ESFRecord> ESFFile { get; set; } public IPubFile<ECFRecord> ECFFile { get; set; } } }
Add IReloadable interface and method
using System.Collections.Generic; using System.Linq; using Wox.Plugin.BrowserBookmark.Commands; using Wox.Plugin.SharedCommands; namespace Wox.Plugin.BrowserBookmark { public class Main : IPlugin { private PluginInitContext context; private List<Bookmark> cachedBookmarks = new List<Bookmark>(); public void Init(PluginInitContext context) { this.context = context; cachedBookmarks = Bookmarks.LoadAllBookmarks(); } public List<Result> Query(Query query) { string param = query.GetAllRemainingParameter().TrimStart(); // Should top results be returned? (true if no search parameters have been passed) var topResults = string.IsNullOrEmpty(param); var returnList = cachedBookmarks; if (!topResults) { // Since we mixed chrome and firefox bookmarks, we should order them again returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList(); returnList = returnList.OrderByDescending(o => o.Score).ToList(); } return returnList.Select(c => new Result() { Title = c.Name, SubTitle = "Bookmark: " + c.Url, IcoPath = @"Images\bookmark.png", Score = 5, Action = (e) => { context.API.HideApp(); c.Url.NewBrowserWindow(""); return true; } }).ToList(); } } }
using System.Collections.Generic; using System.Linq; using Wox.Plugin.BrowserBookmark.Commands; using Wox.Plugin.SharedCommands; namespace Wox.Plugin.BrowserBookmark { public class Main : IPlugin, IReloadable { private PluginInitContext context; private List<Bookmark> cachedBookmarks = new List<Bookmark>(); public void Init(PluginInitContext context) { this.context = context; cachedBookmarks = Bookmarks.LoadAllBookmarks(); } public List<Result> Query(Query query) { string param = query.GetAllRemainingParameter().TrimStart(); // Should top results be returned? (true if no search parameters have been passed) var topResults = string.IsNullOrEmpty(param); var returnList = cachedBookmarks; if (!topResults) { // Since we mixed chrome and firefox bookmarks, we should order them again returnList = cachedBookmarks.Where(o => Bookmarks.MatchProgram(o, param)).ToList(); returnList = returnList.OrderByDescending(o => o.Score).ToList(); } return returnList.Select(c => new Result() { Title = c.Name, SubTitle = "Bookmark: " + c.Url, IcoPath = @"Images\bookmark.png", Score = 5, Action = (e) => { context.API.HideApp(); c.Url.NewBrowserWindow(""); return true; } }).ToList(); } public void ReloadData() { cachedBookmarks.Clear(); cachedBookmarks = Bookmarks.LoadAllBookmarks(); } } }
Change version number to v0.5.1.0
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Skylight")] [assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TakoMan02")] [assembly: AssemblyProduct("Skylight")] [assembly: AssemblyCopyright("Copyright © TakoMan02 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Skylight")] [assembly: ComVisible(false)] [assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")] // // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("0.0.5.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Skylight")] [assembly: AssemblyDescription("An API by TakoMan02 for Everybody Edits")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("TakoMan02")] [assembly: AssemblyProduct("Skylight")] [assembly: AssemblyCopyright("Copyright © TakoMan02 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Skylight")] [assembly: ComVisible(false)] [assembly: Guid("a460c245-2753-4861-ae17-751db86fbae2")] // // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("0.5.1.0")]
Rename fields name pattern to match rest of code
using System; namespace SQLite.Net { public class BlobSerializerDelegate : IBlobSerializer { public delegate byte[] SerializeDelegate(object obj); public delegate bool CanSerializeDelegate(Type type); public delegate object DeserializeDelegate(byte[] data, Type type); private readonly SerializeDelegate serializeDelegate; private readonly DeserializeDelegate deserializeDelegate; private readonly CanSerializeDelegate canDeserializeDelegate; public BlobSerializerDelegate (SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { this.serializeDelegate = serializeDelegate; this.deserializeDelegate = deserializeDelegate; this.canDeserializeDelegate = canDeserializeDelegate; } #region IBlobSerializer implementation public byte[] Serialize<T>(T obj) { return this.serializeDelegate (obj); } public object Deserialize(byte[] data, Type type) { return this.deserializeDelegate (data, type); } public bool CanDeserialize(Type type) { return this.canDeserializeDelegate (type); } #endregion } }
using System; namespace SQLite.Net { public class BlobSerializerDelegate : IBlobSerializer { public delegate byte[] SerializeDelegate(object obj); public delegate bool CanSerializeDelegate(Type type); public delegate object DeserializeDelegate(byte[] data, Type type); private readonly SerializeDelegate _serializeDelegate; private readonly DeserializeDelegate _deserializeDelegate; private readonly CanSerializeDelegate _canDeserializeDelegate; public BlobSerializerDelegate(SerializeDelegate serializeDelegate, DeserializeDelegate deserializeDelegate, CanSerializeDelegate canDeserializeDelegate) { _serializeDelegate = serializeDelegate; _deserializeDelegate = deserializeDelegate; _canDeserializeDelegate = canDeserializeDelegate; } #region IBlobSerializer implementation public byte[] Serialize<T>(T obj) { return _serializeDelegate(obj); } public object Deserialize(byte[] data, Type type) { return _deserializeDelegate(data, type); } public bool CanDeserialize(Type type) { return _canDeserializeDelegate(type); } #endregion } }
Handle update based on a path object as well as the directory/file
using Cake.Core.IO; using Ensconce.Update; using System.IO; namespace Ensconce.Cake { public static class EnsconceFileUpdateExtensions { public static void TextSubstitute(this IFile file, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFile(new FileInfo(file.Path.FullPath), tagDictionary); } public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile) { directory.TextSubstitute("*.*", fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFiles(directory.Path.FullPath, filter, tagDictionary); } } }
using Cake.Core.IO; using Ensconce.Update; using System.IO; namespace Ensconce.Cake { public static class EnsconceFileUpdateExtensions { public static void TextSubstitute(this IFile file, FilePath fixedStructureFile) { file.Path.TextSubstitute(fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, FilePath fixedStructureFile) { directory.Path.TextSubstitute(fixedStructureFile); } public static void TextSubstitute(this IDirectory directory, string filter, FilePath fixedStructureFile) { directory.Path.TextSubstitute(filter, fixedStructureFile); } public static void TextSubstitute(this FilePath file, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFile(new FileInfo(file.FullPath), tagDictionary); } public static void TextSubstitute(this DirectoryPath directory, FilePath fixedStructureFile) { directory.TextSubstitute("*.*", fixedStructureFile); } public static void TextSubstitute(this DirectoryPath directory, string filter, FilePath fixedStructureFile) { var tagDictionary = fixedStructureFile == null ? TagDictionaryBuilder.Build(string.Empty) : TagDictionaryBuilder.Build(fixedStructureFile.FullPath); Update.ProcessFiles.UpdateFiles(directory.FullPath, filter, tagDictionary); } } }
Revert "fixed mandatory field error message"
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using BForms.Models; using BForms.Mvc; namespace BForms.Docs { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //register BForms validation provider ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider()); BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager); //BForms.Utilities.BsUIManager.Theme(BsTheme.Black); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); #if !DEBUG BForms.Utilities.BsConfigurationManager.Release(true); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using BForms.Models; using BForms.Mvc; namespace BForms.Docs { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //register BForms validation provider ModelValidatorProviders.Providers.Add(new BsModelValidatorProvider()); BForms.Utilities.BsResourceManager.Register(Resources.Resource.ResourceManager); //BForms.Utilities.BsUIManager.Theme(BsTheme.Black); #if !DEBUG BForms.Utilities.BsConfigurationManager.Release(true); #endif } } }
Add a const string field for the If-None-Match HTTP header
namespace ServiceStack.Common.Web { public static class HttpHeaders { public const string XParamOverridePrefix = "X-Param-Override-"; public const string XHttpMethodOverride = "X-Http-Method-Override"; public const string XUserAuthId = "X-UAId"; public const string XForwardedFor = "X-Forwarded-For"; public const string XRealIp = "X-Real-IP"; public const string Referer = "Referer"; public const string CacheControl = "Cache-Control"; public const string IfModifiedSince = "If-Modified-Since"; public const string LastModified = "Last-Modified"; public const string Accept = "Accept"; public const string AcceptEncoding = "Accept-Encoding"; public const string ContentType = "Content-Type"; public const string ContentEncoding = "Content-Encoding"; public const string ContentLength = "Content-Length"; public const string ContentDisposition = "Content-Disposition"; public const string Location = "Location"; public const string SetCookie = "Set-Cookie"; public const string ETag = "ETag"; public const string Authorization = "Authorization"; public const string WwwAuthenticate = "WWW-Authenticate"; public const string AllowOrigin = "Access-Control-Allow-Origin"; public const string AllowMethods = "Access-Control-Allow-Methods"; public const string AllowHeaders = "Access-Control-Allow-Headers"; public const string AllowCredentials = "Access-Control-Allow-Credentials"; } }
namespace ServiceStack.Common.Web { public static class HttpHeaders { public const string XParamOverridePrefix = "X-Param-Override-"; public const string XHttpMethodOverride = "X-Http-Method-Override"; public const string XUserAuthId = "X-UAId"; public const string XForwardedFor = "X-Forwarded-For"; public const string XRealIp = "X-Real-IP"; public const string Referer = "Referer"; public const string CacheControl = "Cache-Control"; public const string IfModifiedSince = "If-Modified-Since"; public const string IfNoneMatch = "If-None-Match"; public const string LastModified = "Last-Modified"; public const string Accept = "Accept"; public const string AcceptEncoding = "Accept-Encoding"; public const string ContentType = "Content-Type"; public const string ContentEncoding = "Content-Encoding"; public const string ContentLength = "Content-Length"; public const string ContentDisposition = "Content-Disposition"; public const string Location = "Location"; public const string SetCookie = "Set-Cookie"; public const string ETag = "ETag"; public const string Authorization = "Authorization"; public const string WwwAuthenticate = "WWW-Authenticate"; public const string AllowOrigin = "Access-Control-Allow-Origin"; public const string AllowMethods = "Access-Control-Allow-Methods"; public const string AllowHeaders = "Access-Control-Allow-Headers"; public const string AllowCredentials = "Access-Control-Allow-Credentials"; } }
Make sure to clean my dic.
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { if (!AsyncLocks.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); AsyncLocks.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); } return value; } } } }
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<object, AsyncLock> AsyncLocks { get; } = new Dictionary<object, AsyncLock>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { // Cleanup the evicted asynclocks first. foreach (var toRemove in AsyncLocks.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList()) { AsyncLocks.Remove(toRemove); } if (!AsyncLocks.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); AsyncLocks.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); } return value; } } } }
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Web")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Tests.Integration.Web")]
Add SourceID and SourceType to journal
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public Guid SourceID { get; set; } public string SourceType { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
Fix bug to find non-existent sys db in mysql
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = "sys"; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = ""; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
Remove use of UseWorkingDirectory in default template
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .UseWorkingDirectory("..") .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
Add other upgrades to enum
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD, BEEBALL, SCHOOLBUZZ, BUZZFEED, BEACH, GUM, VISOR }
Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional.
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>(); } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always; } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
Set private.config to optional to fix unit tests on build server
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config") .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config",true) .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
Reduce packet size, remove bloated time codes
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public float serverTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetInt(); serverTime = reader.GetFloat(); } public void Serialize(NetDataWriter writer) { writer.Put(serverUnixTime); writer.Put(serverTime); } } }
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetPackedInt(); } public void Serialize(NetDataWriter writer) { writer.PutPackedInt(serverUnixTime); } } }
Rename refactor;: GCMonitor.work -> GCMonitor._work
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback work; static Internal() { work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback _work; static Internal() { _work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(_work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
Update for new version of Cardboard SDK
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() {} public void Update() { wasTouched |= this.IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!this.IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() { Cardboard cardboard = CardboardGameObject().GetComponent<Cardboard>(); cardboard.TapIsTrigger = false; } private GameObject CardboardGameObject() { GameObject gameObject = Camera.main.gameObject; return gameObject.transform.parent.parent.gameObject; } public void Update() { wasTouched |= IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
Add ability to mark auth handle as successful
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; private set; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } public void MarkSuccessful() { Success = true; } }
Mark ICCSaxDelegator class as internal.
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { public interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { internal interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
Fix the issue with settings name
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]); return Ok(jwt); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]); return Ok(jwt); } } }
Allow Button.Text to be set to null
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value); LayoutIfNeeded(oldSize); } } } }
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value ?? string.Empty); LayoutIfNeeded(oldSize); } } } }
Increase the point at which normal keys start in ManiaAction
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special, [Description("Special")] Specia2, [Description("Key 1")] Key1 = 10, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special, [Description("Special")] Specia2, [Description("Key 1")] Key1 = 1000, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
Remove unused field, for now
using System; using System.Linq; using System.Threading.Tasks; using Octokit; using Rackspace.Threading; using UnityEditor; using UnityEngine; namespace GitHub.Unity { class LoadingView : Subview { private static readonly Vector2 viewSize = new Vector2(300, 250); private bool isBusy; private const string WindowTitle = "Loading..."; private const string Header = ""; public override void InitializeView(IView parent) { base.InitializeView(parent); Title = WindowTitle; Size = viewSize; } public override void OnGUI() {} public override bool IsBusy { get { return false; } } } }
using System; using System.Linq; using System.Threading.Tasks; using Octokit; using Rackspace.Threading; using UnityEditor; using UnityEngine; namespace GitHub.Unity { class LoadingView : Subview { private static readonly Vector2 viewSize = new Vector2(300, 250); private const string WindowTitle = "Loading..."; private const string Header = ""; public override void InitializeView(IView parent) { base.InitializeView(parent); Title = WindowTitle; Size = viewSize; } public override void OnGUI() {} public override bool IsBusy { get { return false; } } } }
Handle physical back button in result view
using System; using Xamarin.Forms; using Xamarin.Forms.OAuth; namespace OAuthTestApp { public class ResultPage : ContentPage { public ResultPage(AuthenticatonResult result, Action returnCallback) { var stack = new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; if (result) { stack.Children.Add(new Label { Text = $"Provider: {result.Account.Provider}" }); stack.Children.Add(new Label { Text = $"Id: {result.Account.Id}" }); stack.Children.Add(new Label { Text = $"Name: {result.Account.DisplayName}" }); stack.Children.Add(new Label { Text = $"Access Token: {result.Account.AccessToken}" }); } else { stack.Children.Add(new Label { Text = "Authentication failed!" }); stack.Children.Add(new Label { Text = $"Reason: {result.ErrorMessage}" }); } stack.Children.Add(new Button { Text = "Back", Command = new Command(returnCallback) }); Content = stack; } } }
using System; using Xamarin.Forms; using Xamarin.Forms.OAuth; using Xamarin.Forms.OAuth.Views; namespace OAuthTestApp { public class ResultPage : ContentPage, IBackHandlingView { private readonly Action _returnCallback; public ResultPage(AuthenticatonResult result, Action returnCallback) { _returnCallback = returnCallback; var stack = new StackLayout { VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; if (result) { stack.Children.Add(new Label { Text = $"Provider: {result.Account.Provider}" }); stack.Children.Add(new Label { Text = $"Id: {result.Account.Id}" }); stack.Children.Add(new Label { Text = $"Name: {result.Account.DisplayName}" }); stack.Children.Add(new Label { Text = $"Access Token: {result.Account.AccessToken}" }); } else { stack.Children.Add(new Label { Text = "Authentication failed!" }); stack.Children.Add(new Label { Text = $"Reason: {result.ErrorMessage}" }); } stack.Children.Add(new Button { Text = "Back", Command = new Command(returnCallback) }); Content = stack; } public void HandleBack() { _returnCallback?.Invoke(); } } }
Move input block for thread safe
using Sync.Command; using Sync.MessageFilter; using Sync.Plugins; using Sync.Source; using Sync.Tools; using System; using System.Diagnostics; using static Sync.Tools.IO; namespace Sync { public static class Program { //public static I18n i18n; static void Main(string[] args) { /* 程序工作流程: * 1.程序枚举所有插件,保存所有IPlugin到List中 * 2.程序整理出所有的List<ISourceBase> * 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance * 4.程序IO Manager开始工作,等待用户输入 */ I18n.Instance.ApplyLanguage(new DefaultI18n()); while(true) { SyncHost.Instance = new SyncHost(); SyncHost.Instance.Load(); CurrentIO.WriteWelcome(); string cmd = CurrentIO.ReadCommand(); while (true) { SyncHost.Instance.Commands.invokeCmdString(cmd); cmd = CurrentIO.ReadCommand(); } } } } }
using Sync.Command; using Sync.MessageFilter; using Sync.Plugins; using Sync.Source; using Sync.Tools; using System; using System.Diagnostics; using static Sync.Tools.IO; namespace Sync { public static class Program { //public static I18n i18n; static void Main(string[] args) { /* 程序工作流程: * 1.程序枚举所有插件,保存所有IPlugin到List中 * 2.程序整理出所有的List<ISourceBase> * 3.初始化Sync类,Sync类检测配置文件,用正确的类初始化SyncInstance * 4.程序IO Manager开始工作,等待用户输入 */ I18n.Instance.ApplyLanguage(new DefaultI18n()); while(true) { SyncHost.Instance = new SyncHost(); SyncHost.Instance.Load(); CurrentIO.WriteWelcome(); string cmd = ""; while (true) { SyncHost.Instance.Commands.invokeCmdString(cmd); cmd = CurrentIO.ReadCommand(); } } } } }
Disable UWP C++ (for now)
using Microsoft.VisualStudio.ConnectedServices; namespace AzureIoTHubConnectedService { [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService", AppliesTo = "VisualC+WindowsAppContainer")] internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler { protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context) { HandlerManifest manifest = new HandlerManifest(); manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8")); manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h")); return manifest; } protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context) { return new AddServiceInstanceResult( "", null ); } protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context) { return new AzureIoTHubConnectedServiceHandlerHelper(context); } } }
using Microsoft.VisualStudio.ConnectedServices; namespace AzureIoTHubConnectedService { #if false // Disabled to a bug: https://github.com/Azure/azure-iot-sdks/issues/289 [ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService", AppliesTo = "VisualC+WindowsAppContainer")] #endif internal class CppHandlerWAC : GenericAzureIoTHubServiceHandler { protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context) { HandlerManifest manifest = new HandlerManifest(); manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8")); manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.cpp")); manifest.Files.Add(new FileToAdd("CPP/WAC/azure_iot_hub.h")); return manifest; } protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context) { return new AddServiceInstanceResult( "", null ); } protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context) { return new AzureIoTHubConnectedServiceHandlerHelper(context); } } }
Add additional params to index request
// 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.Collections.Generic; using Newtonsoft.Json; using osu.Game.Online.API; namespace osu.Game.Online.Multiplayer { public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores> { private readonly int roomId; private readonly int playlistItemId; public IndexPlaylistScoresRequest(int roomId, int playlistItemId) { this.roomId = roomId; this.playlistItemId = playlistItemId; } protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores"; } public class RoomPlaylistScores { [JsonProperty("scores")] public List<MultiplayerScore> Scores { get; set; } } }
// 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.Collections.Generic; using Newtonsoft.Json; using osu.Framework.IO.Network; using osu.Game.Extensions; using osu.Game.Online.API; using osu.Game.Online.API.Requests; namespace osu.Game.Online.Multiplayer { /// <summary> /// Returns a list of scores for the specified playlist item. /// </summary> public class IndexPlaylistScoresRequest : APIRequest<RoomPlaylistScores> { private readonly int roomId; private readonly int playlistItemId; private readonly Cursor cursor; private readonly MultiplayerScoresSort? sort; public IndexPlaylistScoresRequest(int roomId, int playlistItemId, Cursor cursor = null, MultiplayerScoresSort? sort = null) { this.roomId = roomId; this.playlistItemId = playlistItemId; this.cursor = cursor; this.sort = sort; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.AddCursor(cursor); switch (sort) { case MultiplayerScoresSort.Ascending: req.AddParameter("sort", "scores_asc"); break; case MultiplayerScoresSort.Descending: req.AddParameter("sort", "scores_desc"); break; } return req; } protected override string Target => $@"rooms/{roomId}/playlist/{playlistItemId}/scores"; } public class RoomPlaylistScores { [JsonProperty("scores")] public List<MultiplayerScore> Scores { get; set; } } }
Fix concurrency issue accessing Dictionary instance
using System; using System.Collections.Generic; using System.Linq; namespace Orchard.Caching { public class Cache<TKey, TResult> : ICache<TKey, TResult> { private readonly Dictionary<TKey, CacheEntry> _entries; public Cache() { _entries = new Dictionary<TKey, CacheEntry>(); } public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) { CacheEntry entry; if (!_entries.TryGetValue(key, out entry) || entry.Tokens.Any(t => !t.IsCurrent)) { entry = new CacheEntry { Tokens = new List<IVolatileToken>() }; var context = new AcquireContext<TKey>(key, volatileItem => entry.Tokens.Add(volatileItem)); entry.Result = acquire(context); _entries[key] = entry; } return entry.Result; } private class CacheEntry { public TResult Result { get; set; } public IList<IVolatileToken> Tokens { get; set; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Orchard.Caching { public class Cache<TKey, TResult> : ICache<TKey, TResult> { private readonly ConcurrentDictionary<TKey, CacheEntry> _entries; public Cache() { _entries = new ConcurrentDictionary<TKey, CacheEntry>(); } public TResult Get(TKey key, Func<AcquireContext<TKey>, TResult> acquire) { var entry = _entries.AddOrUpdate(key, // "Add" lambda k => CreateEntry(k, acquire), // "Update" lamdba (k, currentEntry) => (currentEntry.Tokens.All(t => t.IsCurrent) ? currentEntry : CreateEntry(k, acquire))); return entry.Result; } private static CacheEntry CreateEntry(TKey k, Func<AcquireContext<TKey>, TResult> acquire) { var entry = new CacheEntry { Tokens = new List<IVolatileToken>() }; var context = new AcquireContext<TKey>(k, volatileItem => entry.Tokens.Add(volatileItem)); entry.Result = acquire(context); return entry; } private class CacheEntry { public TResult Result { get; set; } public IList<IVolatileToken> Tokens { get; set; } } } }
Use local user when not in domain
using FootballLeague.Models; using System.DirectoryServices; namespace FootballLeague.Services { public class UsersADSearcher : IUsersADSearcher { public User LoadUserDetails(string userName) { var entry = new DirectoryEntry(); var searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))"; searcher.PropertiesToLoad.Add("givenName"); searcher.PropertiesToLoad.Add("sn"); searcher.PropertiesToLoad.Add("mail"); var userProps = searcher.FindOne().Properties; var mail = userProps["mail"][0].ToString(); var first = userProps["givenName"][0].ToString(); var last = userProps["sn"][0].ToString(); return new User { Name = userName, Mail = mail, FirstName = first, LastName = last }; } } }
using System.Linq; using System.Web; using FootballLeague.Models; using System.DirectoryServices; namespace FootballLeague.Services { public class UsersADSearcher : IUsersADSearcher { public User LoadUserDetails(string userName) { var entry = new DirectoryEntry(); var searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + userName + "))"; searcher.PropertiesToLoad.Add("givenName"); searcher.PropertiesToLoad.Add("sn"); searcher.PropertiesToLoad.Add("mail"); try { var userProps = searcher.FindOne().Properties; var mail = userProps["mail"][0].ToString(); var first = userProps["givenName"][0].ToString(); var last = userProps["sn"][0].ToString(); return new User { Name = userName, Mail = mail, FirstName = first, LastName = last }; } catch { return new User { Name = HttpContext.Current.User.Identity.Name.Split('\\').Last(), Mail = "local@user.sk", FirstName = "Local", LastName = "User" }; } } } }
Use a set of defines, and some generics
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup); if (!defines.EndsWith(";")) defines += ";"; defines += string.Join(";", TeakDefines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines); } }
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; using System.Collections.Generic; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(";"); HashSet<string> defines = new HashSet<string>(existingDefines); defines.UnionWith(TeakDefines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.ToArray())); } }
Add a detailed comment to explain why we test this
using System; using System.Collections.Generic; namespace Stripe.Tests.Xunit { public class coupons_fixture : IDisposable { public StripeCouponCreateOptions CouponCreateOptions { get; set; } public StripeCouponUpdateOptions CouponUpdateOptions { get; set; } public StripeCoupon Coupon { get; set; } public StripeCoupon CouponRetrieved { get; set; } public StripeCoupon CouponUpdated { get; set; } public StripeDeleted CouponDeleted { get; set; } public StripeList<StripeCoupon> CouponsList { get; } public coupons_fixture() { CouponCreateOptions = new StripeCouponCreateOptions() { Id = "test-coupon-" + Guid.NewGuid().ToString() + " ", PercentOff = 25, Duration = "repeating", DurationInMonths = 3, }; CouponUpdateOptions = new StripeCouponUpdateOptions { Metadata = new Dictionary<string, string>{{"key_1", "value_1"}} }; var service = new StripeCouponService(Cache.ApiKey); Coupon = service.Create(CouponCreateOptions); CouponRetrieved = service.Get(Coupon.Id); CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions); CouponsList = service.List(); CouponDeleted = service.Delete(Coupon.Id); } public void Dispose() { } } }
using System; using System.Collections.Generic; namespace Stripe.Tests.Xunit { public class coupons_fixture : IDisposable { public StripeCouponCreateOptions CouponCreateOptions { get; set; } public StripeCouponUpdateOptions CouponUpdateOptions { get; set; } public StripeCoupon Coupon { get; set; } public StripeCoupon CouponRetrieved { get; set; } public StripeCoupon CouponUpdated { get; set; } public StripeDeleted CouponDeleted { get; set; } public StripeList<StripeCoupon> CouponsList { get; } public coupons_fixture() { CouponCreateOptions = new StripeCouponCreateOptions() { // Add a space at the end to ensure the ID is properly URL encoded // when passed in the URL for other methods Id = "test-coupon-" + Guid.NewGuid().ToString() + " ", PercentOff = 25, Duration = "repeating", DurationInMonths = 3, }; CouponUpdateOptions = new StripeCouponUpdateOptions { Metadata = new Dictionary<string, string>{{"key_1", "value_1"}} }; var service = new StripeCouponService(Cache.ApiKey); Coupon = service.Create(CouponCreateOptions); CouponRetrieved = service.Get(Coupon.Id); CouponUpdated = service.Update(Coupon.Id, CouponUpdateOptions); CouponsList = service.List(); CouponDeleted = service.Delete(Coupon.Id); } public void Dispose() { } } }
Enable NesZord.Tests to se internal members of NesZord.Core
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NesZord.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NesZord.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NesZord.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NesZord.Core")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("NesZord.Tests")]
Allow translation of boolean filtering text.
using UnityEngine; namespace PrepareLanding.Core.Extensions { public static class FilterBooleanExtensions { public static string ToStringHuman(this FilterBoolean filterBool) { switch (filterBool) { case FilterBoolean.AndFiltering: return "AND"; case FilterBoolean.OrFiltering: return "OR"; default: return "UNK"; } } public static FilterBoolean Next(this FilterBoolean filterBoolean) { return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined); } public static Color Color(this FilterBoolean filterBoolean) { switch (filterBoolean) { case FilterBoolean.AndFiltering: return Verse.ColorLibrary.BurntOrange; case FilterBoolean.OrFiltering: return Verse.ColorLibrary.BrightBlue; default: return UnityEngine.Color.black; } } } }
using UnityEngine; using Verse; namespace PrepareLanding.Core.Extensions { public static class FilterBooleanExtensions { public static string ToStringHuman(this FilterBoolean filterBool) { switch (filterBool) { case FilterBoolean.AndFiltering: return "PLMWTT_FilterBooleanOr".Translate(); case FilterBoolean.OrFiltering: return "PLMWTT_FilterBooleanAnd".Translate(); default: return "UNK"; } } public static FilterBoolean Next(this FilterBoolean filterBoolean) { return (FilterBoolean)(((int)filterBoolean + 1) % (int)FilterBoolean.Undefined); } public static Color Color(this FilterBoolean filterBoolean) { switch (filterBoolean) { case FilterBoolean.AndFiltering: return Verse.ColorLibrary.BurntOrange; case FilterBoolean.OrFiltering: return Verse.ColorLibrary.BrightBlue; default: return UnityEngine.Color.black; } } } }
Use correct Gnome3 default DPI
using System; using System.Runtime.InteropServices; namespace OpenSage.Utilities { public static class PlatformUtility { /// <summary> /// Check if current platform is windows /// </summary> /// <returns></returns> public static bool IsWindowsPlatform() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32Windows: case PlatformID.Win32NT: case PlatformID.WinCE: case PlatformID.Win32S: return true; default: return false; } } public static float GetDefaultDpi() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return 96.0f; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return 72.0f; } else { return 1.0f; // TODO: What happens on Linux? } } } }
using System; using System.Runtime.InteropServices; namespace OpenSage.Utilities { public static class PlatformUtility { /// <summary> /// Check if current platform is windows /// </summary> /// <returns></returns> public static bool IsWindowsPlatform() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32Windows: case PlatformID.Win32NT: case PlatformID.WinCE: case PlatformID.Win32S: return true; default: return false; } } public static float GetDefaultDpi() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return 96.0f; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return 72.0f; } else { return 96.0f; // TODO: For GNOME3 the default DPI is 96 } } } }
Make $id and $token properties in plugin objects unmodifiable
using System.Text; using TweetDuck.Plugins.Enums; namespace TweetDuck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("};"); build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } }
using System.Globalization; using TweetDuck.Plugins.Enums; namespace TweetDuck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ return PluginGen .Replace("%params", environment.GetScriptVariables()) .Replace("%id", pluginIdentifier) .Replace("%token", pluginToken.ToString(CultureInfo.InvariantCulture)) .Replace("%contents", pluginContents); } private const string PluginGen = "(function(%params,$d){let tmp={id:'%id',obj:new class extends PluginBase{%contents}};$d(tmp.obj,'$id',{value:'%id'});$d(tmp.obj,'$token',{value:%token});window.TD_PLUGINS.install(tmp);})(%params,Object.defineProperty);"; /* PluginGen (function(%params, $i, $d){ let tmp = { id: '%id', obj: new class extends PluginBase{%contents} }; $d(tmp.obj, '$id', { value: '%id' }); $d(tmp.obj, '$token', { value: %token }); window.TD_PLUGINS.install(tmp); })(%params, Object.defineProperty); */ } }
Make ApplyChangesTogether automatically filled to false if not present.
using System.Collections.Generic; using Newtonsoft.Json; namespace OmniSharp.Models { public class Request : SimpleFileRequest { [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Line { get; set; } [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Column { get; set; } public string Buffer { get; set; } public IEnumerable<LinePositionSpanTextChange> Changes { get; set; } public bool ApplyChangesTogether { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace OmniSharp.Models { public class Request : SimpleFileRequest { [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Line { get; set; } [JsonConverter(typeof(ZeroBasedIndexConverter))] public int Column { get; set; } public string Buffer { get; set; } public IEnumerable<LinePositionSpanTextChange> Changes { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] public bool ApplyChangesTogether { get; set; } } }
Fix JSON file locking issue
using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; namespace LibYear.Lib.FileTypes { public class ProjectJsonFile : IProjectFile { private string _fileContents; public string FileName { get; } public IDictionary<string, PackageVersion> Packages { get; } public ProjectJsonFile(string filename) { FileName = filename; _fileContents = File.ReadAllText(FileName); Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString())); } private IEnumerable<JToken> GetDependencies() { return JObject.Parse(_fileContents).Descendants() .Where(d => d.Type == JTokenType.Property && d.Path.Contains("dependencies") && (!d.Path.Contains("[") || d.Path.EndsWith("]")) && ((JProperty)d).Value.Type == JTokenType.String); } public void Update(IEnumerable<Result> results) { lock (_fileContents) { foreach (var result in results) _fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\""); File.WriteAllText(FileName, _fileContents); } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; namespace LibYear.Lib.FileTypes { public class ProjectJsonFile : IProjectFile { private string _fileContents; public string FileName { get; } public IDictionary<string, PackageVersion> Packages { get; } private readonly object _lock = new object(); public ProjectJsonFile(string filename) { FileName = filename; _fileContents = File.ReadAllText(FileName); Packages = GetDependencies().ToDictionary(p => ((JProperty)p).Name.ToString(), p => PackageVersion.Parse(((JProperty)p).Value.ToString())); } private IEnumerable<JToken> GetDependencies() { return JObject.Parse(_fileContents).Descendants() .Where(d => d.Type == JTokenType.Property && d.Path.Contains("dependencies") && (!d.Path.Contains("[") || d.Path.EndsWith("]")) && ((JProperty)d).Value.Type == JTokenType.String); } public void Update(IEnumerable<Result> results) { lock (_lock) { foreach (var result in results) { _fileContents = _fileContents.Replace($"\"{result.Name}\": \"{result.Installed.Version}\"", $"\"{result.Name}\": \"{result.Latest.Version}\""); } File.WriteAllText(FileName, _fileContents); } } } }
Add example for state init option to quick-start guide example project.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; //JsonObject config = new JsonObject(); JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); //request.set("config", config); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using LearnositySDK.Request; using LearnositySDK.Utils; // static LearnositySDK.Credentials; namespace LearnosityDemo.Pages { public class ItemsAPIDemoModel : PageModel { public void OnGet() { // prepare all the params string service = "items"; JsonObject security = new JsonObject(); security.set("consumer_key", LearnositySDK.Credentials.ConsumerKey); security.set("domain", LearnositySDK.Credentials.Domain); security.set("user_id", Uuid.generate()); string secret = LearnositySDK.Credentials.ConsumerSecret; JsonObject request = new JsonObject(); request.set("user_id", Uuid.generate()); request.set("activity_template_id", "quickstart_examples_activity_template_001"); request.set("session_id", Uuid.generate()); request.set("activity_id", "quickstart_examples_activity_001"); request.set("rendering_type", "assess"); request.set("type", "submit_practice"); request.set("name", "Items API Quickstart"); request.set("state", "initial"); // Instantiate Init class Init init = new Init(service, security, secret, request); // Call the generate() method to retrieve a JavaScript object ViewData["InitJSON"] = init.generate(); } } }
Change "RSS Headlines" widget name
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Headlines"; } }
namespace DesktopWidgets.Widgets.RSSFeed { public static class Metadata { public const string FriendlyName = "RSS Feed"; } }
Add new Google Analytics tracking ID
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('mscTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
@using Microsoft.ApplicationInsights.Extensibility @inject TelemetryConfiguration TelemetryConfiguration <environment names="Production"> <script type="text/javascript"> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-61337531-1', 'auto', { 'name': 'mscTracker' }); ga('create', 'UA-61337531-4', 'auto', { 'name': 'liveaspnetTracker' }); ga('mscTracker.send', 'pageview'); ga('liveaspnetTracker.send', 'pageview'); </script> @Html.ApplicationInsightsJavaScript(TelemetryConfiguration) </environment>
Increment Intrinio time between calls to 1 minute
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMilliseconds(5000)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
using System; using QuantConnect.Parameters; using QuantConnect.Util; namespace QuantConnect.Data.Custom.Intrinio { /// <summary> /// Auxiliary class to access all Intrinio API data. /// </summary> public static class IntrinioConfig { /// <summary> /// </summary> public static RateGate RateGate = new RateGate(1, TimeSpan.FromMinutes(1)); /// <summary> /// Check if Intrinio API user and password are not empty or null. /// </summary> public static bool IsInitialized => !string.IsNullOrWhiteSpace(User) && !string.IsNullOrWhiteSpace(Password); /// <summary> /// Intrinio API password /// </summary> public static string Password = string.Empty; /// <summary> /// Intrinio API user /// </summary> public static string User = string.Empty; /// <summary> /// Set the Intrinio API user and password. /// </summary> public static void SetUserAndPassword(string user, string password) { User = user; Password = password; if (!IsInitialized) { throw new InvalidOperationException("Please set a valid Intrinio user and password."); } } } }
Add missing attributes to paymentSource
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class PaymentSource : Resource { public string id { get; set; } public string type { get; set; } /* In case card token */ public string token_id { get; set; } /* In case card object*/ public string name { get; set; } public string number { get; set; } public string exp_month { get; set; } public string exp_year { get; set; } public string cvc { get; set; } public string last4 { get; set; } public string bin { get; set; } public string brand { get; set; } public Address address { get; set; } public string parent_id { get; set; } public PaymentSource update(string data) { PaymentSource payment_source = this.toClass(this.toObject(this.update("/customers/" + this.parent_id + "/payment_sources/" + this.id, data)).ToString()); return payment_source; } public PaymentSource destroy() { this.delete("/customers/" + this.parent_id + "/payment_sources/" + this.id); return this; } public PaymentSource toClass(string json) { PaymentSource payment_source = JsonConvert.DeserializeObject<PaymentSource>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return payment_source; } } }
Remove redundant getters and setters
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] public string Carrier { get; set; } [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber { get; set; } [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom { get; set; } [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo { get; set; } [JsonProperty (PropertyName = "eta")] public DateTime? Eta { get; set; } [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel { get; set; } [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus { get; set; } [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory { get; set; } [JsonProperty (PropertyName = "metadata")] public string Metadata { get; set; } public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace Shippo { [JsonObject (MemberSerialization.OptIn)] public class Track : ShippoId { [JsonProperty (PropertyName = "carrier")] private string Carrier; [JsonProperty (PropertyName = "tracking_number")] public string TrackingNumber; [JsonProperty (PropertyName = "address_from")] public ShortAddress AddressFrom; [JsonProperty (PropertyName = "address_to")] public ShortAddress AddressTo; [JsonProperty (PropertyName = "eta")] public DateTime? Eta; [JsonProperty (PropertyName = "servicelevel")] public Servicelevel Servicelevel; [JsonProperty (PropertyName = "tracking_status")] public TrackingStatus TrackingStatus; [JsonProperty (PropertyName = "tracking_history")] public List<TrackingHistory> TrackingHistory; [JsonProperty (PropertyName = "metadata")] public string Metadata; public override string ToString () { return string.Format ("[Track: Carrier={0}, TrackingNumber={1}, AddressFrom={2}, AddressTo={3}, Eta={4}," + "Servicelevel={5}, TrackingStatus={6}, TrackingHistory={7}, Metadata={8}]",Carrier, TrackingNumber, AddressFrom, AddressTo, Eta, Servicelevel, TrackingStatus, TrackingHistory, Metadata); } } }
Add comments to physical props
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3 /// </summary> public float Density { get; set; } /// <summary> /// Granularität /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit /// </summary> public float FractureToughness { get; set; } } }
namespace OctoAwesome { /// <summary> /// Repräsentiert die physikalischen Eigenschaften eines Blocks/Items/... /// </summary> public class PhysicalProperties { /// <summary> /// Härte, welche Materialien können abgebaut werden /// </summary> public float Hardness { get; set; } /// <summary> /// Dichte in kg/dm^3, Wie viel benötigt (Volumen berechnung) für Crafting bzw. hit result etc.... /// </summary> public float Density { get; set; } /// <summary> /// Granularität, Effiktivität von "Materialien" Schaufel für hohe Werte, Pickaxe für niedrige /// </summary> public float Granularity { get; set; } /// <summary> /// Bruchzähigkeit, Wie schnell geht etwas zu bruch? Haltbarkeit. /// </summary> public float FractureToughness { get; set; } } }
Add generic version of interface
// 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. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } }
// 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. namespace osu.Framework.Bindables { /// <summary> /// An interface that represents a read-only leased bindable. /// </summary> public interface ILeasedBindable : IBindable { /// <summary> /// End the lease on the source <see cref="Bindable{T}"/>. /// </summary> void Return(); } /// <summary> /// An interface that representes a read-only leased bindable. /// </summary> /// <typeparam name="T">The value type of the bindable.</typeparam> public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T> { } }
Add the MitternachtBot instance and its services to the ASP.NET services.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace MitternachtWeb { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using System.Linq; namespace MitternachtWeb { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.Add(ServiceDescriptor.Singleton(Program.MitternachtBot)); services.Add(Program.MitternachtBot.Services.Services.Select(s => ServiceDescriptor.Singleton(s.Key, s.Value))); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
Revert "make command line host non blocking"
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Start(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }
using System.IO; using Microsoft.AspNetCore.Hosting; using Orchard.Hosting; using Orchard.Web; namespace Orchard.Console { public class Program { public static void Main(string[] args) { var currentDirectory = Directory.GetCurrentDirectory(); var host = new WebHostBuilder() .UseIISIntegration() .UseKestrel() .UseContentRoot(currentDirectory) .UseWebRoot(currentDirectory) .UseStartup<Startup>() .Build(); using (host) { host.Run(); var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args); orchardHost.Run(); } } } }