Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Drop "-message" from all message names
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Glimpse.Extensions; namespace Glimpse.Internal { public class DefaultMessageTypeProcessor : IMessageTypeProcessor { private readonly static Type[] _exclusions = { typeof(object) }; public virtual IEnumerable<string> Derive(object payload) { var typeInfo = payload.GetType().GetTypeInfo(); return typeInfo.BaseTypes(true) .Concat(typeInfo.ImplementedInterfaces) .Except(_exclusions) .Select(t => t.KebabCase()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Glimpse.Extensions; namespace Glimpse.Internal { public class DefaultMessageTypeProcessor : IMessageTypeProcessor { private readonly static Type[] _exclusions = { typeof(object) }; public virtual IEnumerable<string> Derive(object payload) { var typeInfo = payload.GetType().GetTypeInfo(); return typeInfo.BaseTypes(true) .Concat(typeInfo.ImplementedInterfaces) .Except(_exclusions) .Select(t => { var result = t.KebabCase(); if (result.EndsWith("-message")) return result.Substring(0, result.Length - 8); return result; }); } } }
Use the viewBag Title rather than the hard coded one.
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Please wait"; ViewBag.HideSigninLink = "true"; Layout = "~/Views/Shared/_Layout-NoBanner.cshtml"; } <h1 class="heading-xlarge">You've logged in</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Please wait"; ViewBag.HideSigninLink = "true"; Layout = "~/Views/Shared/_Layout-NoBanner.cshtml"; } <h1 class="heading-xlarge">@ViewBag.Title</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
Fix the sample app following previous changes.
// Copyright (c) Solal Pirelli 2014 // See License.txt file for more details using ThinMvvm.WindowsPhone.SampleApp.Resources; using ThinMvvm.WindowsPhone.SampleApp.ViewModels; namespace ThinMvvm.WindowsPhone.SampleApp { public sealed class App : AppBase { protected override string Language { get { return AppResources.ResourceLanguage; } } protected override string FlowDirection { get { return AppResources.ResourceFlowDirection; } } public App() { Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>(); Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>(); Container.Bind<ISettings, Settings>(); } protected override void Start( AppDependencies dependencies, AppArguments arguments ) { // simple app, no additional dependencies or arguments dependencies.NavigationService.Bind<MainViewModel>( "/Views/MainView.xaml" ); dependencies.NavigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" ); dependencies.NavigationService.NavigateTo<MainViewModel, int>( 42 ); } } }
// Copyright (c) Solal Pirelli 2014 // See License.txt file for more details using ThinMvvm.WindowsPhone.SampleApp.Resources; using ThinMvvm.WindowsPhone.SampleApp.ViewModels; namespace ThinMvvm.WindowsPhone.SampleApp { public sealed class App : AppBase { private readonly IWindowsPhoneNavigationService _navigationService; protected override string Language { get { return AppResources.ResourceLanguage; } } protected override string FlowDirection { get { return AppResources.ResourceFlowDirection; } } public App() { _navigationService = Container.Bind<IWindowsPhoneNavigationService, WindowsPhoneNavigationService>(); Container.Bind<ISettingsStorage, WindowsPhoneSettingsStorage>(); Container.Bind<ISettings, Settings>(); } protected override void Start( AppArguments arguments ) { // simple app, no additional dependencies or arguments _navigationService.Bind<MainViewModel>( "/Views/MainView.xaml" ); _navigationService.Bind<AboutViewModel>( "/Views/AboutView.xaml" ); _navigationService.NavigateTo<MainViewModel, int>( 42 ); } } }
Add extension method for IRandom to get an unsigned 64-bit integer.
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } } }
namespace Bakery.Security { using System; public static class RandomExtensions { public static Byte[] GetBytes(this IRandom random, Int32 count) { if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count)); var buffer = new Byte[count]; for (var i = 0; i < count; i++) buffer[i] = random.GetByte(); return buffer; } public static Int64 GetInt64(this IRandom random) { return BitConverter.ToInt64(random.GetBytes(8), 0); } public static UInt64 GetUInt64(this IRandom random) { return BitConverter.ToUInt64(random.GetBytes(8), 0); } } }
Revert changes to the test.
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 100, 100)) { imageA.AddNoise(NoiseType.Random); using (var imageB = new MagickImage(MagickColors.Black, 100, 100)) { imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Xunit; namespace Magick.NET.Tests { public partial class MagickImageTests { public class TheAddNoiseMethod { [Fact] public void ShouldCreateDifferentImagesEachRun() { using (var imageA = new MagickImage(MagickColors.Black, 10, 10)) { using (var imageB = new MagickImage(MagickColors.Black, 10, 10)) { imageA.AddNoise(NoiseType.Random); imageB.AddNoise(NoiseType.Random); Assert.NotEqual(0.0, imageA.Compare(imageB, ErrorMetric.RootMeanSquared)); } } } } } }
Add valid cron expression to test
using IntegrationEngine.Api.Controllers; using IntegrationEngine.Core.Storage; using IntegrationEngine.Model; using IntegrationEngine.Scheduler; using Moq; using NUnit.Framework; namespace IntegrationEngine.Tests.Api.Controllers { public class CronTriggerControllerTest { [Test] public void ShouldScheduleJobWhenCronTriggerIsCreated() { var subject = new CronTriggerController(); var cronExpression = "0 6 * * 1-5"; var jobType = "MyProject.MyIntegrationJob"; var expected = new CronTrigger() { JobType = jobType, CronExpressionString = cronExpression }; var engineScheduler = new Mock<IEngineScheduler>(); engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected)); subject.EngineScheduler = engineScheduler.Object; var esRepository = new Mock<ESRepository<CronTrigger>>(); esRepository.Setup(x => x.Insert(expected)).Returns(expected); subject.Repository = esRepository.Object; subject.PostCronTrigger(expected); engineScheduler.Verify(x => x .ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType && y.CronExpressionString == cronExpression)), Times.Once); } } }
using IntegrationEngine.Api.Controllers; using IntegrationEngine.Core.Storage; using IntegrationEngine.Model; using IntegrationEngine.Scheduler; using Moq; using NUnit.Framework; namespace IntegrationEngine.Tests.Api.Controllers { public class CronTriggerControllerTest { [Test] public void ShouldScheduleJobWhenCronTriggerIsCreatedWithValidCronExpression() { var subject = new CronTriggerController(); var cronExpression = "0 6 * * 1-5 ?"; var jobType = "MyProject.MyIntegrationJob"; var expected = new CronTrigger() { JobType = jobType, CronExpressionString = cronExpression }; var engineScheduler = new Mock<IEngineScheduler>(); engineScheduler.Setup(x => x.ScheduleJobWithCronTrigger(expected)); subject.EngineScheduler = engineScheduler.Object; var esRepository = new Mock<ESRepository<CronTrigger>>(); esRepository.Setup(x => x.Insert(expected)).Returns(expected); subject.Repository = esRepository.Object; subject.PostCronTrigger(expected); engineScheduler.Verify(x => x .ScheduleJobWithCronTrigger(It.Is<CronTrigger>(y => y.JobType == jobType && y.CronExpressionString == cronExpression)), Times.Once); } } }
Fix incorrect title on edit page
@using Orchard.Mvc.Html; @{ Layout.Title = T("New Blog"); } <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
@using Orchard.Mvc.Html; <div class="edit-item"> <div class="edit-item-primary"> @if (Model.Content != null) { <div class="edit-item-content"> @Display(Model.Content) </div> } </div> <div class="edit-item-secondary group"> @if (Model.Actions != null) { <div class="edit-item-actions"> @Display(Model.Actions) </div> } @if (Model.Sidebar != null) { <div class="edit-item-sidebar group"> @Display(Model.Sidebar) </div> } </div> </div>
Format dates properly for the api
using System; using System.Reflection; using SurveyMonkey.RequestSettings; namespace SurveyMonkey.Helpers { internal class RequestSettingsHelper { internal static RequestData GetPopulatedProperties(object obj) { var output = new RequestData(); foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (property.GetValue(obj, null) != null) { Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(property.PropertyType) : property.PropertyType; if (underlyingType.IsEnum) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString())); } else if (underlyingType == typeof(DateTime)) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s")); } else { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null)); } } } return output; } } }
using System; using System.Reflection; using SurveyMonkey.RequestSettings; namespace SurveyMonkey.Helpers { internal class RequestSettingsHelper { internal static RequestData GetPopulatedProperties(object obj) { var output = new RequestData(); foreach (PropertyInfo property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (property.GetValue(obj, null) != null) { Type underlyingType = property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(property.PropertyType) : property.PropertyType; if (underlyingType.IsEnum) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), PropertyCasingHelper.CamelToSnake(property.GetValue(obj, null).ToString())); } else if (underlyingType == typeof(DateTime)) { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), ((DateTime)property.GetValue(obj, null)).ToString("s") + "+00:00"); } else { output.Add(PropertyCasingHelper.CamelToSnake(property.Name), property.GetValue(obj, null)); } } } return output; } } }
Add helpers for finding attributes
using System; using System.Collections.Generic; namespace Konsola.Metadata { public class ObjectMetadata { public ObjectMetadata( Type type, IEnumerable<PropertyMetadata> properties, IEnumerable<AttributeMetadata> attributes) { Type = type; Properties = properties; Attributes = attributes; } public Type Type { get; private set; } public virtual IEnumerable<PropertyMetadata> Properties { get; private set; } public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; } } }
using System; using System.Linq; using System.Collections.Generic; namespace Konsola.Metadata { public class ObjectMetadata { public ObjectMetadata( Type type, IEnumerable<PropertyMetadata> properties, IEnumerable<AttributeMetadata> attributes) { Type = type; Properties = properties; Attributes = attributes; } public Type Type { get; private set; } public virtual IEnumerable<PropertyMetadata> Properties { get; private set; } public virtual IEnumerable<AttributeMetadata> Attributes { get; private set; } public IEnumerable<T> AttributesOfType<T>() { return Attributes .Select(a => a.Attribute) .OfType<T>(); } public T AttributeOfType<T>() { return AttributesOfType<T>() .FirstOrDefault(); } } }
Use bigquerydatatransfer instead of bigquery_data_transfer in region tags
/* * Copyright (c) 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ // [START bigquery_data_transfer_quickstart] using System; using Google.Api.Gax; using Google.Cloud.BigQuery.DataTransfer.V1; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Instantiates a client DataTransferServiceClient client = DataTransferServiceClient.Create(); // Your Google Cloud Platform project ID string projectId = "YOUR-PROJECT-ID"; ProjectName project = new ProjectName(projectId); var sources = client.ListDataSources(ParentNameOneof.From(project)); Console.WriteLine("Supported Data Sources:"); foreach (DataSource source in sources) { Console.WriteLine( $"{source.DataSourceId}: " + $"{source.DisplayName} ({source.Description})"); } } } } // [END bigquery_data_transfer_quickstart]
/* * Copyright (c) 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ // [START bigquerydatatransfer_quickstart] using System; using Google.Api.Gax; using Google.Cloud.BigQuery.DataTransfer.V1; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Instantiates a client DataTransferServiceClient client = DataTransferServiceClient.Create(); // Your Google Cloud Platform project ID string projectId = "YOUR-PROJECT-ID"; ProjectName project = new ProjectName(projectId); var sources = client.ListDataSources(ParentNameOneof.From(project)); Console.WriteLine("Supported Data Sources:"); foreach (DataSource source in sources) { Console.WriteLine( $"{source.DataSourceId}: " + $"{source.DisplayName} ({source.Description})"); } } } } // [END bigquerydatatransfer_quickstart]
Raise exceptions on non-404 error codes
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using LiberisLabs.CompaniesHouse.Response.CompanyProfile; using LiberisLabs.CompaniesHouse.UriBuilders; namespace LiberisLabs.CompaniesHouse { public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient { private readonly IHttpClientFactory _httpClientFactory; private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder; public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder) { _httpClientFactory = httpClientFactory; _companyProfileUriBuilder = companyProfileUriBuilder; } public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken)) { using (var httpClient = _httpClientFactory.CreateHttpClient()) { var requestUri = _companyProfileUriBuilder.Build(companyNumber); var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false); CompanyProfile result = response.IsSuccessStatusCode ? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false) : null; return new CompaniesHouseClientResponse<CompanyProfile>(result); } } } }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using LiberisLabs.CompaniesHouse.Response.CompanyProfile; using LiberisLabs.CompaniesHouse.UriBuilders; namespace LiberisLabs.CompaniesHouse { public class CompaniesHouseCompanyProfileClient : ICompaniesHouseCompanyProfileClient { private readonly IHttpClientFactory _httpClientFactory; private readonly ICompanyProfileUriBuilder _companyProfileUriBuilder; public CompaniesHouseCompanyProfileClient(IHttpClientFactory httpClientFactory, ICompanyProfileUriBuilder companyProfileUriBuilder) { _httpClientFactory = httpClientFactory; _companyProfileUriBuilder = companyProfileUriBuilder; } public async Task<CompaniesHouseClientResponse<CompanyProfile>> GetCompanyProfileAsync(string companyNumber, CancellationToken cancellationToken = default(CancellationToken)) { using (var httpClient = _httpClientFactory.CreateHttpClient()) { var requestUri = _companyProfileUriBuilder.Build(companyNumber); var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false); // Return a null profile on 404s, but raise exception for all other error codes if (response.StatusCode != System.Net.HttpStatusCode.NotFound) response.EnsureSuccessStatusCode(); CompanyProfile result = response.IsSuccessStatusCode ? await response.Content.ReadAsAsync<CompanyProfile>(cancellationToken).ConfigureAwait(false) : null; return new CompaniesHouseClientResponse<CompanyProfile>(result); } } } }
Fix tabs/spaces in test site startup
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using BundlerMiddleware; [assembly: OwinStartup(typeof(BundlerTestSite.Startup))] namespace BundlerTestSite { public class Startup { public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable(); public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable(); public void Configuration(IAppBuilder app) { app.UseBundlerMiddlewareForIIS(); app.UseBundlerMarkdown(MarkdownRoutes); app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate); } } }
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using BundlerMiddleware; [assembly: OwinStartup(typeof(BundlerTestSite.Startup))] namespace BundlerTestSite { public class Startup { public static BundlerRouteTable MarkdownRoutes = new BundlerRouteTable(); public static BundlerRouteTable MarkdownRoutesWithTemplate = new BundlerRouteTable(); public void Configuration(IAppBuilder app) { app.UseBundlerMiddlewareForIIS(); app.UseBundlerMarkdown(MarkdownRoutes); app.UseBundlerMarkdownWithTempalte("~/markdown/markdowntemplate.html", MarkdownRoutesWithTemplate); } } }
Test commit of new line endings
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using CorrugatedIron.Tests.Live.LiveRiakConnectionTests; using NUnit.Framework; namespace CorrugatedIron.Tests.Live { [TestFixture] public class RiakDtTests : LiveRiakConnectionTestBase { private const string Bucket = "riak_dt_bucket"; [TearDown] public void TearDown() { Client.DeleteBucket(Bucket); } } }
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using CorrugatedIron.Tests.Live.LiveRiakConnectionTests; using NUnit.Framework; namespace CorrugatedIron.Tests.Live { [TestFixture] public class RiakDtTests : LiveRiakConnectionTestBase { private const string Bucket = "riak_dt_bucket"; /// <summary> /// The tearing of the down, it is done here. /// </summary> [TearDown] public void TearDown() { Client.DeleteBucket(Bucket); } } }
Check that Data dictionary accepts string keys.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunClientBase { protected internal const string SentKey = "AlreadySentByRaygun"; protected bool CanSend(Exception exception) { return exception == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]); } protected void FlagAsSent(Exception exception) { if (exception != null) { exception.Data[SentKey] = true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mindscape.Raygun4Net { public class RaygunClientBase { protected internal const string SentKey = "AlreadySentByRaygun"; protected bool CanSend(Exception exception) { return exception == null || exception.Data == null || !exception.Data.Contains(SentKey) || false.Equals(exception.Data[SentKey]); } protected void FlagAsSent(Exception exception) { if (exception != null && exception.Data != null) { try { Type[] genericTypes = exception.Data.GetType().GetGenericArguments(); if (genericTypes.Length > 0 && genericTypes[0].IsAssignableFrom(typeof(string))) { exception.Data[SentKey] = true; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(String.Format("Failed to flag exception as sent: {0}", ex.Message)); } } } } }
Fix beatmap lookups failing for beatmaps with no local path
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path)}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetBeatmapRequest : APIRequest<APIBeatmap> { private readonly BeatmapInfo beatmap; public GetBeatmapRequest(BeatmapInfo beatmap) { this.beatmap = beatmap; } protected override string Target => $@"beatmaps/lookup?id={beatmap.OnlineBeatmapID}&checksum={beatmap.MD5Hash}&filename={System.Uri.EscapeUriString(beatmap.Path ?? string.Empty)}"; } }
Add temp dummy impl of IContext.WithDeleted and WithFunction
using System.Linq; using NakedFunctions; namespace AW { public static class Helpers { /// <summary> /// Returns a random instance from the set of all instance of type T /// </summary> public static T Random<T>(IContext context) where T : class { //The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip //which in turn is needed because LINQ to Entities doesn't support .ElementAt(x) var instances = context.Instances<T>().OrderBy(n => ""); return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault(); } } }
using System; using System.Linq; using NakedFunctions; namespace AW { public static class Helpers { /// <summary> /// Returns a random instance from the set of all instance of type T /// </summary> public static T Random<T>(IContext context) where T : class { //The OrderBy(...) doesn't change the ordering, but is a necessary precursor to using .Skip //which in turn is needed because LINQ to Entities doesn't support .ElementAt(x) var instances = context.Instances<T>().OrderBy(n => ""); return instances.Skip(context.RandomSeed().ValueInRange(instances.Count())).FirstOrDefault(); } //TODO: Temporary DUMMY extension method, pending native new method on IContext. public static IContext WithFunction(this IContext context, Func<IContext, IContext> func) => context.WithInformUser($"Registered function {func.ToString()} NOT called."); //TODO: Temporary DUMMY extension method, pending native new method on IContext. public static IContext WithDeleted(this IContext context, object toDelete) => context.WithInformUser($"object {toDelete} scheduled for deletion."); } }
Make sure ProcessAreaLocationSetting is set on first start-up
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } }
using System.IO; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.GUI.Properties; namespace Arkivverket.Arkade.GUI.Util { public static class ArkadeProcessingAreaLocationSetting { public static string Get() { Settings.Default.Reload(); return Settings.Default.ArkadeProcessingAreaLocation; } public static void Set(string locationSetting) { Settings.Default.ArkadeProcessingAreaLocation = locationSetting; Settings.Default.Save(); } public static bool IsValid() { try { string definedLocation = Get(); return DirectoryIsWritable(definedLocation); } catch { return false; // Invalid path string in settings } } public static bool IsApplied() { string appliedLocation = ArkadeProcessingArea.Location?.FullName ?? string.Empty; string definedLocation = Get(); return appliedLocation.Equals(definedLocation); } private static bool DirectoryIsWritable(string directory) { if (string.IsNullOrWhiteSpace(directory)) return false; string tmpFile = Path.Combine(directory, Path.GetRandomFileName()); try { using (File.Create(tmpFile, 1, FileOptions.DeleteOnClose)) { // Attempt to write temporary file to the directory } return true; } catch { return false; } } } }
Implement random walk for 2D
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RandomWalkConsole { class Program { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace RandomWalkConsole { class Program { static void Main(string[] args) { var unfinished = Enumerable.Range(0, 1000) .Select(_ => Walk2()) .Aggregate(0, (u, t) => u + (t.HasValue ? 0 : 1)); Console.WriteLine(unfinished); } static readonly Random random = new Random(); static readonly Int32Vector3[] Directions2 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis }; static int? Walk2() { var current = Int32Vector3.Zero; for (var i = 1; i <= 1000000; i++) { current += Directions2[random.Next(0, Directions2.Length)]; if (current == Int32Vector3.Zero) return i; } Console.WriteLine(current); return null; } } }
Switch to lower case URLs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Dashboard { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Dashboard { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.LowercaseUrls = true; routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
Make public a method which was accidentally committed as private.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.Drawing { /// <summary> /// Various useful utility methods that don't obviously go elsewhere. /// </summary> public static class Utilities { /// <summary> /// Draw the provided model in the world, given the provided matrices. /// </summary> /// <param name="model">The model to draw.</param> /// <param name="world">The world matrix that the model should be drawn in.</param> /// <param name="view">The view matrix that the model should be drawn in.</param> /// <param name="projection">The projection matrix that the model should be drawn in.</param> private static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGameUtils.Drawing { /// <summary> /// Various useful utility methods that don't obviously go elsewhere. /// </summary> public static class Utilities { /// <summary> /// Draw the provided model in the world, given the provided matrices. /// </summary> /// <param name="model">The model to draw.</param> /// <param name="world">The world matrix that the model should be drawn in.</param> /// <param name="view">The view matrix that the model should be drawn in.</param> /// <param name="projection">The projection matrix that the model should be drawn in.</param> public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection) { foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.World = world; effect.View = view; effect.Projection = projection; } mesh.Draw(); } } } }
Remove unnecessary reference to IScheduledEvent
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; using System.Linq; namespace AppBrix.Events.Schedule.Impl { internal abstract class PriorityQueueItem { #region Construction public PriorityQueueItem(object scheduledEvent) { this.ScheduledEvent = scheduledEvent; } #endregion #region Properties public object ScheduledEvent { get; } public DateTime Occurrence { get; protected set; } #endregion #region Public and overriden methods public abstract void Execute(); public abstract void MoveToNextOccurrence(DateTime now); #endregion } internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent { #region Construction public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent) : base(scheduledEvent) { this.app = app; this.scheduledEvent = scheduledEvent; } #endregion #region Public and overriden methods public override void Execute() { try { this.app.GetEventHub().Raise(this.scheduledEvent.Event); } catch (Exception) { } } public override void MoveToNextOccurrence(DateTime now) { this.Occurrence = ((IScheduledEvent<T>)this.ScheduledEvent).GetNextOccurrence(now); } #endregion #region Private fields and constants private readonly IApp app; private readonly IScheduledEvent<T> scheduledEvent; #endregion } }
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; using System.Linq; namespace AppBrix.Events.Schedule.Impl { internal abstract class PriorityQueueItem { #region Properties public abstract object ScheduledEvent { get; } public DateTime Occurrence { get; protected set; } #endregion #region Public and overriden methods public abstract void Execute(); public abstract void MoveToNextOccurrence(DateTime now); #endregion } internal sealed class PriorityQueueItem<T> : PriorityQueueItem where T : IEvent { #region Construction public PriorityQueueItem(IApp app, IScheduledEvent<T> scheduledEvent) { this.app = app; this.scheduledEvent = scheduledEvent; } #endregion #region Properties public override object ScheduledEvent => this.scheduledEvent; #endregion #region Public and overriden methods public override void Execute() { try { this.app.GetEventHub().Raise(this.scheduledEvent.Event); } catch (Exception) { } } public override void MoveToNextOccurrence(DateTime now) { this.Occurrence = this.scheduledEvent.GetNextOccurrence(now); } #endregion #region Private fields and constants private readonly IApp app; private readonly IScheduledEvent<T> scheduledEvent; #endregion } }
Kill auto user insertion in non-debug
using System.Web.Mvc; namespace RightpointLabs.Pourcast.Web.Controllers { using RightpointLabs.Pourcast.Application.Orchestrators.Abstract; public class HomeController : Controller { private readonly ITapOrchestrator _tapOrchestrator; private readonly IIdentityOrchestrator _identityOrchestrator; public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator) { _tapOrchestrator = tapOrchestrator; _identityOrchestrator = identityOrchestrator; } // // GET: /Home/ public ActionResult Index() { // Replace this with a Mock so it doesn't blow up the app //_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01); // TODO : remove this so users aren't added to admin automatically! var roleName = "Administrators"; var username = Request.LogonUserIdentity.Name; if (!_identityOrchestrator.UserExists(username)) { _identityOrchestrator.CreateUser(username); } if (!_identityOrchestrator.RoleExists(roleName)) { _identityOrchestrator.CreateRole(roleName); } if (!_identityOrchestrator.IsUserInRole(username, roleName)) { _identityOrchestrator.AddUserToRole(username, roleName); } return View(); } } }
using System.Web.Mvc; namespace RightpointLabs.Pourcast.Web.Controllers { using RightpointLabs.Pourcast.Application.Orchestrators.Abstract; public class HomeController : Controller { private readonly ITapOrchestrator _tapOrchestrator; private readonly IIdentityOrchestrator _identityOrchestrator; public HomeController(ITapOrchestrator tapOrchestrator, IIdentityOrchestrator identityOrchestrator) { _tapOrchestrator = tapOrchestrator; _identityOrchestrator = identityOrchestrator; } // // GET: /Home/ public ActionResult Index() { // Replace this with a Mock so it doesn't blow up the app //_tapOrchestrator.PourBeerFromTap("534a14b1aed2bf2a00045509", .01); #if DEBUG // TODO : remove this so users aren't added to admin automatically! var roleName = "Administrators"; var username = Request.LogonUserIdentity.Name; if (!_identityOrchestrator.UserExists(username)) { _identityOrchestrator.CreateUser(username); } if (!_identityOrchestrator.RoleExists(roleName)) { _identityOrchestrator.CreateRole(roleName); } if (!_identityOrchestrator.IsUserInRole(username, roleName)) { _identityOrchestrator.AddUserToRole(username, roleName); } #endif return View(); } } }
Update comments & variable name
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Verdeler { internal class MultipleConcurrencyLimiter<TSubject> { private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters = new List<ConcurrencyLimiter<TSubject>>(); public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number) { _concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number)); } public async Task Do(Func<Task> asyncFunc, TSubject subject) { //NOTE: This cannot be replaced with a Linq .ForEach foreach (var cl in _concurrencyLimiters) { await cl.WaitFor(subject).ConfigureAwait(false); } try { await asyncFunc().ConfigureAwait(false); } finally { //Release in the reverse order to prevent deadlocks _concurrencyLimiters .AsEnumerable().Reverse().ToList() .ForEach(l => l.Release(subject)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Verdeler { internal class MultipleConcurrencyLimiter<TSubject> { private readonly List<ConcurrencyLimiter<TSubject>> _concurrencyLimiters = new List<ConcurrencyLimiter<TSubject>>(); public void AddConcurrencyLimiter(Func<TSubject, object> reductionMap, int number) { _concurrencyLimiters.Add(new ConcurrencyLimiter<TSubject>(reductionMap, number)); } public async Task Do(Func<Task> asyncFunc, TSubject subject) { //We must obtain locks in order to prevent cycles from forming. foreach (var concurrencyLimiter in _concurrencyLimiters) { await concurrencyLimiter.WaitFor(subject).ConfigureAwait(false); } try { await asyncFunc().ConfigureAwait(false); } finally { //Release in reverse order _concurrencyLimiters .AsEnumerable().Reverse().ToList() .ForEach(l => l.Release(subject)); } } } }
Support port 0 in remoting
// ----------------------------------------------------------------------- // <copyright file="RemotingSystem.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using Grpc.Core; namespace Proto.Remote { public static class RemotingSystem { private static Server _server; public static PID EndpointManagerPid { get; private set; } public static void Start(string host, int port) { var addr = host + ":" + port; ProcessRegistry.Instance.Address = addr; ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid)); _server = new Server { Services = {Remoting.BindService(new EndpointReader())}, Ports = {new ServerPort(host, port, ServerCredentials.Insecure)} }; _server.Start(); var emProps = Actor.FromProducer(() => new EndpointManager()); EndpointManagerPid = Actor.Spawn(emProps); Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}"); } } }
// ----------------------------------------------------------------------- // <copyright file="RemotingSystem.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Linq; using Grpc.Core; namespace Proto.Remote { public static class RemotingSystem { private static Server _server; public static PID EndpointManagerPid { get; private set; } public static void Start(string host, int port) { ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid)); _server = new Server { Services = {Remoting.BindService(new EndpointReader())}, Ports = {new ServerPort(host, port, ServerCredentials.Insecure)} }; _server.Start(); var boundPort = _server.Ports.Single().BoundPort; var addr = host + ":" + boundPort; ProcessRegistry.Instance.Address = addr; var props = Actor.FromProducer(() => new EndpointManager()); EndpointManagerPid = Actor.Spawn(props); Console.WriteLine($"[REMOTING] Starting Proto.Actor server on {addr}"); } } }
Add voice option to ui test
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using NUnit.Framework; using Palaso.TestUtilities; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture] public class UITests { [Test, Ignore("By hand only")] public void WritingSystemSetupDialog() { using (var folder = new TemporaryFolder("WS-Test")) { new WritingSystemSetupDialog(folder.Path).ShowDialog(); } } [Test, Ignore("By hand only")] public void WritingSystemSetupViewWithComboAttached() { using (var folder = new TemporaryFolder("WS-Test")) { var f = new Form(); f.Size=new Size(800,600); var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path)); var v = new WritingSystemSetupView(model); var combo = new WSPickerUsingComboBox(model); f.Controls.Add(combo); f.Controls.Add(v); f.ShowDialog(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using NUnit.Framework; using Palaso.TestUtilities; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.UI.WindowsForms.WritingSystems.WSTree; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture] public class UITests { [Test, Ignore("By hand only")] public void WritingSystemSetupDialog() { using (var folder = new TemporaryFolder("WS-Test")) { var dlg = new WritingSystemSetupDialog(folder.Path); dlg.WritingSystemSuggestor.SuggestVoice = true; dlg.ShowDialog(); } } [Test, Ignore("By hand only")] public void WritingSystemSetupViewWithComboAttached() { using (var folder = new TemporaryFolder("WS-Test")) { var f = new Form(); f.Size=new Size(800,600); var model = new WritingSystemSetupModel(new LdmlInFolderWritingSystemStore(folder.Path)); var v = new WritingSystemSetupView(model); var combo = new WSPickerUsingComboBox(model); f.Controls.Add(combo); f.Controls.Add(v); f.ShowDialog(); } } } }
Access storage failure is readable.
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; namespace Lokad.Cqrs.Core.Inbox.Events { public sealed class FailedToAccessStorage : ISystemEvent { public Exception Exception { get; private set; } public string QueueName { get; private set; } public string MessageId { get; private set; } public FailedToAccessStorage(Exception exception, string queueName, string messageId) { Exception = exception; QueueName = queueName; MessageId = messageId; } } }
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; namespace Lokad.Cqrs.Core.Inbox.Events { public sealed class FailedToAccessStorage : ISystemEvent { public Exception Exception { get; private set; } public string QueueName { get; private set; } public string MessageId { get; private set; } public FailedToAccessStorage(Exception exception, string queueName, string messageId) { Exception = exception; QueueName = queueName; MessageId = messageId; } public override string ToString() { return string.Format("Failed to read '{0}' from '{1}': {2}", MessageId, QueueName, Exception.Message); } } }
Sort deployment groups in deployment list
using System; using System.Collections.Generic; using System.Linq; using Codestellation.Galaxy.Domain; using Codestellation.Quarks.Collections; using Nejdb.Bson; namespace Codestellation.Galaxy.WebEnd.Models { public class DeploymentListModel { public readonly DeploymentModel[] Deployments; public readonly KeyValuePair<ObjectId, string>[] AllFeeds; public DeploymentListModel(DashBoard dashBoard) { AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count); Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count); Groups = Deployments.Select(GetGroup).Distinct().ToArray(); } public string[] Groups { get; set; } public int Count { get { return Deployments.Length; } } public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup) { var modelsByGroup = Deployments .Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal)) .OrderBy(x => x.ServiceFullName); return modelsByGroup; } private static string GetGroup(DeploymentModel model) { return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group; } } }
using System; using System.Collections.Generic; using System.Linq; using Codestellation.Galaxy.Domain; using Codestellation.Quarks.Collections; using Nejdb.Bson; namespace Codestellation.Galaxy.WebEnd.Models { public class DeploymentListModel { public readonly DeploymentModel[] Deployments; public readonly KeyValuePair<ObjectId, string>[] AllFeeds; public DeploymentListModel(DashBoard dashBoard) { AllFeeds = dashBoard.Feeds.ConvertToArray(feed => new KeyValuePair<ObjectId, string>(feed.Id, feed.Name), dashBoard.Feeds.Count); Deployments = dashBoard.Deployments.ConvertToArray(x => new DeploymentModel(x, AllFeeds), dashBoard.Deployments.Count); Groups = Deployments.Select(GetGroup).Distinct().OrderBy(x => x).ToArray(); } public string[] Groups { get; set; } public int Count { get { return Deployments.Length; } } public IEnumerable<DeploymentModel> GetModelsByGroup(string serviceGroup) { var modelsByGroup = Deployments .Where(model => serviceGroup.Equals(GetGroup(model), StringComparison.Ordinal)) .OrderBy(x => x.ServiceFullName); return modelsByGroup; } private static string GetGroup(DeploymentModel model) { return string.IsNullOrWhiteSpace(model.Group) ? "Everything Else" : model.Group; } } }
Update inventory type and status mappings
using System.Collections.Generic; namespace ApiTest.InventoryApi { public class UnitOfMeasure { public int id { get; set; } public string code { get; set; } } public sealed class InventoryStatus { public static string Active = "active"; public static string OnHold = "onhold"; public static string Inactive = "inactive"; } public sealed class InventoryType { public static string Normal = "normal"; public static string NonPhysical = "nonPhysical"; public static string Manufactured = "manufactured"; public static string Kitted = "kitted"; public static string RawMaterial = "rawMaterial"; } public class Inventory { public int id { get; set; } public string partNo { get; set; } public string whse { get; set; } public string description { get; set; } public string type { get; set; } public string status { get; set; } public decimal onHandQty { get; set; } public decimal committedQty { get; set; } public decimal backorderQty { get; set; } public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; } } public class InventoryClient : BaseObjectClient<Inventory> { public InventoryClient(ApiClient client) : base(client) { } public override string Resource { get { return "inventory/items/"; } } } }
using System.Collections.Generic; namespace ApiTest.InventoryApi { public class UnitOfMeasure { public int id { get; set; } public string code { get; set; } } public sealed class InventoryStatus { public static string Active = 0; public static string OnHold = 1; public static string Inactive = 2; } public sealed class InventoryType { public static string Normal = "N"; public static string NonPhysical = "V"; public static string Manufactured = "M"; public static string Kitted = "K"; public static string RawMaterial = "R"; } public class Inventory { public int id { get; set; } public string partNo { get; set; } public string whse { get; set; } public string description { get; set; } public string type { get; set; } public string status { get; set; } public decimal onHandQty { get; set; } public decimal committedQty { get; set; } public decimal backorderQty { get; set; } public Dictionary<string, UnitOfMeasure> unitOfMeasures { get; set; } } public class InventoryClient : BaseObjectClient<Inventory> { public InventoryClient(ApiClient client) : base(client) { } public override string Resource { get { return "inventory/items/"; } } } }
Add the simples notification test
using System; using NUnit.Framework; using Realms; using System.Threading; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; private void WriteOnDifferentThread(Action<Realm> action) { var thread = new Thread(() => { var r = Realm.GetInstance(_databasePath); r.Write(() => action(r)); r.Close(); }); thread.Start(); thread.Join(); } [Test] public void SimpleTest() { // Arrange // Act } } }
using System; using NUnit.Framework; using Realms; using System.Threading; using System.IO; namespace IntegrationTests.Shared { [TestFixture] public class NotificationTests { private string _databasePath; private Realm _realm; private void WriteOnDifferentThread(Action<Realm> action) { var thread = new Thread(() => { var r = Realm.GetInstance(_databasePath); r.Write(() => action(r)); r.Close(); }); thread.Start(); thread.Join(); } [SetUp] private void Setup() { _databasePath = Path.GetTempFileName(); _realm = Realm.GetInstance(_databasePath); } [Test] public void ShouldTriggerRealmChangedEvent() { // Arrange var wasNotified = false; _realm.RealmChanged += (sender, e) => { wasNotified = true; }; // Act WriteOnDifferentThread((realm) => { realm.CreateObject<Person>(); }); // Assert Assert.That(wasNotified, "RealmChanged notification was not triggered"); } } }
Fix - Corretto reperimento codice chiamata
using Newtonsoft.Json; using SO115App.API.Models.Classi.Soccorso; using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SO115App.FakePersistenceJSon.GestioneIntervento { public class GetMaxCodice : IGetMaxCodice { public int GetMax() { int MaxIdSintesi; string filepath = "Fake/ListaRichiesteAssistenza.json"; string json; using (StreamReader r = new StreamReader(filepath)) { json = r.ReadToEnd(); } List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json); if (ListaRichieste != null) MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]); else MaxIdSintesi = 1; return MaxIdSintesi; } } }
using Newtonsoft.Json; using SO115App.API.Models.Classi.Soccorso; using SO115App.API.Models.Servizi.Infrastruttura.GestioneSoccorso; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SO115App.FakePersistenceJSon.GestioneIntervento { public class GetMaxCodice : IGetMaxCodice { public int GetMax() { int MaxIdSintesi; string filepath = "Fake/ListaRichiesteAssistenza.json"; string json; using (StreamReader r = new StreamReader(filepath)) { json = r.ReadToEnd(); } List<RichiestaAssistenzaRead> ListaRichieste = JsonConvert.DeserializeObject<List<RichiestaAssistenzaRead>>(json); if (ListaRichieste != null) MaxIdSintesi = Convert.ToInt16(ListaRichieste.OrderByDescending(x => x.Codice).FirstOrDefault().Codice.Split('-')[1]); else MaxIdSintesi = 0; return MaxIdSintesi; } } }
Update text case for CreateSampleLesson
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using GGProductions.LetterStorm.Data.Collections; namespace Test.GGProductions.LetterStorm.Data.Collections { [TestClass] public class LessonBookTests { [TestMethod] public void CreateSampleLessonTest() { // Create a lesson book with a sample lesson LessonBook lessonBook = new LessonBook(); lessonBook.CreateSampleLesson(); // Verify a lesson was created and that it has the correct name Assert.AreEqual(1, lessonBook.Lessons.Count); Assert.AreEqual("Sample Lesson", lessonBook.Lessons[0].Name); // Verify the lesson's words were created Assert.AreEqual(4, lessonBook.Lessons[0].Words.Count); Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text); Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text); Assert.AreEqual("fish", lessonBook.Lessons[0].Words[2].Text); Assert.AreEqual("horse", lessonBook.Lessons[0].Words[3].Text); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using GGProductions.LetterStorm.Data.Collections; namespace Test.GGProductions.LetterStorm.Data.Collections { [TestClass] public class LessonBookTests { [TestMethod] public void CreateSampleLessonTest() { // Create a lesson book with a sample lesson LessonBook lessonBook = new LessonBook(); lessonBook.CreateSampleLessons(); // Verify a lesson was created and that it has the correct name Assert.AreEqual(5, lessonBook.Lessons.Count); Assert.AreEqual("K5 Sample", lessonBook.Lessons[0].Name); // Verify the lesson's words were created Assert.AreEqual(5, lessonBook.Lessons[0].Words.Count); Assert.AreEqual("cat", lessonBook.Lessons[0].Words[0].Text); Assert.AreEqual("dog", lessonBook.Lessons[0].Words[1].Text); Assert.AreEqual("bug", lessonBook.Lessons[0].Words[2].Text); Assert.AreEqual("fish", lessonBook.Lessons[0].Words[3].Text); Assert.AreEqual("horse", lessonBook.Lessons[0].Words[4].Text); } } }
Change "Note" widget default height
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Width = 160; Height = 200; } [DisplayName("Saved Text")] public string Text { get; set; } } }
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Note { public class Settings : WidgetSettingsBase { public Settings() { Width = 160; Height = 132; } [DisplayName("Saved Text")] public string Text { get; set; } } }
Fix - Corretta notifica delete utente
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneRuoli { public class NotificationDeleteRuolo : INotifyDeleteRuolo { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteRuoliUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false); await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false); } } }
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.DeleteRuoliUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti.GestioneRuoli; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneRuoli { public class NotificationDeleteRuolo : INotifyDeleteRuolo { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteRuolo(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteRuoliUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); //await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", utente.Id).ConfigureAwait(false); await _notificationHubContext.Clients.All.SendAsync("NotifyModificatoRuoloUtente", utente.Id).ConfigureAwait(false); } } }
Set lifetime scope of services to instance per request
using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Oogstplanner.Models; using Oogstplanner.Data; using Oogstplanner.Services; namespace Oogstplanner.Web { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<OogstplannerUnitOfWork>() .As<IOogstplannerUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<OogstplannerContext>() .As<IOogstplannerContext>() .InstancePerRequest(); var repositoryInstances = new RepositoryFactories(); builder.RegisterInstance(repositoryInstances) .As<RepositoryFactories>() .SingleInstance(); builder.RegisterType<RepositoryProvider>() .As<IRepositoryProvider>() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly) .AsImplementedInterfaces() .Except<UserService>() .Except<AnonymousUserService>(); builder.RegisterType<AnonymousUserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
using System.Web.Mvc; using Autofac; using Autofac.Integration.Mvc; using Oogstplanner.Models; using Oogstplanner.Data; using Oogstplanner.Services; namespace Oogstplanner.Web { public static class IocConfig { public static void RegisterDependencies() { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType<OogstplannerUnitOfWork>() .As<IOogstplannerUnitOfWork>() .InstancePerLifetimeScope(); builder.RegisterType<OogstplannerContext>() .As<IOogstplannerContext>() .InstancePerRequest(); var repositoryFactories = new RepositoryFactories(); builder.RegisterInstance(repositoryFactories) .As<RepositoryFactories>() .SingleInstance(); builder.RegisterType<RepositoryProvider>() .As<IRepositoryProvider>() .InstancePerRequest(); builder.RegisterAssemblyTypes(typeof(ServiceBase).Assembly) .AsImplementedInterfaces() .Except<UserService>() .Except<AnonymousUserService>() .InstancePerRequest(); builder.RegisterType<AnonymousUserService>() .Keyed<IUserService>(AuthenticatedStatus.Anonymous) .InstancePerRequest(); builder.RegisterType<UserService>() .Keyed<IUserService>(AuthenticatedStatus.Authenticated) .InstancePerRequest(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
Remove unnecessary fields/methods for lsp push diagnostics
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { [ContentType(ContentTypeNames.XamlContentType)] [DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere [Export(typeof(ILanguageClient))] internal class XamlLanguageServerClient : AbstractLanguageServerClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider) : base(languageServerProtocol, workspace, diagnosticService, listenerProvider, solutionProvider, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public override string Name => Resources.Xaml_Language_Server_Client; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { [ContentType(ContentTypeNames.XamlContentType)] [DisableUserExperience(disableUserExperience: true)] // Remove this when we are ready to use LSP everywhere [Export(typeof(ILanguageClient))] internal class XamlLanguageServerClient : AbstractLanguageServerClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlLanguageServerClient(XamlLanguageServerProtocol languageServerProtocol, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspSolutionProvider solutionProvider) : base(languageServerProtocol, workspace, listenerProvider, solutionProvider, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public override string Name => Resources.Xaml_Language_Server_Client; } }
Debug output on throttled throughput
using System; using System.Diagnostics; using System.Threading; namespace StreamDeckSharp.Internals { internal class Throttle { private readonly Stopwatch stopwatch = Stopwatch.StartNew(); private long sumBytesInWindow = 0; public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity; public void MeasureAndBlock(int bytes) { sumBytesInWindow += bytes; var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit; if (elapsedSeconds < estimatedSeconds) { var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000)); Thread.Sleep(delta); } if (elapsedSeconds >= 1) { stopwatch.Restart(); sumBytesInWindow = 0; } } } }
using System; using System.Diagnostics; using System.Threading; namespace StreamDeckSharp.Internals { internal class Throttle { private readonly Stopwatch stopwatch = Stopwatch.StartNew(); private long sumBytesInWindow = 0; private int sleepCount = 0; public double BytesPerSecondLimit { get; set; } = double.PositiveInfinity; public void MeasureAndBlock(int bytes) { sumBytesInWindow += bytes; var elapsedSeconds = stopwatch.Elapsed.TotalSeconds; var estimatedSeconds = sumBytesInWindow / BytesPerSecondLimit; if (elapsedSeconds < estimatedSeconds) { var delta = Math.Max(1, (int)((estimatedSeconds - elapsedSeconds) * 1000)); Thread.Sleep(delta); sleepCount++; } if (elapsedSeconds >= 1) { if (sleepCount > 1) { Debug.WriteLine($"[Throttle] {sumBytesInWindow / elapsedSeconds}"); } stopwatch.Restart(); sumBytesInWindow = 0; sleepCount = 0; } } } }
Fix CVC4 support (requires a new version that supports the reset command).
using System; using Symbooglix.Solver; namespace Symbooglix { namespace Solver { public class CVC4SMTLIBSolver : SimpleSMTLIBSolver { SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) : base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags { } // HACK: public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) : this(useNamedAttributes, pathToSolver, persistentProcess) { LogicToUse = logic; } protected override void SetSolverOptions() { Printer.PrintSetLogic(LogicToUse); } } } }
using System; using Symbooglix.Solver; namespace Symbooglix { namespace Solver { public class CVC4SMTLIBSolver : SimpleSMTLIBSolver { SMTLIBQueryPrinter.Logic LogicToUse = SMTLIBQueryPrinter.Logic.ALL_SUPPORTED; // Non standard public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess) : base(useNamedAttributes, pathToSolver, "--lang smt2 --incremental", persistentProcess) // CVC4 specific command line flags { } // HACK: public CVC4SMTLIBSolver(bool useNamedAttributes, string pathToSolver, bool persistentProcess, SMTLIBQueryPrinter.Logic logic) : this(useNamedAttributes, pathToSolver, persistentProcess) { // We should not use DO_NOT_SET because CVC4 complains if no // logic is set which causes a SolverErrorException to be raised. if (logic != SMTLIBQueryPrinter.Logic.DO_NOT_SET) LogicToUse = logic; } protected override void SetSolverOptions() { Printer.PrintSetLogic(LogicToUse); } } } }
Remove unused code and updated directory location.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Cipher { class Utility { public static string directory = @"c:\code\cypher_files"; /// <summary> /// Allows user to choose to display the password on the screen as is being typed. /// </summary> /// <param name="displayPassword"> /// Indicates whether or not password displays on the screen. /// </param> /// <returns> /// A password string. /// </returns> public static string GetPassword(string displayPassword) { string password = ""; if (displayPassword == "y" || displayPassword == "") { password = Console.ReadLine(); } if (displayPassword == "n") { while (true) { var pressedKey = System.Console.ReadKey(true); // Get all typed keys until 'Enter' is pressed. if (pressedKey.Key == ConsoleKey.Enter) { Console.WriteLine(""); break; } password += pressedKey.KeyChar; } } return password; } public static void SaveFileToDisk(string fileName, byte[] fileContents) { File.WriteAllBytes(fileName, fileContents); } } }
using System; using System.IO; namespace Cipher { class Utility { public static string directory = "/Users/emiranda/Documents/code/c#/cipher_files/"; /// <summary> /// Allows user to choose to display the password on the screen as is being typed. /// </summary> /// <param name="displayPassword"> /// Indicates whether or not password displays on the screen. /// </param> /// <returns> /// A password string. /// </returns> public static string GetPassword(string displayPassword) { string password = ""; if (displayPassword == "y" || displayPassword == "") { password = Console.ReadLine(); } if (displayPassword == "n") { while (true) { var pressedKey = System.Console.ReadKey(true); // Get all typed keys until 'Enter' is pressed. if (pressedKey.Key == ConsoleKey.Enter) { Console.WriteLine(""); break; } password += pressedKey.KeyChar; } } return password; } public static void SaveFileToDisk(string fileName, byte[] fileContents) { File.WriteAllBytes(fileName, fileContents); } } }
Add comment for claims transform
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Used by the <see cref="IAuthenticationService"/> for claims transformation. /// </summary> public interface IClaimsTransformation { /// <summary> /// Provides a central transformation point to change the specified principal. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param> /// <returns>The transformed principal.</returns> Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Used by the <see cref="IAuthenticationService"/> for claims transformation. /// </summary> public interface IClaimsTransformation { /// <summary> /// Provides a central transformation point to change the specified principal. /// Note: this will be run on each AuthenticateAsync call, so its safer to /// return a new ClaimsPrincipal if your transformation is not idempotent. /// </summary> /// <param name="principal">The <see cref="ClaimsPrincipal"/> to transform.</param> /// <returns>The transformed principal.</returns> Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal); } }
Handle Invalid format for Upgrade check
using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using Semver; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories.Implement { internal class UpgradeCheckRepository : IUpgradeCheckRepository { private static HttpClient _httpClient; private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade"; public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version) { try { if (_httpClient == null) _httpClient = new HttpClient(); var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter()); var result = await task.Content.ReadAsAsync<UpgradeResult>(); return result ?? new UpgradeResult("None", "", ""); } catch (HttpRequestException) { // this occurs if the server for Our is down or cannot be reached return new UpgradeResult("None", "", ""); } } private class CheckUpgradeDto { public CheckUpgradeDto(SemVersion version) { VersionMajor = version.Major; VersionMinor = version.Minor; VersionPatch = version.Patch; VersionComment = version.Prerelease; } public int VersionMajor { get; } public int VersionMinor { get; } public int VersionPatch { get; } public string VersionComment { get; } } } }
using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using Semver; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories.Implement { internal class UpgradeCheckRepository : IUpgradeCheckRepository { private static HttpClient _httpClient; private const string RestApiUpgradeChecklUrl = "https://our.umbraco.com/umbraco/api/UpgradeCheck/CheckUpgrade"; public async Task<UpgradeResult> CheckUpgradeAsync(SemVersion version) { try { if (_httpClient == null) _httpClient = new HttpClient(); var task = await _httpClient.PostAsync(RestApiUpgradeChecklUrl, new CheckUpgradeDto(version), new JsonMediaTypeFormatter()); var result = await task.Content.ReadAsAsync<UpgradeResult>(); return result ?? new UpgradeResult("None", "", ""); } catch (UnsupportedMediaTypeException) { // this occurs if the server for Our is up but doesn't return a valid result (ex. content type) return new UpgradeResult("None", "", ""); } catch (HttpRequestException) { // this occurs if the server for Our is down or cannot be reached return new UpgradeResult("None", "", ""); } } private class CheckUpgradeDto { public CheckUpgradeDto(SemVersion version) { VersionMajor = version.Major; VersionMinor = version.Minor; VersionPatch = version.Patch; VersionComment = version.Prerelease; } public int VersionMajor { get; } public int VersionMinor { get; } public int VersionPatch { get; } public string VersionComment { get; } } } }
Remove class variable declaration for UINavigationController
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Hello_MultiScreen_iPhone { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { //---- declarations UIWindow window; UINavigationController rootNavigationController; // This method is invoked when the application has loaded its UI and it is ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { this.window = new UIWindow (UIScreen.MainScreen.Bounds); //---- instantiate a new navigation controller this.rootNavigationController = new UINavigationController(); //---- instantiate a new home screen HomeScreen homeScreen = new HomeScreen(); //---- add the home screen to the navigation controller (it'll be the top most screen) this.rootNavigationController.PushViewController(homeScreen, false); //---- set the root view controller on the window. the nav controller will handle the rest this.window.RootViewController = this.rootNavigationController; this.window.MakeKeyAndVisible (); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Hello_MultiScreen_iPhone { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { //---- declarations UIWindow window; // This method is invoked when the application has loaded its UI and it is ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { this.window = new UIWindow (UIScreen.MainScreen.Bounds); //---- instantiate a new navigation controller var rootNavigationController = new UINavigationController(); //---- instantiate a new home screen HomeScreen homeScreen = new HomeScreen(); //---- add the home screen to the navigation controller (it'll be the top most screen) rootNavigationController.PushViewController(homeScreen, false); //---- set the root view controller on the window. the nav controller will handle the rest this.window.RootViewController = rootNavigationController; this.window.MakeKeyAndVisible (); return true; } } }
Remove tracing from the unifier
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program) { var simpleUnifier = new SimpleUnifier(); var traceUnifier = new TraceUnifier(simpleUnifier); // Run the unifier try { Console.WriteLine(query); traceUnifier.QueryUnifier.Compile(query); simpleUnifier.PrepareToRunProgram(); Console.WriteLine(program); traceUnifier.ProgramUnifier.Compile(program); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way yield break; } // Retrieve the unified value for the program // TODO: eventually we'll need to use a unification key var result = simpleUnifier.UnifiedValue(program.UnificationKey ?? program); // If the result was valid, return as the one value from this function if (result != null) { yield return result; } } } }
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IEnumerable<ILiteral> Unify(this ILiteral query, ILiteral program) { var simpleUnifier = new SimpleUnifier(); // Run the unifier try { simpleUnifier.QueryUnifier.Compile(query); simpleUnifier.PrepareToRunProgram(); simpleUnifier.ProgramUnifier.Compile(program); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way yield break; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { yield return result; } } } }
Update bridge to use new interface
using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using TGS.Interface; using TGS.Interface.Components; namespace TGS.Interface.Bridge { /// <summary> /// Holds the proc that DD calls to access <see cref="ITGInterop"/> /// </summary> public static class DreamDaemonBridge { /// <summary> /// The proc that DD calls to access <see cref="ITGInterop"/> /// </summary> /// <param name="argc">The number of arguments passed</param> /// <param name="args">The arguments passed</param> /// <returns>0</returns> [DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)] public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args) { try { var parsedArgs = new List<string>(); parsedArgs.AddRange(args); var instance = parsedArgs[0]; parsedArgs.RemoveAt(0); using (var I = new ServerInterface()) if(I.ConnectToInstance(instance, true).HasFlag(ConnectivityLevel.Connected)) I.GetComponent<ITGInterop>().InteropMessage(String.Join(" ", parsedArgs)); } catch { } return 0; } } }
using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace TGS.Interface.Bridge { /// <summary> /// Holds the proc that DD calls to access <see cref="ITGInterop"/> /// </summary> public static class DreamDaemonBridge { /// <summary> /// The proc that DD calls to access <see cref="ITGInterop"/> /// </summary> /// <param name="argc">The number of arguments passed</param> /// <param name="args">The arguments passed</param> /// <returns>0</returns> [DllExport("DDEntryPoint", CallingConvention = CallingConvention.Cdecl)] public static int DDEntryPoint(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 0)]string[] args) { try { var parsedArgs = new List<string>(); parsedArgs.AddRange(args); var instance = parsedArgs[0]; parsedArgs.RemoveAt(0); using (var I = new ServerInterface()) I.Server.GetInstance(instance).Interop.InteropMessage(String.Join(" ", parsedArgs)); } catch { } return 0; } } }
Add POST REDIRECT GET Pattern to controller
using System.Linq; using Microsoft.AspNetCore.Mvc; using OdeToFood.Entities; using OdeToFood.Services; using OdeToFood.ViewModels; namespace OdeToFood.Controllers { public class HomeController : Controller { private IRestaurantData _restaurantData; private IGreeter _greeter; public HomeController(IRestaurantData restaurantData, IGreeter greeter) { _restaurantData = restaurantData; _greeter = greeter; } public IActionResult Index() { var model = new HomePageViewModel() { Message = _greeter.GetGreeting(), Restaurants = _restaurantData.GetAll() }; return View(model); } public IActionResult Details(int id) { var model = _restaurantData.Get(id); if (model == null) { return RedirectToAction(nameof(Index)); } return View(model); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(RestaurantEditViewModel model) { var restaurant = new Restaurant() { Name = model.Name, Cuisine = model.Cuisine }; restaurant = _restaurantData.Add(restaurant); return View(nameof(Details), restaurant); } } }
using Microsoft.AspNetCore.Mvc; using OdeToFood.Entities; using OdeToFood.Services; using OdeToFood.ViewModels; namespace OdeToFood.Controllers { public class HomeController : Controller { private IRestaurantData _restaurantData; private IGreeter _greeter; public HomeController(IRestaurantData restaurantData, IGreeter greeter) { _restaurantData = restaurantData; _greeter = greeter; } public IActionResult Index() { var model = new HomePageViewModel() { Message = _greeter.GetGreeting(), Restaurants = _restaurantData.GetAll() }; return View(model); } public IActionResult Details(int id) { var model = _restaurantData.Get(id); if (model == null) { return RedirectToAction(nameof(Index)); } return View(model); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(RestaurantEditViewModel model) { var restaurant = new Restaurant() { Name = model.Name, Cuisine = model.Cuisine }; restaurant = _restaurantData.Add(restaurant); return RedirectToAction(nameof(Details), new { Id = restaurant.Id }); } } }
Fix a typo in the NodaTime.Calendars namespace summary.
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Runtime.CompilerServices; namespace NodaTime.Calendars { /// <summary> /// <para> /// The NodaTime.Calendar namespace contains types related to calendars beyond the /// <see cref="CalendarSystem"/> type in the core NodaTime namespace. /// </para> /// </summary> [CompilerGenerated] internal class NamespaceDoc { // No actual code here - it's just for the sake of documenting the namespace. } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Runtime.CompilerServices; namespace NodaTime.Calendars { /// <summary> /// <para> /// The NodaTime.Calendars namespace contains types related to calendars beyond the /// <see cref="CalendarSystem"/> type in the core NodaTime namespace. /// </para> /// </summary> [CompilerGenerated] internal class NamespaceDoc { // No actual code here - it's just for the sake of documenting the namespace. } }
Update cake script to csproj
var configuration = Argument("configuration", "Debug"); Task("Clean") .Does(() => { CleanDirectory("./artifacts/"); }); Task("Restore") .Does(() => { DotNetCoreRestore(); }); Task("Build") .Does(() => { DotNetCoreBuild("./src/**/project.json", new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Pack") .Does(() => { new List<string> { "Stormpath.Owin.Abstractions", "Stormpath.Owin.Middleware", "Stormpath.Owin.Views.Precompiled" }.ForEach(name => { DotNetCorePack("./src/" + name + "/project.json", new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = "./artifacts/" }); }); }); Task("Test") .IsDependentOn("Restore") .IsDependentOn("Build") .Does(() => { new List<string> { "Stormpath.Owin.UnitTest" }.ForEach(name => { DotNetCoreTest("./test/" + name + "/project.json"); }); }); Task("Default") .IsDependentOn("Clean") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Pack"); var target = Argument("target", "Default"); RunTarget(target);
var configuration = Argument("configuration", "Debug"); Task("Clean") .Does(() => { CleanDirectory("./artifacts/"); }); Task("Restore") .Does(() => { DotNetCoreRestore(); }); Task("Build") .Does(() => { DotNetCoreBuild("./src/**/*.csproj", new DotNetCoreBuildSettings { Configuration = configuration }); }); Task("Pack") .Does(() => { new List<string> { "Stormpath.Owin.Abstractions", "Stormpath.Owin.Middleware", "Stormpath.Owin.Views.Precompiled" }.ForEach(name => { DotNetCorePack("./src/" + name + ".csproj", new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = "./artifacts/" }); }); }); Task("Test") .IsDependentOn("Restore") .IsDependentOn("Build") .Does(() => { new List<string> { "Stormpath.Owin.UnitTest" }.ForEach(name => { DotNetCoreTest("./test/" + name + ".csproj"); }); }); Task("Default") .IsDependentOn("Clean") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Pack"); var target = Argument("target", "Default"); RunTarget(target);
Update assembly version of Types.dll to 3.7
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyTitle("NuGetPackageExplorer.Types")] [assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyProduct("NuGet Package Explorer")] [assembly: AssemblyCopyright("\x00a9 Outercurve Foundation. All rights reserved.")] [assembly: AssemblyTitle("NuGetPackageExplorer.Types")] [assembly: AssemblyDescription("Contains types to enable the plugin architecture in NuGet Package Explorer.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("3.7.0.0")] [assembly: AssemblyFileVersion("3.7.0.0")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8bdc7953-73c3-47d6-b0c5-41fda3d55e42")]
Change test back to using a string builder
using System.IO; using System.Text; using CSF.Screenplay.Reporting.Tests; using CSF.Screenplay.Reporting.Tests.Autofixture; using CSF.Screenplay.ReportModel; using NUnit.Framework; namespace CSF.Screenplay.Reporting.Tests { [TestFixture] public class JsonReportRendererTests { [Test,AutoMoqData] public void Write_can_create_a_document_without_crashing([RandomReport] Report report) { // Arrange using(var writer = GetReportOutput()) { var sut = new JsonReportRenderer(writer); // Act & assert Assert.DoesNotThrow(() => sut.Render(report)); } } TextWriter GetReportOutput() { // Uncomment this line to write the report to a file instead of a throwaway string return new StreamWriter("JsonReportRendererTests.json"); //var sb = new StringBuilder(); //return new StringWriter(sb); } } }
using System.IO; using System.Text; using CSF.Screenplay.Reporting.Tests; using CSF.Screenplay.Reporting.Tests.Autofixture; using CSF.Screenplay.ReportModel; using NUnit.Framework; namespace CSF.Screenplay.Reporting.Tests { [TestFixture] public class JsonReportRendererTests { [Test,AutoMoqData] public void Write_can_create_a_document_without_crashing([RandomReport] Report report) { // Arrange using(var writer = GetReportOutput()) { var sut = new JsonReportRenderer(writer); // Act & assert Assert.DoesNotThrow(() => sut.Render(report)); } } TextWriter GetReportOutput() { // Uncomment this line to write the report to a file instead of a throwaway string //return new StreamWriter("JsonReportRendererTests.json"); var sb = new StringBuilder(); return new StringWriter(sb); } } }
Fix number of messages retrieved. Used to be n-1
using System; using System.Collections.Generic; using System.Text; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe { public interface IQueueRetreival { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetreival : IQueueRetreival { public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var channel = connection.CreateModel()) { try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (++count < parameters.NumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName); yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info); } } } } }
using System; using System.Collections.Generic; using System.Text; using RabbitMQ.Client.Exceptions; namespace EasyNetQ.Hosepipe { public interface IQueueRetreival { IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters); } public class QueueRetreival : IQueueRetreival { public IEnumerable<HosepipeMessage> GetMessagesFromQueue(QueueParameters parameters) { using (var connection = HosepipeConnection.FromParamters(parameters)) using (var channel = connection.CreateModel()) { try { channel.QueueDeclarePassive(parameters.QueueName); } catch (OperationInterruptedException exception) { Console.WriteLine(exception.Message); yield break; } var count = 0; while (count++ < parameters.NumberOfMessagesToRetrieve) { var basicGetResult = channel.BasicGet(parameters.QueueName, noAck: parameters.Purge); if (basicGetResult == null) break; // no more messages on the queue var properties = new MessageProperties(basicGetResult.BasicProperties); var info = new MessageReceivedInfo( "hosepipe", basicGetResult.DeliveryTag, basicGetResult.Redelivered, basicGetResult.Exchange, basicGetResult.RoutingKey, parameters.QueueName); yield return new HosepipeMessage(Encoding.UTF8.GetString(basicGetResult.Body), properties, info); } } } } }
Change the default value of the parameter initialization method.
using System; using System.Linq.Expressions; using Abp.Timing; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Abp.EntityFrameworkCore.ValueConverters { public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?> { public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = default) : base(Normalize, Normalize, mappingHints) { } private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x => x.HasValue ? Clock.Normalize(x.Value) : x; } }
using System; using System.Linq.Expressions; using Abp.Timing; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Abp.EntityFrameworkCore.ValueConverters { public class AbpDateTimeValueConverter : ValueConverter<DateTime?, DateTime?> { public AbpDateTimeValueConverter([CanBeNull] ConverterMappingHints mappingHints = null) : base(Normalize, Normalize, mappingHints) { } private static readonly Expression<Func<DateTime?, DateTime?>> Normalize = x => x.HasValue ? Clock.Normalize(x.Value) : x; } }
Change the assembly version to "base"
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")] [assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-9c82a0d-dirty")] [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Reflection.AssemblyTitle("Knapcode.StandardSerializer")] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.Guid("963e0295-1d98-4f44-aadc-8cb4ba91c613")] [assembly: System.Reflection.AssemblyInformationalVersion("1.0.0.0-base")] [assembly: System.Reflection.AssemblyVersion("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")]
Fix sorting and searching on table
@model IList<User> @{ ViewData["Title"] = "List Non Admin Users"; } <div class="col"> <table id="table"> <thead> <tr> <th></th> <th>Name</th> <th>Email</th> <th>Client Id</th> <th>Phone</th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td> <a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a> </td> <td>@user.Name</td> <td>@user.Email</td> <td>@user.ClientId</td> <td>@user.Phone</td> </tr> } </tbody> </table> </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function () { $("#table").dataTable({ "sorting": [[2, "desc"]], "pageLength": 100, }); }); </script> }
@model IList<User> @{ ViewData["Title"] = "List Non Admin Users"; } <div class="col"> <table id="table"> <thead> <tr> <th></th> <th>Name</th> <th>Email</th> <th>Client Id</th> <th>Phone</th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td> <a class="btn btn-default" asp-action="EditUser" asp-route-Id="@user.Id" >Edit</a> </td> <td>@user.Name</td> <td>@user.Email</td> <td>@user.ClientId</td> <td>@user.Phone</td> </tr> } </tbody> </table> </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function () { $("#table").dataTable({ "sorting": [[2, "desc"]], "pageLength": 100, "columnDefs": [ { "orderable": false, "targets": [0] }, { "searchable":false, "targets": 0 } ] }); }); </script> }
Set the document language to English
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/themes/base/css", "~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/themes/base/css", "~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
Add doc for what happens when getting clipboard text fails (SDL)
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern IntPtr SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { IntPtr ptrToText = SDL_GetClipboardText(); string text = Marshal.PtrToStringAnsi(ptrToText); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { private const string lib = "libSDL2-2.0"; [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_free", ExactSpelling = true)] internal static extern void SDL_free(IntPtr ptr); /// <returns>Returns the clipboard text on success or <see cref="IntPtr.Zero"/> on failure. </returns> [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern IntPtr SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { IntPtr ptrToText = SDL_GetClipboardText(); string text = Marshal.PtrToStringAnsi(ptrToText); SDL_free(ptrToText); return text; } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
Optimize query for server time. (not throwing exception)
using Hangfire.Mongo.Database; using MongoDB.Driver; using System; using Hangfire.Mongo.Helpers; using MongoDB.Bson; namespace Hangfire.Mongo.MongoUtils { /// <summary> /// Helper utilities to work with Mongo database /// </summary> public static class MongoExtensions { /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="database">Mongo database</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this IMongoDatabase database) { try { dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1))); return ((DateTime)serverStatus.localTime).ToUniversalTime(); } catch (MongoException) { return DateTime.UtcNow; } } /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="dbContext">Hangfire database context</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext) { return GetServerTimeUtc(dbContext.Database); } } }
using Hangfire.Mongo.Database; using MongoDB.Driver; using System; using System.Collections.Generic; using Hangfire.Mongo.Helpers; using MongoDB.Bson; namespace Hangfire.Mongo.MongoUtils { /// <summary> /// Helper utilities to work with Mongo database /// </summary> public static class MongoExtensions { /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="database">Mongo database</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this IMongoDatabase database) { dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1))); object localTime; if (((IDictionary<string, object>)serverStatus).TryGetValue("localTime", out localTime)) { return ((DateTime)localTime).ToUniversalTime(); } return DateTime.UtcNow; } /// <summary> /// Retreives server time in UTC zone /// </summary> /// <param name="dbContext">Hangfire database context</param> /// <returns>Server time</returns> public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext) { return GetServerTimeUtc(dbContext.Database); } } }
Fix the using. Sometimes atom can be...
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ExpectStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ShouldStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
Use the new Delete command support in CslaDataProvider.
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ProjectTracker.Library.Admin; namespace PTWpf { /// <summary> /// Interaction logic for RolesEdit.xaml /// </summary> public partial class RolesEdit : EditForm { public RolesEdit() { InitializeComponent(); Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider; dp.DataChanged += new EventHandler(base.DataChanged); } protected override void ApplyAuthorization() { this.AuthPanel.Refresh(); if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles))) { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"]; } else { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"]; ((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ProjectTracker.Library.Admin; namespace PTWpf { /// <summary> /// Interaction logic for RolesEdit.xaml /// </summary> public partial class RolesEdit : EditForm { public RolesEdit() { InitializeComponent(); Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider; dp.DataChanged += new EventHandler(base.DataChanged); } protected override void ApplyAuthorization() { if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles))) { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"]; } else { this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"]; ((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel(); } } } }
Implement RouteData resolvement while in wcf context
namespace nuserv.Utility { using System.Net.Http; using System.Web; using System.Web.Http.Routing; public class HttpRouteDataResolver : IHttpRouteDataResolver { #region Public Methods and Operators public IHttpRouteData Resolve() { if (HttpContext.Current != null) { var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage; return requestMessage.GetRouteData(); } return null; } #endregion } }
namespace nuserv.Utility { #region Usings using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http.Routing; #endregion public class HttpRouteDataResolver : IHttpRouteDataResolver { #region Public Methods and Operators public IHttpRouteData Resolve() { if (HttpContext.Current != null) { if (HttpContext.Current.Items.Contains("")) { var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage; if (requestMessage != null) { return requestMessage.GetRouteData(); } } else { return new RouteData(HttpContext.Current.Request.RequestContext.RouteData); } } return null; } #endregion private class RouteData : IHttpRouteData { #region Fields private readonly System.Web.Routing.RouteData originalRouteData; #endregion #region Constructors and Destructors public RouteData(System.Web.Routing.RouteData routeData) { if (routeData == null) { throw new ArgumentNullException("routeData"); } this.originalRouteData = routeData; this.Route = null; } #endregion #region Public Properties public IHttpRoute Route { get; private set; } public IDictionary<string, object> Values { get { return this.originalRouteData.Values; } } #endregion } } }
Make sure to only invoke defaults once
namespace NServiceBus { using Settings; using Features; using Persistence; using Persistence.Sql; /// <summary> /// The <see cref="PersistenceDefinition"/> for the SQL Persistence. /// </summary> public class SqlPersistence : PersistenceDefinition { /// <summary> /// Initializes a new instance of <see cref="SqlPersistence"/>. /// </summary> public SqlPersistence() { Supports<StorageType.Outbox>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlOutboxFeature>(); }); Supports<StorageType.Timeouts>(s => { s.EnableFeatureByDefault<SqlTimeoutFeature>(); }); Supports<StorageType.Sagas>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlSagaFeature>(); s.AddUnrecoverableException(typeof(SerializationException)); }); Supports<StorageType.Subscriptions>(s => { s.EnableFeatureByDefault<SqlSubscriptionFeature>(); }); Defaults(s => { var dialect = s.GetSqlDialect(); var diagnostics = dialect.GetCustomDialectDiagnosticsInfo(); s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new { Name = dialect.Name, CustomDiagnostics = diagnostics }); s.EnableFeatureByDefault<InstallerFeature>(); }); } static void EnableSession(SettingsHolder s) { s.EnableFeatureByDefault<StorageSessionFeature>(); } } }
namespace NServiceBus { using Settings; using Features; using Persistence; using Persistence.Sql; /// <summary> /// The <see cref="PersistenceDefinition"/> for the SQL Persistence. /// </summary> public class SqlPersistence : PersistenceDefinition { /// <summary> /// Initializes a new instance of <see cref="SqlPersistence"/>. /// </summary> public SqlPersistence() { Supports<StorageType.Outbox>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlOutboxFeature>(); }); Supports<StorageType.Timeouts>(s => { s.EnableFeatureByDefault<SqlTimeoutFeature>(); }); Supports<StorageType.Sagas>(s => { EnableSession(s); s.EnableFeatureByDefault<SqlSagaFeature>(); s.AddUnrecoverableException(typeof(SerializationException)); }); Supports<StorageType.Subscriptions>(s => { s.EnableFeatureByDefault<SqlSubscriptionFeature>(); }); Defaults(s => { var defaultsAppliedSettingsKey = "NServiceBus.Persistence.Sql.DefaultApplied"; if (s.HasSetting(defaultsAppliedSettingsKey)) { return; } var dialect = s.GetSqlDialect(); var diagnostics = dialect.GetCustomDialectDiagnosticsInfo(); s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new { Name = dialect.Name, CustomDiagnostics = diagnostics }); s.EnableFeatureByDefault<InstallerFeature>(); s.Set(defaultsAppliedSettingsKey, true); }); } static void EnableSession(SettingsHolder s) { s.EnableFeatureByDefault<StorageSessionFeature>(); } } }
Change order of update operation in RecordRun
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using ExpressRunner.Api; namespace ExpressRunner { public class TestItem : PropertyChangedBase, IRunnableTest { public string Name { get { return Test.Name; } } private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>(); public IObservableCollection<TestRun> Runs { get { return runs; } } private TestStatus status = TestStatus.NotRun; public TestStatus Status { get { return status; } private set { if (status != value) { status = value; NotifyOfPropertyChange("Status"); } } } private readonly Test test; public Test Test { get { return test; } } public TestItem(Test test) { if (test == null) throw new ArgumentNullException("test"); this.test = test; } public void RecordRun(TestRun run) { runs.Add(run); UpdateStatus(run); } private void UpdateStatus(TestRun run) { if (run.Status == TestStatus.Failed) Status = TestStatus.Failed; else if (Status == TestStatus.NotRun) Status = run.Status; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using ExpressRunner.Api; namespace ExpressRunner { public class TestItem : PropertyChangedBase, IRunnableTest { public string Name { get { return Test.Name; } } private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>(); public IObservableCollection<TestRun> Runs { get { return runs; } } private TestStatus status = TestStatus.NotRun; public TestStatus Status { get { return status; } private set { if (status != value) { status = value; NotifyOfPropertyChange("Status"); } } } private readonly Test test; public Test Test { get { return test; } } public TestItem(Test test) { if (test == null) throw new ArgumentNullException("test"); this.test = test; } public void RecordRun(TestRun run) { UpdateStatus(run); runs.Add(run); } private void UpdateStatus(TestRun run) { if (run.Status == TestStatus.Failed) Status = TestStatus.Failed; else if (Status == TestStatus.NotRun) Status = run.Status; } } }
Optimize the detection of IDisposable test classes. Array.Contains performs fewer allocations than the LINQ Any extension method.
namespace Fixie.Execution { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class MethodDiscoverer { readonly Filter filter; readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions; public MethodDiscoverer(Filter filter, Convention convention) { this.filter = filter; testMethodConditions = convention.Config.TestMethodConditions; } public IReadOnlyList<MethodInfo> TestMethods(Type testClass) { try { bool testClassIsDisposable = IsDisposable(testClass); return testClass .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(method => method.DeclaringType != typeof(object)) .Where(method => !(testClassIsDisposable && HasDisposeSignature(method))) .Where(IsMatch) .Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method))) .ToArray(); } catch (Exception exception) { throw new Exception( "Exception thrown while attempting to run a custom method-discovery predicate. " + "Check the inner exception for more details.", exception); } } bool IsMatch(MethodInfo candidate) => testMethodConditions.All(condition => condition(candidate)); static bool IsDisposable(Type type) => type.GetInterfaces().Any(interfaceType => interfaceType == typeof(IDisposable)); static bool HasDisposeSignature(MethodInfo method) => method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0; } }
namespace Fixie.Execution { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; class MethodDiscoverer { readonly Filter filter; readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions; public MethodDiscoverer(Filter filter, Convention convention) { this.filter = filter; testMethodConditions = convention.Config.TestMethodConditions; } public IReadOnlyList<MethodInfo> TestMethods(Type testClass) { try { bool testClassIsDisposable = IsDisposable(testClass); return testClass .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(method => method.DeclaringType != typeof(object)) .Where(method => !(testClassIsDisposable && HasDisposeSignature(method))) .Where(IsMatch) .Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method))) .ToArray(); } catch (Exception exception) { throw new Exception( "Exception thrown while attempting to run a custom method-discovery predicate. " + "Check the inner exception for more details.", exception); } } bool IsMatch(MethodInfo candidate) => testMethodConditions.All(condition => condition(candidate)); static bool IsDisposable(Type type) => type.GetInterfaces().Contains(typeof(IDisposable)); static bool HasDisposeSignature(MethodInfo method) => method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0; } }
Add parent and child app skeleton
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AlertSample { using System; internal sealed class Program { private static void Main(string[] args) { Alert alert = new Alert("AlertSample", 5.0d, 10.0d); try { alert.Start(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e); throw; } finally { alert.Stop(); } } } }
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AlertSample { using System; internal sealed class Program { private static int Main(string[] args) { if (args.Length == 0) { return RunParent(); } else if (args.Length == 1) { return RunChild(args[0]); } else { Console.WriteLine("Invalid arguments."); return 1; } } private static int RunParent() { Alert alert = new Alert("AlertSample", 5.0d, 10.0d); try { alert.Start(); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e); throw; } finally { alert.Stop(); } return 0; } private static int RunChild(string name) { Console.WriteLine("TODO: " + name); return 0; } } }
Add blocking statement to ensure service remains alive
using System.ServiceModel; namespace TfsHipChat { class Program { static void Main() { using (var host = new ServiceHost(typeof(CheckinEventService))) { host.Open(); } } } }
using System; using System.ServiceModel; namespace TfsHipChat { class Program { static void Main() { using (var host = new ServiceHost(typeof(CheckinEventService))) { host.Open(); Console.WriteLine("TfsHipChat started!"); Console.ReadLine(); } } } }
Address ProcessStartInfo envvar case sensitivite issue
using System.Diagnostics; namespace Cake.Core.Polyfill { internal static class ProcessHelper { public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value) { #if NETCORE info.Environment[key] = value; #else info.EnvironmentVariables[key] = value; #endif } } }
using System; using System.Diagnostics; using System.Linq; namespace Cake.Core.Polyfill { internal static class ProcessHelper { public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value) { #if NETCORE var envKey = info.Environment.Keys.FirstOrDefault(exisitingKey => StringComparer.OrdinalIgnoreCase.Equals(exisitingKey, key)) ?? key; info.Environment[envKey] = value; #else var envKey = info.EnvironmentVariables.Keys.Cast<string>().FirstOrDefault(existingKey => StringComparer.OrdinalIgnoreCase.Equals(existingKey, key)) ?? key; info.EnvironmentVariables[key] = value; #endif } } }
Set initial page to LoginPage
using BlueMonkey.ExpenceServices; using BlueMonkey.ExpenceServices.Local; using BlueMonkey.Model; using Prism.Unity; using BlueMonkey.Views; using Xamarin.Forms; using Microsoft.Practices.Unity; namespace BlueMonkey { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("NavigationPage/MainPage"); } protected override void RegisterTypes() { Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager()); Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<MainPage>(); Container.RegisterTypeForNavigation<AddExpensePage>(); Container.RegisterTypeForNavigation<ExpenseListPage>(); Container.RegisterTypeForNavigation<ChartPage>(); Container.RegisterTypeForNavigation<ReportPage>(); Container.RegisterTypeForNavigation<ReceiptPage>(); Container.RegisterTypeForNavigation<AddReportPage>(); Container.RegisterTypeForNavigation<ReportListPage>(); Container.RegisterTypeForNavigation<ExpenseSelectionPage>(); Container.RegisterTypeForNavigation<LoginPage>(); } } }
using BlueMonkey.ExpenceServices; using BlueMonkey.ExpenceServices.Local; using BlueMonkey.Model; using Prism.Unity; using BlueMonkey.Views; using Xamarin.Forms; using Microsoft.Practices.Unity; namespace BlueMonkey { public partial class App : PrismApplication { public App(IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("LoginPage"); } protected override void RegisterTypes() { Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager()); Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<MainPage>(); Container.RegisterTypeForNavigation<AddExpensePage>(); Container.RegisterTypeForNavigation<ExpenseListPage>(); Container.RegisterTypeForNavigation<ChartPage>(); Container.RegisterTypeForNavigation<ReportPage>(); Container.RegisterTypeForNavigation<ReceiptPage>(); Container.RegisterTypeForNavigation<AddReportPage>(); Container.RegisterTypeForNavigation<ReportListPage>(); Container.RegisterTypeForNavigation<ExpenseSelectionPage>(); Container.RegisterTypeForNavigation<LoginPage>(); } } }
Add comment to backwards compat alias
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Batch.Models; using System.Management.Automation; using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants; namespace Microsoft.Azure.Commands.Batch { [Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))] [Alias("Get-AzureRmBatchSubscriptionQuotas")] public class GetBatchLocationQuotasCommand : BatchCmdletBase { [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")] [ValidateNotNullOrEmpty] public string Location { get; set; } public override void ExecuteCmdlet() { PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location); WriteObject(quotas); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Batch.Models; using System.Management.Automation; using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants; namespace Microsoft.Azure.Commands.Batch { [Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))] // This alias was added in 10/2016 for backwards compatibility [Alias("Get-AzureRmBatchSubscriptionQuotas")] public class GetBatchLocationQuotasCommand : BatchCmdletBase { [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")] [ValidateNotNullOrEmpty] public string Location { get; set; } public override void ExecuteCmdlet() { PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location); WriteObject(quotas); } } }
Check if the workitem if a jira issue, before logging time.
using Atlassian.Jira; using TicketTimer.Core.Infrastructure; using TicketTimer.Jira.Extensions; namespace TicketTimer.Jira.Services { public class DefaultJiraService : JiraService { private readonly WorkItemStore _workItemStore; // TODO Insert correct parameters public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword"); public DefaultJiraService(WorkItemStore workItemStore) { _workItemStore = workItemStore; } public void WriteEntireArchive() { var archive = _workItemStore.GetState().WorkItemArchive; foreach (var workItem in archive) { // TODO Check if work item is jira-item. TrackTime(workItem); } } private void TrackTime(WorkItem workItem) { var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment); JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog); } } }
using Atlassian.Jira; using TicketTimer.Core.Infrastructure; using TicketTimer.Jira.Extensions; namespace TicketTimer.Jira.Services { public class DefaultJiraService : JiraService { private readonly WorkItemStore _workItemStore; // TODO Insert correct parameters public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword"); public DefaultJiraService(WorkItemStore workItemStore) { _workItemStore = workItemStore; } public async void WriteEntireArchive() { var archive = _workItemStore.GetState().WorkItemArchive; foreach (var workItem in archive) { var jiraIssue = await JiraClient.Issues.GetIssueAsync(workItem.TicketNumber); if (jiraIssue != null) { TrackTime(workItem); } } } private void TrackTime(WorkItem workItem) { var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment); JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog); } } }
Allow getting a user env variable
using System; using System.Threading.Tasks; using Sdl.Community.GroupShareKit.Clients; using Sdl.Community.GroupShareKit.Http; namespace Sdl.Community.GroupShareKit.Tests.Integration { public static class Helper { public static async Task<GroupShareClient> GetGroupShareClient() { var groupShareUser = Environment.GetEnvironmentVariable("GROUPSHAREKIT_USERNAME"); var groupSharePassword = Environment.GetEnvironmentVariable("GROUPSHAREKIT_PASSWORD"); var token = await GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri, GroupShareClient.AllScopes); var gsClient = await GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri, GroupShareClient.AllScopes); return gsClient; } public static Uri BaseUri => new Uri(Environment.GetEnvironmentVariable("GROUPSHAREKIT_BASEURI")); public static string TestOrganization => Environment.GetEnvironmentVariable("GROUPSHAREKIT_TESTORGANIZATION"); } }
using System; using System.Threading.Tasks; using Sdl.Community.GroupShareKit.Clients; using Sdl.Community.GroupShareKit.Http; namespace Sdl.Community.GroupShareKit.Tests.Integration { public static class Helper { public static string GetVariable(string key) { // by default it gets a process variable. Allow getting user as well return Environment.GetEnvironmentVariable(key) ?? Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User); } public static async Task<GroupShareClient> GetGroupShareClient() { var groupShareUser = Helper.GetVariable("GROUPSHAREKIT_USERNAME"); var groupSharePassword = Helper.GetVariable("GROUPSHAREKIT_PASSWORD"); var token = await GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri, GroupShareClient.AllScopes); var gsClient = await GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri, GroupShareClient.AllScopes); return gsClient; } public static Uri BaseUri => new Uri(Helper.GetVariable("GROUPSHAREKIT_BASEURI")); public static string TestOrganization => Helper.GetVariable("GROUPSHAREKIT_TESTORGANIZATION"); } }
Add a string extension to validate Email
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AnlabMvc.Extensions { public static class StringExtensions { public static string PaymentMethodDescription(this string value) { if (string.Equals(value, "uc", StringComparison.OrdinalIgnoreCase)) { return "UC Account"; } if (string.Equals(value, "creditcard", StringComparison.OrdinalIgnoreCase)) { return "Credit Card"; } return "Other"; } public static string MaxLength(this string value, int maxLength, bool ellipsis = true) { if (string.IsNullOrWhiteSpace(value)) { return value; } if (value.Length > maxLength) { if (ellipsis) { return $"{value.Substring(0, maxLength - 3)}..."; } return value.Substring(0, maxLength); } return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AnlabMvc.Extensions { public static class StringExtensions { const string emailRegex = @"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"; public static string PaymentMethodDescription(this string value) { if (string.Equals(value, "uc", StringComparison.OrdinalIgnoreCase)) { return "UC Account"; } if (string.Equals(value, "creditcard", StringComparison.OrdinalIgnoreCase)) { return "Credit Card"; } return "Other"; } public static string MaxLength(this string value, int maxLength, bool ellipsis = true) { if (string.IsNullOrWhiteSpace(value)) { return value; } if (value.Length > maxLength) { if (ellipsis) { return $"{value.Substring(0, maxLength - 3)}..."; } return value.Substring(0, maxLength); } return value; } public static bool IsEmailValid(this string value) { if (string.IsNullOrWhiteSpace(value)) { return false; } return Regex.IsMatch(value.ToLower(), emailRegex); } } }
Allow indices to be stored for .net assemblies.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { [ExportWorkspaceService(typeof(IAssemblySerializationInfoService), ServiceLayer.Host)] [Shared] internal class AssemblySerializationInfoService : IAssemblySerializationInfoService { public bool Serializable(Solution solution, string assemblyFilePath) { if (assemblyFilePath == null || !File.Exists(assemblyFilePath) || !ReferencePathUtilities.PartOfFrameworkOrReferencePaths(assemblyFilePath)) { return false; } // if solution is not from a disk, just create one. if (solution.FilePath == null || !File.Exists(solution.FilePath)) { return false; } return true; } public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version) { prefix = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath); version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath)); return true; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { [ExportWorkspaceService(typeof(IAssemblySerializationInfoService), ServiceLayer.Host)] [Shared] internal class AssemblySerializationInfoService : IAssemblySerializationInfoService { public bool Serializable(Solution solution, string assemblyFilePath) { if (assemblyFilePath == null || !File.Exists(assemblyFilePath)) { return false; } // if solution is not from a disk, just create one. if (solution.FilePath == null || !File.Exists(solution.FilePath)) { return false; } return true; } public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version) { prefix = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath); version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath)); return true; } } }
Increase timeout to prevent cibuild failures
namespace TestableFileSystem.Fakes.Tests.Specs.FakeWatcher { public abstract class WatcherSpecs { protected const int NotifyWaitTimeoutMilliseconds = 500; protected const int SleepTimeToEnsureOperationHasArrivedAtWatcherConsumerLoop = 250; // TODO: Add specs for File.Encrypt/Decrypt, File.Lock/Unlock, File.Replace, Begin+EndRead/Write // TODO: Add specs for Directory.GetLogicalDrives } }
namespace TestableFileSystem.Fakes.Tests.Specs.FakeWatcher { public abstract class WatcherSpecs { protected const int NotifyWaitTimeoutMilliseconds = 1000; protected const int SleepTimeToEnsureOperationHasArrivedAtWatcherConsumerLoop = 250; // TODO: Add specs for File.Encrypt/Decrypt, File.Lock/Unlock, File.Replace, Begin+EndRead/Write // TODO: Add specs for Directory.GetLogicalDrives } }
Change the wait example to a mock login page.
@{ ViewBag.Title = "ComboLoad"; } <div class="row"> <div class="col-md-12"> <h2>Example page for testing waits</h2> <p>The following combo starts with a placeholder option and after 3 seconds updates with a new item.</p> <select id="combo" > <option>Placeholder</option> </select> </div> </div> @section scripts { <script> $(document).ready(function () { var combo = $("#combo"); // Simulate loading the combo items from another source. // Wait 3 seconds then update the combo. setTimeout(function () { combo.empty(); combo.append( $("<option id=\"loaded\"></option>").text("Loaded") ); }, 3 * 1000); }); </script> }
@{ ViewBag.Title = "ComboLoad"; } <div class="row"> <div class="col-md-12"> <h2>Example page for testing waits</h2> <p class="alert alert-danger" id="message" style="display:none"></p> <div> <div class="form-group"> <label for="username">Username</label> <input type="email" class="form-control" id="username" placeholder="Username"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" placeholder="Password"> </div> <button type="button" class="btn btn-default" id="login">Log in</button> </div> </div> </div> @section scripts { <script> $(document).ready(function () { var loginButton = $("#login"); loginButton.on("click", function () { var usernameTxt = $("#username"), username = usernameTxt[0].value passwordTxt = $("#password"), password = passwordTxt[0].value; // Timeout to simulate making login request. setTimeout(function () { if (username === "user" && password === "password") { window.location = "/"; } else { var messageContainer = $("#message"); messageContainer.text("Invalid username and password.") messageContainer.css("display", ""); } }, 2 * 1000); }); }); </script> }
Fix bug where repo name was used instead of organization in the links.
using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { return -1; } AsyncContext.Run(() => MainAsync(options)); //Console.WriteLine("*** Press ENTER to Exit ***"); //Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi(options.Organization, options.Repository); var milestones = await github.GetOpenMilestones(); foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30)) { var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone); DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { if(options.LinkIssues) Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Repository}/{options.Repository}/issues/{issue.Number}) {issue.Title}"); else Console.WriteLine($" * {issue.Number:####} {issue.Title}"); } Console.WriteLine(); } } }
using Nito.AsyncEx; using Octokit; using System; using System.Collections.Generic; using System.Linq; namespace Alteridem.GetChanges { class Program { static int Main(string[] args) { var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { return -1; } AsyncContext.Run(() => MainAsync(options)); //Console.WriteLine("*** Press ENTER to Exit ***"); //Console.ReadLine(); return 0; } static async void MainAsync(Options options) { var github = new GitHubApi(options.Organization, options.Repository); var milestones = await github.GetOpenMilestones(); foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30)) { var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone); DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues); } } static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues) { Console.WriteLine("## {0}", milestone); Console.WriteLine(); foreach (var issue in issues) { if(options.LinkIssues) Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}"); else Console.WriteLine($" * {issue.Number:####} {issue.Title}"); } Console.WriteLine(); } } }
Add note about what your dod is
using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Web.Models { public class RequestAccessModel { public String Name { get; set; } public String Email { get; set; } [Display(Name = "DOD ID")] public String DoDId { get; set; } public int Unit { get; set; } public IEnumerable<SelectListItem> Units { get; set; } } }
using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BatteryCommander.Web.Models { public class RequestAccessModel { public String Name { get; set; } public String Email { get; set; } [Display(Name = "DOD ID (10 Digits, On Your CAC)")] public String DoDId { get; set; } public int Unit { get; set; } public IEnumerable<SelectListItem> Units { get; set; } } }
Write out raw HTML if SubMessage contains any
@using SFA.DAS.EAS.Web @using SFA.DAS.EAS.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message) || !string.IsNullOrEmpty(viewModel?.FlashMessage?.SubMessage)) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="@(viewModel.FlashMessage.Severity == FlashMessageSeverityLevel.Error ? "bold-medium" : "bold-large")">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@Html.Raw(viewModel.FlashMessage.Message)</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@viewModel.FlashMessage.SubMessage</p> } @if (viewModel.FlashMessage.ErrorMessages.Any()) { <ul class="error-summary-list"> @foreach (var errorMessage in viewModel.FlashMessage.ErrorMessages) { <li> <a class="danger" href="#@errorMessage.Key">@errorMessage.Value</a> </li> } </ul> } </div> </div> </div> }
@using SFA.DAS.EAS.Web @using SFA.DAS.EAS.Web.Models @model dynamic @{ var viewModel = Model as OrchestratorResponse; } @if (!string.IsNullOrEmpty(viewModel?.FlashMessage?.Message) || !string.IsNullOrEmpty(viewModel?.FlashMessage?.SubMessage)) { <div class="grid-row"> <div class="column-full"> <div class="@viewModel.FlashMessage.SeverityCssClass"> @if (!string.IsNullOrWhiteSpace(viewModel.FlashMessage.Headline)) { <h1 class="@(viewModel.FlashMessage.Severity == FlashMessageSeverityLevel.Error ? "bold-medium" : "bold-large")">@viewModel.FlashMessage.Headline</h1> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.Message)) { <p>@Html.Raw(viewModel.FlashMessage.Message)</p> } @if (!string.IsNullOrEmpty(viewModel.FlashMessage.SubMessage)) { <p>@Html.Raw(viewModel.FlashMessage.SubMessage)</p> } @if (viewModel.FlashMessage.ErrorMessages.Any()) { <ul class="error-summary-list"> @foreach (var errorMessage in viewModel.FlashMessage.ErrorMessages) { <li> <a class="danger" href="#@errorMessage.Key">@errorMessage.Value</a> </li> } </ul> } </div> </div> </div> }
Rename types in test code.
namespace Gu.Roslyn.Asserts.Tests.Net472WithAttributes { using Gu.Roslyn.Asserts.Tests.Net472WithAttributes.AnalyzersAndFixes; using NUnit.Framework; public partial class RoslynAssertTests { [Test] public void ResetMetadataReferences() { CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences); RoslynAssert.MetadataReferences.Clear(); CollectionAssert.IsEmpty(RoslynAssert.MetadataReferences); RoslynAssert.ResetMetadataReferences(); CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences); } [Test] public void CodeFixSingleClassOneErrorCorrectFix() { var before = @" namespace RoslynSandbox { class Foo { private readonly int ↓_value; } }"; var after = @" namespace RoslynSandbox { class Foo { private readonly int value; } }"; var analyzer = new FieldNameMustNotBeginWithUnderscore(); var fix = new DontUseUnderscoreCodeFixProvider(); RoslynAssert.CodeFix(analyzer, fix, before, after); } } }
namespace Gu.Roslyn.Asserts.Tests.Net472WithAttributes { using Gu.Roslyn.Asserts.Tests.Net472WithAttributes.AnalyzersAndFixes; using NUnit.Framework; public partial class RoslynAssertTests { [Test] public void ResetMetadataReferences() { CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences); RoslynAssert.MetadataReferences.Clear(); CollectionAssert.IsEmpty(RoslynAssert.MetadataReferences); RoslynAssert.ResetMetadataReferences(); CollectionAssert.IsNotEmpty(RoslynAssert.MetadataReferences); } [Test] public void CodeFixSingleClassOneErrorCorrectFix() { var before = @" namespace RoslynSandbox { class C { private readonly int ↓_value; } }"; var after = @" namespace RoslynSandbox { class C { private readonly int value; } }"; var analyzer = new FieldNameMustNotBeginWithUnderscore(); var fix = new DontUseUnderscoreCodeFixProvider(); RoslynAssert.CodeFix(analyzer, fix, before, after); } } }
Make the chat input only update when enter is not pressed
using LmpClient.Localization; using LmpClient.Systems.Chat; using UnityEngine; namespace LmpClient.Windows.Chat { public partial class ChatWindow { private static string _chatInputText = string.Empty; protected override void DrawWindowContent(int windowId) { var pressedEnter = Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n'; GUILayout.BeginVertical(); GUI.DragWindow(MoveRect); DrawChatMessageBox(); DrawTextInput(pressedEnter); GUILayout.Space(5); GUILayout.EndVertical(); } private static void DrawChatMessageBox() { GUILayout.BeginHorizontal(); _chatScrollPos = GUILayout.BeginScrollView(_chatScrollPos); GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); foreach (var channelMessage in ChatSystem.Singleton.ChatMessages) GUILayout.Label(channelMessage); GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndHorizontal(); } private static void DrawTextInput(bool pressedEnter) { GUILayout.BeginHorizontal(); _chatInputText = GUILayout.TextArea(_chatInputText); if (pressedEnter || GUILayout.Button(LocalizationContainer.ChatWindowText.Send, GUILayout.Width(WindowWidth * .25f))) { if (!string.IsNullOrEmpty(_chatInputText)) { ChatSystem.Singleton.MessageSender.SendChatMsg(_chatInputText.Trim('\n')); } _chatInputText = string.Empty; } GUILayout.EndHorizontal(); } } }
using LmpClient.Localization; using LmpClient.Systems.Chat; using UnityEngine; namespace LmpClient.Windows.Chat { public partial class ChatWindow { private static string _chatInputText = string.Empty; protected override void DrawWindowContent(int windowId) { var pressedEnter = Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n'; GUILayout.BeginVertical(); GUI.DragWindow(MoveRect); DrawChatMessageBox(); DrawTextInput(pressedEnter); GUILayout.Space(5); GUILayout.EndVertical(); } private static void DrawChatMessageBox() { GUILayout.BeginHorizontal(); _chatScrollPos = GUILayout.BeginScrollView(_chatScrollPos); GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); foreach (var channelMessage in ChatSystem.Singleton.ChatMessages) GUILayout.Label(channelMessage); GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndHorizontal(); } private static void DrawTextInput(bool pressedEnter) { GUILayout.BeginHorizontal(); if (pressedEnter || GUILayout.Button(LocalizationContainer.ChatWindowText.Send, GUILayout.Width(WindowWidth * .25f))) { if (!string.IsNullOrEmpty(_chatInputText)) { ChatSystem.Singleton.MessageSender.SendChatMsg(_chatInputText.Trim('\n')); } _chatInputText = string.Empty; } else { _chatInputText = GUILayout.TextArea(_chatInputText); } GUILayout.EndHorizontal(); } } }
Add tooltips and extract inspector classes
using UnityEngine; using System.Collections; using UnityEditor; using OneDayGame; namespace DisableAfterTimeEx { [CustomEditor(typeof (DisableAfterTime))] public class DisableAfterTimeEditor : Editor { private SerializedProperty targetGO; private SerializedProperty delay; private void OnEnable() { targetGO = serializedObject.FindProperty("targetGO"); delay = serializedObject.FindProperty("delay"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(targetGO); EditorGUILayout.PropertyField(delay); serializedObject.ApplyModifiedProperties(); } } }
using UnityEngine; using System.Collections; using UnityEditor; using OneDayGame; namespace DisableAfterTimeEx { [CustomEditor(typeof (DisableAfterTime))] public class DisableAfterTimeEditor : Editor { private SerializedProperty targetGO; private SerializedProperty delay; private void OnEnable() { targetGO = serializedObject.FindProperty("targetGO"); delay = serializedObject.FindProperty("delay"); } public override void OnInspectorGUI() { serializedObject.Update(); DrawTargetGOField(); DrawDelayField(); serializedObject.ApplyModifiedProperties(); } private void DrawDelayField() { EditorGUILayout.PropertyField( delay, new GUIContent( "Delay", "Delay before disabling target game object.")); } private void DrawTargetGOField() { EditorGUILayout.PropertyField( targetGO, new GUIContent( "Target", "Game object to be disabled.")); } } }
Reset console color on exit.
using System; using System.Diagnostics; using EasyHook; namespace LxRunOffline { class Program { static void Main(string[] args) { int pId = 0; try { RemoteHooking.CreateAndInject(@"C:\Windows\System32\LxRun.exe", string.Join(" ", args), 0, "LxRunHook.dll", "LxRunHook.dll", out pId); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Error: Failed to launch LxRun."); Console.WriteLine(e); Environment.Exit(-1); } var process = Process.GetProcessById(pId); process.WaitForExit(); } } }
using System; using System.Diagnostics; using EasyHook; namespace LxRunOffline { class Program { static void Main(string[] args) { int pId = 0; try { RemoteHooking.CreateAndInject(@"C:\Windows\System32\LxRun.exe", string.Join(" ", args), 0, "LxRunHook.dll", "LxRunHook.dll", out pId); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Error: Failed to launch LxRun."); Console.WriteLine(e); Console.ResetColor(); Environment.Exit(-1); } var process = Process.GetProcessById(pId); process.WaitForExit(); } } }
Allow suppression of colour for specific glyphs.
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace QuickFont { public sealed class QFontGlyph { /// <summary> /// Which texture page the glyph is on /// </summary> public int Page { get; private set; } /// <summary> /// The rectangle defining the glyphs position on the page /// </summary> public Rectangle Rect { get; set; } /// <summary> /// How far the glyph would need to be vertically offset to be vertically in line with the tallest glyph in the set of all glyphs /// </summary> public int YOffset { get; set; } /// <summary> /// Which character this glyph represents /// </summary> public char Character { get; private set; } public QFontGlyph (int page, Rectangle rect, int yOffset, char character) { Page = page; Rect = rect; YOffset = yOffset; Character = character; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace QuickFont { public sealed class QFontGlyph { /// <summary> /// Which texture page the glyph is on /// </summary> public int Page { get; private set; } /// <summary> /// The rectangle defining the glyphs position on the page /// </summary> public Rectangle Rect { get; set; } /// <summary> /// How far the glyph would need to be vertically offset to be vertically in line with the tallest glyph in the set of all glyphs /// </summary> public int YOffset { get; set; } /// <summary> /// Which character this glyph represents /// </summary> public char Character { get; private set; } /// <summary> /// Indicates whether colouring should be suppressed for this glyph. /// </summary> /// <value><c>true</c> if suppress colouring; otherwise, <c>false</c>.</value> public bool SuppressColouring { get; set; } public QFontGlyph (int page, Rectangle rect, int yOffset, char character) { Page = page; Rect = rect; YOffset = yOffset; Character = character; } } }
Move config.Configure to BeforeStart which gives the overloads the chance to change it before it throw because it dose not found an configuration.
using System; using System.Reflection; using Rhino.ServiceBus.Config; using Rhino.ServiceBus.Impl; namespace Rhino.ServiceBus.Hosting { public abstract class AbstractBootStrapper : IDisposable { private AbstractRhinoServiceBusConfiguration config; public virtual Assembly Assembly { get { return GetType().Assembly; } } public virtual void AfterStart() { } public virtual void InitializeContainer() { CreateContainer(); config = CreateConfiguration(); ConfigureBusFacility(config); config.Configure(); } public virtual void UseConfiguration(BusConfigurationSection configurationSection) { config.UseConfiguration(configurationSection); } public abstract void CreateContainer(); public abstract void ExecuteDeploymentActions(string user); public abstract void ExecuteEnvironmentValidationActions(); public abstract T GetInstance<T>(); protected virtual bool IsTypeAcceptableForThisBootStrapper(Type t) { return true; } protected virtual AbstractRhinoServiceBusConfiguration CreateConfiguration() { return new RhinoServiceBusConfiguration(); } protected virtual void ConfigureBusFacility(AbstractRhinoServiceBusConfiguration configuration) { } public virtual void BeforeStart() { } public abstract void Dispose(); } }
using System; using System.Reflection; using Rhino.ServiceBus.Config; using Rhino.ServiceBus.Impl; namespace Rhino.ServiceBus.Hosting { public abstract class AbstractBootStrapper : IDisposable { private AbstractRhinoServiceBusConfiguration config; public virtual Assembly Assembly { get { return GetType().Assembly; } } public virtual void InitializeContainer() { CreateContainer(); config = CreateConfiguration(); ConfigureBusFacility(config); } public virtual void UseConfiguration(BusConfigurationSection configurationSection) { config.UseConfiguration(configurationSection); } public abstract void CreateContainer(); public abstract void ExecuteDeploymentActions(string user); public abstract void ExecuteEnvironmentValidationActions(); public abstract T GetInstance<T>(); protected virtual bool IsTypeAcceptableForThisBootStrapper(Type t) { return true; } protected virtual AbstractRhinoServiceBusConfiguration CreateConfiguration() { return new RhinoServiceBusConfiguration(); } protected virtual void ConfigureBusFacility(AbstractRhinoServiceBusConfiguration configuration) { } public virtual void BeforeStart() { config.Configure(); } public virtual void AfterStart() { } public abstract void Dispose(); } }
Fix url of api test
using Bloom.Api; using Bloom.Book; using Bloom.Collection; using NUnit.Framework; namespace BloomTests.web { [TestFixture] public class ReadersApiTests { private EnhancedImageServer _server; [SetUp] public void Setup() { var bookSelection = new BookSelection(); bookSelection.SelectBook(new Bloom.Book.Book()); _server = new EnhancedImageServer(bookSelection); //needed to avoid a check in the server _server.CurrentCollectionSettings = new CollectionSettings(); var controller = new ReadersApi(bookSelection); controller.RegisterWithServer(_server); } [TearDown] public void TearDown() { _server.Dispose(); _server = null; } [Test] public void IsReceivingApiCalls() { var result = ApiTest.GetString(_server,"readers/test"); Assert.That(result, Is.EqualTo("OK")); } } }
using Bloom.Api; using Bloom.Book; using Bloom.Collection; using NUnit.Framework; namespace BloomTests.web { [TestFixture] public class ReadersApiTests { private EnhancedImageServer _server; [SetUp] public void Setup() { var bookSelection = new BookSelection(); bookSelection.SelectBook(new Bloom.Book.Book()); _server = new EnhancedImageServer(bookSelection); //needed to avoid a check in the server _server.CurrentCollectionSettings = new CollectionSettings(); var controller = new ReadersApi(bookSelection); controller.RegisterWithServer(_server); } [TearDown] public void TearDown() { _server.Dispose(); _server = null; } [Test] public void IsReceivingApiCalls() { var result = ApiTest.GetString(_server,"readers/io/test"); Assert.That(result, Is.EqualTo("OK")); } } }
Use the more consistent `lastVertex`, with a comment
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Catch.Objects; using osuTK; namespace osu.Game.Rulesets.Catch.Edit.Blueprints.Components { public class PlacementEditablePath : EditablePath { private JuiceStreamPathVertex originalNewVertex; public PlacementEditablePath(Func<float, double> positionToDistance) : base(positionToDistance) { } public void AddNewVertex() { var endVertex = Vertices[^1]; int index = AddVertex(endVertex.Distance, endVertex.X); for (int i = 0; i < VertexCount; i++) { VertexStates[i].IsSelected = i == index; VertexStates[i].VertexBeforeChange = Vertices[i]; } originalNewVertex = Vertices[index]; } /// <summary> /// Move the vertex added by <see cref="AddNewVertex"/> in the last time. /// </summary> public void MoveLastVertex(Vector2 screenSpacePosition) { Vector2 position = ToRelativePosition(screenSpacePosition); double distanceDelta = PositionToDistance(position.Y) - originalNewVertex.Distance; float xDelta = position.X - originalNewVertex.X; MoveSelectedVertices(distanceDelta, xDelta); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Rulesets.Catch.Objects; using osuTK; namespace osu.Game.Rulesets.Catch.Edit.Blueprints.Components { public class PlacementEditablePath : EditablePath { /// <summary> /// The original position of the last added vertex. /// This is not same as the last vertex of the current path because the vertex ordering can change. /// </summary> private JuiceStreamPathVertex lastVertex; public PlacementEditablePath(Func<float, double> positionToDistance) : base(positionToDistance) { } public void AddNewVertex() { var endVertex = Vertices[^1]; int index = AddVertex(endVertex.Distance, endVertex.X); for (int i = 0; i < VertexCount; i++) { VertexStates[i].IsSelected = i == index; VertexStates[i].VertexBeforeChange = Vertices[i]; } lastVertex = Vertices[index]; } /// <summary> /// Move the vertex added by <see cref="AddNewVertex"/> in the last time. /// </summary> public void MoveLastVertex(Vector2 screenSpacePosition) { Vector2 position = ToRelativePosition(screenSpacePosition); double distanceDelta = PositionToDistance(position.Y) - lastVertex.Distance; float xDelta = position.X - lastVertex.X; MoveSelectedVertices(distanceDelta, xDelta); } } }
Fix room password not being percent-encoded in join request
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; return req; } // Todo: Password needs to be specified here rather than via AddParameter() because this is a PUT request. May be a framework bug. protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}?password={Password}"; } }
// 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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; req.AddParameter(@"password", Password, RequestParameterType.Query); return req; } protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}"; } }
Disable document selection by id.
using System.ComponentModel.Composition; namespace Flood.Editor.Controls { class ToolClose : EditorTool, BarTool { [Import] DocumentManager docManager; public void OnSelect() { if (docManager.Current != null) docManager.Close(docManager.Current.Id); } public string Text { get { return "Close"; } } public string Image { get { return "close.png"; } } } }
using System.ComponentModel.Composition; namespace Flood.Editor.Controls { class ToolClose : EditorTool, BarTool { [Import] DocumentManager docManager; public void OnSelect() { //if (docManager.Current != null) // docManager.Close(docManager.Current.Id); } public string Text { get { return "Close"; } } public string Image { get { return "close.png"; } } } }
Add deleted and copied to the parsed statuses
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitDataExplorer.Results.Commits; namespace GitDataExplorer.Results { class ListSimpleCommitsResult : IResult { public ExecutionResult ExecutionResult { get; private set; } public IList<SimpleCommitResult> Commits { get; } = new List<SimpleCommitResult>(); public void ParseResult(IList<string> lines) { var tmpList = new List<string>(); foreach (var line in lines) { if (line.StartsWith("A") || line.StartsWith("M") || line.StartsWith("R")) { tmpList.Add(line); } else { if (tmpList.Count > 0) { var result = new SimpleCommitResult(); result.ParseResult(tmpList); Commits.Add(result); } tmpList.Clear(); tmpList.Add(line); } } if (tmpList.Count > 0) { var result = new SimpleCommitResult(); result.ParseResult(tmpList); Commits.Add(result); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitDataExplorer.Results.Commits; namespace GitDataExplorer.Results { class ListSimpleCommitsResult : IResult { private char[] statusLetters = { 'M', 'A', 'R', 'C', 'D' }; public ExecutionResult ExecutionResult { get; private set; } public IList<SimpleCommitResult> Commits { get; } = new List<SimpleCommitResult>(); public void ParseResult(IList<string> lines) { var tmpList = new List<string>(); foreach (var line in lines) { if (Array.IndexOf(statusLetters, line[0]) >= 0) { tmpList.Add(line); } else { if (tmpList.Count > 0) { var result = new SimpleCommitResult(); result.ParseResult(tmpList); Commits.Add(result); } tmpList.Clear(); tmpList.Add(line); } } if (tmpList.Count > 0) { var result = new SimpleCommitResult(); result.ParseResult(tmpList); Commits.Add(result); } } } }
Add missing Nullable example
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ShouldStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
namespace Nilgiri.Examples { using Xunit; using Nilgiri.Tests.Common; using static Nilgiri.ShouldStyle; public partial class ExampleOf_Should { public class Not_Be_Ok { [Fact] public void Int32() { _(0).Should.Not.Be.Ok(); _(() => 0).Should.Not.Be.Ok(); } [Fact] public void Nullable() { _((bool?)false).Should.Not.Be.Ok(); _(() => (bool?)false).Should.Not.Be.Ok(); _((bool?)null).Should.Not.Be.Ok(); _(() => (bool?)null).Should.Not.Be.Ok(); } [Fact] public void String() { _((string)null).Should.Not.Be.Ok(); _(() => (string)null).Should.Not.Be.Ok(); _(System.String.Empty).Should.Not.Be.Ok(); _(() => System.String.Empty).Should.Not.Be.Ok(); _("").Should.Not.Be.Ok(); _(() => "").Should.Not.Be.Ok(); _(" ").Should.Not.Be.Ok(); _(() => " ").Should.Not.Be.Ok(); } [Fact] public void ReferenceTypes() { _((StubClass)null).Should.Not.Be.Ok(); _(() => (StubClass)null).Should.Not.Be.Ok(); } } } }
Change "Search" "Frame Padding" option default value
using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } [Category("Behavior (Hideable)")] [DisplayName("Hide On Search")] public bool HideOnSearch { get; set; } = true; } }
using System.ComponentModel; using System.Windows; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 150; Style.FramePadding = new Thickness(0); } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } [Category("Behavior (Hideable)")] [DisplayName("Hide On Search")] public bool HideOnSearch { get; set; } = true; } }
Set continuation opcode for non-first frames in the writer
using System; using System.Threading; using System.Threading.Tasks; namespace wslib.Protocol.Writer { public class WsMessageWriter : IDisposable { private readonly MessageType messageType; private readonly Action onDispose; private readonly IWsMessageWriteStream stream; public WsMessageWriter(MessageType messageType, Action onDispose, IWsMessageWriteStream stream) { this.messageType = messageType; this.onDispose = onDispose; this.stream = stream; } public Task WriteFrame(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var header = generateFrameHeader(false); // TODO: change opcode to continuation return stream.WriteFrame(header, buffer, offset, count, cancellationToken); } public Task CloseMessageAsync(CancellationToken cancellationToken) { var header = generateFrameHeader(true); return stream.WriteFrame(header, new byte[0], 0, 0, cancellationToken); } public Task WriteMessageAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var header = generateFrameHeader(true); return stream.WriteFrame(header, buffer, offset, count, cancellationToken); } private WsFrameHeader generateFrameHeader(bool finFlag) { var opcode = messageType == MessageType.Text ? WsFrameHeader.Opcodes.TEXT : WsFrameHeader.Opcodes.BINARY; return new WsFrameHeader { FIN = finFlag, OPCODE = opcode }; } public void Dispose() { stream.Dispose(); onDispose(); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace wslib.Protocol.Writer { public class WsMessageWriter : IDisposable { private readonly MessageType messageType; private readonly Action onDispose; private readonly IWsMessageWriteStream stream; private bool firstFrame = true; public WsMessageWriter(MessageType messageType, Action onDispose, IWsMessageWriteStream stream) { this.messageType = messageType; this.onDispose = onDispose; this.stream = stream; } public Task WriteFrameAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var header = generateFrameHeader(false); firstFrame = false; return stream.WriteFrame(header, buffer, offset, count, cancellationToken); } public Task CloseMessageAsync(CancellationToken cancellationToken) { var header = generateFrameHeader(true); return stream.WriteFrame(header, new byte[0], 0, 0, cancellationToken); } public Task WriteMessageAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var header = generateFrameHeader(true); return stream.WriteFrame(header, buffer, offset, count, cancellationToken); } private WsFrameHeader generateFrameHeader(bool finFlag) { var opcode = firstFrame ? (messageType == MessageType.Text ? WsFrameHeader.Opcodes.TEXT : WsFrameHeader.Opcodes.BINARY) : WsFrameHeader.Opcodes.CONTINUATION; return new WsFrameHeader { FIN = finFlag, OPCODE = opcode }; } public void Dispose() { stream.Dispose(); onDispose(); } } }
Use string instead of String.
using System; using System.Collections.Generic; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException(nameof(file)); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(String pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public String ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
using System; using System.Collections.Generic; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException(nameof(file)); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(string pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public string ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
Add Support for MysqlConnector 1 namespace changes
#region License // Copyright (c) 2007-2018, FluentMigrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; namespace FluentMigrator.Runner.Processors.MySql { public class MySqlDbFactory : ReflectionBasedDbFactory { private static readonly TestEntry[] _entries = { new TestEntry("MySql.Data", "MySql.Data.MySqlClient.MySqlClientFactory"), new TestEntry("MySqlConnector", "MySql.Data.MySqlClient.MySqlClientFactory"), }; [Obsolete] public MySqlDbFactory() : this(serviceProvider: null) { } public MySqlDbFactory(IServiceProvider serviceProvider) : base(serviceProvider, _entries) { } } }
#region License // Copyright (c) 2007-2018, FluentMigrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; namespace FluentMigrator.Runner.Processors.MySql { public class MySqlDbFactory : ReflectionBasedDbFactory { private static readonly TestEntry[] _entries = { new TestEntry("MySql.Data", "MySql.Data.MySqlClient.MySqlClientFactory"), new TestEntry("MySqlConnector", "MySql.Data.MySqlClient.MySqlClientFactory"), new TestEntry("MySqlConnector", "MySqlConnector.MySqlConnectorFactory") }; [Obsolete] public MySqlDbFactory() : this(serviceProvider: null) { } public MySqlDbFactory(IServiceProvider serviceProvider) : base(serviceProvider, _entries) { } } }
Use lowered transform value in hash computing
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace RestImageResize.Security { public class HashGenerator { public string ComputeHash(string privateKey, int width, int height, ImageTransform transform) { var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString() }; var bytes = Encoding.ASCII.GetBytes(string.Join(":", values)); var sha1 = SHA1.Create(); sha1.ComputeHash(bytes); return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace RestImageResize.Security { public class HashGenerator { public string ComputeHash(string privateKey, int width, int height, ImageTransform transform) { var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString().ToLower() }; var bytes = Encoding.ASCII.GetBytes(string.Join(":", values)); var sha1 = SHA1.Create(); sha1.ComputeHash(bytes); return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower(); } } }
Improve form safe name regex
using System.Text.RegularExpressions; namespace FormEditor { public static class FieldHelper { private static readonly Regex FormSafeNameRegex = new Regex("[ -]", RegexOptions.Compiled); public static string FormSafeName(string name) { return FormSafeNameRegex.Replace(name ?? string.Empty, "_"); } } }
using System.Text.RegularExpressions; namespace FormEditor { public static class FieldHelper { private static readonly Regex FormSafeNameRegex = new Regex("[^a-zA-Z0-9_]", RegexOptions.Compiled); public static string FormSafeName(string name) { return FormSafeNameRegex.Replace(name ?? string.Empty, "_"); } } }
Improve performance of puzzle 10
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } Answer = ParallelEnumerable.Range(2, max - 2) .Where((p) => Maths.IsPrime(p)) .Select((p) => (long)p) .Sum(); return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle010 : Puzzle { /// <inheritdoc /> public override string Question => "Find the sum of all the primes below the specified value."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int max; if (!TryParseInt32(args[0], out max) || max < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } long sum = ParallelEnumerable.Range(3, max - 3) .Where((p) => p % 2 != 0) .Where((p) => Maths.IsPrime(p)) .Select((p) => (long)p) .Sum(); Answer = sum + 2; return 0; } } }
Fix a http request issues.
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
using System; using System.IO; using System.Net; using System.Text; using Wox.Plugin; namespace Wox.Infrastructure.Http { public class HttpRequest { public static string Get(string url, string encoding = "UTF-8") { return Get(url, encoding, HttpProxy.Instance); } private static string Get(string url, string encoding, IHttpProxy proxy) { if (string.IsNullOrEmpty(url)) return string.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Timeout = 10 * 1000; if (proxy != null && proxy.Enabled && !string.IsNullOrEmpty(proxy.Server)) { if (string.IsNullOrEmpty(proxy.UserName) || string.IsNullOrEmpty(proxy.Password)) { request.Proxy = new WebProxy(proxy.Server, proxy.Port); } else { request.Proxy = new WebProxy(proxy.Server, proxy.Port) { Credentials = new NetworkCredential(proxy.UserName, proxy.Password) }; } } try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response != null) { Stream stream = response.GetResponseStream(); if (stream != null) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { return reader.ReadToEnd(); } } } } catch (Exception e) { return string.Empty; } return string.Empty; } } }
Make consistent and add a comment for clarification
@model OrderModifyModel @{ var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}}; var submitText = submitMap[ViewBag.Title]; var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty; } <section id="order-submit-section"> <div class="section-contents"> @if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer)) { <div class="section-text"> <p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p> </div> } <ul> <li><div class="editor-label">&nbsp;</div> <div class="editor-field"> <input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/> | @if (submitText == "Create") { <input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text> } @Html.ActionLink("Cancel", "Landing", "Home", null, new {id="order-cancel"}) </div> </li> </ul> </div>
@model OrderModifyModel @{ var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}}; var submitText = submitMap[ViewBag.Title]; var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty; } <section id="order-submit-section"> <div class="section-contents"> @if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer)) { <div class="section-text"> <p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p> </div> } <ul> <li><div class="editor-label">&nbsp;</div> <div class="editor-field"> <input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/> | @if (submitText == "Create") { <input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text> } @Html.ActionLink("Cancel", "Landing", "Home", new {}, new {id="order-cancel"}) @*This id is an element so the local storage gets cleared out. It is not a route value.*@ </div> </li> </ul> </div>
Remove nameof operator because it caused a build error in AppHarbor
using System; using System.Web.Mvc; namespace Website.Security { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class EnforceHttpsAttribute : RequireHttpsAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if(filterContext == null) { throw new ArgumentNullException(nameof(filterContext)); } if(filterContext.HttpContext.Request.IsSecureConnection) { return; } if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase)) { return; } if(filterContext.HttpContext.Request.IsLocal) { return; } HandleNonHttpsRequest(filterContext); } } }
using System; using System.Web.Mvc; namespace Website.Security { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class EnforceHttpsAttribute : RequireHttpsAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if(filterContext == null) { throw new ArgumentNullException("filterContext"); } if(filterContext.HttpContext.Request.IsSecureConnection) { return; } if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase)) { return; } if(filterContext.HttpContext.Request.IsLocal) { return; } HandleNonHttpsRequest(filterContext); } } }
Change test settings default Redis Db
using System.Collections.Generic; using CacheSleeve.Tests.TestObjects; namespace CacheSleeve.Tests { public static class TestSettings { public static string RedisHost = "localhost"; public static int RedisPort = 6379; public static string RedisPassword = null; public static int RedisDb = 0; public static string KeyPrefix = "cs."; // don't mess with George.. you'll break a lot of tests public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }}; } }
using System.Collections.Generic; using CacheSleeve.Tests.TestObjects; namespace CacheSleeve.Tests { public static class TestSettings { public static string RedisHost = "localhost"; public static int RedisPort = 6379; public static string RedisPassword = null; public static int RedisDb = 5; public static string KeyPrefix = "cs."; // don't mess with George.. you'll break a lot of tests public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }}; } }
Add configuration options for HMRC to use MI Feed
namespace SFA.DAS.EAS.Domain.Configuration { public class HmrcConfiguration { public string BaseUrl { get; set; } public string ClientId { get; set; } public string Scope { get; set; } public string ClientSecret { get; set; } public string ServerToken { get; set; } public string OgdSecret { get; set; } public string OgdClientId { get; set; } } }
namespace SFA.DAS.EAS.Domain.Configuration { public class HmrcConfiguration { public string BaseUrl { get; set; } public string ClientId { get; set; } public string Scope { get; set; } public string ClientSecret { get; set; } public string ServerToken { get; set; } public string OgdSecret { get; set; } public string OgdClientId { get; set; } public string AzureClientId { get; set; } public string AzureAppKey { get; set; } public string AzureResourceId { get; set; } public string AzureTenant { get; set; } public bool UseHiDataFeed { get; set; } } }
Add group support for NoVehiclesUsage
using System.Collections.Generic; using Rocket.Unturned.Player; using RocketRegions.Util; using SDG.Unturned; using UnityEngine; namespace RocketRegions.Model.Flag.Impl { public class NoVehiclesUsageFlag : BoolFlag { public override string Description => "Allow/Disallow usage of vehicles in region"; private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>(); public override void UpdateState(List<UnturnedPlayer> players) { foreach (var player in players) { var id = PlayerUtil.GetId(player); var veh = player.Player.movement.getVehicle(); var isInVeh = veh != null; if (!_lastVehicleStates.ContainsKey(id)) _lastVehicleStates.Add(id, veh); var wasDriving = _lastVehicleStates[id]; if (!isInVeh || wasDriving || !GetValueSafe(Region.GetGroup(player))) continue; byte seat; Vector3 point; byte angle; veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle); veh.removePlayer(seat, point, angle, true); } } public override void OnRegionEnter(UnturnedPlayer p) { //do nothing } public override void OnRegionLeave(UnturnedPlayer p) { //do nothing } } }
using System.Collections.Generic; using Rocket.Unturned.Player; using RocketRegions.Util; using SDG.Unturned; using UnityEngine; namespace RocketRegions.Model.Flag.Impl { public class NoVehiclesUsageFlag : BoolFlag { public override string Description => "Allow/Disallow usage of vehicles in region"; public override bool SupportsGroups => true; private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>(); public override void UpdateState(List<UnturnedPlayer> players) { foreach (var player in players) { var group = Region.GetGroup(player); if(!GetValueSafe(group)) continue; var id = PlayerUtil.GetId(player); var veh = player.Player.movement.getVehicle(); var isInVeh = veh != null; if (!_lastVehicleStates.ContainsKey(id)) _lastVehicleStates.Add(id, veh); var wasDriving = _lastVehicleStates[id]; if (!isInVeh || wasDriving || !GetValueSafe(Region.GetGroup(player))) continue; byte seat; Vector3 point; byte angle; veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle); veh.removePlayer(seat, point, angle, true); } } public override void OnRegionEnter(UnturnedPlayer p) { //do nothing } public override void OnRegionLeave(UnturnedPlayer p) { //do nothing } } }