Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add using statement for Swashbuckle 4.0
using Swashbuckle.AspNetCore.SwaggerGen; namespace Swashbuckle.AspNetCore.Filters { public static class SwaggerGenOptionsExtensions { public static void ExampleFilters(this SwaggerGenOptions swaggerGenOptions) { swaggerGenOptions.OperationFilter<ExamplesOperationFilter>(); swaggerGenOptions.OperationFilter<ServiceProviderExamplesOperationFilter>(); } } }
using Microsoft.Extensions.DependencyInjection; using Swashbuckle.AspNetCore.SwaggerGen; namespace Swashbuckle.AspNetCore.Filters { public static class SwaggerGenOptionsExtensions { public static void ExampleFilters(this SwaggerGenOptions swaggerGenOptions) { swaggerGenOptions.OperationFilter<ExamplesOperationFilter>(); swaggerGenOptions.OperationFilter<ServiceProviderExamplesOperationFilter>(); } } }
Use slug for single search result
using Hops.Repositories; using Microsoft.AspNet.Mvc; using System.Collections.Generic; using System.Linq; namespace Hops.Controllers { [Route("[controller]")] public class SearchController : Controller { private ISqliteRepository sqliteRepository; public SearchController(ISqliteRepository sqliteRepository) { this.sqliteRepository = sqliteRepository; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet("{searchTerm}/{page:int?}")] public IActionResult Results(string searchTerm, int page = 1) { var results = sqliteRepository.Search(searchTerm, page); if (results.List.Count == 0) { return View("NoResults", sqliteRepository.GetRandomHop()); } if (results.List.Count == 1) { return Redirect($"/Hop/{results.List.First().Hop.Id}"); } return View(results); } [HttpGet("inventory/{page:int?}")] public IActionResult Inventory(string searchTerm, int page = 1) { return View(page); } [HttpGet("aroma/{profile:int}/{page:int?}")] public IActionResult Results(int profile, int page = 1) { var results = sqliteRepository.Search(profile, page); return View(results); } [HttpGet("autocomplete/{searchTerm}")] public List<string> AutoComplete(string searchTerm) { return sqliteRepository.Autocomplete(searchTerm); } } }
using Hops.Repositories; using Microsoft.AspNet.Mvc; using System.Collections.Generic; using System.Linq; namespace Hops.Controllers { [Route("[controller]")] public class SearchController : Controller { private ISqliteRepository sqliteRepository; public SearchController(ISqliteRepository sqliteRepository) { this.sqliteRepository = sqliteRepository; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet("{searchTerm}/{page:int?}")] public IActionResult Results(string searchTerm, int page = 1) { var results = sqliteRepository.Search(searchTerm, page); if (results.List.Count == 0) { return View("NoResults", sqliteRepository.GetRandomHop()); } if (results.List.Count == 1) { return Redirect($"/hop/{results.List.First().Hop.Slug()}"); } return View(results); } [HttpGet("inventory/{page:int?}")] public IActionResult Inventory(string searchTerm, int page = 1) { return View(page); } [HttpGet("aroma/{profile:int}/{page:int?}")] public IActionResult Results(int profile, int page = 1) { var results = sqliteRepository.Search(profile, page); return View(results); } [HttpGet("autocomplete/{searchTerm}")] public List<string> AutoComplete(string searchTerm) { return sqliteRepository.Autocomplete(searchTerm); } } }
Fix compilation error introduced with last minute cleanup added when looking at the diff.
using System.Collections.Generic; namespace Parser { // Assigns each locale an ID from 0 to n - 1 internal static class LocaleIdAllocator { public static void Run(ParserContext parser, IList<CompilationScope> scopes) { foreach (CompilationScope scope in scopes) { if (!parser.LocaleIds.ContainsKey(scope.Locale)) { parser.LocaleIds.Add(scope.Locale, parser.LocaleIds.Count); } } } } }
using System.Collections.Generic; namespace Parser { // Assigns each locale an ID from 0 to n - 1 internal static class LocaleIdAllocator { // TODO: merge this with the current ID allocator in ParserContext. public static void Run(ParserContext parser, IList<CompilationScope> scopes) { /* foreach (CompilationScope scope in scopes) { if (!parser.LocaleIds.ContainsKey(scope.Locale)) { parser.LocaleIds.Add(scope.Locale, parser.LocaleIds.Count); } }//*/ } } }
Remove explicit default value initialization.
using System; using System.Runtime.CompilerServices; using System.Threading; namespace GUtils.Testing { /// <summary> /// A class that tracks the amount of times its <see cref="WrappedDelegate" /> was invoked. /// </summary> /// <typeparam name="T"></typeparam> public class DelegateInvocationCounter<T> where T : Delegate { private Int32 _invocationCount = 0; /// <summary> /// The number of times <see cref="WrappedDelegate" /> was invoked. /// </summary> public Int32 InvocationCount => this._invocationCount; /// <summary> /// The wrapper delegate that increments the invocation count when invoked. /// </summary> public T WrappedDelegate { get; internal set; } = null!; /// <summary> /// Atomically increments the number of invocations of this delegate. /// </summary> [MethodImpl ( MethodImplOptions.AggressiveInlining )] internal void Increment ( ) => Interlocked.Increment ( ref this._invocationCount ); /// <summary> /// Resets the number of invocations of this counter. /// </summary> public void Reset ( ) => this._invocationCount = 0; } }
using System; using System.Runtime.CompilerServices; using System.Threading; namespace GUtils.Testing { /// <summary> /// A class that tracks the amount of times its <see cref="WrappedDelegate" /> was invoked. /// </summary> /// <typeparam name="T"></typeparam> public class DelegateInvocationCounter<T> where T : Delegate { private Int32 _invocationCount; /// <summary> /// The number of times <see cref="WrappedDelegate" /> was invoked. /// </summary> public Int32 InvocationCount => this._invocationCount; /// <summary> /// The wrapper delegate that increments the invocation count when invoked. /// </summary> public T WrappedDelegate { get; internal set; } = null!; /// <summary> /// Atomically increments the number of invocations of this delegate. /// </summary> [MethodImpl ( MethodImplOptions.AggressiveInlining )] internal void Increment ( ) => Interlocked.Increment ( ref this._invocationCount ); /// <summary> /// Resets the number of invocations of this counter. /// </summary> public void Reset ( ) => this._invocationCount = 0; } }
Use login/getting started background image.
using Foundation; using System; using UIKit; namespace MyDriving.iOS { public partial class GettingStartedContentViewController : UIViewController { public UIImage Image { get; set; } public int PageIndex { get; set; } public GettingStartedContentViewController (IntPtr handle) : base (handle) { } public static GettingStartedContentViewController ControllerForPageIndex(int pageIndex) { var imagePath = string.Format($"screen_{pageIndex+1}.png"); var image = UIImage.FromBundle(imagePath); var page = (GettingStartedContentViewController)UIStoryboard.FromName("Main", null).InstantiateViewController("gettingStartedContentViewController"); page.Image = image; page.PageIndex = pageIndex; return page; } public override void ViewDidLoad() { base.ViewDidLoad(); imageView.Image = Image; } } }
using Foundation; using System; using UIKit; namespace MyDriving.iOS { public partial class GettingStartedContentViewController : UIViewController { public UIImage Image { get; set; } public int PageIndex { get; set; } public GettingStartedContentViewController (IntPtr handle) : base (handle) { } public static GettingStartedContentViewController ControllerForPageIndex(int pageIndex) { var imagePath = string.Format($"screen_{pageIndex+1}.png"); var image = UIImage.FromBundle(imagePath); var page = (GettingStartedContentViewController)UIStoryboard.FromName("Main", null).InstantiateViewController("gettingStartedContentViewController"); page.Image = image; page.PageIndex = pageIndex; return page; } public override void ViewDidLoad() { base.ViewDidLoad(); View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle("background_started.png")); imageView.Image = Image; } } }
Add volatile keyword accroding to the doc
using System; using System.Linq; using System.Collections.Generic; using Wukong.Models; namespace Wukong.Services { public sealed class Storage { static readonly Lazy<Storage> instance = new Lazy<Storage>(() => new Storage()); IDictionary<string, User> userMap = new Dictionary<string, User>(); IDictionary<string, Channel> channelMap = new Dictionary<string, Channel>(); public static Storage Instance { get { return instance.Value; } } Storage() { } public User GetUser(string userId) { if (!userMap.ContainsKey(userId)) { userMap.Add(userId, new User(userId)); } return userMap[userId]; } public Channel GetChannel(string channelId) { if (channelId == null || !channelMap.ContainsKey(channelId)) { return null; } return channelMap[channelId]; } public void RemoveChannel(string channelId) { channelMap.Remove(channelId); } public List<Channel> GetAllChannelsWithUserId(string userId) { return channelMap.Values.Where(x => x.HasUser(userId)).ToList(); } public Channel CreateChannel(string channelId, ISocketManager socketManager, IProvider provider) { channelMap[channelId] = new Channel(channelId, socketManager, provider); return channelMap[channelId]; } } }
using System; using System.Linq; using System.Collections.Generic; using Wukong.Models; namespace Wukong.Services { public sealed class Storage { static readonly Lazy<Storage> instance = new Lazy<Storage>(() => new Storage()); volatile IDictionary<string, User> userMap = new Dictionary<string, User>(); volatile IDictionary<string, Channel> channelMap = new Dictionary<string, Channel>(); public static Storage Instance { get { return instance.Value; } } Storage() { } public User GetUser(string userId) { if (!userMap.ContainsKey(userId)) { userMap.Add(userId, new User(userId)); } return userMap[userId]; } public Channel GetChannel(string channelId) { if (channelId == null || !channelMap.ContainsKey(channelId)) { return null; } return channelMap[channelId]; } public void RemoveChannel(string channelId) { channelMap.Remove(channelId); } public List<Channel> GetAllChannelsWithUserId(string userId) { return channelMap.Values.Where(x => x.HasUser(userId)).ToList(); } public Channel CreateChannel(string channelId, ISocketManager socketManager, IProvider provider) { channelMap[channelId] = new Channel(channelId, socketManager, provider); return channelMap[channelId]; } } }
Fix cursors sent to osu-web being potentially string formatted in incorrect culture
// 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.IO.Network; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Game.Online.API.Requests; namespace osu.Game.Extensions { public static class WebRequestExtensions { /// <summary> /// Add a pagination cursor to the web request in the format required by osu-web. /// </summary> public static void AddCursor(this WebRequest webRequest, Cursor cursor) { cursor?.Properties.ForEach(x => { webRequest.AddParameter("cursor[" + x.Key + "]", x.Value.ToString()); }); } } }
// 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 Newtonsoft.Json.Linq; using osu.Framework.IO.Network; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Game.Online.API.Requests; namespace osu.Game.Extensions { public static class WebRequestExtensions { /// <summary> /// Add a pagination cursor to the web request in the format required by osu-web. /// </summary> public static void AddCursor(this WebRequest webRequest, Cursor cursor) { cursor?.Properties.ForEach(x => { webRequest.AddParameter("cursor[" + x.Key + "]", (x.Value as JValue)?.ToString(CultureInfo.InvariantCulture) ?? x.Value.ToString()); }); } } }
Add more diagnostics to FileThumbPrint
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Security.Cryptography; namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests { public class FileThumbPrint : IEquatable<FileThumbPrint> { private FileThumbPrint(DateTime lastWriteTimeUtc, string hash) { LastWriteTimeUtc = lastWriteTimeUtc; Hash = hash; } public DateTime LastWriteTimeUtc { get; } public string Hash { get; } public static FileThumbPrint Create(string path) { byte[] hashBytes; using (var sha1 = SHA1.Create()) using (var fileStream = File.OpenRead(path)) { hashBytes = sha1.ComputeHash(fileStream); } var hash = Convert.ToBase64String(hashBytes); var lastWriteTimeUtc = File.GetLastWriteTimeUtc(path); return new FileThumbPrint(lastWriteTimeUtc, hash); } public bool Equals(FileThumbPrint other) { return LastWriteTimeUtc == other.LastWriteTimeUtc && string.Equals(Hash, other.Hash, StringComparison.Ordinal); } public override int GetHashCode() => LastWriteTimeUtc.GetHashCode(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Security.Cryptography; namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests { public class FileThumbPrint : IEquatable<FileThumbPrint> { private FileThumbPrint(string path, DateTime lastWriteTimeUtc, string hash) { Path = path; LastWriteTimeUtc = lastWriteTimeUtc; Hash = hash; } public string Path { get; } public DateTime LastWriteTimeUtc { get; } public string Hash { get; } public static FileThumbPrint Create(string path) { byte[] hashBytes; using (var sha1 = SHA1.Create()) using (var fileStream = File.OpenRead(path)) { hashBytes = sha1.ComputeHash(fileStream); } var hash = Convert.ToBase64String(hashBytes); var lastWriteTimeUtc = File.GetLastWriteTimeUtc(path); return new FileThumbPrint(path, lastWriteTimeUtc, hash); } public bool Equals(FileThumbPrint other) { return string.Equals(Path, other.Path, StringComparison.Ordinal) && LastWriteTimeUtc == other.LastWriteTimeUtc && string.Equals(Hash, other.Hash, StringComparison.Ordinal); } public override int GetHashCode() => LastWriteTimeUtc.GetHashCode(); } }
Fix broken implementation of static HttpClient
using System; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.Extensions.Options; namespace AllReady.Hangfire.Jobs { public class SendRequestStatusToGetASmokeAlarm : ISendRequestStatusToGetASmokeAlarm { private readonly IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings; private static readonly HttpClient HttpClient = new HttpClient(); public SendRequestStatusToGetASmokeAlarm(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { this.getASmokeAlarmApiSettings = getASmokeAlarmApiSettings; } public void Send(string serial, string status, bool acceptance) { var baseAddress = getASmokeAlarmApiSettings.Value.BaseAddress; var token = getASmokeAlarmApiSettings.Value.Token; var updateRequestMessage = new { acceptance, status }; HttpClient.BaseAddress = new Uri(baseAddress); HttpClient.DefaultRequestHeaders.Accept.Clear(); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpClient.DefaultRequestHeaders.Add("Authorization", token); var response = HttpClient.PostAsJsonAsync($"admin/requests/status/{serial}", updateRequestMessage).Result; //throw HttpRequestException if response is not a success code. response.EnsureSuccessStatusCode(); } } public interface ISendRequestStatusToGetASmokeAlarm { void Send(string serial, string status, bool acceptance); } }
using System; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.Extensions.Options; namespace AllReady.Hangfire.Jobs { public class SendRequestStatusToGetASmokeAlarm : ISendRequestStatusToGetASmokeAlarm { private static HttpClient httpClient; public SendRequestStatusToGetASmokeAlarm(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { CreateStaticHttpClient(getASmokeAlarmApiSettings); } public void Send(string serial, string status, bool acceptance) { var updateRequestMessage = new { acceptance, status }; var response = httpClient.PostAsJsonAsync($"admin/requests/status/{serial}", updateRequestMessage).Result; //throw HttpRequestException if response is not a success code. response.EnsureSuccessStatusCode(); } private void CreateStaticHttpClient(IOptions<GetASmokeAlarmApiSettings> getASmokeAlarmApiSettings) { if (httpClient == null) { httpClient = new HttpClient { BaseAddress = new Uri(getASmokeAlarmApiSettings.Value.BaseAddress)}; httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //TODO mgmccarthy: the one drawback here is if GASA were to give us a new authorization token, we'd have to reload the web app to get it to update b/c this is now static httpClient.DefaultRequestHeaders.Add("Authorization", getASmokeAlarmApiSettings.Value.Token); } } } public interface ISendRequestStatusToGetASmokeAlarm { void Send(string serial, string status, bool acceptance); } }
Fix default icon path when add new web search
using System.IO; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Wox.Plugin.WebSearch { public class WebSearch { public const string DefaultIcon = "web_search.png"; public string Title { get; set; } public string ActionKeyword { get; set; } [NotNull] private string _icon = DefaultIcon; [NotNull] public string Icon { get { return _icon; } set { _icon = value; IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value); } } /// <summary> /// All icon should be put under Images directory /// </summary> [NotNull] [JsonIgnore] internal string IconPath { get; private set; } public string Url { get; set; } public bool Enabled { get; set; } } }
using System.IO; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Wox.Plugin.WebSearch { public class WebSearch { public const string DefaultIcon = "web_search.png"; public string Title { get; set; } public string ActionKeyword { get; set; } [NotNull] private string _icon = DefaultIcon; [NotNull] public string Icon { get { return _icon; } set { _icon = value; IconPath = Path.Combine(WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, value); } } /// <summary> /// All icon should be put under Images directory /// </summary> [NotNull] [JsonIgnore] internal string IconPath { get; private set; } = Path.Combine ( WebSearchPlugin.PluginDirectory, WebSearchPlugin.ImageDirectory, DefaultIcon ); public string Url { get; set; } public bool Enabled { get; set; } } }
Align url invalid char unit tests with changes done to the validation logic
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Utilities; using System.Collections.Generic; namespace OfficeDevPnP.Core.Tests.AppModelExtensions { [TestClass] public class UrlUtilityTests { [TestMethod] public void ContainsInvalidCharsReturnsFalseForValidString() { string validString = "abd-123"; Assert.IsFalse(validString.ContainsInvalidUrlChars()); } [TestMethod] public void ContainsInvalidUrlCharsReturnsTrueForInvalidString() { var targetVals = new List<char> { '#', '%', '&', '*', '{', '}', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; targetVals.ForEach(v => Assert.IsTrue((string.Format("abc{0}abc", v).ContainsInvalidUrlChars()))); } [TestMethod] public void StripInvalidUrlCharsReturnsStrippedString() { var invalidString = "a#%&*{}\\:<>?/+|b"; Assert.AreEqual("ab", invalidString.StripInvalidUrlChars()); } [TestMethod] public void ReplaceInvalidUrlCharsReturnsStrippedString() { var invalidString = "a#%&*{}\\:<>?/+|b"; Assert.AreEqual("a------------------------------------------b", invalidString.ReplaceInvalidUrlChars("---")); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeDevPnP.Core.Utilities; using System.Collections.Generic; namespace OfficeDevPnP.Core.Tests.AppModelExtensions { [TestClass] public class UrlUtilityTests { [TestMethod] public void ContainsInvalidCharsReturnsFalseForValidString() { string validString = "abd-123"; Assert.IsFalse(validString.ContainsInvalidUrlChars()); } [TestMethod] public void ContainsInvalidUrlCharsReturnsTrueForInvalidString() { #if !CLIENTSDKV15 var targetVals = new List<char> { '#', '%', '*', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; #else var targetVals = new List<char> { '#', '~', '%', '&', '*', '{', '}', '\\', ':', '<', '>', '?', '/', '+', '|', '"' }; #endif targetVals.ForEach(v => Assert.IsTrue((string.Format("abc{0}abc", v).ContainsInvalidUrlChars()))); } [TestMethod] public void StripInvalidUrlCharsReturnsStrippedString() { #if !CLIENTSDKV15 var invalidString = "a#%*\\:<>?/+|b"; #else var invalidString = "a#~%&*{}\\:<>?/+|b"; #endif Assert.AreEqual("ab", invalidString.StripInvalidUrlChars()); } [TestMethod] public void ReplaceInvalidUrlCharsReturnsStrippedString() { #if !CLIENTSDKV15 var invalidString = "a#%*\\:<>?/+|b"; #else var invalidString = "a#~%&*{}\\:<>?/+|b"; #endif Assert.AreEqual("a------------------------------------------b", invalidString.ReplaceInvalidUrlChars("---")); } } }
Add support for removing okanshi instances
using System.Collections.Generic; namespace Okanshi.Dashboard { public interface IConfiguration { void Add(OkanshiServer server); IEnumerable<OkanshiServer> GetAll(); } }
using System.Collections.Generic; namespace Okanshi.Dashboard { public interface IConfiguration { void Add(OkanshiServer server); IEnumerable<OkanshiServer> GetAll(); void Remove(string name); } }
Update tests to use explicit globals
using NUnit.Framework; namespace Mond.Tests { [TestFixture] public class MondStateTests { [Test] public void MultiplePrograms() { const string source1 = @" hello = fun (x) { return 'hi ' + x; }; a = hello('nerd'); "; const string source2 = @" b = hello('brian'); "; var state = Script.Load(source1, source2); var result1 = state["a"]; var result2 = state["b"]; Assert.True(result1 == "hi nerd"); Assert.True(result2 == "hi brian"); } [Test] public void NativeFunction() { var state = new MondState(); state["function"] = new MondFunction((_, args) => args[0]); var program = MondProgram.Compile(@" return function('arg'); "); var result = state.Load(program); Assert.True(result == "arg"); } [Test] public void NativeInstanceFunction() { var state = new MondState(); state["value"] = 123; state["function"] = new MondInstanceFunction((_, instance, arguments) => instance[arguments[0]]); var program = MondProgram.Compile(@" return function('value'); "); var result = state.Load(program); Assert.True(result == 123); } } }
using NUnit.Framework; namespace Mond.Tests { [TestFixture] public class MondStateTests { [Test] public void MultiplePrograms() { const string source1 = @" global.hello = fun (x) { return 'hi ' + x; }; global.a = global.hello('nerd'); "; const string source2 = @" global.b = global.hello('brian'); "; var state = Script.Load(source1, source2); var result1 = state["a"]; var result2 = state["b"]; Assert.True(result1 == "hi nerd"); Assert.True(result2 == "hi brian"); } [Test] public void NativeFunction() { var state = new MondState(); state["function"] = new MondFunction((_, args) => args[0]); var program = MondProgram.Compile(@" return global.function('arg'); "); var result = state.Load(program); Assert.True(result == "arg"); } [Test] public void NativeInstanceFunction() { var state = new MondState(); state["value"] = 123; state["function"] = new MondInstanceFunction((_, instance, arguments) => instance[arguments[0]]); var program = MondProgram.Compile(@" return global.function('value'); "); var result = state.Load(program); Assert.True(result == 123); } } }
Allow blank/root route to be configured
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; ValueProviderFactories.Factories.Insert(0, new NavigationDataValueProviderFactory()); string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
using System.Web.Mvc; using System.Web.Routing; namespace Navigation.Mvc { public class RouteConfig { public static void AddStateRoutes() { if (StateInfoConfig.Dialogs == null) return; ValueProviderFactories.Factories.Insert(0, new NavigationDataValueProviderFactory()); string controller, action; Route route; using (RouteTable.Routes.GetWriteLock()) { foreach (Dialog dialog in StateInfoConfig.Dialogs) { foreach (State state in dialog.States) { controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty; action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty; if (controller.Length != 0 && action.Length != 0) { state.StateHandler = new MvcStateHandler(); route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route); route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route); route.Defaults["controller"] = controller; route.Defaults["action"] = action; route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } }; route.RouteHandler = new MvcStateRouteHandler(state); } } } } } } }
Update to make hidden input for token self-closing
using System.Web.Mvc; using System.Web.Mvc.Html; using CourtesyFlush; namespace System.Web.WebPages { public static class HtmlHelperExtension { public static MvcHtmlString FlushHead(this HtmlHelper html) { return FlushHead(html, null); } public static MvcHtmlString FlushHead(this HtmlHelper html, string headername) { if (String.IsNullOrWhiteSpace(headername)) headername = "_Head"; if (!html.ViewData.ContainsKey("HeadFlushed")) return html.Partial(headername); return new MvcHtmlString(string.Empty); } #if NET45 public static MvcHtmlString FlushedAntiForgeryToken(this HtmlHelper html) { var token = html.ViewContext.HttpContext.Items[ControllerBaseExtension.FlushedAntiForgeryTokenKey] as string; if (string.IsNullOrEmpty(token)) { // Fall back to the standard AntiForgeryToken if no FlushedAntiForgeryToken exists. return html.AntiForgeryToken(); } var tag = new TagBuilder("input"); tag.Attributes["type"] = "hidden"; tag.Attributes["name"] = "__RequestVerificationToken"; tag.Attributes["value"] = token; return new MvcHtmlString(tag.ToString()); } #endif } }
using System.Web.Mvc; using System.Web.Mvc.Html; using CourtesyFlush; namespace System.Web.WebPages { public static class HtmlHelperExtension { public static MvcHtmlString FlushHead(this HtmlHelper html) { return FlushHead(html, null); } public static MvcHtmlString FlushHead(this HtmlHelper html, string headername) { if (String.IsNullOrWhiteSpace(headername)) headername = "_Head"; if (!html.ViewData.ContainsKey("HeadFlushed")) return html.Partial(headername); return new MvcHtmlString(string.Empty); } #if NET45 public static MvcHtmlString FlushedAntiForgeryToken(this HtmlHelper html) { var token = html.ViewContext.HttpContext.Items[ControllerBaseExtension.FlushedAntiForgeryTokenKey] as string; if (string.IsNullOrEmpty(token)) { // Fall back to the standard AntiForgeryToken if no FlushedAntiForgeryToken exists. return html.AntiForgeryToken(); } var tag = new TagBuilder("input"); tag.Attributes["type"] = "hidden"; tag.Attributes["name"] = "__RequestVerificationToken"; tag.Attributes["value"] = token; return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing)); } #endif } }
Allow access to the Data object
using System.Collections.Generic; using Hangfire.MemoryStorage.Database; using Hangfire.Server; using Hangfire.Storage; namespace Hangfire.MemoryStorage { public class MemoryStorage : JobStorage { private readonly MemoryStorageOptions _options; private readonly Data _data; public MemoryStorage() : this(new MemoryStorageOptions(), new Data()) { } public MemoryStorage(MemoryStorageOptions options) : this(options, new Data()) { } public MemoryStorage(MemoryStorageOptions options, Data data) { _options = options; _data = data; } public override IStorageConnection GetConnection() { return new MemoryStorageConnection(_data, _options.FetchNextJobTimeout); } public override IMonitoringApi GetMonitoringApi() { return new MemoryStorageMonitoringApi(_data); } #pragma warning disable 618 public override IEnumerable<IServerComponent> GetComponents() #pragma warning restore 618 { yield return new ExpirationManager(_data, _options.JobExpirationCheckInterval); yield return new CountersAggregator(_data, _options.CountersAggregateInterval); } } }
using System.Collections.Generic; using Hangfire.MemoryStorage.Database; using Hangfire.Server; using Hangfire.Storage; namespace Hangfire.MemoryStorage { public class MemoryStorage : JobStorage { private readonly MemoryStorageOptions _options; public Data Data { get; } public MemoryStorage() : this(new MemoryStorageOptions(), new Data()) { } public MemoryStorage(MemoryStorageOptions options) : this(options, new Data()) { } public MemoryStorage(MemoryStorageOptions options, Data data) { _options = options; Data = data; } public override IStorageConnection GetConnection() { return new MemoryStorageConnection(Data, _options.FetchNextJobTimeout); } public override IMonitoringApi GetMonitoringApi() { return new MemoryStorageMonitoringApi(Data); } #pragma warning disable 618 public override IEnumerable<IServerComponent> GetComponents() #pragma warning restore 618 { yield return new ExpirationManager(Data, _options.JobExpirationCheckInterval); yield return new CountersAggregator(Data, _options.CountersAggregateInterval); } } }
Remove `internal-reportinstallsuccess` from `dotnet complete`.
// 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.Linq; using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli { internal static class InternalReportinstallsuccessCommandParser { public static Command InternalReportinstallsuccess() => Create.Command( "internal-reportinstallsuccess", "internal only", Accept.ExactlyOneArgument()); } }
// 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.Linq; using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli { internal static class InternalReportinstallsuccessCommandParser { public static Command InternalReportinstallsuccess() => Create.Command( "internal-reportinstallsuccess", "", Accept.ExactlyOneArgument()); } }
Replace order of default settings
using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
Add scenario test to check the minimum string length constraint is ignored
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } private class ClassWithLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public readonly string ShortText; public ClassWithLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText) { this.ShortText = shortText; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } [Fact] public void FixtureCorrectlyCreatesLongText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.Equal( ClassWithLengthConstrainedConstructorArgument.LongTextLength, actual.LongText.Length); // Teardown } private class ClassWithLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public const int LongTextLength = 50; public readonly string ShortText; public readonly string LongText; public ClassWithLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText, [StringLength(LongTextLength, MinimumLength = LongTextLength)]string longText) { this.ShortText = shortText; this.LongText = longText; } } } }
Break build again for TeamCity email notify test.
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoSomething(); } } }
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoAllOfTheThings(); } } }
Fix indentation for scheduled triggers
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.GitHubActions.Configuration { public class GitHubActionsScheduledTrigger : GitHubActionsDetailedTrigger { public string Cron { get; set; } public override void Write(CustomFileWriter writer) { using (writer.Indent()) { writer.WriteLine("schedule:"); using (writer.Indent()) { writer.WriteLine($" - cron: '{Cron}'"); } } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.GitHubActions.Configuration { public class GitHubActionsScheduledTrigger : GitHubActionsDetailedTrigger { public string Cron { get; set; } public override void Write(CustomFileWriter writer) { writer.WriteLine("schedule:"); using (writer.Indent()) { writer.WriteLine($"- cron: '{Cron}'"); } } } }
Check dVers versions for null (version numbers such as 1, 1.2 and 1.3)
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace KerbalPackageManager { internal class dotVersion { public dotVersion(string toFilename) { var jObj = JObject.Parse(File.ReadAllText(toFilename)); Name = (string)jObj["NAME"]; Url = (Uri)jObj["URL"]; var ver = jObj["VERSION"]; Version = new Version((int)ver["MAJOR"], (int)ver["MINOR"], (int)ver["PATCH"], (int)ver["BUILD"]); } public string Name { get; set; } public Uri Url { get; set; } public Version Version { get; set; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace KerbalPackageManager { internal class dotVersion { public dotVersion(string toFilename) { var jObj = JObject.Parse(File.ReadAllText(toFilename)); Name = (string)jObj["NAME"]; Url = (Uri)jObj["URL"]; if (jObj["VERSION"] != null) { string ver = (string)jObj["VERSION"]["MAJOR"]; if (jObj["VERSION"]["MINOR"] != null) ver += "." + jObj["VERSION"]["MINOR"]; if (jObj["VERSION"]["PATCH"] != null) ver += "." + jObj["VERSION"]["PATCH"]; if (jObj["VERSION"]["BUILD"] != null) ver += "." + jObj["VERSION"]["BUILD"]; Version = new Version(ver); } else Version = null; } public string Name { get; set; } public Uri Url { get; set; } public Version Version { get; set; } } }
Refactor - rename test class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class IntuitivelyTests { [Test] public void Find_WithNoTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void Find_WithEmptyTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(""), Throws.Exception.TypeOf<ArgumentException>()); } [Test] public void Find_WithUnidentifiableTerm_ReturnsNothing() { var intuitively = new Intuitively(); var element = intuitively.Find("unidentifiable term"); Assert.That(element, Is.Null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class EdgeCaseTests { [Test] public void Find_WithNoTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void Find_WithEmptyTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(""), Throws.Exception.TypeOf<ArgumentException>()); } [Test] public void Find_WithUnidentifiableTerm_ReturnsNothing() { var intuitively = new Intuitively(); var element = intuitively.Find("unidentifiable term"); Assert.That(element, Is.Null); } } }
Put loop test's variables in a local scope
using NUnit.Framework; namespace Rant.Tests.Expressions { [TestFixture] public class Loops { private readonly RantEngine rant = new RantEngine(); [Test] public void StringBuildingWhileLoop() { var output = rant.Do(@" [@ var parts = (""this"", ""is"", ""a"", ""test""); var i = 0; var buffer = """"; while(i < parts.length) { if (i > 0) buffer ~= "" ""; buffer ~= parts[i]; i++; } return buffer; ]"); Assert.AreEqual("this is a test", output.Main); } } }
using NUnit.Framework; namespace Rant.Tests.Expressions { [TestFixture] public class Loops { private readonly RantEngine rant = new RantEngine(); [Test] public void StringBuildingWhileLoop() { var output = rant.Do(@" [@ (function() { var parts = (""this"", ""is"", ""a"", ""test""); var i = 0; var buffer = """"; while(i < parts.length) { if (i > 0) buffer ~= "" ""; buffer ~= parts[i]; i++; } return buffer; })(); ]"); Assert.AreEqual("this is a test", output.Main); } } }
Remove "Get" statement from example docs
using Discord; using Discord.Commands; using Discord.WebSocket; public class ModuleA : ModuleBase { private readonly DatabaseService _database; // Dependencies can be injected via the constructor public ModuleA(DatabaseService database) { _database = database; } public async Task ReadFromDb() { var x = _database.getX(); await ReplyAsync(x); } } public class ModuleB { // Public settable properties will be injected public AnnounceService { get; set; } // Public properties without setters will not public CommandService Commands { get; } // Public properties annotated with [DontInject] will not [DontInject] public NotificationService { get; set; } public ModuleB(CommandService commands, IDependencyMap map) { Commands = commands; _notification = map.Get<NotificationService>(); } }
using Discord; using Discord.Commands; using Discord.WebSocket; public class ModuleA : ModuleBase { private readonly DatabaseService _database; // Dependencies can be injected via the constructor public ModuleA(DatabaseService database) { _database = database; } public async Task ReadFromDb() { var x = _database.getX(); await ReplyAsync(x); } } public class ModuleB { // Public settable properties will be injected public AnnounceService { get; set; } // Public properties without setters will not public CommandService Commands { get; } // Public properties annotated with [DontInject] will not [DontInject] public NotificationService { get; set; } public ModuleB(CommandService commands) { Commands = commands; } }
Improve cfx default settings (removing hack switch)
using Chromium; using Chromium.Event; using Neutronium.Core; using Neutronium.WPF; namespace Neutronium.WebBrowserEngine.ChromiumFx { public abstract class ChromiumFxWebBrowserApp : HTMLApp { protected virtual bool DisableWebSecurity => true; protected override IWPFWebWindowFactory GetWindowFactory(IWebSessionLogger logger) => new ChromiumFXWPFWebWindowFactory(logger, UpdateChromiumSettings, PrivateUpdateLineCommandArg); protected virtual void UpdateChromiumSettings(CfxSettings settings) { } private void PrivateUpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { var commandLine = beforeLineCommand.CommandLine; commandLine.AppendSwitch("disable-gpu"); // Needed to avoid crash when using devtools application tab with custom schema commandLine.AppendSwitch("disable-kill-after-bad-ipc"); if (DisableWebSecurity) commandLine.AppendSwitch("disable-web-security"); UpdateLineCommandArg(beforeLineCommand); } protected virtual void UpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { } } }
using Chromium; using Chromium.Event; using Neutronium.Core; using Neutronium.WPF; namespace Neutronium.WebBrowserEngine.ChromiumFx { public abstract class ChromiumFxWebBrowserApp : HTMLApp { protected virtual bool DisableWebSecurity => false; protected override IWPFWebWindowFactory GetWindowFactory(IWebSessionLogger logger) => new ChromiumFXWPFWebWindowFactory(logger, UpdateChromiumSettings, PrivateUpdateLineCommandArg); protected virtual void UpdateChromiumSettings(CfxSettings settings) { } private void PrivateUpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { var commandLine = beforeLineCommand.CommandLine; commandLine.AppendSwitch("disable-gpu"); if (DisableWebSecurity) commandLine.AppendSwitch("disable-web-security"); UpdateLineCommandArg(beforeLineCommand); } protected virtual void UpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand) { } } }
Remove User ID from device credential creation payload
using Auth0.Core; using Newtonsoft.Json; namespace Auth0.ManagementApi.Models { /// <summary> /// /// </summary> public class DeviceCredentialCreateRequest : DeviceCredentialBase { /// <summary> /// Gets or sets the ID of the client for which the credential will be created. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the ID of the user using the device for which the credential will be created. /// </summary> [JsonProperty("user_id")] public string UserId { get; set; } /// <summary> /// Gets or sets the value of the credentia /// </summary> [JsonProperty("value")] public string Value { get; set; } } }
using System; using Auth0.Core; using Newtonsoft.Json; namespace Auth0.ManagementApi.Models { /// <summary> /// /// </summary> public class DeviceCredentialCreateRequest : DeviceCredentialBase { /// <summary> /// Gets or sets the ID of the client for which the credential will be created. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the ID of the user using the device for which the credential will be created. /// </summary> [Obsolete("This property has been removed from the Auth0 API and sending it has no effect")] [JsonIgnore] [JsonProperty("user_id")] public string UserId { get; set; } /// <summary> /// Gets or sets the value of the credentia /// </summary> [JsonProperty("value")] public string Value { get; set; } } }
Add option to control whether player can use twisting
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public static GameManager Instance; public Mode CurrentMode = Mode.TopDown; CameraController cameraController; void Awake() { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(Instance.gameObject); Instance = this; } cameraController = GetComponent<CameraController>(); if (CurrentMode == Mode.TopDown) { cameraController.SwitchToTopDown(); } else { cameraController.SwitchToSideScroller(); } } void Update() { if (Input.GetButtonDown("Twist")) { if (CurrentMode == Mode.TopDown) { cameraController.RotateToSideScroller(); GetComponent<TransitionManager>().Twist(Mode.SideScroller); } else if(CurrentMode == Mode.SideScroller) { GetComponent<TransitionManager>().Twist(Mode.TopDown); cameraController.RotateToTopDown(); } } } } public enum Mode { SideScroller, TopDown, TransitioningToSideScroller, TransitioningToTopDown }
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public static GameManager Instance; public Mode CurrentMode = Mode.TopDown; public bool AllowTwisting = true; CameraController cameraController; void Awake() { if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(Instance.gameObject); Instance = this; } cameraController = GetComponent<CameraController>(); if (CurrentMode == Mode.TopDown) { cameraController.SwitchToTopDown(); } else { cameraController.SwitchToSideScroller(); } } void Update() { if (Input.GetButtonDown("Twist") && AllowTwisting) { if (CurrentMode == Mode.TopDown) { cameraController.RotateToSideScroller(); GetComponent<TransitionManager>().Twist(Mode.SideScroller); } else if(CurrentMode == Mode.SideScroller) { GetComponent<TransitionManager>().Twist(Mode.TopDown); cameraController.RotateToTopDown(); } } } } public enum Mode { SideScroller, TopDown, TransitioningToSideScroller, TransitioningToTopDown }
Fix migration to handle identical aliases for different group names and write error to log
using System.Linq; using Umbraco.Core.Persistence.Dtos; namespace Umbraco.Core.Migrations.Upgrade.V_8_16_0 { public class AddPropertyTypeGroupColumns : MigrationBase { public AddPropertyTypeGroupColumns(IMigrationContext context) : base(context) { } public override void Migrate() { AddColumn<PropertyTypeGroupDto>("type"); AddColumn<PropertyTypeGroupDto>("alias", out var sqls); var dtos = Database.Fetch<PropertyTypeGroupDto>(); foreach (var dto in dtos) { // Generate alias from current name dto.Alias = dto.Text.ToSafeAlias(true); Database.Update(dto, x => new { x.Alias }); } foreach (var sql in sqls) Database.Execute(sql); } } }
using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Persistence.Dtos; namespace Umbraco.Core.Migrations.Upgrade.V_8_16_0 { public class AddPropertyTypeGroupColumns : MigrationBase { public AddPropertyTypeGroupColumns(IMigrationContext context) : base(context) { } public override void Migrate() { AddColumn<PropertyTypeGroupDto>("type"); AddColumn<PropertyTypeGroupDto>("alias", out var sqls); var dtos = Database.Fetch<PropertyTypeGroupDto>(); foreach (var dtosPerAlias in dtos.GroupBy(x => x.Text.ToSafeAlias(true))) { var dtosPerAliasAndText = dtosPerAlias.GroupBy(x => x.Text); var numberSuffix = 1; foreach (var dtosPerText in dtosPerAliasAndText) { foreach (var dto in dtosPerText) { dto.Alias = dtosPerAlias.Key; if (numberSuffix > 1) { // More than 1 name found for the alias, so add a suffix dto.Alias += numberSuffix; } Database.Update(dto, x => new { x.Alias }); } numberSuffix++; } if (numberSuffix > 2) { Logger.Error<AddPropertyTypeGroupColumns>("Detected the same alias {Alias} for different property group names {Names}, the migration added suffixes, but this might break backwards compatibility.", dtosPerAlias.Key, dtosPerAliasAndText.Select(x => x.Key)); } } foreach (var sql in sqls) Database.Execute(sql); } } }
Use await instead of hand-written continuation.
using System; using System.Threading.Tasks; namespace MySql.Data { internal static class ValueTaskExtensions { public static ValueTask<TResult> ContinueWith<T, TResult>(this ValueTask<T> valueTask, Func<T, ValueTask<TResult>> continuation) { return valueTask.IsCompleted ? continuation(valueTask.Result) : new ValueTask<TResult>(valueTask.AsTask().ContinueWith(task => continuation(task.GetAwaiter().GetResult()).AsTask()).Unwrap()); } public static ValueTask<T> FromException<T>(Exception exception) => new ValueTask<T>(Utility.TaskFromException<T>(exception)); } }
using System; using System.Threading.Tasks; namespace MySql.Data { internal static class ValueTaskExtensions { public static async ValueTask<TResult> ContinueWith<T, TResult>(this ValueTask<T> valueTask, Func<T, ValueTask<TResult>> continuation) => await continuation(await valueTask); public static ValueTask<T> FromException<T>(Exception exception) => new ValueTask<T>(Utility.TaskFromException<T>(exception)); } }
Fix missing plot in claims
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Models.Plot @model PlotElementViewModel @if (!Model.Visible) { return; } @{ var hideClass = Model.Status == PlotStatus.InWork ? "world-object-hidden" : ""; } @if (Model.HasEditAccess) { <div> @Html.DisplayFor(model => model.Status) @Html.ActionLink("Изменить", "Edit", "Plot", new { Model.PlotFolderId, Model.ProjectId }, null) @if (Model.CharacterId != null) { @Html.MoveControl(model => Model, "MoveElementForCharacter", "Plot", Model.CharacterId) } </div> } @if (Model.HasMasterAccess || Model.PublishMode) { <br/> <b>Для</b> if (Model.TargetsForDisplay.Any()) { foreach (var target in Model.TargetsForDisplay) { @Html.DisplayFor(model => target) } } else { <span>Не установлено</span> } } @if (!string.IsNullOrWhiteSpace(Model.TodoField) && Model.HasMasterAccess) { <p><b>Доделать</b>: @Model.TodoField</p> } <div class="@hideClass"> @Html.DisplayFor(model => Model.Content) </div>
@using JoinRpg.Web.App_Code @using JoinRpg.Web.Models.Plot @model PlotElementViewModel @if (!Model.Visible) { return; } @{ var hideClass = Model.Status == PlotStatus.InWork ? "world-object-hidden" : ""; } @if (Model.HasEditAccess) { <div> @Html.DisplayFor(model => model.Status) @Html.ActionLink("Изменить", "Edit", "Plot", new { Model.PlotFolderId, Model.ProjectId }, null) @if (Model.CharacterId != null) { @Html.MoveControl(model => Model, "MoveElementForCharacter", "Plot", Model.CharacterId) } </div> } @if (Model.HasMasterAccess || Model.PublishMode) { <br/> <b>Для</b> if (Model.TargetsForDisplay.Any()) { foreach (var target in Model.TargetsForDisplay) { @Html.DisplayFor(model => target) } } else { <span>Не установлено</span> } } @if (!string.IsNullOrWhiteSpace(Model.TodoField) && Model.HasMasterAccess) { <p><b>Доделать</b>: @Model.TodoField</p> } <div class="@hideClass"> @Model.Content </div>
Fix invalid logic when start server
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LiteNetLibHighLevel { [RequireComponent(typeof(LiteNetLibAssets))] public class LiteNetLibGameManager : LiteNetLibManager { private LiteNetLibAssets assets; public LiteNetLibAssets Assets { get { if (assets == null) assets = GetComponent<LiteNetLibAssets>(); return assets; } } protected override void Awake() { base.Awake(); Assets.ClearRegisterPrefabs(); Assets.RegisterPrefabs(); } public override bool StartServer() { if (base.StartServer()) Assets.RegisterSceneObjects(); return false; } public override LiteNetLibClient StartClient() { var client = base.StartClient(); if (client != null) Assets.RegisterSceneObjects(); return client; } protected override void RegisterServerMessages() { base.RegisterServerMessages(); } protected override void RegisterClientMessages() { base.RegisterClientMessages(); } #region Relates components functions public LiteNetLibIdentity NetworkSpawn(GameObject gameObject) { return Assets.NetworkSpawn(gameObject); } public bool NetworkDestroy(GameObject gameObject) { return Assets.NetworkDestroy(gameObject); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LiteNetLibHighLevel { [RequireComponent(typeof(LiteNetLibAssets))] public class LiteNetLibGameManager : LiteNetLibManager { private LiteNetLibAssets assets; public LiteNetLibAssets Assets { get { if (assets == null) assets = GetComponent<LiteNetLibAssets>(); return assets; } } protected override void Awake() { base.Awake(); Assets.ClearRegisterPrefabs(); Assets.RegisterPrefabs(); } public override bool StartServer() { if (base.StartServer()) { Assets.RegisterSceneObjects(); return true; } return false; } public override LiteNetLibClient StartClient() { var client = base.StartClient(); if (client != null) Assets.RegisterSceneObjects(); return client; } protected override void RegisterServerMessages() { base.RegisterServerMessages(); } protected override void RegisterClientMessages() { base.RegisterClientMessages(); } #region Relates components functions public LiteNetLibIdentity NetworkSpawn(GameObject gameObject) { return Assets.NetworkSpawn(gameObject); } public bool NetworkDestroy(GameObject gameObject) { return Assets.NetworkDestroy(gameObject); } #endregion } }
Make username password fields fit on Mac Chrome
@using JabbR; <form class="form-horizontal" action="@Url.Content("~/account/login")" method="post"> @Html.ValidationSummary() <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> @Html.TextBox("username", "input-block-level", "Username") </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> @Html.Password("password", "input-block-level", "Password") </div> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Sign in</button> </div> </div> @if (Model) { <div class="control-group"> <div class="controls"> <a href="@Url.Content("~/account/register")">Register</a> if you don't have an account. </div> </div> } @Html.AntiForgeryToken() </form>
@using JabbR; <form class="form-horizontal" action="@Url.Content("~/account/login")" method="post"> @Html.ValidationSummary() <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-user"></i></span> @Html.TextBox("username", "span10", "Username") </div> </div> </div> <div class="control-group"> <div class="controls"> <div class="input-prepend"> <span class="add-on"><i class="icon-lock"></i></span> @Html.Password("password", "span10", "Password") </div> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn">Sign in</button> </div> </div> @if (Model) { <div class="control-group"> <div class="controls"> <a href="@Url.Content("~/account/register")">Register</a> if you don't have an account. </div> </div> } @Html.AntiForgeryToken() </form>
Use empty hit windows for spinner ticks
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); protected override HitWindows CreateHitWindows() => null; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Audio; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { public class SpinnerTick : OsuHitObject { public SpinnerTick() { Samples.Add(new HitSampleInfo { Name = "spinnerbonus" }); } public override Judgement CreateJudgement() => new OsuSpinnerTickJudgement(); protected override HitWindows CreateHitWindows() => HitWindows.Empty; } }
Fix TestGetPlaylistFormats after adding more extensions to the PlaylistReaderFactory
using System; using ATL.AudioReaders; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace ATL.test { [TestClass] public class FactoryTest { [TestMethod] public void TestGetPlaylistFormats() { StringBuilder filter = new StringBuilder(""); foreach (Format f in ATL.PlaylistReaders.PlaylistReaderFactory.GetInstance().getFormats()) { if (f.Readable) { foreach (String extension in f) { filter.Append(extension).Append(";"); } } } // Removes the last separator filter.Remove(filter.Length - 1, 1); Assert.AreEqual(".PLS;.M3U;.M3U8;.FPL;.XSPF;.SMIL;.SMI;.ASX;.WAX;.WVX;.B4S", filter.ToString()); } } }
using System; using ATL.AudioReaders; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace ATL.test { [TestClass] public class FactoryTest { [TestMethod] public void TestGetPlaylistFormats() { StringBuilder filter = new StringBuilder(""); foreach (Format f in ATL.PlaylistReaders.PlaylistReaderFactory.GetInstance().getFormats()) { if (f.Readable) { foreach (String extension in f) { filter.Append(extension).Append(";"); } } } // Removes the last separator filter.Remove(filter.Length - 1, 1); Assert.AreEqual(".PLS;.M3U;.M3U8;.FPL;.XSPF;.SMIL;.SMI;.ZPL;.WPL;.ASX;.WAX;.WVX;.B4S", filter.ToString()); } } }
Fix iOS cache folder path
using System; using System.IO; namespace Amica.vNext { public class SqliteObjectCache : SqliteObjectCacheBase { protected override string GetDatabasePath() { const string sqliteFilename = "cache.db3"; var cacheFolder = Path.Combine(ApplicationName, "SimpleCache"); var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var cachePath = Path.Combine(documentsPath, "..", "Library", cacheFolder); Directory.CreateDirectory(cachePath); return Path.Combine(cachePath, sqliteFilename); } } }
using System; using System.IO; using Amica.vNext; [assembly: Xamarin.Forms.Dependency(typeof(SqliteObjectCache))] namespace Amica.vNext { public class SqliteObjectCache : SqliteObjectCacheBase { protected override string GetDatabasePath() { const string sqliteFilename = "cache.db3"; var cacheFolder = Path.Combine(ApplicationName, "SimpleCache"); var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var cachePath = Path.Combine(documentsPath, cacheFolder); Directory.CreateDirectory(cachePath); return Path.Combine(cachePath, sqliteFilename); } } }
Add API comments for Git Testing ;)
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; namespace UnityAutoMoq { /// <summary> /// Provide extensions for Unity Auto Moq /// </summary> public class UnityAutoMoqExtension : UnityContainerExtension { private readonly UnityAutoMoqContainer autoMoqContainer; public UnityAutoMoqExtension(UnityAutoMoqContainer autoMoqContainer) { this.autoMoqContainer = autoMoqContainer; } protected override void Initialize() { Context.Strategies.Add(new UnityAutoMoqBuilderStrategy(autoMoqContainer), UnityBuildStage.PreCreation); } } }
Switch to the less restrictive IConfiguration
#if NETSTANDARD1_6 using System; using Microsoft.Extensions.Configuration; namespace RapidCore.Configuration { /// <summary> /// Base class for strongly typed configuration classes. /// /// The idea is to allow you to define a config class specific /// for your project, but gain easy access to reading config values /// from wherever. /// </summary> public abstract class ConfigBase { private readonly IConfigurationRoot configuration; public ConfigBase(IConfigurationRoot configuration) { this.configuration = configuration; } protected T Get<T>(string key, T defaultValue) { string value = configuration[key]; if (string.IsNullOrEmpty(value)) { return defaultValue; } return (T)Convert.ChangeType(value, typeof(T)); } } } #endif
#if NETSTANDARD1_6 using System; using Microsoft.Extensions.Configuration; namespace RapidCore.Configuration { /// <summary> /// Base class for strongly typed configuration classes. /// /// The idea is to allow you to define a config class specific /// for your project, but gain easy access to reading config values /// from wherever. /// </summary> public abstract class ConfigBase { private readonly IConfiguration configuration; protected ConfigBase(IConfiguration configuration) { this.configuration = configuration; } protected T Get<T>(string key, T defaultValue) { string value = configuration[key]; if (string.IsNullOrEmpty(value)) { return defaultValue; } return (T)Convert.ChangeType(value, typeof(T)); } } } #endif
Add Travis to contact list.
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Travis:</strong> <a href="mailto:travis.elkins@zirmed.com">travis.elkins@zirmed.com</a> </address>
Change assembly version for release
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Flirper1.0")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Flirper1.1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.1.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
Add missing Include for CircleType
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Xml.Serialization; using Rocket.Unturned.Player; namespace Safezone.Model { [XmlInclude(typeof(RectangleType))] public abstract class SafeZoneType { private static readonly Dictionary<String, Type> RegistereTypes = new Dictionary<String, Type>(); public static SafeZoneType CreateSafeZoneType(String name) { if (!RegistereTypes.ContainsKey(name)) { return null; } Type t = RegistereTypes[name]; return (SafeZoneType)Activator.CreateInstance(t); } public static void RegisterSafeZoneType(String name, Type t) { if(typeof(SafeZoneType).IsAssignableFrom(t)) { throw new ArgumentException(t.Name + " is not a SafeZoneType!"); } if (RegistereTypes.ContainsKey(name)) { throw new ArgumentException(name + " is already registered!"); } RegistereTypes.Add(name, t); } public abstract SafeZone Create(RocketPlayer player, String name, string[] args); public abstract bool IsInSafeZone(Position p); public abstract bool Redefine(RocketPlayer player, string[] args); public static ReadOnlyCollection<String> GetTypes() { return new ReadOnlyCollection<string>(new List<string>(RegistereTypes.Keys)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Xml.Serialization; using Rocket.Unturned.Player; namespace Safezone.Model { [XmlInclude(typeof(RectangleType))] [XmlInclude(typeof(CircleType))] public abstract class SafeZoneType { private static readonly Dictionary<String, Type> RegistereTypes = new Dictionary<String, Type>(); public static SafeZoneType CreateSafeZoneType(String name) { if (!RegistereTypes.ContainsKey(name)) { return null; } Type t = RegistereTypes[name]; return (SafeZoneType)Activator.CreateInstance(t); } public static void RegisterSafeZoneType(String name, Type t) { if(typeof(SafeZoneType).IsAssignableFrom(t)) { throw new ArgumentException(t.Name + " is not a SafeZoneType!"); } if (RegistereTypes.ContainsKey(name)) { throw new ArgumentException(name + " is already registered!"); } RegistereTypes.Add(name, t); } public abstract SafeZone Create(RocketPlayer player, String name, string[] args); public abstract bool IsInSafeZone(Position p); public abstract bool Redefine(RocketPlayer player, string[] args); public static ReadOnlyCollection<String> GetTypes() { return new ReadOnlyCollection<string>(new List<string>(RegistereTypes.Keys)); } } }
Change destination for slack notifications
using AzureStorage.Queue; using Core; using Core.Notifiers; using Lykke.JobTriggers.Abstractions; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace AzureRepositories.Notifiers { public class SlackNotifier : ISlackNotifier, IPoisionQueueNotifier { private readonly IQueueExt _queue; private const string _sender = "ethereumcoreservice"; public SlackNotifier(Func<string, IQueueExt> queueFactory) { _queue = queueFactory(Constants.SlackNotifierQueue); } public async Task WarningAsync(string message) { var obj = new { Type = "Warnings", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public async Task ErrorAsync(string message) { var obj = new { Type = "Errors", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public async Task FinanceWarningAsync(string message) { var obj = new { Type = "Financewarnings", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public Task NotifyAsync(string message) { return ErrorAsync(message); } } }
using AzureStorage.Queue; using Core; using Core.Notifiers; using Lykke.JobTriggers.Abstractions; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace AzureRepositories.Notifiers { public class SlackNotifier : ISlackNotifier, IPoisionQueueNotifier { private readonly IQueueExt _queue; private const string _sender = "ethereumcoreservice"; public SlackNotifier(Func<string, IQueueExt> queueFactory) { _queue = queueFactory(Constants.SlackNotifierQueue); } public async Task WarningAsync(string message) { var obj = new { Type = "Warnings", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public async Task ErrorAsync(string message) { var obj = new { Type = "Ethereum",//"Errors", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public async Task FinanceWarningAsync(string message) { var obj = new { Type = "Financewarnings", Sender = _sender, Message = message }; await _queue.PutRawMessageAsync(JsonConvert.SerializeObject(obj)); } public Task NotifyAsync(string message) { return ErrorAsync(message); } } }
Add --base-tile option to Deserialize-Tilemap.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class DeserializeTilemapCmd : CliCommand { public DeserializeTilemapCmd() : base("Deserialize-Tilemap") { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Deserializing tilemap..."); workbench.Stream.Position = 0; workbench.Tilemap = new Tilemap(); int bpe = 2; // bytes per tile entry byte[] buffer = new byte[bpe]; while (workbench.Stream.Read(buffer, 0, 2) == bpe) { int scrn = buffer[0] | (buffer[1] << 8); TileEntry te = new TileEntry() { TileNumber = scrn & 0x3FF, HFlip = (scrn & (1 << 10)) != 0, VFlip = (scrn & (1 << 11)) != 0, PaletteNumber = (scrn >> 12) & 0xF }; workbench.Tilemap.TileEntries.Add(te); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PixelPet.Commands { internal class DeserializeTilemapCmd : CliCommand { public DeserializeTilemapCmd() : base("Deserialize-Tilemap", new Parameter[] { new Parameter("base-tile", "bt", false, new ParameterValue("index", "0")) }) { } public override void Run(Workbench workbench, Cli cli) { int baseTile = FindNamedParameter("--base-tile").Values[0].ToInt32(); cli.Log("Deserializing tilemap..."); workbench.Stream.Position = 0; workbench.Tilemap = new Tilemap(); int bpe = 2; // bytes per tile entry byte[] buffer = new byte[bpe]; while (workbench.Stream.Read(buffer, 0, 2) == bpe) { int scrn = buffer[0] | (buffer[1] << 8); TileEntry te = new TileEntry() { TileNumber = (scrn & 0x3FF) - baseTile, HFlip = (scrn & (1 << 10)) != 0, VFlip = (scrn & (1 << 11)) != 0, PaletteNumber = (scrn >> 12) & 0xF }; workbench.Tilemap.TileEntries.Add(te); } } } }
Convert this in a different way
using System; using System.Collections.Generic; using BugsnagUnity.Payload; using UnityEngine; namespace BugsnagUnity { static class DictionaryExtensions { private static IntPtr Arrays { get; } = AndroidJNI.FindClass("java/util/Arrays"); private static IntPtr ToStringMethod { get; } = AndroidJNIHelper.GetMethodID(Arrays, "toString", "([Ljava/lang/Object;)Ljava/lang/String;", true); internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source) { using (var set = source.Call<AndroidJavaObject>("entrySet")) using (var iterator = set.Call<AndroidJavaObject>("iterator")) { while (iterator.Call<bool>("hasNext")) { using (var mapEntry = iterator.Call<AndroidJavaObject>("next")) { var key = mapEntry.Call<string>("getKey"); using (var value = mapEntry.Call<AndroidJavaObject>("getValue")) { if (value != null) { using (var @class = value.Call<AndroidJavaObject>("getClass")) { if (@class.Call<bool>("isArray")) { var args = AndroidJNIHelper.CreateJNIArgArray(new[] {value}); var formattedValue = AndroidJNI.CallStaticStringMethod(Arrays, ToStringMethod, args); dictionary.AddToPayload(key, formattedValue); } else { dictionary.AddToPayload(key, value.Call<string>("toString")); } } } } } } } } } }
using System; using System.Collections.Generic; using BugsnagUnity.Payload; using UnityEngine; namespace BugsnagUnity { static class DictionaryExtensions { internal static void PopulateDictionaryFromAndroidData(this IDictionary<string, object> dictionary, AndroidJavaObject source) { using (var set = source.Call<AndroidJavaObject>("entrySet")) using (var iterator = set.Call<AndroidJavaObject>("iterator")) { while (iterator.Call<bool>("hasNext")) { using (var mapEntry = iterator.Call<AndroidJavaObject>("next")) { var key = mapEntry.Call<string>("getKey"); using (var value = mapEntry.Call<AndroidJavaObject>("getValue")) { if (value != null) { using (var @class = value.Call<AndroidJavaObject>("getClass")) { if (@class.Call<bool>("isArray")) { var values = AndroidJNIHelper.ConvertFromJNIArray<string[]>(value.GetRawObject()); dictionary.AddToPayload(key, values); } else { dictionary.AddToPayload(key, value.Call<string>("toString")); } } } } } } } } } }
Fix image hash computing (PNG gives different results on different ms windows versions)
using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace MaintainableSelenium.MvcPages.Utils { public static class ImageExtensions { public static Bitmap ToBitmap(this byte[] screenshot) { using (MemoryStream memoryStream = new MemoryStream(screenshot)) { var image = Image.FromStream(memoryStream); return new Bitmap(image); } } public static byte[] ToBytes(this Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms, ImageFormat.Png); return ms.ToArray(); } } } }
using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace MaintainableSelenium.MvcPages.Utils { public static class ImageExtensions { public static Bitmap ToBitmap(this byte[] screenshot) { using (MemoryStream memoryStream = new MemoryStream(screenshot)) { var image = Image.FromStream(memoryStream); return new Bitmap(image); } } public static byte[] ToBytes(this Image imageIn) { using (var ms = new MemoryStream()) { imageIn.Save(ms, ImageFormat.Bmp); return ms.ToArray(); } } } }
Remove obsolete ifdefs and property
using System; using Xablu.WebApiClient.Exceptions; namespace Xablu.WebApiClient { public class CrossRestApiClient { private static Action<RestApiClientOptions> _configureRestApiClient; private static Lazy<IRestApiClient> _restApiClientImplementation = new Lazy<IRestApiClient>(() => CreateRestApiClient(), System.Threading.LazyThreadSafetyMode.PublicationOnly); public static bool IsSupported => _restApiClientImplementation.Value == null ? false : true; public static void Configure(Action<RestApiClientOptions> options) { _configureRestApiClient = options; } public static IRestApiClient Current { get { var ret = _restApiClientImplementation.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } private static IRestApiClient CreateRestApiClient() { #if NETSTANDARD2_0 return null; #else if (_configureRestApiClient == null) throw NotConfiguredException(); var options = new RestApiClientOptions(); _configureRestApiClient.Invoke(options); return new RestApiClientImplementation(options); #endif } internal static Exception NotImplementedInReferenceAssembly() => new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."); internal static Exception NotConfiguredException() => new NotConfiguredException("The `CrossRestApiClient` has not been configured. Make sure you call the `CrossRestApiClient.Configure` method before accessing the `CrossRestApiClient.Current` property."); } }
using System; using Xablu.WebApiClient.Exceptions; namespace Xablu.WebApiClient { public class CrossRestApiClient { private static Action<RestApiClientOptions> _configureRestApiClient; private static Lazy<IRestApiClient> _restApiClientImplementation = new Lazy<IRestApiClient>(() => CreateRestApiClient(), System.Threading.LazyThreadSafetyMode.PublicationOnly); public static void Configure(Action<RestApiClientOptions> options) { _configureRestApiClient = options; } public static IRestApiClient Current { get { var ret = _restApiClientImplementation.Value; if (ret == null) { throw NotImplementedInReferenceAssembly(); } return ret; } } private static IRestApiClient CreateRestApiClient() { if (_configureRestApiClient == null) throw NotConfiguredException(); var options = new RestApiClientOptions(); _configureRestApiClient.Invoke(options); return new RestApiClientImplementation(options); } internal static Exception NotImplementedInReferenceAssembly() => new NotImplementedException("This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."); internal static Exception NotConfiguredException() => new NotConfiguredException("The `CrossRestApiClient` has not been configured. Make sure you call the `CrossRestApiClient.Configure` method before accessing the `CrossRestApiClient.Current` property."); } }
Fix installments to use the correct type
namespace Stripe { using System; using Newtonsoft.Json; using Stripe.Infrastructure; public class PaymentIntentPaymentMethodOptionsCard : StripeEntity<PaymentIntentPaymentMethodOptionsCard> { /// <summary> /// Installment details for this payment (Mexico only). /// </summary> [JsonProperty("installments")] public string Installments { get; set; } /// <summary> /// We strongly recommend that you rely on our SCA engine to automatically prompt your /// customers for authentication based on risk level and other requirements. However, if /// you wish to request authentication based on logic from your own fraud engine, provide /// this option. Permitted values include: <c>automatic</c>, <c>any</c>, or /// <c>challenge_only</c>. /// </summary> [JsonProperty("request_three_d_secure")] public string RequestThreeDSecure { get; set; } } }
namespace Stripe { using System; using Newtonsoft.Json; using Stripe.Infrastructure; public class PaymentIntentPaymentMethodOptionsCard : StripeEntity<PaymentIntentPaymentMethodOptionsCard> { /// <summary> /// Installment details for this payment (Mexico only). /// </summary> [JsonProperty("installments")] public PaymentIntentPaymentMethodOptionsCardInstallments Installments { get; set; } /// <summary> /// We strongly recommend that you rely on our SCA engine to automatically prompt your /// customers for authentication based on risk level and other requirements. However, if /// you wish to request authentication based on logic from your own fraud engine, provide /// this option. Permitted values include: <c>automatic</c>, <c>any</c>, or /// <c>challenge_only</c>. /// </summary> [JsonProperty("request_three_d_secure")] public string RequestThreeDSecure { get; set; } } }
Use {0:c} rather than ToString("c") where possible.
@using System.Linq; @using Nwazet.Commerce.Models; @{ var priceTiers = new List<PriceTier>(Model.PriceTiers); var discountedPriceTiers = new List<PriceTier>(Model.DiscountedPriceTiers); } @if (Model.PriceTiers != null && Enumerable.Count(Model.PriceTiers) > 0) { <table class="tiered-prices"> <tr> <td>@T("Quantity")</td> <td>@T("Price")</td> </tr> @for (var i = 0; i < priceTiers.Count(); i++ ) { <tr> <td>@priceTiers[i].Quantity</td> <td> @if (priceTiers[i].Price != discountedPriceTiers[i].Price) { <span class="inactive-price" style="text-decoration:line-through" title="@T("Was {0}", priceTiers[i].Price.ToString("c"))">@priceTiers[i].Price.ToString("c")</span> <span class="discounted-price" title="@T("Now {0}", discountedPriceTiers[i].Price.ToString("c"))">@discountedPriceTiers[i].Price.ToString("c")</span> } else { <span class="regular-price">@priceTiers[i].Price.ToString("c")</span> } </td> </tr> } </table> }
@using System.Linq; @using Nwazet.Commerce.Models; @{ var priceTiers = new List<PriceTier>(Model.PriceTiers); var discountedPriceTiers = new List<PriceTier>(Model.DiscountedPriceTiers); } @if (Model.PriceTiers != null && Enumerable.Count(Model.PriceTiers) > 0) { <table class="tiered-prices"> <tr> <td>@T("Quantity")</td> <td>@T("Price")</td> </tr> @for (var i = 0; i < priceTiers.Count(); i++ ) { <tr> <td>@priceTiers[i].Quantity</td> <td> @if (priceTiers[i].Price != discountedPriceTiers[i].Price) { <span class="inactive-price" style="text-decoration:line-through" title="@T("Was {0:c}", priceTiers[i].Price)">@priceTiers[i].Price.ToString("c")</span> <span class="discounted-price" title="@T("Now {0:c}", discountedPriceTiers[i].Price)">@discountedPriceTiers[i].Price.ToString("c")</span> } else { <span class="regular-price">@priceTiers[i].Price.ToString("c")</span> } </td> </tr> } </table> }
Save created towers in an array
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public GameObject towerBase; public GameObject gameField; void Start () { Debug.Log ("GameController: Game Started"); this.initGamePlatform (); } void Update () { } void initGamePlatform() { for (int x = 0; x < gameField.transform.localScale.x; x++) { for (int z = 0; z < gameField.transform.localScale.z; z++) { GameObject newTowerBase = Instantiate (towerBase); newTowerBase.AddComponent<Rigidbody> (); newTowerBase.transform.position = new Vector3 (towerBase.transform.position.x+x, 0.1f, towerBase.transform.position.z-z); // TODO:: Set transform to Parent. // Doesn't work: newTowerBase.transform.SetParent (towerBase.transform); } } } }
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public GameObject towerBase; public GameObject gameField; private GameObject[,] towerBases; private int gameFieldWidth = 0; private int gameFieldHeight = 0; void Start () { this.gameFieldWidth = (int)(gameField.transform.localScale.x); this.gameFieldHeight = (int)(gameField.transform.localScale.z); this.towerBases = new GameObject[this.gameFieldWidth, this.gameFieldHeight]; this.initGamePlatform (); } void initGamePlatform() { for (int x = 0; x < this.gameFieldWidth; x++) { for (int z = 0; z < this.gameFieldHeight; z++) { GameObject newTowerBase = Instantiate (towerBase); newTowerBase.AddComponent<Rigidbody> (); newTowerBase.transform.position = new Vector3 (towerBase.transform.position.x+x, 0.1f, towerBase.transform.position.z-z); this.towerBases [x, z] = newTowerBase; } } } }
Fix for always using front
using Android.Content; using Android.Hardware; namespace Plugin.Media { internal static class IntentExtraExtensions { private const string extraFrontPre25 = "android.intent.extras.CAMERA_FACING"; private const string extraFrontPost25 = "android.intent.extras.LENS_FACING_FRONT"; private const string extraBackPost25 = "android.intent.extras.LENS_FACING_BACK"; private const string extraUserFront = "android.intent.extra.USE_FRONT_CAMERA"; public static void UseFrontCamera(this Intent intent) { // Android before API 25 (7.1) intent.PutExtra(extraFrontPre25, (int)CameraFacing.Front); // Android API 25 and up intent.PutExtra(extraFrontPost25, 1); intent.PutExtra(extraUserFront, true); } public static void UseBackCamera(this Intent intent) { // Android before API 25 (7.1) intent.PutExtra(extraFrontPre25, (int)CameraFacing.Front); // Android API 25 and up intent.PutExtra(extraBackPost25, 1); intent.PutExtra(extraUserFront, false); } } }
using Android.Content; using Android.Hardware; namespace Plugin.Media { internal static class IntentExtraExtensions { private const string extraFrontPre25 = "android.intent.extras.CAMERA_FACING"; private const string extraFrontPost25 = "android.intent.extras.LENS_FACING_FRONT"; private const string extraBackPost25 = "android.intent.extras.LENS_FACING_BACK"; private const string extraUserFront = "android.intent.extra.USE_FRONT_CAMERA"; public static void UseFrontCamera(this Intent intent) { // Android before API 25 (7.1) intent.PutExtra(extraFrontPre25, (int)CameraFacing.Front); // Android API 25 and up intent.PutExtra(extraFrontPost25, 1); intent.PutExtra(extraUserFront, true); } public static void UseBackCamera(this Intent intent) { // Android before API 25 (7.1) intent.PutExtra(extraFrontPre25, (int)CameraFacing.Back); // Android API 25 and up intent.PutExtra(extraBackPost25, 1); intent.PutExtra(extraUserFront, false); } } }
Hide "Rank Achieved" sorting mode until it's supported
// 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.ComponentModel; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))] Artist, [Description("Author")] Author, [LocalisableDescription(typeof(BeatmapsetsStrings), nameof(BeatmapsetsStrings.ShowStatsBpm))] BPM, [Description("Date Added")] DateAdded, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))] Difficulty, [LocalisableDescription(typeof(SortStrings), nameof(SortStrings.ArtistTracksLength))] Length, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchFiltersRank))] RankAchieved, [LocalisableDescription(typeof(BeatmapsetsStrings), nameof(BeatmapsetsStrings.ShowInfoSource))] Source, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))] Title, } }
// 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.ComponentModel; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Screens.Select.Filter { public enum SortMode { [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingArtist))] Artist, [Description("Author")] Author, [LocalisableDescription(typeof(BeatmapsetsStrings), nameof(BeatmapsetsStrings.ShowStatsBpm))] BPM, [Description("Date Added")] DateAdded, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingDifficulty))] Difficulty, [LocalisableDescription(typeof(SortStrings), nameof(SortStrings.ArtistTracksLength))] Length, // todo: pending support (https://github.com/ppy/osu/issues/4917) // [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchFiltersRank))] // RankAchieved, [LocalisableDescription(typeof(BeatmapsetsStrings), nameof(BeatmapsetsStrings.ShowInfoSource))] Source, [LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.ListingSearchSortingTitle))] Title, } }
Revert accidental change of async flag .
using System; using System.Diagnostics; namespace NuGetConsole.Implementation.PowerConsole { /// <summary> /// Represents a host with extra info. /// </summary> class HostInfo : ObjectWithFactory<PowerConsoleWindow> { Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; } public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider) : base(factory) { UtilityMethods.ThrowIfArgumentNull(hostProvider); this.HostProvider = hostProvider; } /// <summary> /// Get the HostName attribute value of this host. /// </summary> public string HostName { get { return HostProvider.Metadata.HostName; } } IWpfConsole _wpfConsole; /// <summary> /// Get/create the console for this host. If not already created, this /// actually creates the (console, host) pair. /// /// Note: Creating the console is handled by this package and mostly will /// succeed. However, creating the host could be from other packages and /// fail. In that case, this console is already created and can be used /// subsequently in limited ways, such as displaying an error message. /// </summary> public IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = Factory.WpfConsoleService.CreateConsole( Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName); _wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: false); } return _wpfConsole; } } } }
using System; using System.Diagnostics; namespace NuGetConsole.Implementation.PowerConsole { /// <summary> /// Represents a host with extra info. /// </summary> class HostInfo : ObjectWithFactory<PowerConsoleWindow> { Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; } public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider) : base(factory) { UtilityMethods.ThrowIfArgumentNull(hostProvider); this.HostProvider = hostProvider; } /// <summary> /// Get the HostName attribute value of this host. /// </summary> public string HostName { get { return HostProvider.Metadata.HostName; } } IWpfConsole _wpfConsole; /// <summary> /// Get/create the console for this host. If not already created, this /// actually creates the (console, host) pair. /// /// Note: Creating the console is handled by this package and mostly will /// succeed. However, creating the host could be from other packages and /// fail. In that case, this console is already created and can be used /// subsequently in limited ways, such as displaying an error message. /// </summary> public IWpfConsole WpfConsole { get { if (_wpfConsole == null) { _wpfConsole = Factory.WpfConsoleService.CreateConsole( Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName); _wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: true); } return _wpfConsole; } } } }
Update the example precondition to use IServiceProvider
// (Note: This precondition is obsolete, it is recommended to use the RequireOwnerAttribute that is bundled with Discord.Commands) using Discord.Commands; using Discord.WebSocket; using System.Threading.Tasks; // Inherit from PreconditionAttribute public class RequireOwnerAttribute : PreconditionAttribute { // Override the CheckPermissions method public async override Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IDependencyMap map) { // Get the ID of the bot's owner var ownerId = (await map.Get<DiscordSocketClient>().GetApplicationInfoAsync()).Owner.Id; // If this command was executed by that user, return a success if (context.User.Id == ownerId) return PreconditionResult.FromSuccess(); // Since it wasn't, fail else return PreconditionResult.FromError("You must be the owner of the bot to run this command."); } }
// (Note: This precondition is obsolete, it is recommended to use the RequireOwnerAttribute that is bundled with Discord.Commands) using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; // Inherit from PreconditionAttribute public class RequireOwnerAttribute : PreconditionAttribute { // Override the CheckPermissions method public async override Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { // Get the ID of the bot's owner var ownerId = (await services.GetService<DiscordSocketClient>().GetApplicationInfoAsync()).Owner.Id; // If this command was executed by that user, return a success if (context.User.Id == ownerId) return PreconditionResult.FromSuccess(); // Since it wasn't, fail else return PreconditionResult.FromError("You must be the owner of the bot to run this command."); } }
Configure data portal before using data portal
using Csla.Configuration; using ProjectTracker.Library; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace ProjectTracker.Ui.Xamarin { public partial class App : Application { public static Page RootPage { get; private set; } private ContentPage startPage = new XamarinFormsUi.Views.Dashboard(); public App () { InitializeComponent(); MainPage = new NavigationPage(startPage); RootPage = MainPage; } protected override async void OnStart () { // Handle when your app starts CslaConfiguration.Configure() .DataPortal() .DefaultProxy(typeof(Csla.DataPortalClient.HttpProxy), "https://ptrackerserver.azurewebsites.net/api/dataportal"); Library.Security.PTPrincipal.Logout(); await Library.Security.PTPrincipal.LoginAsync("manager", "manager"); await RoleList.CacheListAsync(); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } public static async Task NavigateTo(Type page) { var target = (Page)Activator.CreateInstance(page); await NavigateTo(target); } public static async Task NavigateTo(Type page, object parameter) { var target = (Page)Activator.CreateInstance(page, parameter); await NavigateTo(target); } private static async Task NavigateTo(Page page) { await RootPage.Navigation.PushAsync(page); } } }
using Csla.Configuration; using ProjectTracker.Library; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace ProjectTracker.Ui.Xamarin { public partial class App : Application { public static Page RootPage { get; private set; } public App () { InitializeComponent(); CslaConfiguration.Configure() .DataPortal() .DefaultProxy(typeof(Csla.DataPortalClient.HttpProxy), "https://ptrackerserver.azurewebsites.net/api/dataportal"); Library.Security.PTPrincipal.Logout(); MainPage = new NavigationPage(new XamarinFormsUi.Views.Dashboard()); RootPage = MainPage; } protected override async void OnStart () { await Library.Security.PTPrincipal.LoginAsync("manager", "manager"); await RoleList.CacheListAsync(); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } public static async Task NavigateTo(Type page) { var target = (Page)Activator.CreateInstance(page); await NavigateTo(target); } public static async Task NavigateTo(Type page, object parameter) { var target = (Page)Activator.CreateInstance(page, parameter); await NavigateTo(target); } private static async Task NavigateTo(Page page) { await RootPage.Navigation.PushAsync(page); } } }
Sort attribute types as documentation
namespace Akeneo.Model { public class AttributeType { public const string Date = "pim_catalog_date"; public const string Metric = "pim_catalog_metric"; public const string Price = "pim_catalog_price_collection"; public const string Number = "pim_catalog_number"; public const string Text = "pim_catalog_text"; public const string TextArea = "pim_catalog_textarea"; public const string Identifier = "pim_catalog_identifier"; public const string SimpleSelect = "pim_catalog_simpleselect"; public const string Boolean = "pim_catalog_boolean"; } }
namespace Akeneo.Model { public class AttributeType { /// <summary> /// It is the unique product’s identifier. The catalog can contain only one. /// </summary> public const string Identifier = "pim_catalog_identifier"; /// <summary> /// Text /// </summary> public const string Text = "pim_catalog_text"; /// <summary> /// Long texts /// </summary> public const string TextArea = "pim_catalog_textarea"; /// <summary> /// Yes/No /// </summary> public const string Boolean = "pim_catalog_boolean"; /// <summary> /// Number (integer and float) /// </summary> public const string Number = "pim_catalog_number"; /// <summary> /// Simple choice list /// </summary> public const string SimpleSelect = "pim_catalog_simpleselect"; /// <summary> /// Date /// </summary> public const string Date = "pim_catalog_date"; /// <summary> /// Metric. It consists of a value and a unit (a weight for example). /// </summary> public const string Metric = "pim_catalog_metric"; /// <summary> /// Collection of prices. Each price contains a value and a currency. /// </summary> public const string Price = "pim_catalog_price_collection"; } }
Add implementation for change tracking.
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SmugMug.v2.Types { public class SmugMugEntity { protected void NotifyPropertyValueChanged(string name, object value) { } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; namespace SmugMug.v2.Types { public class SmugMugEntity { private Dictionary<string, object> _storage = new Dictionary<string, object>(); private readonly object _syncLock = new object(); protected void NotifyPropertyValueChanged(string propertyName, object newValue) { object firstCapturedData; if (_storage.TryGetValue(propertyName, out firstCapturedData)) { // currentData is the value that was first captured. // setting it back to that value should remove this property from the // list of changed values if (firstCapturedData.Equals(newValue)) { Debug.WriteLine("Same as original {0}, remove tracking", newValue); lock (_syncLock) { _storage.Remove(propertyName); } } return; } lock (_syncLock) { Debug.WriteLine("New value! '{0}'", newValue); _storage.Add(propertyName, newValue); } } } }
Add flag to know if the package is bundled or not.
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Package.cs" company="Naos"> // Copyright 2015 Naos // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Deployment.Contract { using System; using System.Security.Cryptography; /// <summary> /// A full package, description and the file bytes as of a date and time. /// </summary> public class Package { /// <summary> /// Gets or sets the description of the package. /// </summary> public PackageDescription PackageDescription { get; set; } /// <summary> /// Gets or sets the bytes of the package file at specified date and time. /// </summary> public byte[] PackageFileBytes { get; set; } /// <summary> /// Gets or sets the date and time UTC that the package file bytes were retrieved. /// </summary> public DateTime PackageFileBytesRetrievalDateTimeUtc { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Package.cs" company="Naos"> // Copyright 2015 Naos // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Deployment.Contract { using System; using System.Security.Cryptography; /// <summary> /// A full package, description and the file bytes as of a date and time. /// </summary> public class Package { /// <summary> /// Gets or sets the description of the package. /// </summary> public PackageDescription PackageDescription { get; set; } /// <summary> /// Gets or sets the bytes of the package file at specified date and time. /// </summary> public byte[] PackageFileBytes { get; set; } /// <summary> /// Gets or sets the date and time UTC that the package file bytes were retrieved. /// </summary> public DateTime PackageFileBytesRetrievalDateTimeUtc { get; set; } /// <summary> /// Gets or sets a value indicating whether or not the dependencies have been bundled with the specific package. /// </summary> public bool AreDependenciesBundled { get; set; } } }
Switch back to hello world example,
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.RunProxy(new ProxyOptions { Host = "jsonplaceholder.typicode.com" }); } } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Tiesmaster.Dcc { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(RunDccProxyAsync); } private static async Task RunDccProxyAsync(HttpContext context) { await context.Response.WriteAsync("Hello from DCC ;)"); } } }
Add placeholder for agent config
using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet; using Microsoft.Framework.DependencyInjection; namespace Glimpse.Agent.AspNet.Sample { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddGlimpse() .RunningAgent() .ForWeb() .WithRemoteStreamAgent(); //.WithRemoteHttpAgent(); } public void Configure(IApplicationBuilder app) { app.UseGlimpse(); app.UseWelcomePage(); } } }
using Glimpse.Agent.Web; using Microsoft.AspNet.Builder; using Glimpse.Host.Web.AspNet; using Microsoft.Framework.DependencyInjection; namespace Glimpse.Agent.AspNet.Sample { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddGlimpse() .RunningAgent() .ForWeb() .Configure<GlimpseAgentWebOptions>(options => { //options.IgnoredStatusCodes.Add(200); }) .WithRemoteStreamAgent(); //.WithRemoteHttpAgent(); } public void Configure(IApplicationBuilder app) { app.UseGlimpse(); app.UseWelcomePage(); } } }
Fix Missing magic extension and max version of decoder
/* Copyright 2016 Daro Cutillas Carrillo * * 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 FenixLib.Core; using static FenixLib.IO.NativeFormat; namespace FenixLib.IO { public sealed class DivFilePaletteDecoder : NativeDecoder<Palette> { public override int MaxSupportedVersion { get; } protected override string[] KnownFileExtensions { get; } protected override string[] KnownFileMagics { get; } protected override Palette ReadBody ( Header header, NativeFormatReader reader ) { // Map files have the Palette data in a different position than the // rest of the files if ( header.Magic == "map" ) reader.ReadBytes ( 40 ); return reader.ReadPalette (); } } }
/* Copyright 2016 Daro Cutillas Carrillo * * 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 FenixLib.Core; using static FenixLib.IO.NativeFormat; namespace FenixLib.IO { public sealed class DivFilePaletteDecoder : NativeDecoder<Palette> { public override int MaxSupportedVersion { get; } = 0; protected override string[] KnownFileExtensions { get; } = { "pal", "map", "fpg", "fnt" }; protected override string[] KnownFileMagics { get; } = { "fnt", "map", "fpg", "pal" }; protected override Palette ReadBody ( Header header, NativeFormatReader reader ) { // Map files have the Palette data in a different position than the // rest of the files if ( header.Magic == "map" ) reader.ReadBytes ( 40 ); return reader.ReadPalette (); } } }
Remove VerifyMessage extension (implemented in NBitcoin)
using HiddenWallet.Models; using System; using System.Collections.Generic; using System.Text; namespace NBitcoin { public static class NBitcoinExtensions { public static ChainedBlock GetBlock(this ConcurrentChain me, Height height) => me.GetBlock(height.Value); public static string ToHex(this IBitcoinSerializable me) { return HexHelpers.ToString(me.ToBytes()); } public static void FromHex(this IBitcoinSerializable me, string hex) { if (me == null) throw new ArgumentNullException(nameof(me)); me.FromBytes(HexHelpers.GetBytes(hex)); } public static bool VerifyMessage(this BitcoinWitPubKeyAddress me, string message, string signature) { var key = PubKey.RecoverFromMessage(message, signature); return key.Hash == me.Hash; } } }
using HiddenWallet.Models; using System; using System.Collections.Generic; using System.Text; namespace NBitcoin { public static class NBitcoinExtensions { public static ChainedBlock GetBlock(this ConcurrentChain me, Height height) => me.GetBlock(height.Value); public static string ToHex(this IBitcoinSerializable me) { return HexHelpers.ToString(me.ToBytes()); } public static void FromHex(this IBitcoinSerializable me, string hex) { if (me == null) throw new ArgumentNullException(nameof(me)); me.FromBytes(HexHelpers.GetBytes(hex)); } } }
Rename tests to reflect recent naming changes.
using System; using System.Threading.Tasks; using Xunit; namespace Nocto.Tests.Integration { public class UsersEndpointTests { public class TheGetUserAsyncMethod { [Fact] public async Task ReturnsSpecifiedUser() { var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" }; // Get a user by username var user = await github.User.Get("tclem"); Assert.Equal("GitHub", user.Company); } } public class TheGetAuthenticatedUserAsyncMethod { [Fact] public async Task ReturnsSpecifiedUser() { var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" }; // Get a user by username var user = await github.User.Current(); Assert.Equal("xapitestaccountx", user.Login); } } public class TheGetUsersAsyncMethod { [Fact] public async Task ReturnsAllUsers() { var github = new GitHubClient(); // Get a user by username var users = await github.User.GetAll(); Console.WriteLine(users); } } } }
using System; using System.Threading.Tasks; using Xunit; namespace Nocto.Tests.Integration { public class UsersEndpointTests { public class TheGetMethod { [Fact] public async Task ReturnsSpecifiedUser() { var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" }; // Get a user by username var user = await github.User.Get("tclem"); Assert.Equal("GitHub", user.Company); } } public class TheCurrentMethod { [Fact] public async Task ReturnsSpecifiedUser() { var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" }; // Get a user by username var user = await github.User.Current(); Assert.Equal("xapitestaccountx", user.Login); } } public class TheGetAllMethod { [Fact] public async Task ReturnsAllUsers() { var github = new GitHubClient(); // Get a user by username var users = await github.User.GetAll(); Console.WriteLine(users); } } } }
Revert "fix(logging): 🐛 try alt AppInsights IKey init"
using System; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; namespace FilterLists.SharedKernel.Logging { public static class HostRunner { public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default) { _ = host ?? throw new ArgumentNullException(nameof(host)); Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration .WriteTo.Conditional( _ => host.Services.GetService<IHostEnvironment>().IsProduction(), c => c.ApplicationInsights( ((IConfiguration)host.Services.GetService(typeof(IConfiguration)))[ "ApplicationInsights:InstrumentationKey"], TelemetryConverter.Traces)) .CreateLogger(); try { if (runPreHostAsync != null) { Log.Information("Initializing pre-host"); await runPreHostAsync(); } Log.Information("Initializing host"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } } }
using System; using System.Threading.Tasks; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; namespace FilterLists.SharedKernel.Logging { public static class HostRunner { public static async Task TryRunWithLoggingAsync(this IHost host, Func<Task>? runPreHostAsync = default) { _ = host ?? throw new ArgumentNullException(nameof(host)); Log.Logger = ConfigurationBuilder.BaseLoggerConfiguration .WriteTo.Conditional( _ => host.Services.GetService<IHostEnvironment>().IsProduction(), c => c.ApplicationInsights( host.Services.GetRequiredService<TelemetryConfiguration>(), TelemetryConverter.Traces)) .CreateLogger(); try { // TODO: rm, for debugging var client = host.Services.GetService<TelemetryClient>(); Log.Warning("Application Insights Instrumentation Key: {InstrumentationKey}", client.InstrumentationKey); if (runPreHostAsync != null) { Log.Information("Initializing pre-host"); await runPreHostAsync(); } Log.Information("Initializing host"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); throw; } finally { Log.CloseAndFlush(); } } } }
Remove specific references to .sln files.
using System; using System.IO; using SourceBrowser.Generator; namespace SourceBrowser.Samples { class Program { static void Main(string[] args) { // Combined with, or replaced by, provided paths to create absolute paths string userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // For developers that set test variables in code: string solutionPath = @"Documents\GitHub\Kiwi\TestSolution\TestSolution.sln"; string saveDirectory = @"Documents\SourceBrowserResult\"; // For developers that provide test variables in arguments: if (args.Length == 2) { solutionPath = args[0]; saveDirectory = args[1]; } // Combine user's root with relative solution paths, or use absolute paths. // (Path.Combine returns just second argument if it is an absolute path) string absoluteSolutionPath = Path.Combine(userProfilePath, solutionPath); string absoluteSaveDirectory = Path.Combine(userProfilePath, saveDirectory); // Open and analyze the solution. try { Console.Write("Opening " + absoluteSolutionPath); Console.WriteLine("..."); var solutionAnalyzer = new SolutionAnalayzer(absoluteSolutionPath); Console.Write("Analyzing and saving into " + absoluteSaveDirectory); Console.WriteLine("..."); solutionAnalyzer.AnalyzeAndSave(saveDirectory); Console.WriteLine("Job successful!"); } catch (Exception ex) { Console.WriteLine("Error:"); Console.WriteLine(ex.ToString()); } } } }
using System; using System.IO; using SourceBrowser.Generator; namespace SourceBrowser.Samples { class Program { static void Main(string[] args) { // Combined with, or replaced by, provided paths to create absolute paths string userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // For developers that set test variables in code: string solutionPath = @""; string saveDirectory = @""; // For developers that provide test variables in arguments: if (args.Length == 2) { solutionPath = args[0]; saveDirectory = args[1]; } // Combine user's root with relative solution paths, or use absolute paths. // (Path.Combine returns just second argument if it is an absolute path) string absoluteSolutionPath = Path.Combine(userProfilePath, solutionPath); string absoluteSaveDirectory = Path.Combine(userProfilePath, saveDirectory); // Open and analyze the solution. try { Console.Write("Opening " + absoluteSolutionPath); Console.WriteLine("..."); var solutionAnalyzer = new SolutionAnalayzer(absoluteSolutionPath); Console.Write("Analyzing and saving into " + absoluteSaveDirectory); Console.WriteLine("..."); solutionAnalyzer.AnalyzeAndSave(saveDirectory); Console.WriteLine("Job successful!"); } catch (Exception ex) { Console.WriteLine("Error:"); Console.WriteLine(ex.ToString()); } } } }
Use constants in upgrade migration
using Umbraco.Core.Logging; using Umbraco.Core.Persistence.SqlSyntax; namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFourteenZero { /// <summary> /// Migrates member group picker properties from NVarchar to NText. See https://github.com/umbraco/Umbraco-CMS/issues/3268. /// </summary> [Migration("7.14.0", 1, Constants.System.UmbracoMigrationName)] public class UpdateMemberGroupPickerData : MigrationBase { public UpdateMemberGroupPickerData(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger) { } public override void Up() { // move the data for all member group properties from the NVarchar to the NText column and clear the NVarchar column Execute.Sql(@"UPDATE cmsPropertyData SET dataNtext = dataNvarchar, dataNvarchar = NULL WHERE dataNtext IS NULL AND id IN ( SELECT id FROM cmsPropertyData WHERE propertyTypeId in ( SELECT id from cmsPropertyType where dataTypeID IN ( SELECT nodeId FROM cmsDataType WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker' ) ) )"); // ensure that all exising member group properties are defined as NText Execute.Sql("UPDATE cmsDataType SET dbType = 'Ntext' WHERE propertyEditorAlias = 'Umbraco.MemberGroupPicker'"); } public override void Down() { } } }
using Umbraco.Core.Logging; using Umbraco.Core.Persistence.SqlSyntax; namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFourteenZero { /// <summary> /// Migrates member group picker properties from NVarchar to NText. See https://github.com/umbraco/Umbraco-CMS/issues/3268. /// </summary> [Migration("7.14.0", 1, Constants.System.UmbracoMigrationName)] public class UpdateMemberGroupPickerData : MigrationBase { public UpdateMemberGroupPickerData(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger) { } public override void Up() { // move the data for all member group properties from the NVarchar to the NText column and clear the NVarchar column Execute.Sql($@"UPDATE cmsPropertyData SET dataNtext = dataNvarchar, dataNvarchar = NULL WHERE dataNtext IS NULL AND id IN ( SELECT id FROM cmsPropertyData WHERE propertyTypeId in ( SELECT id from cmsPropertyType where dataTypeID IN ( SELECT nodeId FROM cmsDataType WHERE propertyEditorAlias = '{Constants.PropertyEditors.MemberGroupPickerAlias}' ) ) )"); // ensure that all exising member group properties are defined as NText Execute.Sql($"UPDATE cmsDataType SET dbType = 'Ntext' WHERE propertyEditorAlias = '{Constants.PropertyEditors.MemberGroupPickerAlias}'"); } public override void Down() { } } }
Add sample code to get the authenticated user from the site.
using SmugMug.v2.Authentication; using SmugMug.v2.Authentication.Tokens; using System.Diagnostics; namespace SmugMugTest { class Program { private static OAuthToken s_oauthToken; static void Main(string[] args) { s_oauthToken = ConsoleAuthentication.GetOAuthTokenFromProvider(new FileTokenProvider()); Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid)); } } }
using SmugMug.v2.Authentication; using SmugMug.v2.Authentication.Tokens; using SmugMug.v2.Types; using System.Diagnostics; namespace SmugMugTest { class Program { private static OAuthToken s_oauthToken; static void Main(string[] args) { s_oauthToken = ConsoleAuthentication.GetOAuthTokenFromProvider(new FileTokenProvider()); Debug.Assert(!s_oauthToken.Equals(OAuthToken.Invalid)); SiteEntity site = new SiteEntity(s_oauthToken); var user = site.GetAuthenticatedUserAsync().Result; } } }
Make it work with any number of arguments
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConComp { class Program { static void Main(string[] args) { var fname1 = args[0]; var fname2 = args[1]; var task1 = Task<long>.Factory.StartNew(() => new FileInfo(fname1).Length); var task2 = Task<long>.Factory.StartNew(() => new FileInfo(fname2).Length); Task.WaitAll(task1, task2); if (task1.Result > task2.Result) { Console.WriteLine($"{fname1} is bigger"); } else if (task2.Result > task1.Result) { Console.WriteLine($"{fname2} is bigger"); } else { Console.WriteLine("The files are the same size"); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace ConComp { internal class Program { private static void Main(string[] args) { var tasks = new Dictionary<string, Task<long>>(); foreach (var arg in args) { var task = Task<long>.Factory.StartNew(() => new FileInfo(arg).Length); tasks.Add(arg, task); } Task.WaitAll(tasks.Values.Cast<Task>().ToArray()); var maxFileSize = tasks.Max(t => t.Value.Result); var biggests = tasks.Where(t => t.Value.Result == maxFileSize).ToList(); if (biggests.Count == tasks.Count) { Console.WriteLine("All files are even"); } else if (biggests.Count > 1) { var all = string.Join(", ", biggests.Select(b => b.Key)); Console.WriteLine($"{all} are the biggest"); } else { var biggest = biggests.Single(); Console.WriteLine($"{biggest.Key} is the biggest"); } } } }
Add a method to create an instance of the applicable path element type to resolver
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Reflection; using Pather.CSharp.PathElements; namespace Pather.CSharp { public class Resolver { private IList<Type> pathElementTypes; public Resolver() { pathElementTypes = new List<Type>(); pathElementTypes.Add(typeof(Property)); } public object Resolve(object target, string path) { var pathElements = path.Split('.'); var tempResult = target; foreach(var pathElement in pathElements) { PropertyInfo p = tempResult.GetType().GetProperty(pathElement); if (p == null) throw new ArgumentException($"The property {pathElement} could not be found."); tempResult = p.GetValue(tempResult); } var result = tempResult; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Reflection; using Pather.CSharp.PathElements; namespace Pather.CSharp { public class Resolver { private IList<Type> pathElementTypes; public Resolver() { pathElementTypes = new List<Type>(); pathElementTypes.Add(typeof(Property)); } public object Resolve(object target, string path) { var pathElements = path.Split('.'); var tempResult = target; foreach(var pathElement in pathElements) { PropertyInfo p = tempResult.GetType().GetProperty(pathElement); if (p == null) throw new ArgumentException($"The property {pathElement} could not be found."); tempResult = p.GetValue(tempResult); } var result = tempResult; return result; } private object createPathElement(string pathElement) { //get the first applicable path element type var pathElementType = pathElementTypes.Where(t => { MethodInfo applicableMethod = t.GetMethod("IsApplicable", BindingFlags.Static | BindingFlags.Public); if (applicableMethod == null) throw new InvalidOperationException($"The type {t.Name} does not have a static method IsApplicable"); bool? applicable = applicableMethod.Invoke(null, new[] { pathElement }) as bool?; if (applicable == null) throw new InvalidOperationException($"IsApplicable of type {t.Name} does not return bool"); return applicable.Value; }).FirstOrDefault(); if (pathElementType == null) throw new InvalidOperationException($"There is no applicable path element type for {pathElement}"); var result = Activator.CreateInstance(pathElementType, pathElement); //each path element type must have a constructor that takes a string parameter return result; } } }
Bring back the LoadFrom method.
using System.Collections.Generic; using System.Net.Mail; using SparkPost.Utilities; namespace SparkPost { public class Transmission { public Transmission() { Recipients = new List<Recipient>(); Metadata = new Dictionary<string, object>(); SubstitutionData = new Dictionary<string, object>(); Content = new Content(); Options = new Options(); } public Transmission(MailMessage message) : this() { MailMessageMapping.ToTransmission(message, this); } public string Id { get; set; } public string State { get; set; } public Options Options { get; set; } public IList<Recipient> Recipients { get; set; } public string ListId { get; set; } public string CampaignId { get; set; } public string Description { get; set; } public IDictionary<string, object> Metadata { get; set; } public IDictionary<string, object> SubstitutionData { get; set; } public string ReturnPath { get; set; } public Content Content { get; set; } public int TotalRecipients { get; set; } public int NumGenerated { get; set; } public int NumFailedGeneration { get; set; } public int NumInvalidRecipients { get; set; } } }
using System.Collections.Generic; using System.Net.Mail; using SparkPost.Utilities; namespace SparkPost { public class Transmission { public Transmission() { Recipients = new List<Recipient>(); Metadata = new Dictionary<string, object>(); SubstitutionData = new Dictionary<string, object>(); Content = new Content(); Options = new Options(); } public Transmission(MailMessage message) : this() { MailMessageMapping.ToTransmission(message, this); } public string Id { get; set; } public string State { get; set; } public Options Options { get; set; } public IList<Recipient> Recipients { get; set; } public string ListId { get; set; } public string CampaignId { get; set; } public string Description { get; set; } public IDictionary<string, object> Metadata { get; set; } public IDictionary<string, object> SubstitutionData { get; set; } public string ReturnPath { get; set; } public Content Content { get; set; } public int TotalRecipients { get; set; } public int NumGenerated { get; set; } public int NumFailedGeneration { get; set; } public int NumInvalidRecipients { get; set; } public void LoadFrom(MailMessage message) { MailMessageMapping.ToTransmission(message, this); } } }
Fix bug argument matcher would cause index out of range
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ApiPorter.Patterns { internal sealed class ArgumentMatcher : Matcher { private readonly ArgumentVariable _variable; private readonly int _following; public ArgumentMatcher(ArgumentVariable variable, int following) { _variable = variable; _following = following; } public override Match Run(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.Kind() != SyntaxKind.Argument) return Match.NoMatch; var argument = (ArgumentSyntax) nodeOrToken.AsNode(); if (_variable.MinOccurrences == 1 && _variable.MaxOccurrences == 1) return Match.Success.WithSyntaxNodeOrToken(argument); var argumentList = argument.Parent as ArgumentListSyntax; if (argumentList == null) return Match.NoMatch; var currentIndex = argumentList.Arguments.IndexOf(argument); var availableCount = argumentList.Arguments.Count - currentIndex - _following; var captureCount = _variable.MaxOccurrences == null ? availableCount : Math.Min(availableCount, _variable.MaxOccurrences.Value); if (captureCount < _variable.MinOccurrences) return Match.NoMatch; var endIndex = currentIndex + captureCount - 1; var endArgument = argumentList.Arguments[endIndex]; return Match.Success.AddCapture(_variable, argument, endArgument); } } }
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ApiPorter.Patterns { internal sealed class ArgumentMatcher : Matcher { private readonly ArgumentVariable _variable; private readonly int _following; public ArgumentMatcher(ArgumentVariable variable, int following) { _variable = variable; _following = following; } public override Match Run(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.Kind() != SyntaxKind.Argument) return Match.NoMatch; var argument = (ArgumentSyntax) nodeOrToken.AsNode(); if (_variable.MinOccurrences == 1 && _variable.MaxOccurrences == 1) return Match.Success.WithSyntaxNodeOrToken(argument); var argumentList = argument.Parent as ArgumentListSyntax; if (argumentList == null) return Match.NoMatch; var currentIndex = argumentList.Arguments.IndexOf(argument); var availableCount = argumentList.Arguments.Count - currentIndex - _following; if (availableCount == 0) return Match.NoMatch; var captureCount = _variable.MaxOccurrences == null ? availableCount : Math.Min(availableCount, _variable.MaxOccurrences.Value); if (captureCount < _variable.MinOccurrences) return Match.NoMatch; var endIndex = currentIndex + captureCount - 1; var endArgument = argumentList.Arguments[endIndex]; return Match.Success.AddCapture(_variable, argument, endArgument); } } }
Use static properties instead of static constructor ==> if exception is thrown, detailed information is available, else TypeInitialiser exception is thrown
using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; namespace PPWCode.Vernacular.NHibernate.I.Test { public static class NhConfigurator { private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;"; private static readonly Configuration s_Configuration; private static readonly ISessionFactory s_SessionFactory; static NhConfigurator() { s_Configuration = new Configuration() .Configure() .DataBaseIntegration( db => { db.Dialect<SQLiteDialect>(); db.Driver<SQLite20Driver>(); db.ConnectionProvider<TestConnectionProvider>(); db.ConnectionString = ConnectionString; }) .SetProperty(Environment.CurrentSessionContextClass, "thread_static"); IDictionary<string, string> props = s_Configuration.Properties; if (props.ContainsKey(Environment.ConnectionStringName)) { props.Remove(Environment.ConnectionStringName); } s_SessionFactory = s_Configuration.BuildSessionFactory(); } public static Configuration Configuration { get { return s_Configuration; } } public static ISessionFactory SessionFactory { get { return s_SessionFactory; } } } }
using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; namespace PPWCode.Vernacular.NHibernate.I.Test { public static class NhConfigurator { private const string ConnectionString = "Data Source=:memory:;Version=3;New=True;"; private static readonly object s_Locker = new object(); private static volatile Configuration s_Configuration; private static volatile ISessionFactory s_SessionFactory; public static Configuration Configuration { get { if (s_Configuration == null) { lock (s_Locker) { if (s_Configuration == null) { s_Configuration = new Configuration() .Configure() .DataBaseIntegration( db => { db.Dialect<SQLiteDialect>(); db.Driver<SQLite20Driver>(); db.ConnectionProvider<TestConnectionProvider>(); db.ConnectionString = ConnectionString; }) .SetProperty(Environment.CurrentSessionContextClass, "thread_static"); IDictionary<string, string> props = s_Configuration.Properties; if (props.ContainsKey(Environment.ConnectionStringName)) { props.Remove(Environment.ConnectionStringName); } } } } return s_Configuration; } } public static ISessionFactory SessionFactory { get { if (s_SessionFactory == null) { lock (s_Locker) { if (s_SessionFactory == null) { s_SessionFactory = Configuration.BuildSessionFactory(); } } } return s_SessionFactory; } } } }
Fix for issue U4-5364 without trying to fix the localization of the error text.
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Umbraco.Core.Models; namespace Umbraco.Core.PropertyEditors { /// <summary> /// A validator that validates an email address /// </summary> [ValueValidator("Email")] internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator { public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) { var asString = value.ToString(); var emailVal = new EmailAddressAttribute(); if (emailVal.IsValid(asString) == false) { //TODO: localize these! yield return new ValidationResult("Email is invalid", new[] { "value" }); } } public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor) { return Validate(value, null, preValues, editor); } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Umbraco.Core.Models; namespace Umbraco.Core.PropertyEditors { /// <summary> /// A validator that validates an email address /// </summary> [ValueValidator("Email")] internal sealed class EmailValidator : ManifestValueValidator, IPropertyValidator { public override IEnumerable<ValidationResult> Validate(object value, string config, PreValueCollection preValues, PropertyEditor editor) { var asString = value.ToString(); var emailVal = new EmailAddressAttribute(); if (asString != string.Empty && emailVal.IsValid(asString) == false) { // TODO: localize these! yield return new ValidationResult("Email is invalid", new[] { "value" }); } } public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor) { return this.Validate(value, null, preValues, editor); } } }
Add trace with some quotes
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Web; using System.Web.Mvc; using MyCoolLib; namespace Mvc52Application.Controllers { public class HomeController : Controller { public ActionResult Index() { Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now); Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now); Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now); return View(); } public ActionResult About() { ViewBag.Message = $"SayHello: {Hello.SayHello("David")}, Foo Appsetting: {ConfigurationManager.AppSettings["foo"]}"; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Web; using System.Web.Mvc; using MyCoolLib; namespace Mvc52Application.Controllers { public class HomeController : Controller { public ActionResult Index() { Trace.TraceInformation("{0}: This is an informational trace message", DateTime.Now); Trace.TraceWarning("{0}: Here is trace warning", DateTime.Now); Trace.TraceError("{0}: Something is broken; tracing an error!", DateTime.Now); Trace.TraceInformation("123&quot;456\"789"); return View(); } public ActionResult About() { ViewBag.Message = $"SayHello: {Hello.SayHello("David")}, Foo Appsetting: {ConfigurationManager.AppSettings["foo"]}"; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
Remove usage of FX_DEPS_FILE as a fallback for locating `dotnet`, since that can find the wrong result when a newer patch is installed to the global dotnet location than the one installed into the folder containing Process.MainModule.
#if !NET452 namespace Fixie.Cli { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; class Dotnet { public static readonly string Path = FindDotnet(); static string FindDotnet() { var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; //If `dotnet` is the currently running process, return the full path to that executable. var mainModule = GetCurrentProcessMainModule(); var currentProcessIsDotNet = !string.IsNullOrEmpty(mainModule?.FileName) && System.IO.Path.GetFileName(mainModule.FileName) .Equals(fileName, StringComparison.OrdinalIgnoreCase); if (currentProcessIsDotNet) return mainModule.FileName; // Find "dotnet" by using the location of the shared framework. var fxDepsFile = AppContext.GetData("FX_DEPS_FILE") as string; if (string.IsNullOrEmpty(fxDepsFile)) throw new CommandLineException("While attempting to locate `dotnet`, FX_DEPS_FILE could not be found in the AppContext."); var dotnetDirectory = new FileInfo(fxDepsFile) // Microsoft.NETCore.App.deps.json .Directory? // (version) .Parent? // Microsoft.NETCore.App .Parent? // shared .Parent; // DOTNET_HOME if (dotnetDirectory == null) throw new CommandLineException("While attempting to locate `dotnet`. Could not traverse directories from FX_DEPS_FILE to DOTNET_HOME."); var dotnetPath = System.IO.Path.Combine(dotnetDirectory.FullName, fileName); if (!File.Exists(dotnetPath)) throw new CommandLineException($"Failed to locate `dotnet`. The path does not exist: {dotnetPath}"); return dotnetPath; } static ProcessModule GetCurrentProcessMainModule() { using (var currentProcess = Process.GetCurrentProcess()) return currentProcess.MainModule; } } } #endif
#if !NET452 namespace Fixie.Cli { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; class Dotnet { public static readonly string Path = FindDotnet(); static string FindDotnet() { var fileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; //If `dotnet` is the currently running process, return the full path to that executable. using (var currentProcess = Process.GetCurrentProcess()) { var mainModule = currentProcess.MainModule; var currentProcessIsDotNet = !string.IsNullOrEmpty(mainModule?.FileName) && System.IO.Path.GetFileName(mainModule.FileName) .Equals(fileName, StringComparison.OrdinalIgnoreCase); if (currentProcessIsDotNet) return mainModule.FileName; throw new CommandLineException($"Failed to locate `dotnet`."); } } } } #endif
Put markers in a dictionary for reuse.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPlacer : MonoBehaviour { public CountryLocation reader; public GameObject prefab; // Use this for initialization void Start () { Debug.Log ("LOOK WE ARE DOING THINGS"); reader.NotANormalWord (); Debug.Log ("Size of our data: " + reader.countries.Count); foreach (KeyValuePair<string, List<float>> entry in reader.countries) { int numItems = entry.Value.Count; if(numItems == 1) { Debug.Log(entry.Key + ", num items: " + entry.Value.Count); } Debug.Log (entry.Key + ", lat: " + entry.Value[1] + ", long: " + entry.Value[2]); GameObject marker = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.Euler(new Vector3(0, -entry.Value[2], entry.Value[1]))); marker.name = entry.Key; } Debug.Log ("THINGS HAVE BEEN DONE"); } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPlacer : MonoBehaviour { public CountryLocation reader; public GameObject prefab; private Dictionary<string, GameObject> markers; // Use this for initialization void Start () { Debug.Log ("LOOK WE ARE DOING THINGS"); reader.NotANormalWord (); Debug.Log ("Size of our data: " + reader.countries.Count); foreach (KeyValuePair<string, List<float>> entry in reader.countries) { int numItems = entry.Value.Count; if(numItems == 1) { Debug.Log(entry.Key + ", num items: " + entry.Value.Count); } Debug.Log (entry.Key + ", lat: " + entry.Value[1] + ", long: " + entry.Value[2]); GameObject marker = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.Euler(new Vector3(0, -entry.Value[2], entry.Value[1]))); marker.name = entry.Key; markers.Add(entry.Key, marker); } Debug.Log ("THINGS HAVE BEEN DONE"); } // Update is called once per frame void Update () { } }
Add bot class method stubs
using System; /// <summary> /// Summary description for Class1 /// </summary> public class Bot { public Bot() { // // TODO: Add constructor logic here // } }
using System; /// <summary> /// Summary description for Class1 /// </summary> public class Bot { private const int chromosomeSize = 10; private Chromosome<double> chromosome; public Bot() { chromosome = new Chromosome<double>(chromosomeSize); } public Bot(double[] values) { chromosome = new Chromosome<double>(values); } public bool betOrFold(int currentBet) { // True is bet, False is fold return true; } public int makeBet() { // returns the ammount to bet return 0; } private double getEnemyWinProb() { // Returns the probability of the enemy winning return 0.0; } private double getSelfWinProb() { // Returns the probability of us winning return 0.0; } }
Bring welcome page back to project
using Microsoft.AspNet.Builder; namespace KWebStartup { public class Startup { public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); } } }
using Microsoft.AspNet.Builder; namespace KWebStartup { public class Startup { public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseWelcomePage(); } } }
Remove PremiumRS edition value due to public preview schedule changes
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Sql.Database.Model { /// <summary> /// The database edition /// </summary> public enum DatabaseEdition { /// <summary> /// No database edition specified /// </summary> None = 0, /// <summary> /// A database premium edition /// </summary> Premium = 3, /// <summary> /// A database basic edition /// </summary> Basic = 4, /// <summary> /// A database standard edition /// </summary> Standard = 5, /// <summary> /// Azure SQL Data Warehouse database edition /// </summary> DataWarehouse = 6, /// <summary> /// Azure SQL Stretch database edition /// </summary> Stretch = 7, /// <summary> /// Free database edition. Reserved for special use cases/scenarios. /// </summary> Free = 8, /// <summary> /// A database PremiumRS edition /// </summary> PremiumRS = 9, } }
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Sql.Database.Model { /// <summary> /// The database edition /// </summary> public enum DatabaseEdition { /// <summary> /// No database edition specified /// </summary> None = 0, /// <summary> /// A database premium edition /// </summary> Premium = 3, /// <summary> /// A database basic edition /// </summary> Basic = 4, /// <summary> /// A database standard edition /// </summary> Standard = 5, /// <summary> /// Azure SQL Data Warehouse database edition /// </summary> DataWarehouse = 6, /// <summary> /// Azure SQL Stretch database edition /// </summary> Stretch = 7, /// <summary> /// Free database edition. Reserved for special use cases/scenarios. /// </summary> Free = 8, } }
Add LateUpdate check to scaler
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class TextMeshLimitSize : MonoBehaviour { #pragma warning disable 0649 //Serialized Fields [SerializeField] private Vector2 maxExtents; [SerializeField] private TextMesh textMesh; [SerializeField] private Renderer textRenderer; [SerializeField] private Vector3 defaultScale; #pragma warning restore 0649 private string lastString; void Awake() { if (textMesh == null) textMesh = GetComponent<TextMesh>(); if (textRenderer == null) textRenderer = textMesh.GetComponent<Renderer>(); if (maxExtents == Vector2.zero) maxExtents = textRenderer.bounds.extents; if (!Application.isPlaying) defaultScale = transform.localScale; } void Start() { lastString = ""; updateScale(); } void Update() { if (textMesh.text != lastString) updateScale(); } public void updateScale() { transform.localScale = defaultScale; if (textRenderer.bounds.extents.x > maxExtents.x || textRenderer.bounds.extents.y > maxExtents.y) transform.localScale *= Mathf.Min(maxExtents.x / textRenderer.bounds.extents.x, maxExtents.y / textRenderer.bounds.extents.y); lastString = textMesh.text; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class TextMeshLimitSize : MonoBehaviour { #pragma warning disable 0649 //Serialized Fields [SerializeField] private Vector2 maxExtents; [SerializeField] private TextMesh textMesh; [SerializeField] private Renderer textRenderer; [SerializeField] private Vector3 defaultScale; #pragma warning restore 0649 private string lastString; void Awake() { if (textMesh == null) textMesh = GetComponent<TextMesh>(); if (textRenderer == null) textRenderer = textMesh.GetComponent<Renderer>(); if (maxExtents == Vector2.zero) maxExtents = textRenderer.bounds.extents; if (!Application.isPlaying) defaultScale = transform.localScale; } void Start() { lastString = ""; updateScale(); } void Update() { if (textMesh.text != lastString) updateScale(); } void LateUpdate() { if (textMesh.text != lastString) updateScale(); } public void updateScale() { transform.localScale = defaultScale; if (textRenderer.bounds.extents.x > maxExtents.x || textRenderer.bounds.extents.y > maxExtents.y) transform.localScale *= Mathf.Min(maxExtents.x / textRenderer.bounds.extents.x, maxExtents.y / textRenderer.bounds.extents.y); lastString = textMesh.text; } }
Add comment to Auth Login action describing redirect
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { // GET: Session/Login public ActionResult Login() { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] // GET: Session/Logout public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
Allow products to have 0 price
using System; using System.Globalization; using System.Text.RegularExpressions; namespace RohlikAPI.Helpers { public class PriceParser { public double ParsePrice(string priceString) { var priceStringWithoutSpaces = priceString.Replace(" ", "").Replace("&nbsp;",""); var cleanPriceString = Regex.Match(priceStringWithoutSpaces, @"(\d*?,\d*)|(\d+)").Value; try { var price = double.Parse(cleanPriceString, new CultureInfo("cs-CZ")); if (price <= 0) { throw new Exception($"Failed to get product price from string '{priceString}'. Resulting price was {price}"); } return price; } catch (Exception ex) { throw new Exception($"Failed to parse product price from string '{priceString}'. Exception: {ex}"); } } } }
using System; using System.Globalization; using System.Text.RegularExpressions; namespace RohlikAPI.Helpers { public class PriceParser { public double ParsePrice(string priceString) { var priceStringWithoutSpaces = priceString.Replace(" ", "").Replace("&nbsp;",""); var cleanPriceString = Regex.Match(priceStringWithoutSpaces, @"(\d*?,\d*)|(\d+)").Value; try { var price = double.Parse(cleanPriceString, new CultureInfo("cs-CZ")); return price; } catch (Exception ex) { throw new Exception($"Failed to parse product price from string '{priceString}'. Exception: {ex}"); } } } }
Add comment as this may be removed in the future
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform.Linux.Native; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform.Linux.Native; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { internal LinuxGameHost(string gameName, bool bindIPC = false) : base(gameName, bindIPC) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != OpenTK.WindowState.Minimized) OnActivated(); else OnDeactivated(); }; // required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852) Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); } protected override Storage GetStorage(string baseName) => new LinuxStorage(baseName, this); public override Clipboard GetClipboard() => new LinuxClipboard(); } }
Fix the EF causing issues identity framework
using System; using Microsoft.AspNet.Identity.EntityFramework; using Project.Data.Configuration; using System.Data.Entity; using Project.Domain.Entities; namespace Project.Data { public class ProjectContext : IdentityDbContext<ApplicationUser> { public ProjectContext() : base("ProjectContext") { } public DbSet<Gadget> Gadgets { get; set; } public DbSet<Category> Categories { get; set; } public virtual void Commit() { base.SaveChanges(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new GadgetConfiguration()); modelBuilder.Configurations.Add(new CategoryConfiguration()); } public static ProjectContext Create() { return new ProjectContext(); } } }
using Microsoft.AspNet.Identity.EntityFramework; using Project.Data.Configuration; using System.Data.Entity; using Project.Domain.Entities; namespace Project.Data { public class ProjectContext : IdentityDbContext<ApplicationUser> { public ProjectContext() : base("ProjectContext") { } public DbSet<Gadget> Gadgets { get; set; } public DbSet<Category> Categories { get; set; } public virtual void Commit() { base.SaveChanges(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Configurations.Add(new GadgetConfiguration()); modelBuilder.Configurations.Add(new CategoryConfiguration()); } public static ProjectContext Create() { return new ProjectContext(); } } }
Add Response Bad Request on Detail Page
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex){ TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid id) { var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CarFuel.DataAccess; using CarFuel.Models; using CarFuel.Services; using Microsoft.AspNet.Identity; namespace CarFuel.Controllers { public class CarsController : Controller { private ICarDb db; private CarService carService; public CarsController() { db = new CarDb(); carService = new CarService(db); } [Authorize] public ActionResult Index() { var userId = new Guid(User.Identity.GetUserId()); IEnumerable<Car> cars = carService.GetCarsByMember(userId); return View(cars); } [Authorize] public ActionResult Create() { return View(); } [HttpPost] [Authorize] public ActionResult Create(Car item) { var userId = new Guid(User.Identity.GetUserId()); try { carService.AddCar(item, userId); } catch (OverQuotaException ex){ TempData["error"] = ex.Message; } return RedirectToAction("Index"); } public ActionResult Details(Guid id) { if( id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request"); } var userId = new Guid(User.Identity.GetUserId()); var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id); return View(c); } } }
Undo a change which causes compiler error in .NET 4.0 (but not .NET 4.5
using System.Collections.Generic; using System.Linq; namespace NuGet.Common { public static class AggregateRepositoryHelper { public static AggregateRepository CreateAggregateRepositoryFromSources(IPackageRepositoryFactory factory, IPackageSourceProvider sourceProvider, IEnumerable<string> sources) { AggregateRepository repository; if (sources != null && sources.Any()) { var repositories = sources.Select(sourceProvider.ResolveSource) .Select(factory.CreateRepository) .ToList(); repository = new AggregateRepository(repositories); } else { repository = sourceProvider.GetAggregate(factory, ignoreFailingRepositories: true); } return repository; } } }
using System.Collections.Generic; using System.Linq; namespace NuGet.Common { public static class AggregateRepositoryHelper { public static AggregateRepository CreateAggregateRepositoryFromSources(IPackageRepositoryFactory factory, IPackageSourceProvider sourceProvider, IEnumerable<string> sources) { AggregateRepository repository; if (sources != null && sources.Any()) { var repositories = sources.Select(s => sourceProvider.ResolveSource(s)) .Select(factory.CreateRepository) .ToList(); repository = new AggregateRepository(repositories); } else { repository = sourceProvider.GetAggregate(factory, ignoreFailingRepositories: true); } return repository; } } }
Replace tournament routes with generic {year}/{discipline}/{slug}
using System; using System.Threading.Tasks; using System.Web.Mvc; using CroquetAustralia.Website.App.Infrastructure; namespace CroquetAustralia.Website.App.tournaments { [RoutePrefix("tournaments")] public class TournamentsController : ApplicationController { private readonly WebApi _webApi; public TournamentsController(WebApi webApi) { _webApi = webApi; } [Route("2016/ac/mens-open")] public ViewResult Mens_AC_Open_2016() { return View("tournament"); } [Route("2016/ac/womens-open")] public ViewResult Womens_AC_Open_2016() { return View("tournament"); } [Route("2016/gc/open-doubles")] public ViewResult GC_Open_Doubles_2016() { return View("tournament"); } [Route("2016/gc/open-singles")] public ViewResult GC_Open_Singles_2016() { return View("tournament"); } [Route("deposited")] public async Task<ViewResult> Deposited(Guid id) { await _webApi.PostAsync("/tournament-entry/payment-received", new {entityId = id, paymentMethod = "EFT"}); return View("deposited"); } } }
using System; using System.Threading.Tasks; using System.Web.Mvc; using CroquetAustralia.Website.App.Infrastructure; namespace CroquetAustralia.Website.App.tournaments { [RoutePrefix("tournaments")] public class TournamentsController : ApplicationController { private readonly WebApi _webApi; public TournamentsController(WebApi webApi) { _webApi = webApi; } [Route("{year}/{discipline}/{slug}")] public ViewResult Tournament() { return View("tournament"); } [Route("deposited")] public async Task<ViewResult> Deposited(Guid id) { await _webApi.PostAsync("/tournament-entry/payment-received", new {entityId = id, paymentMethod = "EFT"}); return View("deposited"); } } }
Fix initializing the auth view'
using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { private const string Title = "Sign in"; [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { // Set window title titleContent = new GUIContent(Title, Styles.SmallLogo); Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); Initialize(EntryPoint.ApplicationManager); authView.InitializeView(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } }
using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { private const string Title = "Sign in"; [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { if (authView == null) { CreateViews(); } authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { // Set window title titleContent = new GUIContent(Title, Styles.SmallLogo); Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); Initialize(EntryPoint.ApplicationManager); authView.InitializeView(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } }
Switch back to tabbed winforms example being the default (maybe one day create a method to switch between the two)
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Forms; using CefSharp.Example; using CefSharp.WinForms.Example.Minimal; namespace CefSharp.WinForms.Example { class Program { [STAThread] static void Main() { CefExample.Init(); //var browser = new BrowserForm(); var browser = new SimpleBrowserForm(); Application.Run(browser); } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Forms; using CefSharp.Example; using CefSharp.WinForms.Example.Minimal; namespace CefSharp.WinForms.Example { class Program { [STAThread] static void Main() { CefExample.Init(); var browser = new BrowserForm(); //var browser = new SimpleBrowserForm(); Application.Run(browser); } } }
Write to debug in debug env
using System; using System.IO; namespace WebScriptHook.Framework { public class Logger { public static string FileName { get; internal set; } = "WebScriptHook.log"; public static LogType LogLevel { get; internal set; } = LogType.Info | LogType.Warning | LogType.Error; public static void Log(object message, LogType logType) { if ((LogLevel & logType) != LogType.None) { File.AppendAllText(FileName, "[" + DateTime.Now + "] [" + logType.ToString() + "]: " + message + Environment.NewLine); } } public static void Log(object message) { Log(message, LogType.Info); } } }
using System; using System.IO; using System.Diagnostics; namespace WebScriptHook.Framework { public class Logger { public static string FileName { get; internal set; } = "WebScriptHook.log"; public static LogType LogLevel { get; internal set; } = LogType.Info | LogType.Warning | LogType.Error; public static void Log(object message, LogType logType) { if ((LogLevel & logType) != LogType.None) { string formatedMessage = "[" + DateTime.Now + "] [" + logType.ToString() + "]: " + message; File.AppendAllText(FileName, formatedMessage + Environment.NewLine); #if DEBUG Debug.WriteLine(formatedMessage); #endif } } public static void Log(object message) { Log(message, LogType.Info); } } }
Fix for unsubscribe freezing ui thread
using System.Threading.Tasks; using CryptoExchange.Net.Interfaces; namespace Binance.Net.Objects { internal class BinanceStream { internal bool TryReconnect { get; set; } = true; public IWebsocket Socket { get; set; } public BinanceStreamSubscription StreamResult { get; set; } public async Task Close() { TryReconnect = false; await Socket.Close(); } } }
using System.Threading.Tasks; using CryptoExchange.Net.Interfaces; namespace Binance.Net.Objects { internal class BinanceStream { internal bool TryReconnect { get; set; } = true; public IWebsocket Socket { get; set; } public BinanceStreamSubscription StreamResult { get; set; } public async Task Close() { TryReconnect = false; await Socket.Close().ConfigureAwait(false); } } }
Print "Other:" for single choice questions
using System; using System.Text; using SurveyMonkey.Helpers; namespace SurveyMonkey.ProcessedAnswers { public class SingleChoiceAnswer : IProcessedResponse { public string Choice { get; set; } public string OtherText { get; set; } public string Printable { get { var sb = new StringBuilder(); if (Choice != null) { sb.Append(Choice); sb.Append(Environment.NewLine); } if (OtherText != null) { sb.Append(OtherText); } return ProcessedAnswerFormatHelper.Trim(sb); } } } }
using System; using System.Text; using SurveyMonkey.Helpers; namespace SurveyMonkey.ProcessedAnswers { public class SingleChoiceAnswer : IProcessedResponse { public string Choice { get; set; } public string OtherText { get; set; } public string Printable { get { var sb = new StringBuilder(); if (Choice != null) { sb.Append(Choice); sb.Append(Environment.NewLine); } if (OtherText != null) { sb.Append($"Other: {OtherText}"); } return ProcessedAnswerFormatHelper.Trim(sb); } } } }
Adjust the CoinWarz price / exchange rate so that BTC is 1 (100%)
using MultiMiner.Coin.Api; using Newtonsoft.Json.Linq; namespace MultiMiner.CoinWarz.Api { public static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken) { coinInformation.Symbol = jToken.Value<string>("CoinTag"); coinInformation.Name = jToken.Value<string>("CoinName"); coinInformation.Algorithm = jToken.Value<string>("Algorithm"); coinInformation.CurrentBlocks = jToken.Value<int>("BlockCount"); coinInformation.Difficulty = jToken.Value<double>("Difficulty"); coinInformation.Reward = jToken.Value<double>("BlockReward"); coinInformation.Price = jToken.Value<double>("ExchangeRate"); coinInformation.Exchange = jToken.Value<string>("Exchange"); coinInformation.Profitability = jToken.Value<double>("ProfitRatio"); coinInformation.AdjustedProfitability = jToken.Value<double>("ProfitRatio"); coinInformation.AverageProfitability = jToken.Value<double>("AvgProfitRatio"); } } }
using MultiMiner.Coin.Api; using Newtonsoft.Json.Linq; namespace MultiMiner.CoinWarz.Api { public static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken) { coinInformation.Symbol = jToken.Value<string>("CoinTag"); coinInformation.Name = jToken.Value<string>("CoinName"); coinInformation.Algorithm = jToken.Value<string>("Algorithm"); coinInformation.CurrentBlocks = jToken.Value<int>("BlockCount"); coinInformation.Difficulty = jToken.Value<double>("Difficulty"); coinInformation.Reward = jToken.Value<double>("BlockReward"); if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase)) coinInformation.Price = 1; else coinInformation.Price = jToken.Value<double>("ExchangeRate"); coinInformation.Exchange = jToken.Value<string>("Exchange"); coinInformation.Profitability = jToken.Value<double>("ProfitRatio"); coinInformation.AdjustedProfitability = jToken.Value<double>("ProfitRatio"); coinInformation.AverageProfitability = jToken.Value<double>("AvgProfitRatio"); } } }
Revert "Added log of exceptions"
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace EasySnippets { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args) { Console.WriteLine(@"An unexpected application exception occurred {0}", args.Exception); File.AppendAllLines(@".\es.log", new[] { $"{DateTime.UtcNow:yyyy-MM-dd HH\\:mm\\:ss.fff} {args.Exception.Message}", args.Exception.StackTrace }); MessageBox.Show("An unexpected exception has occurred. Shutting down the application. Please check the log file for more details."); // Prevent default unhandled exception processing args.Handled = true; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace EasySnippets { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args) { Console.WriteLine(@"An unexpected application exception occurred {0}", args.Exception); MessageBox.Show("An unexpected exception has occurred. Shutting down the application. Please check the log file for more details."); // Prevent default unhandled exception processing args.Handled = true; Environment.Exit(0); } } }
Fix bug in reset code
using UnityEngine; public class Trials { public static void Reset() { Debug.Log("Reset trials"); } public static void AddSuccess() { string trials = PlayerPrefs.GetString("Trials"); trials += "S"; while(trials.Length > 100) { trials = trials.Substring(1); } PlayerPrefs.SetString("Trials", trials); } public static void AddFailure() { string trials = PlayerPrefs.GetString("Trials"); trials += "F"; while(trials.Length > 100) { trials = trials.Substring(1); } PlayerPrefs.SetString("Trials", trials); } public static int GetSuccess() { int count = 0; string trials = PlayerPrefs.GetString("Trials"); foreach(char trial in trials) { if(trial == 'S') { count += 1; } } return count; } public static int GetFailure() { int count = 0; string trials = PlayerPrefs.GetString("Trials"); foreach(char trial in trials) { if(trial == 'F') { count += 1; } } return count; } }
using UnityEngine; public class Trials { public static void Reset() { PlayerPrefs.SetString("Trials", ""); } public static void AddSuccess() { string trials = PlayerPrefs.GetString("Trials"); trials += "S"; while(trials.Length > 100) { trials = trials.Substring(1); } PlayerPrefs.SetString("Trials", trials); } public static void AddFailure() { string trials = PlayerPrefs.GetString("Trials"); trials += "F"; while(trials.Length > 100) { trials = trials.Substring(1); } PlayerPrefs.SetString("Trials", trials); } public static int GetSuccess() { int count = 0; string trials = PlayerPrefs.GetString("Trials"); foreach(char trial in trials) { if(trial == 'S') { count += 1; } } return count; } public static int GetFailure() { int count = 0; string trials = PlayerPrefs.GetString("Trials"); foreach(char trial in trials) { if(trial == 'F') { count += 1; } } return count; } }
Convert code to use extension method
using System; using System.Diagnostics; using System.Linq; using System.DoubleNumerics; using JetBrains.Annotations; using SolidworksAddinFramework.OpenGl; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework.Geometry { public class BSpline3D : BSpline<Vector4> { public BSpline3D([NotNull] Vector4[] controlPoints, [NotNull] double[] knotVectorU, int order, bool isClosed, bool isRational) : base(controlPoints, knotVectorU, order, isClosed, isRational) { if(!IsRational) { Debug.Assert(controlPoints.All(c => Math.Abs(c.W - 1.0) < 1e-9)); } } public ICurve ToCurve() { var propsDouble = PropsDouble; var knots = KnotVectorU; var ctrlPtCoords = ControlPoints.SelectMany(p => Vector3Extensions.ToDoubles((Vector4) p)).ToArray(); return (ICurve) SwAddinBase.Active.Modeler.CreateBsplineCurve( propsDouble, knots, ctrlPtCoords); } public double[] ToDoubles(Vector4 t) { return t.ToDoubles(); } public override int Dimension => IsRational ? 4 : 3; } }
using System; using System.Diagnostics; using System.Linq; using System.DoubleNumerics; using JetBrains.Annotations; using SolidworksAddinFramework.OpenGl; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework.Geometry { public class BSpline3D : BSpline<Vector4> { public BSpline3D([NotNull] Vector4[] controlPoints, [NotNull] double[] knotVectorU, int order, bool isClosed, bool isRational) : base(controlPoints, knotVectorU, order, isClosed, isRational) { if(!IsRational) { Debug.Assert(controlPoints.All(c => Math.Abs(c.W - 1.0) < 1e-9)); } } public ICurve ToCurve() { var propsDouble = PropsDouble; var knots = KnotVectorU; var ctrlPtCoords = ControlPoints.SelectMany(p => p.ToDoubles()).ToArray(); return (ICurve) SwAddinBase.Active.Modeler.CreateBsplineCurve( propsDouble, knots, ctrlPtCoords); } public double[] ToDoubles(Vector4 t) { return t.ToDoubles(); } public override int Dimension => IsRational ? 4 : 3; } }
Set version number of unit tests to be different
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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2cc38a28-87ec-4b55-8130-ce705cdb49e8")] // 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.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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2cc38a28-87ec-4b55-8130-ce705cdb49e8")] // 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.2.0.0")]
Revert AssemblyVersion to 2.0.0 because there are no breaking changes in this version
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")] [assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Fix creating a font with a specific style
using System; using Eto.Drawing; using System.Collections.Generic; using MonoTouch.UIKit; using System.Linq; namespace Eto.Platform.iOS.Drawing { public class FontFamilyHandler : WidgetHandler<object, FontFamily>, IFontFamily { public FontFamilyHandler () { } public FontFamilyHandler (string familyName) { Create (familyName); } public void Create (string familyName) { this.Name = familyName; } public string Name { get; private set; } public IEnumerable<FontTypeface> Typefaces { get { return UIFont.FontNamesForFamilyName(this.Name).Select(r => new FontTypeface(Widget, new FontTypefaceHandler(r))); } } public UIFont CreateFont (float size, FontStyle style) { // scan! var handler = Typefaces.First().Handler as FontTypefaceHandler; return handler.CreateFont(size); } public FontTypeface GetFace(UIFont font) { return Typefaces.FirstOrDefault (r => string.Equals (((FontTypefaceHandler)r.Handler).FontName, font.Name, StringComparison.InvariantCultureIgnoreCase)); } } }
using System; using Eto.Drawing; using System.Collections.Generic; using MonoTouch.UIKit; using System.Linq; namespace Eto.Platform.iOS.Drawing { public class FontFamilyHandler : WidgetHandler<object, FontFamily>, IFontFamily { public FontFamilyHandler () { } public FontFamilyHandler (string familyName) { Create (familyName); } public void Create (string familyName) { this.Name = familyName; } public string Name { get; private set; } public IEnumerable<FontTypeface> Typefaces { get { return UIFont.FontNamesForFamilyName(this.Name).Select(r => new FontTypeface(Widget, new FontTypefaceHandler(r))); } } public UIFont CreateFont (float size, FontStyle style) { var matched = Typefaces.FirstOrDefault (r => r.FontStyle == style); if (matched == null) matched = Typefaces.First (); var handler = matched.Handler as FontTypefaceHandler; return handler.CreateFont(size); } public FontTypeface GetFace(UIFont font) { return Typefaces.FirstOrDefault (r => string.Equals (((FontTypefaceHandler)r.Handler).FontName, font.Name, StringComparison.InvariantCultureIgnoreCase)); } } }
Change to using TypeCatalog instead of AssemblyCatalog
using System.ComponentModel.Composition.Hosting; namespace IocPerformance.Adapters { public sealed class MefContainerAdapter : IContainerAdapter { private CompositionContainer container; public void Prepare() { var catalog = new AssemblyCatalog(typeof(Program).Assembly); this.container = new CompositionContainer(catalog); } public T Resolve<T>() where T : class { return this.container.GetExportedValue<T>(); } public void Dispose() { this.container = null; } } }
using System.ComponentModel.Composition.Hosting; namespace IocPerformance.Adapters { public sealed class MefContainerAdapter : IContainerAdapter { private CompositionContainer container; public void Prepare() { var catalog = new TypeCatalog(typeof(Implementation1), typeof(Implementation2), typeof(Combined)); this.container = new CompositionContainer(catalog); } public T Resolve<T>() where T : class { return this.container.GetExportedValue<T>(); } public void Dispose() { // Allow the container and everything it references to be disposed. this.container = null; } } }
Make sure debugger is attached for DebugBreak, otherwise user is prompted to attach a debugger
using System; using System.Collections.Generic; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> getObject) { Console.WriteLine(getObject(obj)); return obj; } public static T DebugPrint<T>(this T obj, Func<T, IEnumerable<object>> getEnumerable) { getEnumerable(obj).Each(Console.WriteLine); return obj; } public static T DebugBreak<T>(this T obj) { System.Diagnostics.Debugger.Break(); return obj; } public static T PlaySound<T>(this T obj, int pause = 0) { System.Media.SystemSounds.Exclamation.Play(); return obj.Pause(pause); } public static T Pause<T>(this T block, int miliseconds) { if (miliseconds > 0) Thread.Sleep(miliseconds); return block; } } }
using System; using System.Collections.Generic; using System.Threading; namespace Bumblebee.Extensions { public static class Debugging { public static T DebugPrint<T>(this T obj) { Console.WriteLine(obj.ToString()); return obj; } public static T DebugPrint<T>(this T obj, string message) { Console.WriteLine(message); return obj; } public static T DebugPrint<T>(this T obj, Func<T, object> getObject) { Console.WriteLine(getObject(obj)); return obj; } public static T DebugPrint<T>(this T obj, Func<T, IEnumerable<object>> getEnumerable) { getEnumerable(obj).Each(Console.WriteLine); return obj; } public static T DebugBreak<T>(this T obj) { if(System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); return obj; } public static T PlaySound<T>(this T obj, int pause = 0) { System.Media.SystemSounds.Exclamation.Play(); return obj.Pause(pause); } public static T Pause<T>(this T block, int miliseconds) { if (miliseconds > 0) Thread.Sleep(miliseconds); return block; } } }