Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add AtataContextBuilder_OnBuilding and AtataContextBuilder_OnBuilding_WithoutDriver tests | using System;
using NUnit.Framework;
namespace Atata.Tests
{
public class AtataContextBuilderTests : UITestFixtureBase
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
[Test]
public void AtataContextBuilder_OnDriverCreated()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(driver =>
{
executionsCount++;
}).
Build();
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnDriverCreated_RestartDriver()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(() =>
{
executionsCount++;
}).
Build();
AtataContext.Current.RestartDriver();
Assert.That(executionsCount, Is.EqualTo(2));
}
}
}
| using System;
using NUnit.Framework;
namespace Atata.Tests
{
public class AtataContextBuilderTests : UITestFixtureBase
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
[Test]
public void AtataContextBuilder_OnBuilding()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnBuilding(() => executionsCount++).
Build();
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnBuilding_WithoutDriver()
{
int executionsCount = 0;
Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().
UseDriver(() => null).
OnBuilding(() => executionsCount++).
Build());
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnDriverCreated()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(driver => executionsCount++).
Build();
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnDriverCreated_RestartDriver()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(() => executionsCount++).
Build();
AtataContext.Current.RestartDriver();
Assert.That(executionsCount, Is.EqualTo(2));
}
}
}
|
Remove extra config param that's not used | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Default services
/// </summary>
public class IdentityEntityFrameworkServices
{
public static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType = null, IConfiguration config = null)
{
Type userStoreType;
Type roleStoreType;
if (keyType != null)
{
userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
}
else
{
userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType);
roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, contextType);
}
var services = new ServiceCollection();
services.AddScoped(
typeof(IUserStore<>).MakeGenericType(userType),
userStoreType);
services.AddScoped(
typeof(IRoleStore<>).MakeGenericType(roleType),
roleStoreType);
return services;
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Default services
/// </summary>
public class IdentityEntityFrameworkServices
{
public static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType = null)
{
Type userStoreType;
Type roleStoreType;
if (keyType != null)
{
userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
}
else
{
userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType);
roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, contextType);
}
var services = new ServiceCollection();
services.AddScoped(
typeof(IUserStore<>).MakeGenericType(userType),
userStoreType);
services.AddScoped(
typeof(IRoleStore<>).MakeGenericType(roleType),
roleStoreType);
return services;
}
}
} |
Fix interaction with popover when textbox is disabled | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal abstract class LabelledTextBoxWithPopover : LabelledTextBox, IHasPopover
{
public abstract Popover GetPopover();
protected override OsuTextBox CreateTextBox() =>
new PopoverTextBox
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
CornerRadius = CORNER_RADIUS,
OnFocused = this.ShowPopover
};
internal class PopoverTextBox : OsuTextBox
{
public Action OnFocused;
protected override bool OnDragStart(DragStartEvent e)
{
// This text box is intended to be "read only" without actually specifying that.
// As such we don't want to allow the user to select its content with a drag.
return false;
}
protected override void OnFocus(FocusEvent e)
{
OnFocused?.Invoke();
base.OnFocus(e);
GetContainingInputManager().TriggerFocusContention(this);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal abstract class LabelledTextBoxWithPopover : LabelledTextBox, IHasPopover
{
public abstract Popover GetPopover();
protected override OsuTextBox CreateTextBox() =>
new PopoverTextBox
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
CornerRadius = CORNER_RADIUS,
OnFocused = this.ShowPopover
};
internal class PopoverTextBox : OsuTextBox
{
public Action OnFocused;
protected override bool OnDragStart(DragStartEvent e)
{
// This text box is intended to be "read only" without actually specifying that.
// As such we don't want to allow the user to select its content with a drag.
return false;
}
protected override void OnFocus(FocusEvent e)
{
if (Current.Disabled)
return;
OnFocused?.Invoke();
base.OnFocus(e);
GetContainingInputManager().TriggerFocusContention(this);
}
}
}
}
|
Fix Unable to connect to backend on access denied | using System.IO;
using System.Linq;
namespace ELFinder.Connector.Drivers.FileSystem.Extensions
{
/// <summary>
/// File system info extensions
/// </summary>
public static class FIleSystemInfoExtensions
{
#region Extension methods
/// <summary>
/// Get visible files in directory
/// </summary>
/// <param name="info">Directory info</param>
/// <returns>Result directories</returns>
public static FileInfo[] GetVisibleFiles(this DirectoryInfo info)
{
return info.GetFiles().Where(x => !x.IsHidden()).ToArray();
}
/// <summary>
/// Get visible directories
/// </summary>
/// <param name="info">Directory info</param>
/// <returns>Result directories</returns>
public static DirectoryInfo[] GetVisibleDirectories(this DirectoryInfo info)
{
return info.GetDirectories().Where(x => !x.IsHidden()).ToArray();
}
/// <summary>
/// Get if file is hidden
/// </summary>
/// <param name="info">File info</param>
/// <returns>True/False based on result</returns>
public static bool IsHidden(this FileSystemInfo info)
{
return (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
#endregion
}
} | using System.IO;
using System.Linq;
namespace ELFinder.Connector.Drivers.FileSystem.Extensions
{
/// <summary>
/// File system info extensions
/// </summary>
public static class FIleSystemInfoExtensions
{
#region Extension methods
/// <summary>
/// Get visible files in directory
/// </summary>
/// <param name="info">Directory info</param>
/// <returns>Result directories</returns>
public static FileInfo[] GetVisibleFiles(this DirectoryInfo info)
{
try
{
return info.GetFiles().Where(x => !x.IsHidden()).ToArray();
}
catch (System.Exception)
{
return new FileInfo[0];
}
}
/// <summary>
/// Get visible directories
/// </summary>
/// <param name="info">Directory info</param>
/// <returns>Result directories</returns>
public static DirectoryInfo[] GetVisibleDirectories(this DirectoryInfo info)
{
try
{
return info.GetDirectories().Where(x => !x.IsHidden()).ToArray();
}
catch (System.Exception)
{
return new DirectoryInfo[0];
}
}
/// <summary>
/// Get if file is hidden
/// </summary>
/// <param name="info">File info</param>
/// <returns>True/False based on result</returns>
public static bool IsHidden(this FileSystemInfo info)
{
return (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
}
#endregion
}
} |
Use the tel uri in windows store for phone calls | // MvxPhoneCallTask.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using Windows.System;
namespace Cirrious.MvvmCross.Plugins.PhoneCall.WindowsStore
{
public class MvxPhoneCallTask : IMvxPhoneCallTask
{
public void MakePhoneCall(string name, string number)
{
// TODO! This is far too skype specific
// TODO! name/number need looking at
// this is the best I can do so far...
var uri = new Uri("skype:" + number + "?call", UriKind.Absolute);
Launcher.LaunchUriAsync(uri);
}
}
} | // MvxPhoneCallTask.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using Windows.System;
namespace Cirrious.MvvmCross.Plugins.PhoneCall.WindowsStore
{
public class MvxPhoneCallTask : IMvxPhoneCallTask
{
public void MakePhoneCall(string name, string number)
{
//The tel URI for Telephone Numbers : http://tools.ietf.org/html/rfc3966
//Handled by skype
var uri = new Uri("tel:" + Uri.EscapeDataString(phoneNumber), UriKind.Absolute);
Launcher.LaunchUriAsync(uri);
}
}
}
|
Allow option to prevent system checkers from being auto registered | using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace HealthNet.AspNetCore
{
public static class HealthNetMiddlewareExtensions
{
private static readonly Type VersionProviderType = typeof(IVersionProvider);
private static readonly Type SystemCheckerType = typeof(ISystemChecker);
public static IApplicationBuilder UseHealthNet(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HealthNetMiddleware>();
}
public static IServiceCollection AddHealthNet(this IServiceCollection service)
{
return service.AddTransient<HealthCheckService>();
}
public static IServiceCollection AddHealthNet<THealthNetConfig>(this IServiceCollection service) where THealthNetConfig : class, IHealthNetConfiguration
{
var assembyTypes = typeof(THealthNetConfig).Assembly.GetTypes();
service.AddSingleton<IHealthNetConfiguration, THealthNetConfig>();
var versionProvider = assembyTypes
.FirstOrDefault(x => x.IsClass && !x.IsAbstract && VersionProviderType.IsAssignableFrom(x));
service.AddSingleton(VersionProviderType, versionProvider ?? typeof(AssemblyFileVersionProvider));
var systemCheckers = assembyTypes
.Where(x => x.IsClass && !x.IsAbstract && SystemCheckerType.IsAssignableFrom(x));
foreach (var checkerType in systemCheckers)
{
service.AddTransient(SystemCheckerType, checkerType);
}
return service.AddHealthNet();
}
}
} | using System;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace HealthNet.AspNetCore
{
public static class HealthNetMiddlewareExtensions
{
private static readonly Type VersionProviderType = typeof(IVersionProvider);
private static readonly Type SystemCheckerType = typeof(ISystemChecker);
public static IApplicationBuilder UseHealthNet(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HealthNetMiddleware>();
}
public static IServiceCollection AddHealthNet(this IServiceCollection service)
{
return service.AddTransient<HealthCheckService>();
}
public static IServiceCollection AddHealthNet<THealthNetConfig>(this IServiceCollection service, bool autoRegisterCheckers = true) where THealthNetConfig : class, IHealthNetConfiguration
{
var assembyTypes = typeof(THealthNetConfig).Assembly.GetTypes();
service.AddSingleton<IHealthNetConfiguration, THealthNetConfig>();
var versionProvider = assembyTypes
.FirstOrDefault(x => x.IsClass && !x.IsAbstract && VersionProviderType.IsAssignableFrom(x));
service.AddSingleton(VersionProviderType, versionProvider ?? typeof(AssemblyFileVersionProvider));
if (autoRegisterCheckers)
{
var systemCheckers = assembyTypes
.Where(x => x.IsClass && !x.IsAbstract && SystemCheckerType.IsAssignableFrom(x));
foreach (var checkerType in systemCheckers)
{
service.AddTransient(SystemCheckerType, checkerType);
}
}
return service.AddHealthNet();
}
}
} |
Change string formatting due to appveyor failing | using Newtonsoft.Json;
using Telegram.Bot.Types.ReplyMarkups;
using Xunit;
namespace Telegram.Bot.Tests.Unit.Serialization
{
public class ReplyMarkupSerializationTests
{
[Theory(DisplayName = "Should serialize request poll keyboard button")]
[InlineData(null)]
[InlineData("regular")]
[InlineData("quiz")]
public void Should_Serialize_Request_Poll_Keyboard_Button(string type)
{
IReplyMarkup replyMarkup = new ReplyKeyboardMarkup(
KeyboardButton.WithRequestPoll("Create a poll", type)
);
string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup);
string expectedType = string.IsNullOrEmpty(type)
? "{}"
: @$"{{""type"":""{type}""}}";
Assert.Contains(@$"""request_poll"":{expectedType}", serializedReplyMarkup);
}
}
}
| using Newtonsoft.Json;
using Telegram.Bot.Types.ReplyMarkups;
using Xunit;
namespace Telegram.Bot.Tests.Unit.Serialization
{
public class ReplyMarkupSerializationTests
{
[Theory(DisplayName = "Should serialize request poll keyboard button")]
[InlineData(null)]
[InlineData("regular")]
[InlineData("quiz")]
public void Should_Serialize_Request_Poll_Keyboard_Button(string type)
{
IReplyMarkup replyMarkup = new ReplyKeyboardMarkup(
KeyboardButton.WithRequestPoll("Create a poll", type)
);
string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup);
string expectedType = string.IsNullOrEmpty(type)
? "{}"
: string.Format(@"{{""type"":""{0}""}}", type);
Assert.Contains(@$"""request_poll"":{expectedType}", serializedReplyMarkup);
}
}
}
|
Fix a small, old typo | using Halforbit.DataStores.FileStores.Implementation;
using Halforbit.DataStores.FileStores.LocalStorage.Implementation;
using Halforbit.Facets.Attributes;
using System;
namespace HalfOrbit.DataStores.FileStores.LocalStorage.Attributes
{
public class RootPathAttribute : FacetParameterAttribute
{
public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { }
public override Type TargetType => typeof(LocalFileStore);
public override string ParameterName => "rootPath";
public override Type[] ImpliedTypes => new Type[]
{
typeof(FileStoreDataStore<,>)
};
}
}
| using Halforbit.DataStores.FileStores.Implementation;
using Halforbit.DataStores.FileStores.LocalStorage.Implementation;
using Halforbit.Facets.Attributes;
using System;
namespace Halforbit.DataStores.FileStores.LocalStorage.Attributes
{
public class RootPathAttribute : FacetParameterAttribute
{
public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { }
public override Type TargetType => typeof(LocalFileStore);
public override string ParameterName => "rootPath";
public override Type[] ImpliedTypes => new Type[]
{
typeof(FileStoreDataStore<,>)
};
}
}
|
Create Sequence Marker only if it is used. | using System;
using Platform.Data.Core.Pairs;
namespace Platform.Data.Core.Sequences
{
public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function.
{
public ulong SequenceMarkerLink;
public bool UseCascadeUpdate;
public bool UseCascadeDelete;
public bool UseSequenceMarker;
public bool UseCompression;
public bool UseGarbageCollection;
public bool EnforceSingleSequenceVersionOnWrite;
public bool EnforceSingleSequenceVersionOnRead; // TODO: Реализовать компактификацию при чтении
public bool UseRequestMarker;
public bool StoreRequestResults;
public void InitOptions(ILinks<ulong> links)
{
if (SequenceMarkerLink == LinksConstants.Null)
SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself);
}
public void ValidateOptions()
{
if (UseGarbageCollection && !UseSequenceMarker)
throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on.");
}
}
}
| using System;
using Platform.Data.Core.Pairs;
namespace Platform.Data.Core.Sequences
{
public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function.
{
public ulong SequenceMarkerLink;
public bool UseCascadeUpdate;
public bool UseCascadeDelete;
public bool UseSequenceMarker;
public bool UseCompression;
public bool UseGarbageCollection;
public bool EnforceSingleSequenceVersionOnWrite;
// TODO: Реализовать компактификацию при чтении
//public bool EnforceSingleSequenceVersionOnRead;
//public bool UseRequestMarker;
//public bool StoreRequestResults;
public void InitOptions(ILinks<ulong> links)
{
if (UseSequenceMarker && SequenceMarkerLink == LinksConstants.Null)
SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself);
}
public void ValidateOptions()
{
if (UseGarbageCollection && !UseSequenceMarker)
throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on.");
}
}
}
|
Add property for response content, mapped to Data collection. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mios.Payment {
[Serializable]
public class VerificationProviderException : Exception {
public VerificationProviderException() { }
public VerificationProviderException(string message) : base(message) { }
public VerificationProviderException(string message, Exception inner) : base(message, inner) { }
protected VerificationProviderException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mios.Payment {
[Serializable]
public class VerificationProviderException : Exception {
public string ResponseContent {
get { return Data["Response"] as string; }
set { Data["Response"] = value; }
}
public VerificationProviderException() { }
public VerificationProviderException(string message) : base(message) { }
public VerificationProviderException(string message, Exception inner) : base(message, inner) { }
protected VerificationProviderException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
|
Fix Blockbusters not accepting uppercase input | using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
public class BlockbustersComponentSolver : ComponentSolver
{
public BlockbustersComponentSolver(TwitchModule module) :
base(module)
{
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row.");
}
int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1';
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = Regex.Replace(inputCommand, @"(\W|_|^(press|submit|click|answer))", "");
if (inputCommand.Length != 2) yield break;
int column = CharacterToIndex(inputCommand[0]);
int row = CharacterToIndex(inputCommand[1]);
if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1))
{
yield return null;
yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]);
}
}
private readonly KMSelectable[] selectables;
}
| using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
public class BlockbustersComponentSolver : ComponentSolver
{
public BlockbustersComponentSolver(TwitchModule module) :
base(module)
{
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row.");
}
int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1';
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
inputCommand = Regex.Replace(inputCommand.ToLowerInvariant(), @"(\W|_|^(press|submit|click|answer))", "");
if (inputCommand.Length != 2) yield break;
int column = CharacterToIndex(inputCommand[0]);
int row = CharacterToIndex(inputCommand[1]);
if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1))
{
yield return null;
yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]);
}
}
private readonly KMSelectable[] selectables;
}
|
Set DOTNET_HOST_PATH so Roslyn tasks will use the right host |
using Xunit;
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
|
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Xunit;
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
// Register test framework for assembly fixture
[assembly: TestFramework("Xunit.NetCore.Extensions.XunitTestFrameworkWithAssemblyFixture", "Xunit.NetCore.Extensions")]
[assembly: AssemblyFixture(typeof(MSBuildTestAssemblyFixture))]
public class MSBuildTestAssemblyFixture
{
public MSBuildTestAssemblyFixture()
{
// Find correct version of "dotnet", and set DOTNET_HOST_PATH so that the Roslyn tasks will use the right host
var currentFolder = System.AppContext.BaseDirectory;
while (currentFolder != null)
{
string potentialVersionsPropsPath = Path.Combine(currentFolder, "build", "Versions.props");
if (File.Exists(potentialVersionsPropsPath))
{
var doc = XDocument.Load(potentialVersionsPropsPath);
var ns = doc.Root.Name.Namespace;
var cliVersionElement = doc.Root.Elements(ns + "PropertyGroup").Elements(ns + "DotNetCliVersion").FirstOrDefault();
if (cliVersionElement != null)
{
string cliVersion = cliVersionElement.Value;
string dotnetPath = Path.Combine(currentFolder, "artifacts", ".dotnet", cliVersion, "dotnet");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
dotnetPath += ".exe";
}
Environment.SetEnvironmentVariable("DOTNET_HOST_PATH", dotnetPath);
}
break;
}
currentFolder = Directory.GetParent(currentFolder)?.FullName;
}
}
}
|
Remove async helper methods for json serialization. | namespace TraktApiSharp.Utils
{
using Newtonsoft.Json;
using System.Threading.Tasks;
internal static class Json
{
internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS
= new JsonSerializerSettings
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore
};
internal static string Serialize(object value)
{
return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS);
}
internal static TResult Deserialize<TResult>(string value)
{
return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS);
}
internal static async Task<string> SerializeAsync(object value)
{
return await Task.Run(() => JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS));
}
internal static async Task<TResult> DeserializeAsync<TResult>(string value)
{
return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS));
}
}
}
| namespace TraktApiSharp.Utils
{
using Newtonsoft.Json;
internal static class Json
{
internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS
= new JsonSerializerSettings
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore
};
internal static string Serialize(object value)
{
return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS);
}
internal static TResult Deserialize<TResult>(string value)
{
return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS);
}
}
}
|
Use private accessor for property | using System;
namespace UDIR.PAS2.OAuth.Client
{
internal class AuthorizationServer
{
public AuthorizationServer(Uri baseAddress)
{
BaseAddress = baseAddress;
TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString();
}
public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress))
{
}
public string TokenEndpoint { get; }
public Uri BaseAddress { get; }
}
}
| using System;
namespace UDIR.PAS2.OAuth.Client
{
internal class AuthorizationServer
{
public AuthorizationServer(Uri baseAddress)
{
BaseAddress = baseAddress;
TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString();
}
public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress))
{
}
public string TokenEndpoint { get; private set; }
public Uri BaseAddress { get; private set; }
}
}
|
Use builtin MongoDB Bson serialization | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using Newtonsoft.Json;
namespace M101DotNet
{
public class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
Console.WriteLine();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task MainAsync(string[] args)
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var db = client.GetDatabase("test");
var person = new Person
{
Name = "Jones",
Age = 30,
Colors = new List<string> {"red", "blue"},
Pets = new List<Pet>
{
new Pet
{
Name = "Puffy",
Type = "Pig"
}
}
};
Console.WriteLine(person);
// using (var writer = new JsonWriter(Console.Out))
// {
// BsonSerializer.Serialize(writer, person);
// };
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.IO;
namespace M101DotNet
{
public class Program
{
public static void Main(string[] args)
{
MainAsync(args).Wait();
Console.WriteLine();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task MainAsync(string[] args)
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var db = client.GetDatabase("test");
var person = new Person
{
Name = "Jones",
Age = 30,
Colors = new List<string> {"red", "blue"},
Pets = new List<Pet>
{
new Pet
{
Name = "Puffy",
Type = "Pig"
}
}
};
Console.WriteLine(person);
using (var writer = new JsonWriter(Console.Out))
{
BsonSerializer.Serialize(writer, person);
};
}
}
} |
Add a little more info to the thread listing. | using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class ThreadsCommand : ICommand
{
public string Name
{
get { return "Threads"; }
}
public string Description
{
get { return "Lists all active threads."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var session = SoftDebugger.Session;
if (SoftDebugger.State == DebuggerState.Null)
{
Logger.WriteErrorLine("No session active.");
return;
}
if (SoftDebugger.State == DebuggerState.Initialized)
{
Logger.WriteErrorLine("No process active.");
return;
}
var threads = session.VirtualMachine.GetThreads();
foreach (var thread in threads)
Logger.WriteInfoLine("[{0}] {1}: {2}", thread.Id, thread.Name, thread.ThreadState);
}
}
}
| using System.Collections.Generic;
using Mono.Debugger.Cli.Debugging;
using Mono.Debugger.Cli.Logging;
namespace Mono.Debugger.Cli.Commands
{
public sealed class ThreadsCommand : ICommand
{
public string Name
{
get { return "Threads"; }
}
public string Description
{
get { return "Lists all active threads."; }
}
public IEnumerable<string> Arguments
{
get { return Argument.None(); }
}
public void Execute(CommandArguments args)
{
var session = SoftDebugger.Session;
if (SoftDebugger.State == DebuggerState.Null)
{
Logger.WriteErrorLine("No session active.");
return;
}
if (SoftDebugger.State == DebuggerState.Initialized)
{
Logger.WriteErrorLine("No process active.");
return;
}
var threads = session.VirtualMachine.GetThreads();
foreach (var thread in threads)
{
var id = thread.Id.ToString();
if (thread.IsThreadPoolThread)
id += " (TP)";
Logger.WriteInfoLine("[{0}: {1}] {2}: {3}", thread.Domain.FriendlyName, id, thread.Name, thread.ThreadState);
}
}
}
}
|
Add OSX default install location for BeyondCompare. | using System;
using System.Collections.Generic;
using System.Linq;
namespace Assent.Reporters.DiffPrograms
{
public class BeyondCompareDiffProgram : DiffProgramBase
{
static BeyondCompareDiffProgram()
{
var paths = new List<string>();
if (DiffReporter.IsWindows)
{
paths.AddRange(WindowsProgramFilePaths
.SelectMany(p =>
new[]
{
$@"{p}\Beyond Compare 4\BCompare.exe",
$@"{p}\Beyond Compare 3\BCompare.exe"
})
.ToArray());
}
else
{
paths.Add("/usr/bin/bcompare");
}
DefaultSearchPaths = paths;
}
public static readonly IReadOnlyList<string> DefaultSearchPaths;
public BeyondCompareDiffProgram() : base(DefaultSearchPaths)
{
}
public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths)
: base(searchPaths)
{
}
protected override string CreateProcessStartArgs(string receivedFile, string approvedFile)
{
var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile);
var argChar = DiffReporter.IsWindows ? "/" : "-";
return $"{defaultArgs} {argChar}solo" ;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Assent.Reporters.DiffPrograms
{
public class BeyondCompareDiffProgram : DiffProgramBase
{
static BeyondCompareDiffProgram()
{
var paths = new List<string>();
if (DiffReporter.IsWindows)
{
paths.AddRange(WindowsProgramFilePaths
.SelectMany(p =>
new[]
{
$@"{p}\Beyond Compare 4\BCompare.exe",
$@"{p}\Beyond Compare 3\BCompare.exe"
})
.ToArray());
}
else
{
paths.Add("/usr/bin/bcompare");
paths.Add("/usr/local/bin/bcompare");
}
DefaultSearchPaths = paths;
}
public static readonly IReadOnlyList<string> DefaultSearchPaths;
public BeyondCompareDiffProgram() : base(DefaultSearchPaths)
{
}
public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths)
: base(searchPaths)
{
}
protected override string CreateProcessStartArgs(string receivedFile, string approvedFile)
{
var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile);
var argChar = DiffReporter.IsWindows ? "/" : "-";
return $"{defaultArgs} {argChar}solo" ;
}
}
}
|
Add some simple runtime stats while implementing the Z80 core | using System;
using elbsms_core;
namespace elbsms_console
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: elbsms_console <path to rom>");
return;
}
string romPath = args[0];
Cartridge cartridge = Cartridge.LoadFromFile(romPath);
MasterSystem masterSystem = new MasterSystem(cartridge);
try
{
while (true)
{
masterSystem.SingleStep();
}
}
catch (NotImplementedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
| using System;
using System.Diagnostics;
using elbsms_core;
namespace elbsms_console
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: elbsms_console <path to rom>");
return;
}
string romPath = args[0];
Cartridge cartridge = Cartridge.LoadFromFile(romPath);
MasterSystem masterSystem = new MasterSystem(cartridge);
Console.WriteLine($"Starting: {DateTime.Now}");
Console.WriteLine();
ulong instructionCount = 0;
var sw = Stopwatch.StartNew();
try
{
while (true)
{
instructionCount++;
masterSystem.SingleStep();
}
}
catch (NotImplementedException ex)
{
Console.WriteLine(ex.Message);
}
sw.Stop();
Console.WriteLine();
Console.WriteLine($"Finished: {DateTime.Now}");
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms Instructions: {instructionCount}, Instructions/ms: {instructionCount/(double)sw.ElapsedMilliseconds}");
}
}
}
|
Make the next release version 0.1.1 (bug fixes) | using System.Reflection;
[assembly: AssemblyProduct("SqlStreamStore")]
[assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| using System.Reflection;
[assembly: AssemblyProduct("SqlStreamStore")]
[assembly: AssemblyCopyright("Copyright Damian Hickey & Contributors 2015 - 2016")]
[assembly: AssemblyVersion("0.1.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
|
Move Seq 'Compact' flag, default | namespace Cash_Flow_Projection
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
| namespace Cash_Flow_Projection
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
|
Add mx handling and not implemented if non supported type request | using ARSoft.Tools.Net.Dns;
using System;
using System.Net;
using System.Net.Sockets;
namespace DNSRootServerResolver
{
public class Program
{
public static void Main(string[] args)
{
using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler))
{
server.Start();
string command;
while ((command = Console.ReadLine()) != "exit")
{
if (command == "clear")
{
DNS.GlobalCache.Clear();
}
}
}
}
public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType)
{
DnsMessage query = dnsMessageBase as DnsMessage;
foreach (var question in query.Questions)
{
switch (question.RecordType)
{
case RecordType.A:
query.AnswerRecords.AddRange(DNS.Resolve(question.Name)); break;
case RecordType.Ptr:
{
if (question.Name == "1.0.0.127.in-addr.arpa")
{
query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost"));
}
}; break;
}
}
return query;
}
}
}
| using ARSoft.Tools.Net.Dns;
using System;
using System.Net;
using System.Net.Sockets;
namespace DNSRootServerResolver
{
public class Program
{
public static void Main(string[] args)
{
using (var server = new DnsServer(IPAddress.Any, 25, 25, DnsServerHandler))
{
server.Start();
string command;
while ((command = Console.ReadLine()) != "exit")
{
if (command == "clear")
{
DNS.GlobalCache.Clear();
}
}
}
}
public static DnsMessageBase DnsServerHandler(DnsMessageBase dnsMessageBase, IPAddress clientAddress, ProtocolType protocolType)
{
DnsMessage query = dnsMessageBase as DnsMessage;
foreach (var question in query.Questions)
{
Console.WriteLine(question);
switch (question.RecordType)
{
case RecordType.A:
case RecordType.Mx:
query.AnswerRecords.AddRange(DNS.Resolve(question.Name, question.RecordType, question.RecordClass)); break;
case RecordType.Ptr:
{
if (question.Name == "1.0.0.127.in-addr.arpa")
{
query.AnswerRecords.Add(new PtrRecord("127.0.0.1", 172800 /*2 days*/, "localhost"));
}
}; break;
default:
{
query.ReturnCode = ReturnCode.NotImplemented;
Console.WriteLine("Unknown record type: " + question.RecordType + " (class: " + question.RecordClass + ", " + question.Name + ")");
} break;
}
}
return query;
}
}
}
|
Add missing namespace to resolve asset retargeting failures | using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler
{
#region Event handlers
public TouchEvent OnTouchStarted = new TouchEvent();
public TouchEvent OnTouchCompleted = new TouchEvent();
public TouchEvent OnTouchUpdated = new TouchEvent();
#endregion
void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData)
{
OnTouchCompleted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData)
{
OnTouchStarted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData)
{
OnTouchUpdated.Invoke(eventData);
}
}
| using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
public class TouchHandler : MonoBehaviour, IMixedRealityTouchHandler
{
#region Event handlers
public TouchEvent OnTouchStarted = new TouchEvent();
public TouchEvent OnTouchCompleted = new TouchEvent();
public TouchEvent OnTouchUpdated = new TouchEvent();
#endregion
void IMixedRealityTouchHandler.OnTouchCompleted(HandTrackingInputEventData eventData)
{
OnTouchCompleted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchStarted(HandTrackingInputEventData eventData)
{
OnTouchStarted.Invoke(eventData);
}
void IMixedRealityTouchHandler.OnTouchUpdated(HandTrackingInputEventData eventData)
{
OnTouchUpdated.Invoke(eventData);
}
}
}
|
Implement ESDATModel test for OSM2.Actions | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters
{
class ESDATDataConverterTest
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Hatfield.EnviroData.Core;
using Hatfield.EnviroData.DataAcquisition.ESDAT;
using Hatfield.EnviroData.DataAcquisition.ESDAT.Converters;
namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Test.Converters
{
[TestFixture]
public class ESDATConverterTest
{
// See https://github.com/HatfieldConsultants/Hatfield.EnviroData.Core/wiki/Loading-ESDAT-data-into-ODM2#actions for expected values
[Test]
public void ESDATConverterConvertToODMActionActionTest()
{
var mockDbContext = new Mock<IDbContext>().Object;
var esdatConverter = new ESDATConverter(mockDbContext);
ESDATModel esdatModel = new ESDATModel();
DateTime sampledDateTime = DateTime.Now;
esdatModel.SampleFileData.SampledDateTime = sampledDateTime;
var action = esdatConverter.ConvertToODMAction(esdatModel);
Assert.AreEqual(action.ActionID, 0);
Assert.AreEqual(action.ActionTypeCV, "specimenCollection");
Assert.AreEqual(action.BeginDateTime, sampledDateTime);
Assert.AreEqual(action.EndDateTime, null);
Assert.AreEqual(action.EndDateTimeUTCOffset, null);
Assert.AreEqual(action.ActionDescription, null);
Assert.AreEqual(action.ActionFileLink, null);
}
}
}
|
Fix repository permission checks. Yes, that was stupid. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bonobo.Git.Server.Data;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
namespace Bonobo.Git.Server.Security
{
public class ADRepositoryPermissionService : IRepositoryPermissionService
{
[Dependency]
public IRepositoryRepository Repository { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
[Dependency]
public ITeamRepository TeamRepository { get; set; }
public bool AllowsAnonymous(string repositoryName)
{
return Repository.GetRepository(repositoryName).AnonymousAccess;
}
public bool HasPermission(string username, string repositoryName)
{
bool result = true;
RepositoryModel repositoryModel = Repository.GetRepository(repositoryName);
result &= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
result &= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase));
return result;
}
public bool IsRepositoryAdministrator(string username, string repositoryName)
{
bool result = true;
result &= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result &= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
return result;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bonobo.Git.Server.Data;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
namespace Bonobo.Git.Server.Security
{
public class ADRepositoryPermissionService : IRepositoryPermissionService
{
[Dependency]
public IRepositoryRepository Repository { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
[Dependency]
public ITeamRepository TeamRepository { get; set; }
public bool AllowsAnonymous(string repositoryName)
{
return Repository.GetRepository(repositoryName).AnonymousAccess;
}
public bool HasPermission(string username, string repositoryName)
{
bool result = false;
RepositoryModel repositoryModel = Repository.GetRepository(repositoryName);
result |= repositoryModel.Users.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= repositoryModel.Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
result |= TeamRepository.GetTeams(username).Any(x => repositoryModel.Teams.Contains(x.Name, StringComparer.OrdinalIgnoreCase));
return result;
}
public bool IsRepositoryAdministrator(string username, string repositoryName)
{
bool result = false;
result |= Repository.GetRepository(repositoryName).Administrators.Contains(username, StringComparer.OrdinalIgnoreCase);
result |= RoleProvider.GetRolesForUser(username).Contains(Definitions.Roles.Administrator);
return result;
}
}
} |
Fix test to use the appropriate config | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionToCodeLib;
using Xunit;
namespace ExpressionToCodeTest
{
public class AnonymousObjectFormattingTest
{
[Fact]
public void AnonymousObjectsRenderAsCode()
{
Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", }));
}
[Fact]
public void AnonymousObjectsInArray()
{
Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } }));
}
[Fact]
public void EnumerableInAnonymousObject()
{
Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) }));
}
[Fact]
public void EnumInAnonymousObject()
{
Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A }));
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpressionToCodeLib;
using Xunit;
namespace ExpressionToCodeTest
{
public class AnonymousObjectFormattingTest
{
[Fact]
public void AnonymousObjectsRenderAsCode()
{
Assert.Equal("new {\n A = 1,\n Foo = \"Bar\",\n}", ObjectToCode.ComplexObjectToPseudoCode(new { A = 1, Foo = "Bar", }));
}
[Fact]
public void AnonymousObjectsInArray()
{
Assert.Equal("new[] {\n new {\n Val = 3,\n },\n new {\n Val = 42,\n },\n}", ObjectToCode.ComplexObjectToPseudoCode(new[] { new { Val = 3, }, new { Val = 42 } }));
}
[Fact]
public void EnumerableInAnonymousObject()
{
Assert.Equal("new {\n Nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...},\n}", ExpressionToCodeConfiguration.DefaultAssertionConfiguration.ComplexObjectToPseudoCode(new { Nums = Enumerable.Range(1, 13) }));
}
[Fact]
public void EnumInAnonymousObject()
{
Assert.Equal("new {\n Enum = ConsoleKey.A,\n}", ObjectToCode.ComplexObjectToPseudoCode(new { Enum = ConsoleKey.A }));
}
}
} |
Fix update installer not running as administrator due to breaking change in .NET | using System;
using System.ComponentModel;
using System.Diagnostics;
using TweetDuck.Configuration;
using TweetLib.Core;
using TweetLib.Utils.Static;
namespace TweetDuck.Updates {
sealed class UpdateInstaller {
private string Path { get; }
public UpdateInstaller(string path) {
this.Path = path;
}
public bool Launch() {
// ProgramPath has a trailing backslash
string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : "");
bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath);
try {
using (Process.Start(new ProcessStartInfo {
FileName = Path,
Arguments = arguments,
Verb = runElevated ? "runas" : string.Empty,
ErrorDialog = true
})) {
return true;
}
} catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user
return false;
} catch (Exception e) {
App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e);
return false;
}
}
}
}
| using System;
using System.ComponentModel;
using System.Diagnostics;
using TweetDuck.Configuration;
using TweetLib.Core;
using TweetLib.Utils.Static;
namespace TweetDuck.Updates {
sealed class UpdateInstaller {
private string Path { get; }
public UpdateInstaller(string path) {
this.Path = path;
}
public bool Launch() {
// ProgramPath has a trailing backslash
string arguments = "/SP- /SILENT /FORCECLOSEAPPLICATIONS /UPDATEPATH=\"" + App.ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentForInstallerCmd() + "\"" + (App.IsPortable ? " /PORTABLE=1" : "");
bool runElevated = !App.IsPortable || !FileUtils.CheckFolderWritePermission(App.ProgramPath);
try {
using (Process.Start(new ProcessStartInfo {
FileName = Path,
Arguments = arguments,
Verb = runElevated ? "runas" : string.Empty,
UseShellExecute = true,
ErrorDialog = true
})) {
return true;
}
} catch (Win32Exception e) when (e.NativeErrorCode == 0x000004C7) { // operation canceled by the user
return false;
} catch (Exception e) {
App.ErrorHandler.HandleException("Update Installer Error", "Could not launch update installer.", true, e);
return false;
}
}
}
}
|
Set default delay value = 1000 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hqub.Lastfm
{
public static class Configure
{
/// <summary>
/// Set value delay between requests.
/// </summary>
public static int Delay { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hqub.Lastfm
{
public static class Configure
{
static Configure()
{
Delay = 1000;
}
/// <summary>
/// Set value delay between requests.
/// </summary>
public static int Delay { get; set; }
}
}
|
Fix parameters supported in `Recurring` for `PriceData` across the API | namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SubscriptionItemPriceDataRecurringOptions : INestedOptions
{
/// <summary>
/// Specifies a usage aggregation strategy for prices where <see cref="UsageType"/> is
/// <c>metered</c>. Allowed values are <c>sum</c> for summing up all usage during a period,
/// <c>last_during_period</c> for picking the last usage record reported within a period,
/// <c>last_ever</c> for picking the last usage record ever (across period bounds) or
/// <c>max</c> which picks the usage record with the maximum reported usage during a
/// period. Defaults to <c>sum</c>.
/// </summary>
[JsonProperty("aggregate_usage")]
public string AggregateUsage { get; set; }
/// <summary>
/// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>,
/// <c>month</c> or <c>year</c>.
/// </summary>
[JsonProperty("interval")]
public string Interval { get; set; }
/// <summary>
/// The number of intervals (specified in the <see cref="Interval"/> property) between
/// subscription billings.
/// </summary>
[JsonProperty("interval_count")]
public long? IntervalCount { get; set; }
/// <summary>
/// Default number of trial days when subscribing a customer to this price using
/// <c>trial_from_price=true</c>.
/// </summary>
[JsonProperty("trial_period_days")]
public long? TrialPeriodDays { get; set; }
/// <summary>
/// Configures how the quantity per period should be determined, can be either
/// <c>metered</c> or <c>licensed</c>. <c>licensed</c> will automatically bill the quantity
/// set for a price when adding it to a subscription, <c>metered</c> will aggregate the
/// total usage based on usage records. Defaults to <c>licensed</c>.
/// </summary>
[JsonProperty("usage_type")]
public string UsageType { get; set; }
}
}
| namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class SubscriptionItemPriceDataRecurringOptions : INestedOptions
{
/// <summary>
/// he frequency at which a subscription is billed. One of <c>day</c>, <c>week</c>,
/// <c>month</c> or <c>year</c>.
/// </summary>
[JsonProperty("interval")]
public string Interval { get; set; }
/// <summary>
/// The number of intervals (specified in the <see cref="Interval"/> property) between
/// subscription billings.
/// </summary>
[JsonProperty("interval_count")]
public long? IntervalCount { get; set; }
}
}
|
Add usage comment to interface | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
interface IVsTypeScriptRemoteLanguageServiceWorkspace
{
}
}
| // 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 Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
/// <summary>
/// Used to acquire the RemoteLanguageServiceWorkspace. Its members should be accessed by casting to <see cref="Workspace"/>.
/// </summary>
interface IVsTypeScriptRemoteLanguageServiceWorkspace
{
}
}
|
Disable tests coverage for unsupported Unity versions | using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features;
using JetBrains.ReSharper.Host.Features.UnitTesting;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Rider.Model;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
var solution = element.Id.Project.GetSolution();
var tracker = solution.GetComponent<UnitySolutionTracker>();
if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value)
return HostProviderAvailability.Available;
var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel();
if (rdUnityModel.UnitTestPreference.Value != UnitTestLaunchPreference.PlayMode)
return HostProviderAvailability.Available;
return HostProviderAvailability.Nonexistent;
}
}
} | using System;
using JetBrains.Application;
using JetBrains.Application.Components;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Host.Features;
using JetBrains.ReSharper.Host.Features.UnitTesting;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Rider.Model;
namespace JetBrains.ReSharper.Plugins.Unity.Rider
{
[ShellComponent]
public class UnityRiderUnitTestCoverageAvailabilityChecker : IRiderUnitTestCoverageAvailabilityChecker, IHideImplementation<DefaultRiderUnitTestCoverageAvailabilityChecker>
{
private static readonly Version ourMinSupportedUnityVersion = new Version(2018, 3);
// this method should be very fast as it gets called a lot
public HostProviderAvailability GetAvailability(IUnitTestElement element)
{
var solution = element.Id.Project.GetSolution();
var tracker = solution.GetComponent<UnitySolutionTracker>();
if (tracker.IsUnityProject.HasValue() && !tracker.IsUnityProject.Value)
return HostProviderAvailability.Available;
var rdUnityModel = solution.GetProtocolSolution().GetRdUnityModel();
switch (rdUnityModel.UnitTestPreference.Value)
{
case UnitTestLaunchPreference.NUnit:
return HostProviderAvailability.Available;
case UnitTestLaunchPreference.PlayMode:
return HostProviderAvailability.Nonexistent;
case UnitTestLaunchPreference.EditMode:
{
var unityVersion = UnityVersion.Parse(rdUnityModel.ApplicationVersion.Maybe.ValueOrDefault ?? string.Empty);
return unityVersion == null || unityVersion < ourMinSupportedUnityVersion
? HostProviderAvailability.Nonexistent
: HostProviderAvailability.Available;
}
default:
return HostProviderAvailability.Nonexistent;
}
}
}
} |
Add documentation for person images. | namespace TraktApiSharp.Objects.Get.People
{
using Basic;
using Newtonsoft.Json;
public class TraktPersonImages
{
[JsonProperty(PropertyName = "headshot")]
public TraktImageSet Headshot { get; set; }
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.People
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt person.</summary>
public class TraktPersonImages
{
/// <summary>Gets or sets the headshot image set.</summary>
[JsonProperty(PropertyName = "headshot")]
public TraktImageSet Headshot { get; set; }
/// <summary>Gets or sets the fan art image set.</summary>
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
}
}
|
Fix bug in Paragraph rewriter | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
public class MarkdownParagraphBlockToken : IMarkdownToken, IMarkdownRewritable<MarkdownParagraphBlockToken>
{
public MarkdownParagraphBlockToken(IMarkdownRule rule, IMarkdownContext context, InlineContent inlineTokens, string rawMarkdown)
{
Rule = rule;
Context = context;
InlineTokens = inlineTokens;
RawMarkdown = rawMarkdown;
}
public IMarkdownRule Rule { get; }
public IMarkdownContext Context { get; }
public InlineContent InlineTokens { get; }
public string RawMarkdown { get; set; }
public static MarkdownParagraphBlockToken Create(IMarkdownRule rule, MarkdownParser engine, string content, string rawMarkdown)
{
return new MarkdownParagraphBlockToken(rule, engine.Context, engine.TokenizeInline(content), rawMarkdown);
}
public MarkdownParagraphBlockToken Rewrite(IMarkdownRewriteEngine rewriterEngine)
{
var c = InlineTokens.Rewrite(rewriterEngine);
if (c == InlineTokens)
{
return this;
}
return new MarkdownParagraphBlockToken(Rule, Context, InlineTokens, RawMarkdown);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
public class MarkdownParagraphBlockToken : IMarkdownToken, IMarkdownRewritable<MarkdownParagraphBlockToken>
{
public MarkdownParagraphBlockToken(IMarkdownRule rule, IMarkdownContext context, InlineContent inlineTokens, string rawMarkdown)
{
Rule = rule;
Context = context;
InlineTokens = inlineTokens;
RawMarkdown = rawMarkdown;
}
public IMarkdownRule Rule { get; }
public IMarkdownContext Context { get; }
public InlineContent InlineTokens { get; }
public string RawMarkdown { get; set; }
public static MarkdownParagraphBlockToken Create(IMarkdownRule rule, MarkdownParser engine, string content, string rawMarkdown)
{
return new MarkdownParagraphBlockToken(rule, engine.Context, engine.TokenizeInline(content), rawMarkdown);
}
public MarkdownParagraphBlockToken Rewrite(IMarkdownRewriteEngine rewriterEngine)
{
var c = InlineTokens.Rewrite(rewriterEngine);
if (c == InlineTokens)
{
return this;
}
return new MarkdownParagraphBlockToken(Rule, Context, c, RawMarkdown);
}
}
}
|
Make content root path independent of working directory. | using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System.Threading.Tasks;
namespace MitternachtWeb {
public class Program {
public static MitternachtBot MitternachtBot;
public static async Task Main(string[] args) {
MitternachtBot = new MitternachtBot(0, 0);
await MitternachtBot.RunAsync(args);
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) => {
config.AddJsonFile("mitternachtweb.config");
}).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}
| using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Mitternacht;
using System;
using System.IO;
using System.Threading.Tasks;
namespace MitternachtWeb {
public class Program {
public static MitternachtBot MitternachtBot;
public static async Task Main(string[] args) {
MitternachtBot = new MitternachtBot(0, 0);
await MitternachtBot.RunAsync(args);
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) => {
config.SetBasePath(Environment.CurrentDirectory);
config.AddJsonFile("mitternachtweb.config");
}).ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
webBuilder.UseContentRoot(Path.GetDirectoryName(typeof(Program).Assembly.Location));
});
}
}
|
Fix tray icon double click not activating switcher window | using System;
using System.Windows;
using System.Windows.Media.Imaging;
using Hardcodet.Wpf.TaskbarNotification;
using SteamAccountSwitcher.Properties;
namespace SteamAccountSwitcher
{
internal class TrayIconHelper
{
public static void ShowRunningInTrayBalloon()
{
ShowTrayBalloon(
$"{Resources.AppName} is running in system tray.\nDouble click icon to show window.",
BalloonIcon.Info);
}
public static void ShowTrayBalloon(string text, BalloonIcon icon)
{
if (!Settings.Default.ShowTrayNotifications)
return;
App.NotifyIcon.ShowBalloonTip(Resources.AppName, text, icon);
}
public static void RefreshTrayIcon()
{
if (Settings.Default.AlwaysOn)
App.NotifyIcon.ContextMenu = MenuHelper.NotifyMenu();
}
public static void CreateTrayIcon()
{
if (App.NotifyIcon != null)
return;
App.NotifyIcon = new TaskbarIcon {ToolTipText = Resources.AppName};
var logo = new BitmapImage();
logo.BeginInit();
logo.UriSource =
new Uri($"pack://application:,,,/SteamAccountSwitcher;component/steam.ico");
logo.EndInit();
App.NotifyIcon.IconSource = logo;
App.NotifyIcon.Visibility = Settings.Default.AlwaysOn ? Visibility.Visible : Visibility.Hidden;
App.NotifyIcon.TrayMouseDoubleClick += (sender, args) => SwitchWindowHelper.ShowSwitcherWindow();
App.Accounts.CollectionChanged += (sender, args) => RefreshTrayIcon();
RefreshTrayIcon();
}
}
} | using System;
using System.Windows;
using System.Windows.Media.Imaging;
using Hardcodet.Wpf.TaskbarNotification;
using SteamAccountSwitcher.Properties;
namespace SteamAccountSwitcher
{
internal class TrayIconHelper
{
public static void ShowRunningInTrayBalloon()
{
ShowTrayBalloon(
$"{Resources.AppName} is running in system tray.\nDouble click icon to show window.",
BalloonIcon.Info);
}
public static void ShowTrayBalloon(string text, BalloonIcon icon)
{
if (!Settings.Default.ShowTrayNotifications)
return;
App.NotifyIcon.ShowBalloonTip(Resources.AppName, text, icon);
}
public static void RefreshTrayIcon()
{
if (Settings.Default.AlwaysOn)
App.NotifyIcon.ContextMenu = MenuHelper.NotifyMenu();
}
public static void CreateTrayIcon()
{
if (App.NotifyIcon != null)
return;
App.NotifyIcon = new TaskbarIcon {ToolTipText = Resources.AppName};
var logo = new BitmapImage();
logo.BeginInit();
logo.UriSource =
new Uri($"pack://application:,,,/SteamAccountSwitcher;component/steam.ico");
logo.EndInit();
App.NotifyIcon.IconSource = logo;
App.NotifyIcon.Visibility = Settings.Default.AlwaysOn ? Visibility.Visible : Visibility.Hidden;
App.NotifyIcon.TrayMouseDoubleClick += (sender, args) => SwitchWindowHelper.ActivateSwitchWindow();
App.Accounts.CollectionChanged += (sender, args) => RefreshTrayIcon();
RefreshTrayIcon();
}
}
} |
Add method to extract and zip | using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace ExcelMediaConsole
{
class Program
{
static void Main(string[] args)
{
var excelFilePath = "Book1.xlsx";
var outputDirPath = "Media";
Directory.CreateDirectory(outputDirPath);
using (var archive = ZipFile.OpenRead(excelFilePath))
{
var query = archive.Entries
.Where(e => e.FullName.StartsWith("xl/media/", StringComparison.InvariantCultureIgnoreCase));
foreach (var entry in query)
{
var filePath = Path.Combine(outputDirPath, entry.Name);
entry.ExtractToFile(filePath, true);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
namespace ExcelMediaConsole
{
class Program
{
static void Main(string[] args)
{
var excelFilePath = "Book1.xlsx";
var outputDirPath = "Media";
Directory.CreateDirectory(outputDirPath);
using (var archive = ZipFile.OpenRead(excelFilePath))
{
// In case of Excel, the path separator is "/" not "\".
var query = archive.Entries
.Where(e => e.FullName.StartsWith("xl/media/", StringComparison.InvariantCultureIgnoreCase));
foreach (var entry in query)
{
var filePath = Path.Combine(outputDirPath, entry.Name);
entry.ExtractToFile(filePath, true);
}
}
}
static void ExtractAndZip()
{
var targetFilePath = "Book1.xlsx";
var extractDirPath = "Book1";
var zipFilePath = "Book1.zip";
ZipFile.ExtractToDirectory(targetFilePath, extractDirPath);
ZipFile.CreateFromDirectory(extractDirPath, zipFilePath);
}
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Web")]
[assembly: AssemblyDescription("Autofac ASP.NET Integration")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Autofac.Integration.Web")]
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Web, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
[assembly: ComVisible(false)]
|
Drop alpha status, it is a 1.0.0 release as is | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Commons;
[assembly: AssemblyTitle("TickTack")]
[assembly: AssemblyDescription("Delayed reminder!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rafael Teixeira")]
[assembly: AssemblyProduct("TickTack")]
[assembly: AssemblyCopyright("Copyright © 2008-2015 Rafael Teixeira")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ac8af955-f068-4e26-af5e-f07c8f1c1e6e")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-Alpha")]
[assembly: License(LicenseType.MIT)]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Commons;
[assembly: AssemblyTitle("TickTack")]
[assembly: AssemblyDescription("Delayed reminder!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rafael Teixeira")]
[assembly: AssemblyProduct("TickTack")]
[assembly: AssemblyCopyright("Copyright © 2008-2015 Rafael Teixeira")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ac8af955-f068-4e26-af5e-f07c8f1c1e6e")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: License(LicenseType.MIT)]
|
Add git commands to tool. | namespace Pagination.ReleaseActions {
class Tag : ReleaseAction {
public override void Work() {
var tag = Context.Version.StagedVersion;
Process("git", "commit", "-a", "-m", $"\"(Auto-)Commit version '{tag}'.\"");
Process("git", "tag", "-a", tag, "-m", $"\"(Auto-)Tag version '{tag}'.\"");
Process("git", "push", "origin", tag);
}
}
}
| namespace Pagination.ReleaseActions {
class Tag : ReleaseAction {
public override void Work() {
var tag = Context.Version.StagedVersion;
Process("git", "status");
Process("git", "commit", "-a", "-m", $"\"(Auto-)Commit version '{tag}'.\"");
Process("git", "push");
Process("git", "tag", "-a", tag, "-m", $"\"(Auto-)Tag version '{tag}'.\"");
Process("git", "push", "origin", tag);
}
}
}
|
Add test case for fading hold note | // 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.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
public class TestSceneHoldNote : ManiaHitObjectTestScene
{
[Test]
public void TestHoldNote()
{
AddToggleStep("toggle hitting", v =>
{
foreach (var holdNote in CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>()))
{
((Bindable<bool>)holdNote.IsHitting).Value = v;
}
});
}
protected override DrawableManiaHitObject CreateHitObject()
{
var note = new HoldNote { Duration = 1000 };
note.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
return new DrawableHoldNote(note);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Tests.Skinning
{
public class TestSceneHoldNote : ManiaHitObjectTestScene
{
[Test]
public void TestHoldNote()
{
AddToggleStep("toggle hitting", v =>
{
foreach (var holdNote in CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>()))
{
((Bindable<bool>)holdNote.IsHitting).Value = v;
}
});
}
[Test]
public void TestFadeOnMiss()
{
AddStep("miss tick", () =>
{
foreach (var holdNote in holdNotes)
holdNote.ChildrenOfType<DrawableHoldNoteHead>().First().MissForcefully();
});
}
private IEnumerable<DrawableHoldNote> holdNotes => CreatedDrawables.SelectMany(d => d.ChildrenOfType<DrawableHoldNote>());
protected override DrawableManiaHitObject CreateHitObject()
{
var note = new HoldNote { Duration = 1000 };
note.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
return new DrawableHoldNote(note);
}
}
}
|
Make hold note ticks affect combo score rather than bonus | // 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.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class HoldNoteTickJudgement : ManiaJudgement
{
public override bool AffectsCombo => false;
protected override int NumericResultFor(HitResult result) => 20;
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 0.01;
}
}
}
}
| // 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.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Judgements
{
public class HoldNoteTickJudgement : ManiaJudgement
{
protected override int NumericResultFor(HitResult result) => 20;
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 0.01;
}
}
}
}
|
Fix a syntax error causing typo | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Events
{
public partial class SnowflakeEventSource
{
public static SnowflakeEventSource SnowflakeEventSource;
SnowflakeEventSource()
{
}
public static void InitEventSource()
{
if (SnowflakeEventSource.SnowflakeEventSource == null)
{
SnowflakeEventSource.SnowflakeEventSource = new SnowflakeEventSource();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Events
{
public partial class SnowflakeEventSource
{
public static SnowflakeEventSource EventSource;
SnowflakeEventSource()
{
}
public static void InitEventSource()
{
if (SnowflakeEventSource.EventSource == null)
{
SnowflakeEventSource.EventSource = new SnowflakeEventSource();
}
}
}
}
|
Switch stream publisher over to use new proxy | using System;
namespace Glimpse.Agent
{
public class RemoteStreamMessagePublisher : BaseMessagePublisher
{
public override void PublishMessage(IMessage message)
{
var newMessage = ConvertMessage(message);
// TODO: Use SignalR to publish message
}
}
} | using Glimpse.Agent.Connection.Stream.Connection;
using System;
namespace Glimpse.Agent
{
public class RemoteStreamMessagePublisher : BaseMessagePublisher
{
private readonly IStreamProxy _messagePublisherHub;
public RemoteStreamMessagePublisher(IStreamProxy messagePublisherHub)
{
_messagePublisherHub = messagePublisherHub;
}
public override void PublishMessage(IMessage message)
{
var newMessage = ConvertMessage(message);
_messagePublisherHub.UseSender(x => x.Invoke("HandleMessage", newMessage));
}
}
} |
Unify DispatchWrapper behavior for null | // 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 Xunit;
namespace System.Runtime.InteropServices.Tests
{
#pragma warning disable 0618 // DispatchWrapper is marked as Obsolete.
public class DispatchWrapperTests
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Throws PlatformNotSupportedException in UapAot")]
public void Ctor_NullWindows_Success()
{
var wrapper = new DispatchWrapper(null);
Assert.Null(wrapper.WrappedObject);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.UapAot, "Throws PlatformNotSupportedException in UapAot")]
public void Ctor_NullUapAot_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(null));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void Ctor_NullUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(null));
}
[Theory]
[InlineData("")]
[InlineData(0)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Marshal.GetIDispatchForObject is not supported in .NET Core.")]
public void Ctor_NonNull_ThrowsPlatformNotSupportedException(object value)
{
Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(value));
}
}
#pragma warning restore 0618
}
| // 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 Xunit;
namespace System.Runtime.InteropServices.Tests
{
#pragma warning disable 0618 // DispatchWrapper is marked as Obsolete.
public class DispatchWrapperTests
{
[Fact]
public void Ctor_Null_Success()
{
var wrapper = new DispatchWrapper(null);
Assert.Null(wrapper.WrappedObject);
}
[Theory]
[InlineData("")]
[InlineData(0)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Marshal.GetIDispatchForObject is not supported in .NET Core.")]
public void Ctor_NonNull_ThrowsPlatformNotSupportedException(object value)
{
Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(value));
}
}
#pragma warning restore 0618
}
|
Fix a dialog display glitch on Linux (20190725) | using System.Windows.Forms;
namespace Bloom.WebLibraryIntegration
{
public partial class OverwriteWarningDialog : Form
{
public OverwriteWarningDialog()
{
InitializeComponent();
}
}
}
| using System.Windows.Forms;
namespace Bloom.WebLibraryIntegration
{
public partial class OverwriteWarningDialog : Form
{
public OverwriteWarningDialog()
{
InitializeComponent();
}
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
// Fix a display glitch on Linux with the Mono SWF implementation. The button were half off
// the bottom of the dialog on Linux, but fine on Windows.
if (SIL.PlatformUtilities.Platform.IsLinux)
{
if (ClientSize.Height < _replaceExistingButton.Location.Y + _replaceExistingButton.Height)
{
var delta = ClientSize.Height - (_replaceExistingButton.Location.Y + _replaceExistingButton.Height) - 4;
_replaceExistingButton.Location = new System.Drawing.Point(_replaceExistingButton.Location.X, _replaceExistingButton.Location.Y + delta);
}
if (ClientSize.Height < _cancelButton.Location.Y + _cancelButton.Height)
{
var delta = ClientSize.Height - (_cancelButton.Location.Y + _cancelButton.Height) - 4;
_cancelButton.Location = new System.Drawing.Point(_cancelButton.Location.X, _cancelButton.Location.Y + delta);
}
}
}
}
}
|
Test password for new students. | using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using StudentFollowingSystem.Data.Repositories;
using StudentFollowingSystem.Filters;
using StudentFollowingSystem.Models;
using StudentFollowingSystem.ViewModels;
using Validatr.Filters;
namespace StudentFollowingSystem.Controllers
{
[AuthorizeCounseler]
public class StudentsController : Controller
{
private readonly StudentRepository _studentRepository = new StudentRepository();
public ActionResult Dashboard()
{
var model = new StudentDashboardModel();
return View(model);
}
public ActionResult List()
{
var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll());
return View(students);
}
public ActionResult Add()
{
return View(new StudentModel());
}
[HttpPost]
public ActionResult Add(StudentModel model)
{
if (ModelState.IsValid)
{
var student = Mapper.Map<Student>(model);
_studentRepository.Add(student);
return RedirectToAction("List");
}
return View(model);
}
}
}
| using System.Collections.Generic;
using System.Web.Helpers;
using System.Web.Mvc;
using AutoMapper;
using StudentFollowingSystem.Data.Repositories;
using StudentFollowingSystem.Filters;
using StudentFollowingSystem.Models;
using StudentFollowingSystem.ViewModels;
namespace StudentFollowingSystem.Controllers
{
[AuthorizeCounseler]
public class StudentsController : Controller
{
private readonly StudentRepository _studentRepository = new StudentRepository();
public ActionResult Dashboard()
{
var model = new StudentDashboardModel();
return View(model);
}
public ActionResult List()
{
var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll());
return View(students);
}
public ActionResult Add()
{
return View(new StudentModel());
}
[HttpPost]
public ActionResult Add(StudentModel model)
{
if (ModelState.IsValid)
{
var student = Mapper.Map<Student>(model);
student.Password = Crypto.HashPassword("test");
_studentRepository.Add(student);
return RedirectToAction("List");
}
return View(model);
}
}
}
|
Fix hand-written Monitoring snippet to use resource names | // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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 Google.Api;
using Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Cloud.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class MetricServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public MetricServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ListMetricDescriptors()
{
string projectId = _fixture.ProjectId;
// Sample: ListMetricDescriptors
// Additional: ListMetricDescriptors(*,*,*,*)
MetricServiceClient client = MetricServiceClient.Create();
string projectName = new ProjectName(projectId).ToString();
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName);
foreach (MetricDescriptor metric in metrics.Take(10))
{
Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
}
// End sample
}
}
}
| // Copyright 2016 Google Inc. All Rights Reserved.
//
// 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 Google.Api;
using Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Cloud.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class MetricServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public MetricServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ListMetricDescriptors()
{
string projectId = _fixture.ProjectId;
// Sample: ListMetricDescriptors
// Additional: ListMetricDescriptors(*,*,*,*)
MetricServiceClient client = MetricServiceClient.Create();
ProjectName projectName = new ProjectName(projectId);
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName);
foreach (MetricDescriptor metric in metrics.Take(10))
{
Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
}
// End sample
}
}
}
|
Add get method for teacher name | using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Teacher
{
public Requirements requirements { get; internal set; }
public string name { get; internal set; }
public Teacher(Requirements requirements, string name)
{
this.requirements = requirements;
this.name = name;
}
}
}
| using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Teacher
{
public Requirements requirements { get; internal set; }
public string name { get; internal set; }
public string Name
{
get { return name; }
}
public Teacher(Requirements requirements, string name)
{
this.requirements = requirements;
this.name = name;
}
}
}
|
Make styling consistent between files | // Note.cs
// <copyright file="Note.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
namespace Todo_List
{
/// <summary>
/// A data representation of a note.
/// </summary>
public class Note
{
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
public Note()
{
this.Title = string.Empty;
this.Categories = new string[0];
}
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
/// <param name="title"> The title of the note. </param>
/// <param name="categories"> The categories the note is in. </param>
public Note(string title, string[] categories)
{
this.Title = title;
this.Categories = categories;
}
/// <summary>
/// Gets or sets the title of the note.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the categories the note is in.
/// </summary>
public string[] Categories { get; set; }
}
}
| // Note.cs
// <copyright file="Note.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
namespace Todo_List
{
/// <summary>
/// A data representation of a note.
/// </summary>
public class Note
{
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
public Note()
{
Title = string.Empty;
Categories = new string[0];
}
/// <summary>
/// Initializes a new instance of the <see cref="Note" /> class.
/// </summary>
/// <param name="title"> The title of the note. </param>
/// <param name="categories"> The categories the note is in. </param>
public Note(string title, string[] categories)
{
Title = title;
Categories = categories;
}
/// <summary>
/// Gets or sets the title of the note.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the categories the note is in.
/// </summary>
public string[] Categories { get; set; }
}
}
|
Fix bug when deactivating ibus keyboards Setting the Keyboard to null in GlobalInputContext.Clear prevented the IbusKeyboardAdaptor.SetIMEKeyboard method from disabling the keyboard. | #if __MonoCS__
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using IBusDotNet;
using NDesk.DBus;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// a global cache used only to reduce traffic with ibus via dbus.
/// </summary>
internal static class GlobalCachedInputContext
{
/// <summary>
/// Caches the current InputContext.
/// </summary>
public static InputContext InputContext { get; set; }
/// <summary>
/// Cache the keyboard of the InputContext.
/// </summary>
public static IBusKeyboardDescription Keyboard { get; set; }
/// <summary>
/// Clear the cached InputContext details.
/// </summary>
public static void Clear()
{
Keyboard = null;
InputContext = null;
}
}
}
#endif | #if __MonoCS__
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using IBusDotNet;
using NDesk.DBus;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// a global cache used only to reduce traffic with ibus via dbus.
/// </summary>
internal static class GlobalCachedInputContext
{
/// <summary>
/// Caches the current InputContext.
/// </summary>
public static InputContext InputContext { get; set; }
/// <summary>
/// Cache the keyboard of the InputContext.
/// </summary>
public static IBusKeyboardDescription Keyboard { get; set; }
/// <summary>
/// Clear the cached InputContext details.
/// </summary>
public static void Clear()
{
InputContext = null;
}
}
}
#endif |
Remove old serialization check that is no longer required | using System;
using System.IO;
using System.Runtime.Serialization;
using ProtoBuf;
using ProtoBuf.Meta;
namespace Dx.Runtime
{
public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer
{
private readonly ILocalNode m_LocalNode;
public DefaultObjectWithTypeSerializer(ILocalNode localNode)
{
this.m_LocalNode = localNode;
}
public ObjectWithType Serialize(object obj)
{
if (obj == null)
{
return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null };
}
byte[] serializedObject;
using (var memory = new MemoryStream())
{
Serializer.Serialize(memory, obj);
var length = (int)memory.Position;
memory.Seek(0, SeekOrigin.Begin);
serializedObject = new byte[length];
memory.Read(serializedObject, 0, length);
}
return new ObjectWithType
{
AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName,
SerializedObject = serializedObject
};
}
public object Deserialize(ObjectWithType owt)
{
if (owt.AssemblyQualifiedTypeName == null)
{
return null;
}
var type = Type.GetType(owt.AssemblyQualifiedTypeName);
if (type == null)
{
throw new TypeLoadException();
}
using (var memory = new MemoryStream(owt.SerializedObject))
{
object instance;
if (type == typeof(string))
{
instance = string.Empty;
}
else
{
instance = FormatterServices.GetUninitializedObject(type);
}
var value = RuntimeTypeModel.Default.Deserialize(memory, instance, type);
GraphWalker.Apply(value, this.m_LocalNode);
return value;
}
}
}
}
| using System;
using System.IO;
using System.Runtime.Serialization;
using ProtoBuf;
using ProtoBuf.Meta;
namespace Dx.Runtime
{
public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer
{
private readonly ILocalNode m_LocalNode;
public DefaultObjectWithTypeSerializer(ILocalNode localNode)
{
this.m_LocalNode = localNode;
}
public ObjectWithType Serialize(object obj)
{
if (obj == null)
{
return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null };
}
byte[] serializedObject;
using (var memory = new MemoryStream())
{
Serializer.Serialize(memory, obj);
var length = (int)memory.Position;
memory.Seek(0, SeekOrigin.Begin);
serializedObject = new byte[length];
memory.Read(serializedObject, 0, length);
}
return new ObjectWithType
{
AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName,
SerializedObject = serializedObject
};
}
public object Deserialize(ObjectWithType owt)
{
if (owt.AssemblyQualifiedTypeName == null)
{
return null;
}
var type = Type.GetType(owt.AssemblyQualifiedTypeName);
if (type == null)
{
throw new TypeLoadException();
}
using (var memory = new MemoryStream(owt.SerializedObject))
{
var value = RuntimeTypeModel.Default.Deserialize(memory, null, type);
GraphWalker.Apply(value, this.m_LocalNode);
return value;
}
}
}
}
|
Clean code with using instead of fixed namespaces | namespace TheCollection.Domain.Contracts.Repository {
using System.Collections.Generic;
using System.Threading.Tasks;
public interface ILinqSearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchItemsAsync(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate = null, int pageSize = 0, int page = 0);
}
}
| namespace TheCollection.Domain.Contracts.Repository {
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
public interface ILinqSearchRepository<T> where T : class {
Task<IEnumerable<T>> SearchItemsAsync(Expression<Func<T, bool>> predicate = null, int pageSize = 0, int page = 0);
}
}
|
Simplify logic in user profile validation | using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
[Display(Name = "Associated skills")]
public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();
public string Name { get; set; }
[Display(Name = "Time Zone")]
[Required]
public string TimeZoneId { get; set; }
public string PendingNewEmail { get; set; }
public IEnumerable<ValidationResult> ValidateProfileCompleteness()
{
List<ValidationResult> validationResults = new List<ValidationResult>();
if (!EmailConfirmed)
{
validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
}
if (string.IsNullOrWhiteSpace(Name))
{
validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
}
if (string.IsNullOrWhiteSpace(PhoneNumber))
{
validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
}
if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumberConfirmed)
{
validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
}
return validationResults;
}
public bool IsProfileComplete()
{
return !ValidateProfileCompleteness().Any();
}
}
} | using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
[Display(Name = "Associated skills")]
public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();
public string Name { get; set; }
[Display(Name = "Time Zone")]
[Required]
public string TimeZoneId { get; set; }
public string PendingNewEmail { get; set; }
public IEnumerable<ValidationResult> ValidateProfileCompleteness()
{
List<ValidationResult> validationResults = new List<ValidationResult>();
if (!EmailConfirmed)
{
validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
}
if (string.IsNullOrWhiteSpace(Name))
{
validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
}
if (string.IsNullOrWhiteSpace(PhoneNumber))
{
validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
}
else if (!PhoneNumberConfirmed)
{
validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
}
return validationResults;
}
public bool IsProfileComplete()
{
return !ValidateProfileCompleteness().Any();
}
}
} |
Add unit test for partition change | using System.Linq;
using Xunit;
namespace PagedList.Tests
{
public class SplitAndPartitionFacts
{
[Fact]
public void Partition_Works()
{
//arrange
var list = Enumerable.Range(1, 9999);
//act
var splitList = list.Partition(1000);
//assert
Assert.Equal(10, splitList.Count());
Assert.Equal(1000, splitList.First().Count());
Assert.Equal(999, splitList.Last().Count());
}
[Fact]
public void Split_Works()
{
//arrange
var list = Enumerable.Range(1, 9999);
//act
var splitList = list.Split(10);
//assert
Assert.Equal(10, splitList.Count());
Assert.Equal(1000, splitList.First().Count());
Assert.Equal(999, splitList.Last().Count());
}
}
} | using System.Linq;
using Xunit;
namespace PagedList.Tests
{
public class SplitAndPartitionFacts
{
[Fact]
public void Partition_Works()
{
//arrange
var list = Enumerable.Range(1, 9999);
//act
var splitList = list.Partition(1000);
//assert
Assert.Equal(10, splitList.Count());
Assert.Equal(1000, splitList.First().Count());
Assert.Equal(999, splitList.Last().Count());
}
[Fact]
public void Paritiion_Returns_Enumerable_With_One_Item_When_Count_Less_Than_Page_Size()
{
//arrange
var list = Enumerable.Range(1,10);
//act
var partitionList = list.Partition(1000);
//assert
Assert.Equal(1, splitList.Count());
Assert.Equal(10, splitList.First().Count());
}
[Fact]
public void Split_Works()
{
//arrange
var list = Enumerable.Range(1, 9999);
//act
var splitList = list.Split(10);
//assert
Assert.Equal(10, splitList.Count());
Assert.Equal(1000, splitList.First().Count());
Assert.Equal(999, splitList.Last().Count());
}
}
} |
Improve error message when BlogPost.Content markdown to html fails | using System;
using System.Web;
using Casper.Domain.Features.BlogPosts;
using CroquetAustraliaWebsite.Library.Content;
namespace CroquetAustraliaWebsite.Application.App.home
{
public class BlogPostViewModel
{
private readonly BlogPost _blogPost;
private readonly Lazy<IHtmlString> _contentFactory;
public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer)
{
_blogPost = blogPost;
_contentFactory = new Lazy<IHtmlString>(() => markdownTransformer.MarkdownToHtml(_blogPost.Content));
}
public string Title { get { return _blogPost.Title; } }
public IHtmlString Content { get { return _contentFactory.Value; } }
public DateTimeOffset Published { get { return _blogPost.Published; } }
}
} | using System;
using System.Web;
using Anotar.NLog;
using Casper.Domain.Features.BlogPosts;
using CroquetAustraliaWebsite.Library.Content;
namespace CroquetAustraliaWebsite.Application.App.home
{
public class BlogPostViewModel
{
private readonly BlogPost _blogPost;
private readonly Lazy<IHtmlString> _contentFactory;
public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer)
{
_blogPost = blogPost;
_contentFactory = new Lazy<IHtmlString>(() => MarkdownToHtml(markdownTransformer));
}
public string Title => _blogPost.Title;
public IHtmlString Content => _contentFactory.Value;
public DateTimeOffset Published => _blogPost.Published;
private IHtmlString MarkdownToHtml(IMarkdownTransformer markdownTransformer)
{
try
{
return markdownTransformer.MarkdownToHtml(_blogPost.Content);
}
catch (Exception innerException)
{
var exception = new Exception($"Could not convert content of blog post '{Title}' to HTML.",
innerException);
exception.Data.Add("BlogPost.Title", _blogPost.Title);
exception.Data.Add("BlogPost.Content", _blogPost.Content);
exception.Data.Add("BlogPost.Published", _blogPost.Published);
exception.Data.Add("BlogPost.RelativeUri", _blogPost.RelativeUri);
LogTo.ErrorException(exception.Message, exception);
return new HtmlString("<p>Content currently not available.<p>");
}
}
}
} |
Fix misordered hit error in score meter types | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (bottom)")]
HitErrorBottom,
[Description("Hit Error (left+right)")]
HitErrorBoth,
[Description("Colour (left)")]
ColourLeft,
[Description("Colour (right)")]
ColourRight,
[Description("Colour (left+right)")]
ColourBoth,
[Description("Colour (bottom)")]
ColourBottom,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (left+right)")]
HitErrorBoth,
[Description("Hit Error (bottom)")]
HitErrorBottom,
[Description("Colour (left)")]
ColourLeft,
[Description("Colour (right)")]
ColourRight,
[Description("Colour (left+right)")]
ColourBoth,
[Description("Colour (bottom)")]
ColourBottom,
}
}
|
Replace hardcoded string with constant | using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
namespace AuthSamples.ClaimsTransformer.Controllers
{
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
private bool ValidateLogin(string userName, string password)
{
// For this sample, all logins are successful.
return true;
}
[HttpPost]
public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
// Normally Identity handles sign in, but you can do it directly
if (ValidateLogin(userName, password))
{
var claims = new List<Claim>
{
new Claim("user", userName),
new Claim("role", "Member")
};
await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role")));
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return Redirect("/");
}
}
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
}
| using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
namespace AuthSamples.ClaimsTransformer.Controllers
{
public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
private bool ValidateLogin(string userName, string password)
{
// For this sample, all logins are successful.
return true;
}
[HttpPost]
public async Task<IActionResult> Login(string userName, string password, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
// Normally Identity handles sign in, but you can do it directly
if (ValidateLogin(userName, password))
{
var claims = new List<Claim>
{
new Claim("user", userName),
new Claim("role", "Member")
};
await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme, "user", "role")));
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return Redirect("/");
}
}
return View();
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
}
|
Change subcommand60 packet test case name in VS | namespace Booma.Proxy
{
public sealed partial class CapturedPacketsTests
{
public class PacketCaptureTestEntry
{
public short OpCode { get; }
public byte[] BinaryData { get; }
public string FileName { get; }
/// <inheritdoc />
public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName)
{
OpCode = opCode;
BinaryData = binaryData;
FileName = fileName;
}
/// <inheritdoc />
public override string ToString()
{
//Special naming for 0x60 to make it easier to search
if(OpCode == 0x60)
return FileName.Replace("0x60_", $"0x60_0x{BinaryData[6]:X}_");
return $"{FileName}";
}
/// <inheritdoc />
public override int GetHashCode()
{
return FileName.GetHashCode();
}
}
}
}
| namespace Booma.Proxy
{
public sealed partial class CapturedPacketsTests
{
public class PacketCaptureTestEntry
{
public short OpCode { get; }
public byte[] BinaryData { get; }
public string FileName { get; }
/// <inheritdoc />
public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName)
{
OpCode = opCode;
BinaryData = binaryData;
FileName = fileName;
}
/// <inheritdoc />
public override string ToString()
{
//Special naming for 0x60 to make it easier to search
if(OpCode == 0x60)
return FileName.Replace("0x60_", $"0x60_0x{(int)(BinaryData[6]):X2}_");
return $"{FileName}";
}
/// <inheritdoc />
public override int GetHashCode()
{
return FileName.GetHashCode();
}
}
}
}
|
Tweak screenshot notification script (minor edit) | using System;
using System.Windows.Forms;
using CefSharp;
using TweetDck.Core.Bridge;
using TweetDck.Core.Controls;
using TweetDck.Resources;
namespace TweetDck.Core.Notification.Screenshot{
sealed class FormNotificationScreenshotable : FormNotification{
public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){
browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback));
browser.FrameLoadEnd += (sender, args) => {
if (args.Frame.IsMain && browser.Address != "about:blank"){
ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout(() => $TD_NotificationScreenshot.trigger(), 25)", "gen:screenshot");
}
};
UpdateTitle();
}
public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){
browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks);
Location = ControlExtensions.InvisibleLocation;
FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None;
SetNotificationSize(width, height, false);
}
public void TakeScreenshotAndHide(){
MoveToVisibleLocation();
Activate();
SendKeys.SendWait("%{PRTSC}");
Reset();
}
public void Reset(){
Location = ControlExtensions.InvisibleLocation;
browser.LoadHtml("", "about:blank");
}
}
}
| using System;
using System.Windows.Forms;
using CefSharp;
using TweetDck.Core.Bridge;
using TweetDck.Core.Controls;
using TweetDck.Resources;
namespace TweetDck.Core.Notification.Screenshot{
sealed class FormNotificationScreenshotable : FormNotification{
public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){
browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback));
browser.FrameLoadEnd += (sender, args) => {
if (args.Frame.IsMain && browser.Address != "about:blank"){
ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout($TD_NotificationScreenshot.trigger, 25)", "gen:screenshot");
}
};
UpdateTitle();
}
public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){
browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks);
Location = ControlExtensions.InvisibleLocation;
FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None;
SetNotificationSize(width, height, false);
}
public void TakeScreenshotAndHide(){
MoveToVisibleLocation();
Activate();
SendKeys.SendWait("%{PRTSC}");
Reset();
}
public void Reset(){
Location = ControlExtensions.InvisibleLocation;
browser.LoadHtml("", "about:blank");
}
}
}
|
Add temporary warning of upcoming lab closure. | @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="col-8">
<p class="lead">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</p>
<p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p>
<p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.
</p>
<p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the
operation of a number of analytical methods and instruments.</p>
</div>
<div class="col-4">
<address>
<p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p>
</address>
</div>
|
Fix IP look up page broken | using Newtonsoft.Json;
namespace AzureSpeed.WebUI.Models
{
public class Prefix
{
[JsonProperty("ip_prefix")]
public string IpPrefix { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("region")]
public string Service { get; set; }
}
} | using Newtonsoft.Json;
namespace AzureSpeed.WebUI.Models
{
public class Prefix
{
[JsonProperty("ip_prefix")]
public string IpPrefix { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("service")]
public string Service { get; set; }
}
} |
Remove Idle timeout in IIS | using System;
using System.Diagnostics;
using Microsoft.Web.Administration;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Linq;
namespace SFA.DAS.ReferenceData.Api
{
public class WebRole : RoleEntryPoint
{
public override void Run()
{
using (var serverManager = new ServerManager())
{
foreach (var application in serverManager.Sites.SelectMany(x => x.Applications))
{
application["preloadEnabled"] = true;
}
foreach (var applicationPool in serverManager.ApplicationPools)
{
applicationPool["startMode"] = "AlwaysRunning";
}
serverManager.CommitChanges();
}
base.Run();
}
}
} | using System;
using System.Diagnostics;
using Microsoft.Web.Administration;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Linq;
namespace SFA.DAS.ReferenceData.Api
{
public class WebRole : RoleEntryPoint
{
public override void Run()
{
using (var serverManager = new ServerManager())
{
foreach (var application in serverManager.Sites.SelectMany(x => x.Applications))
{
application["preloadEnabled"] = true;
}
foreach (var applicationPool in serverManager.ApplicationPools)
{
applicationPool["startMode"] = "AlwaysRunning";
applicationPool.ProcessModel.IdleTimeout = new System.TimeSpan(0);
}
serverManager.CommitChanges();
}
base.Run();
}
}
} |
Fix example of strings exercise | static class LogLine
{
public static string Message(string logLine)
{
return logLine.Substring(logLine.IndexOf(":") + 1).Trim();
}
public static string LogLevel(string logLine)
{
return logLine.Substring(1, (logLine.IndexOf("]") - 1).ToLower();
}
public static string Reformat(string logLine)
{
return $"{Message(logLine)} ({LogLevel(logLine)})";
}
}
| static class LogLine
{
public static string Message(string logLine)
{
return logLine.Substring(logLine.IndexOf(":") + 1).Trim();
}
public static string LogLevel(string logLine)
{
return logLine.Substring(1, logLine.IndexOf("]") - 1).ToLower();
}
public static string Reformat(string logLine)
{
return $"{Message(logLine)} ({LogLevel(logLine)})";
}
}
|
Use new Process interface in tests | using System;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Interfaces;
using Moq;
namespace CIV.Test
{
public static class Common
{
/// <summary>
/// Setup a mock process that can only do the given action.
/// </summary>
/// <returns>The mock process.</returns>
/// <param name="action">Action.</param>
public static CcsProcess SetupMockProcess(String action = "action")
{
return Mock.Of<CcsProcess>(p => p.Transitions() == new List<Transition>
{
SetupTransition(action)
}
);
}
static Transition SetupTransition(String label)
{
return new Transition
{
Label = label,
Process = Mock.Of<CcsProcess>()
};
}
}
}
| using System;
using System.Collections.Generic;
using CIV.Ccs;
using CIV.Interfaces;
using Moq;
namespace CIV.Test
{
public static class Common
{
/// <summary>
/// Setup a mock process that can only do the given action.
/// </summary>
/// <returns>The mock process.</returns>
/// <param name="action">Action.</param>
public static CcsProcess SetupMockProcess(String action = "action")
{
return Mock.Of<CcsProcess>(p => p.GetTransitions() == new List<Transition>
{
SetupTransition(action)
}
);
}
static Transition SetupTransition(String label)
{
return new Transition
{
Label = label,
Process = Mock.Of<CcsProcess>()
};
}
}
}
|
Add Link method to compare string with wildcards | using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework
{
public static class Extension
{
public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
{
using (ct.Register(() => request.Abort(), useSynchronizationContext: false))
{
try
{
var response = await request.GetResponseAsync();
ct.ThrowIfCancellationRequested();
return (HttpWebResponse)response;
}
catch (WebException webEx)
{
if (ct.IsCancellationRequested)
{
throw new OperationCanceledException(webEx.Message, webEx, ct);
}
throw;
}
}
}
public static T[] Dequeue<T>(this Queue<T> queue, int count)
{
T[] list = new T[count];
for (int i = 0; i < count; i++)
{
list[i] = queue.Dequeue();
}
return list;
}
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace TirkxDownloader.Framework
{
public static class Extension
{
public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
{
using (ct.Register(() => request.Abort(), useSynchronizationContext: false))
{
try
{
var response = await request.GetResponseAsync();
ct.ThrowIfCancellationRequested();
return (HttpWebResponse)response;
}
catch (WebException webEx)
{
if (ct.IsCancellationRequested)
{
throw new OperationCanceledException(webEx.Message, webEx, ct);
}
throw;
}
}
}
public static T[] Dequeue<T>(this Queue<T> queue, int count)
{
T[] list = new T[count];
for (int i = 0; i < count; i++)
{
list[i] = queue.Dequeue();
}
return list;
}
/// <summary>
/// Compares the string against a given pattern.
/// </summary>
/// <param name="str">The string.</param>
/// <param name="pattern">The pattern to match, where "*" means any sequence of characters, and "?" means any single character.</param>
/// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns>
public static bool Like(this string str, string pattern)
{
return new Regex(
"^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
).IsMatch(str);
}
}
}
|
Add parameter for a REQUEST type API Gateway Custom Authorizer | namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// For requests coming in to a custom API Gateway authorizer function.
/// </summary>
public class APIGatewayCustomAuthorizerRequest
{
/// <summary>
/// Gets or sets the 'type' property.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the 'authorizationToken' property.
/// </summary>
public string AuthorizationToken { get; set; }
/// <summary>
/// Gets or sets the 'methodArn' property.
/// </summary>
public string MethodArn { get; set; }
}
}
| using System.Collections.Generic;
namespace Amazon.Lambda.APIGatewayEvents
{
/// <summary>
/// For requests coming in to a custom API Gateway authorizer function.
/// </summary>
public class APIGatewayCustomAuthorizerRequest
{
/// <summary>
/// Gets or sets the 'type' property.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the 'authorizationToken' property.
/// </summary>
public string AuthorizationToken { get; set; }
/// <summary>
/// Gets or sets the 'methodArn' property.
/// </summary>
public string MethodArn { get; set; }
/// <summary>
/// The url path for the caller. For Request type API Gateway Custom Authorizer only.
/// </summary>
public string Path { get; set; }
/// <summary>
/// The HTTP method used. For Request type API Gateway Custom Authorizer only.
/// </summary>
public string HttpMethod { get; set; }
/// <summary>
/// The headers sent with the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> Headers {get;set;}
/// <summary>
/// The query string parameters that were part of the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> QueryStringParameters { get; set; }
/// <summary>
/// The path parameters that were part of the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> PathParameters { get; set; }
/// <summary>
/// The stage variables defined for the stage in API Gateway. For Request type API Gateway Custom Authorizer only.
/// </summary>
public IDictionary<string, string> StageVariables { get; set; }
/// <summary>
/// The request context for the request. For Request type API Gateway Custom Authorizer only.
/// </summary>
public APIGatewayProxyRequest.ProxyRequestContext RequestContext { get; set; }
}
}
|
Increment library version as version on pre-release line messed up versioning | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyProduct("Aggregates.NET")]
[assembly: AssemblyDescription(".NET event sourced domain driven design model via NServiceBus and EventStore")]
[assembly: AssemblyCopyright("Copyright © Charles Solar 2017")]
[assembly: AssemblyVersion("0.12.0.0")]
[assembly: AssemblyFileVersion("0.12.0.0")]
[assembly: AssemblyInformationalVersion("0.12.0.0")]
[assembly: InternalsVisibleTo("Aggregates.NET.UnitTests")]
[assembly: InternalsVisibleTo("Aggregates.NET")]
[assembly: InternalsVisibleTo("Aggregates.NET.EventStore")]
[assembly: InternalsVisibleTo("Aggregates.NET.NServiceBus")]
[assembly: InternalsVisibleTo("Aggregates.NET.NewtonsoftJson")]
[assembly: InternalsVisibleTo("Aggregates.NET.StructureMap")]
[assembly: InternalsVisibleTo("Aggregates.NET.SimpleInjector")]
| using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyProduct("Aggregates.NET")]
[assembly: AssemblyDescription(".NET event sourced domain driven design model via NServiceBus and EventStore")]
[assembly: AssemblyCopyright("Copyright © Charles Solar 2017")]
[assembly: AssemblyVersion("0.13.0.0")]
[assembly: AssemblyFileVersion("0.13.0.0")]
[assembly: AssemblyInformationalVersion("0.13.0.0")]
[assembly: InternalsVisibleTo("Aggregates.NET.UnitTests")]
[assembly: InternalsVisibleTo("Aggregates.NET")]
[assembly: InternalsVisibleTo("Aggregates.NET.EventStore")]
[assembly: InternalsVisibleTo("Aggregates.NET.NServiceBus")]
[assembly: InternalsVisibleTo("Aggregates.NET.NewtonsoftJson")]
[assembly: InternalsVisibleTo("Aggregates.NET.StructureMap")]
[assembly: InternalsVisibleTo("Aggregates.NET.SimpleInjector")]
|
Add description for magic params | namespace HeyRed.Mime
{
public enum MagicParams
{
MAGIC_PARAM_INDIR_MAX = 0,
MAGIC_PARAM_NAME_MAX,
MAGIC_PARAM_ELF_PHNUM_MAX,
MAGIC_PARAM_ELF_SHNUM_MAX,
MAGIC_PARAM_ELF_NOTES_MAX,
MAGIC_PARAM_REGEX_MAX,
MAGIC_PARAM_BYTES_MAX
}
}
| namespace HeyRed.Mime
{
public enum MagicParams
{
/// <summary>
/// The parameter controls how many levels of recursion will be followed for indirect magic entries.
/// </summary>
MAGIC_PARAM_INDIR_MAX = 0,
/// <summary>
/// The parameter controls the maximum number of calls for name/use.
/// </summary>
MAGIC_PARAM_NAME_MAX,
/// <summary>
/// The parameter controls how many ELF program sections will be processed.
/// </summary>
MAGIC_PARAM_ELF_PHNUM_MAX,
/// <summary>
/// The parameter controls how many ELF sections will be processed.
/// </summary>
MAGIC_PARAM_ELF_SHNUM_MAX,
/// <summary>
/// The parameter controls how many ELF notes will be processed.
/// </summary>
MAGIC_PARAM_ELF_NOTES_MAX,
MAGIC_PARAM_REGEX_MAX,
MAGIC_PARAM_BYTES_MAX
}
}
|
Make main screen a bit more identifiable | using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Screens;
namespace TemplateGame.Game
{
public class MainScreen : Screen
{
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new SpinningBox
{
Anchor = Anchor.Centre,
});
}
}
}
| using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Screens;
using osuTK.Graphics;
namespace TemplateGame.Game
{
public class MainScreen : Screen
{
[BackgroundDependencyLoader]
private void load()
{
InternalChildren = new Drawable[]
{
new Box
{
Colour = Color4.Violet,
RelativeSizeAxes = Axes.Both,
},
new SpriteText
{
Y = 20,
Text = "Main Screen",
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Font = FontUsage.Default.With(size: 40)
},
new SpinningBox
{
Anchor = Anchor.Centre,
}
};
}
}
}
|
Change expiry job back to 28th | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
public ExpireFundsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 0 10 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ExpireFundsCommand());
}
}
} | using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using NServiceBus;
using SFA.DAS.EmployerFinance.Messages.Commands;
namespace SFA.DAS.EmployerFinance.Jobs.ScheduledJobs
{
public class ExpireFundsJob
{
private readonly IMessageSession _messageSession;
public ExpireFundsJob(IMessageSession messageSession)
{
_messageSession = messageSession;
}
public Task Run([TimerTrigger("0 0 0 28 * *")] TimerInfo timer, ILogger logger)
{
return _messageSession.Send(new ExpireFundsCommand());
}
}
} |
Use file version as client version | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.EventHubs
{
using System;
using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.Azure.Amqp;
static class ClientInfo
{
static readonly string product;
static readonly string version;
static readonly string framework;
static readonly string platform;
static ClientInfo()
{
try
{
Assembly assembly = typeof(ClientInfo).GetTypeInfo().Assembly;
product = GetAssemblyAttributeValue<AssemblyProductAttribute>(assembly, p => p.Product);
version = GetAssemblyAttributeValue<AssemblyVersionAttribute>(assembly, v => v.Version);
framework = GetAssemblyAttributeValue<TargetFrameworkAttribute>(assembly, f => f.FrameworkName);
#if NETSTANDARD
platform = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
#else
platform = Environment.OSVersion.VersionString;
#endif
}
catch { }
}
public static void Add(AmqpConnectionSettings settings)
{
settings.AddProperty("product", product);
settings.AddProperty("version", version);
settings.AddProperty("framework", framework);
settings.AddProperty("platform", platform);
}
static string GetAssemblyAttributeValue<T>(Assembly assembly, Func<T, string> getter) where T : Attribute
{
var attribute = assembly.GetCustomAttribute(typeof(T)) as T;
return attribute == null ? null : getter(attribute);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.EventHubs
{
using System;
using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.Azure.Amqp;
static class ClientInfo
{
static readonly string product;
static readonly string version;
static readonly string framework;
static readonly string platform;
static ClientInfo()
{
try
{
Assembly assembly = typeof(ClientInfo).GetTypeInfo().Assembly;
product = GetAssemblyAttributeValue<AssemblyProductAttribute>(assembly, p => p.Product);
version = GetAssemblyAttributeValue<AssemblyFileVersionAttribute>(assembly, v => v.Version);
framework = GetAssemblyAttributeValue<TargetFrameworkAttribute>(assembly, f => f.FrameworkName);
#if NETSTANDARD
platform = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
#else
platform = Environment.OSVersion.VersionString;
#endif
}
catch { }
}
public static void Add(AmqpConnectionSettings settings)
{
settings.AddProperty("product", product);
settings.AddProperty("version", version);
settings.AddProperty("framework", framework);
settings.AddProperty("platform", platform);
}
static string GetAssemblyAttributeValue<T>(Assembly assembly, Func<T, string> getter) where T : Attribute
{
var attribute = assembly.GetCustomAttribute(typeof(T)) as T;
return attribute == null ? null : getter(attribute);
}
}
}
|
Make different mod name in patched version | using ICities;
using MetroOverhaul.OptionsFramework.Extensions;
namespace MetroOverhaul
{
public class Mod : IUserMod
{
public string Name => "Metro Overhaul";
public string Description => "Brings metro depots, ground and elevated metro tracks";
public void OnSettingsUI(UIHelperBase helper)
{
helper.AddOptionsGroup<Options>();
}
}
}
| using ICities;
using MetroOverhaul.OptionsFramework.Extensions;
namespace MetroOverhaul
{
public class Mod : IUserMod
{
#if IS_PATCH
public const bool isPatch = true;
#else
public const bool isPatch = false;
#endif
public string Name => "Metro Overhaul" + (isPatch ? " [Patched]" : "");
public string Description => "Brings metro depots, ground and elevated metro tracks";
public void OnSettingsUI(UIHelperBase helper)
{
helper.AddOptionsGroup<Options>();
}
}
}
|
Remove requirement for [schema_owner] = 'dbo' | using NBi.Core.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Structure.Relational.Builders
{
class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder
{
protected override string BasicCommandText
{
get { return base.BasicCommandText + " and [schema_owner]='dbo'"; }
}
public SchemaDiscoveryCommandBuilder()
{
CaptionName = "schema";
TableName = "schemata";
}
protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters)
{
var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
if (filter != null)
yield return new CommandFilter(string.Format("[schema_name]='{0}'"
, filter.Caption
));
}
}
}
| using NBi.Core.Structure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Structure.Relational.Builders
{
class SchemaDiscoveryCommandBuilder : RelationalDiscoveryCommandBuilder
{
protected override string BasicCommandText
{
get { return base.BasicCommandText; }
}
public SchemaDiscoveryCommandBuilder()
{
CaptionName = "schema";
TableName = "schemata";
}
protected override IEnumerable<ICommandFilter> BuildCaptionFilters(IEnumerable<CaptionFilter> filters)
{
var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
if (filter != null)
yield return new CommandFilter(string.Format("[schema_name]='{0}'"
, filter.Caption
));
}
}
}
|
Correct href in <see/> tag | using System;
namespace Plethora
{
public static class MathEx
{
/// <summary>
/// Returns the greatest common divisor of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <remarks>
/// This implementation uses the Euclidean algorithm.
/// <seealso cref="https://en.wikipedia.org/wiki/Euclidean_algorithm"/>
/// </remarks>
public static int GreatestCommonDivisor(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
while (b != 0)
{
int rem = a % b;
a = b;
b = rem;
}
return a;
}
}
}
| using System;
namespace Plethora
{
public static class MathEx
{
/// <summary>
/// Returns the greatest common divisor of two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The greatest common divisor of <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <remarks>
/// This implementation uses the Euclidean algorithm.
/// <seealso href="https://en.wikipedia.org/wiki/Euclidean_algorithm"/>
/// </remarks>
public static int GreatestCommonDivisor(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
while (b != 0)
{
int rem = a % b;
a = b;
b = rem;
}
return a;
}
}
}
|
Throw an exception of [CallerMemberName] misbehaves. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ShopifyAPIAdapterLibrary.Models
{
public class ShopifyResourceModel : IResourceModel
{
public event PropertyChangedEventHandler PropertyChanged;
private HashSet<string> Dirty;
public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "")
{
// thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/
if (!EqualityComparer<T>.Default.Equals(field, value))
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
field = value;
Dirty.Add(name);
}
}
public void Reset()
{
Dirty.Clear();
}
public bool IsFieldDirty(string field)
{
return Dirty.Contains(field);
}
public bool IsClean()
{
return Dirty.Count == 0;
}
private int? id;
public int? Id
{
get { return id; }
set
{
SetProperty(ref id, value);
}
}
public ShopifyResourceModel()
{
Dirty = new HashSet<string>();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ShopifyAPIAdapterLibrary.Models
{
public class ShopifyResourceModel : IResourceModel
{
public event PropertyChangedEventHandler PropertyChanged;
private HashSet<string> Dirty;
public void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = null)
{
if (name == null)
{
throw new ShopifyConfigurationException("Field name is coming up null in SetProperty. Something's wrong.");
}
Console.WriteLine("SETTING PROPERTY {0} to {1}", name, value);
// thanks to http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/
if (!EqualityComparer<T>.Default.Equals(field, value))
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
field = value;
Dirty.Add(name);
}
}
public void Reset()
{
Dirty.Clear();
}
public bool IsFieldDirty(string field)
{
return Dirty.Contains(field);
}
public bool IsClean()
{
return Dirty.Count == 0;
}
private int? id;
public int? Id
{
get { return id; }
set
{
SetProperty(ref id, value);
}
}
public ShopifyResourceModel()
{
Dirty = new HashSet<string>();
}
}
}
|
Reduce exposure of public API | using System;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
public class IndexEntry
{
public IndexEntryState State { get; set; }
public string Path { get; private set; }
public ObjectId Id { get; private set; }
internal static IndexEntry CreateFromPtr(IntPtr ptr)
{
var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry));
return new IndexEntry
{
Path = entry.Path,
Id = new ObjectId(entry.oid),
};
}
}
} | using System;
using System.Runtime.InteropServices;
using LibGit2Sharp.Core;
namespace LibGit2Sharp
{
public class IndexEntry
{
public IndexEntryState State { get; private set; }
public string Path { get; private set; }
public ObjectId Id { get; private set; }
internal static IndexEntry CreateFromPtr(IntPtr ptr)
{
var entry = (GitIndexEntry) Marshal.PtrToStructure(ptr, typeof (GitIndexEntry));
return new IndexEntry
{
Path = entry.Path,
Id = new ObjectId(entry.oid),
};
}
}
} |
Change version to 0.9.0.0 for the premature build | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TweetDick")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TweetDick")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TweetDick")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TweetDick")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7f09373d-8beb-416f-a48d-45d8aaeb8caf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
|
Remove list element when switching scene | using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LeaderboardUI : MonoBehaviour
{
[SerializeField] private RectTransform _scoresList;
[SerializeField] private Text _sceneTitle;
[SerializeField] private string _defaultScene = "Tuto";
private const string _path = "./";
private string _filePath;
private Leaderboard _leaderboard;
private const string _leaderboardTitle = "Leaderboard - ";
private void Start ()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
LoadScene(_defaultScene);
}
public void LoadScene(string scene)
{
_filePath = _path + scene + ".json";
_leaderboard = new Leaderboard(_filePath);
_leaderboard.Show(_scoresList);
UpdateLeaderboardTitle(scene);
}
public void BackToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
private void UpdateLeaderboardTitle(string sceneTitle)
{
_sceneTitle.text = _leaderboardTitle + sceneTitle;
}
}
| using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LeaderboardUI : MonoBehaviour
{
[SerializeField] private RectTransform _scoresList;
[SerializeField] private Text _sceneTitle;
[SerializeField] private string _defaultScene = "Tuto";
private const string _path = "./";
private string _filePath;
private Leaderboard _leaderboard;
private const string _leaderboardTitle = "Leaderboard - ";
private void Start ()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
LoadScene(_defaultScene);
}
public void LoadScene(string scene)
{
ResetList();
_filePath = _path + scene + ".json";
_leaderboard = new Leaderboard(_filePath);
_leaderboard.Show(_scoresList);
UpdateLeaderboardTitle(scene);
}
private void ResetList()
{
for (var i = 0; i < _scoresList.childCount; ++i)
{
Destroy(_scoresList.GetChild(i).gameObject);
}
}
public void BackToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
private void UpdateLeaderboardTitle(string sceneTitle)
{
_sceneTitle.text = _leaderboardTitle + sceneTitle;
}
}
|
Fix for content type NULL in rare cercumstances | using System.Net.Http;
using MyCouch.Extensions;
namespace MyCouch.Responses.Materializers
{
public class BasicResponseMaterializer
{
public virtual void Materialize(Response response, HttpResponseMessage httpResponse)
{
response.RequestUri = httpResponse.RequestMessage.RequestUri;
response.StatusCode = httpResponse.StatusCode;
response.RequestMethod = httpResponse.RequestMessage.Method;
response.ContentLength = httpResponse.Content.Headers.ContentLength;
response.ContentType = httpResponse.Content.Headers.ContentType.ToString();
response.ETag = httpResponse.Headers.GetETag();
}
}
} | using System.Net.Http;
using MyCouch.Extensions;
namespace MyCouch.Responses.Materializers
{
public class BasicResponseMaterializer
{
public virtual void Materialize(Response response, HttpResponseMessage httpResponse)
{
response.RequestUri = httpResponse.RequestMessage.RequestUri;
response.StatusCode = httpResponse.StatusCode;
response.RequestMethod = httpResponse.RequestMessage.Method;
response.ContentLength = httpResponse.Content.Headers.ContentLength;
response.ContentType = httpResponse.Content.Headers.ContentType != null ? httpResponse.Content.Headers.ContentType.ToString() : null;
response.ETag = httpResponse.Headers.GetETag();
}
}
} |
Set fixed height and add debug messages for OnAppearing/OnDisappearing | using Telerik.XamarinForms.DataControls.ListView;
using TelerikListViewPoc.Components;
using Xamarin.Forms;
namespace TelerikListViewPoc.Controls
{
public class BookListCell : ListViewTemplateCell
{
public BookListCell()
{
var titleLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label))
};
titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay);
var authorLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay);
var yearLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay);
var viewLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { titleLabel, authorLabel, yearLabel }
};
this.View = viewLayout;
}
public Book DataContext
{
get { return this.BindingContext as Book; }
}
}
}
| using System.Diagnostics;
using Telerik.XamarinForms.DataControls.ListView;
using TelerikListViewPoc.Components;
using Xamarin.Forms;
namespace TelerikListViewPoc.Controls
{
public class BookListCell : ListViewTemplateCell
{
public BookListCell()
{
var titleLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Default, typeof(Label))
};
titleLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Title), BindingMode.OneWay);
var authorLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
authorLabel.SetBinding (Label.TextProperty, nameof(this.DataContext.Author), BindingMode.OneWay);
var yearLabel = new Label
{
FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label))
};
yearLabel.SetBinding(Label.TextProperty, nameof(this.DataContext.Year), BindingMode.OneWay);
var viewLayout = new StackLayout
{
Orientation = StackOrientation.Vertical,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children = { titleLabel, authorLabel, yearLabel },
HeightRequest = 100
};
this.View = viewLayout;
}
public Book DataContext
{
get { return this.BindingContext as Book; }
}
protected override void OnAppearing()
{
Debug.WriteLine("OnAppearing");
base.OnAppearing();
}
protected override void OnDisappearing()
{
Debug.WriteLine("OnDisappearing");
base.OnDisappearing();
}
}
}
|
Use struct instead of class for event/notification data. | using System;
namespace DanTup.DartAnalysis
{
#region JSON deserialisation objects
class ServerStatusEvent
{
public ServerAnalysisStatus analysis = null;
}
class ServerAnalysisStatus
{
public bool analyzing = false;
}
#endregion
public class ServerStatusNotification
{
public bool IsAnalysing { get; internal set; }
}
internal static class ServerStatusEventImplementation
{
public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler)
{
if (handler != null)
handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing });
}
}
}
| using System;
namespace DanTup.DartAnalysis
{
#region JSON deserialisation objects
class ServerStatusEvent
{
public ServerAnalysisStatus analysis = null;
}
class ServerAnalysisStatus
{
public bool analyzing = false;
}
#endregion
public struct ServerStatusNotification
{
public bool IsAnalysing { get; internal set; }
}
internal static class ServerStatusEventImplementation
{
public static void RaiseServerStatusEvent(this DartAnalysisService service, ServerStatusEvent notification, EventHandler<ServerStatusNotification> handler)
{
if (handler != null)
handler.Invoke(service, new ServerStatusNotification { IsAnalysing = notification.analysis.analyzing });
}
}
}
|
Update StringExtension to validate email | namespace AdamS.StoreTemp.Models.Common
{
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string emailAddress)
{
return !string.IsNullOrWhiteSpace(emailAddress);
}
}
} | using System.Text.RegularExpressions;
namespace AdamS.StoreTemp.Models.Common
{
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string emailAddress)
{
Regex regex = new Regex(@"^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$");
Match match = regex.Match(emailAddress);
return match.Success;
}
}
} |
Replace ASN array with IList | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected const int BgpHeaderLength = 19;
protected BgpMessage(ref ArraySegment<byte> data)
{
Header = new BgpHeader(data);
var offset = data.Offset + BgpHeaderLength;
var count = Header.Length - BgpHeaderLength;
data = new ArraySegment<byte>(data.Array, offset, count);
}
public enum Type
{
Open = 1,
Update,
Notification,
Keepalive,
RouteRefresh
}
public BgpHeader Header { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (Type) data.ElementAt(18);
switch (msgType)
{
case Type.Open:
return new BgpOpenMessage(data);
case Type.Update:
return new BgpUpdateMessage(data);
case Type.Notification:
return new BgpNotification(data);
case Type.Keepalive:
throw new NotImplementedException();
case Type.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} | using System;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected const int BgpHeaderLength = 19;
protected BgpMessage(ArraySegment<byte> data)
{
Header = new BgpHeader(data);
var offset = data.Offset + BgpHeaderLength;
var count = Header.Length - BgpHeaderLength;
MessageData = new ArraySegment<byte>(data.Array, offset, count);
}
public enum Type
{
Open = 1,
Update,
Notification,
Keepalive,
RouteRefresh
}
protected ArraySegment<byte> MessageData { get; }
public BgpHeader Header { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var msgType = (Type)data.Array[data.Offset + 18];
switch (msgType)
{
case Type.Open:
return new BgpOpenMessage(data);
case Type.Update:
return new BgpUpdateMessage(data);
case Type.Notification:
return new BgpNotification(data);
case Type.Keepalive:
throw new NotImplementedException();
case Type.RouteRefresh:
throw new NotImplementedException();
default:
throw new NotImplementedException();
}
}
}
} |
Fix MediatR examples exception handlers overrides | using MediatR.Pipeline;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediatR.Examples.ExceptionHandler.Overrides;
public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong>
{
private readonly TextWriter _writer;
public CommonExceptionHandler(TextWriter writer) => _writer = writer;
protected override async Task Handle(PingResourceTimeout request,
Exception exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler
{
private readonly TextWriter _writer;
public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer;
public override async Task Handle(PingNewResource request,
ServerException exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
} | using MediatR.Pipeline;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediatR.Examples.ExceptionHandler.Overrides;
public class CommonExceptionHandler : AsyncRequestExceptionHandler<PingResourceTimeout, Pong>
{
private readonly TextWriter _writer;
public CommonExceptionHandler(TextWriter writer) => _writer = writer;
protected override async Task Handle(PingResourceTimeout request,
Exception exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
// Exception type name required because it is checked later in messages
await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}");
// Exception handler type name required because it is checked later in messages
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(CommonExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
public class ServerExceptionHandler : ExceptionHandler.ServerExceptionHandler
{
private readonly TextWriter _writer;
public ServerExceptionHandler(TextWriter writer) : base(writer) => _writer = writer;
public override async Task Handle(PingNewResource request,
ServerException exception,
RequestExceptionHandlerState<Pong> state,
CancellationToken cancellationToken)
{
// Exception type name required because it is checked later in messages
await _writer.WriteLineAsync($"Handling {exception.GetType().FullName}");
// Exception handler type name required because it is checked later in messages
await _writer.WriteLineAsync($"---- Exception Handler: '{typeof(ServerExceptionHandler).FullName}'").ConfigureAwait(false);
state.SetHandled(new Pong());
}
}
|
Move from MSTest to NUnit | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using SharpResume.Model;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace SharpResume.Tests
{
[TestClass]
public class UnitTest
{
const string JsonName = "resume.json";
static readonly string _json = File.ReadAllText(Path.Combine(
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName,
JsonName));
readonly Resume _resume = Resume.Create(_json);
readonly dynamic _expected = JObject.Parse(_json);
[TestMethod]
public void TestName()
{
string name = _expected.basics.name;
Assert.AreEqual(name, _resume.Basics.Name);
}
[TestMethod]
public void TestCoursesCount()
{
var educations = _expected.education.ToObject<List<Education>>();
Assert.AreEqual(educations.Count, _resume.Education.Length);
}
}
}
| using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using SharpResume.Model;
using Assert = NUnit.Framework.Assert;
namespace SharpResume.Tests
{
[TestFixture]
public class UnitTest
{
const string JsonName = "resume.json";
static readonly string _json = File.ReadAllText(Path.Combine(
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName,
JsonName));
readonly Resume _resume = Resume.Create(_json);
readonly dynamic _expected = JObject.Parse(_json);
[Test]
public void TestName()
{
string name = _expected.basics.name;
Assert.AreEqual(name, _resume.Basics.Name);
}
[Test]
public void TestCoursesCount()
{
var educations = _expected.education.ToObject<List<Education>>();
Assert.AreEqual(educations.Count, _resume.Education.Length);
}
}
}
|
Fix comment (which was in an unsaved file, unfortunately) | // Copyright 2020, 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event and event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
| // Copyright 2020, 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
//
// https://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.
// TODO: Generate this file!
// This file contains partial classes for all event data messages, to apply
// the converter attributes to them.
namespace Google.Events.Protobuf.Cloud.PubSub.V1
{
[CloudEventDataConverter(typeof(ProtobufCloudEventDataConverter<PubsubMessage>))]
public partial class PubsubMessage { }
}
|
Prepare for a release - this will go out with v2 R255 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XiboClientWatchdog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XiboClientWatchdog")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XiboClientWatchdog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XiboClientWatchdog")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ec4eaabc-ad30-4ac5-8e0a-0ddb06dad4b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
|
Return IEnumerable<FulfillmentOrder> instead of ListResult<FulfillmentOrder> | using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using System;
using System.Threading;
using ShopifySharp.Lists;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify fulfillment orders.
/// </summary>
public class FulfillmentOrderService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="FulfillmentOrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a list of up to 250 of the order's fulfillments.
/// </summary>
/// <param name="orderId">The order id to which the fulfillments belong.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<ListResult<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default)
{
return await ExecuteGetListAsync<FulfillmentOrder>($"orders/{orderId}/fulfillment_orders.json", "fulfillment_orders",null, cancellationToken);
}
}
}
| using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using System;
using System.Threading;
using ShopifySharp.Lists;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify fulfillment orders.
/// </summary>
public class FulfillmentOrderService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="FulfillmentOrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public FulfillmentOrderService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a list of up to 250 of the order's fulfillments.
/// </summary>
/// <param name="orderId">The order id to which the fulfillments belong.</param>
/// <param name="cancellationToken">Cancellation Token</param>
public virtual async Task<IEnumerable<FulfillmentOrder>> ListAsync(long orderId, CancellationToken cancellationToken = default)
{
var req = PrepareRequest($"orders/{orderId}/fulfillment_orders.json");
var response = await ExecuteRequestAsync<IEnumerable<FulfillmentOrder>>(req, HttpMethod.Get, cancellationToken, rootElement: "fulfillment_orders");
return response.Result;
}
}
}
|
Fix crash when acrobat is not correctly installed | using System.Windows.Forms;
namespace XComponent.Common.UI.Pdf
{
public partial class WinFormPdfHost : UserControl
{
public WinFormPdfHost()
{
InitializeComponent();
if(!DesignMode)
axAcroPDF1.setShowToolbar(true);
}
public void LoadFile(string path)
{
if (path != null)
{
axAcroPDF1.LoadFile(path);
axAcroPDF1.src = path;
axAcroPDF1.setViewScroll("FitH", 0);
}
}
public void SetShowToolBar(bool on)
{
axAcroPDF1.setShowToolbar(on);
}
}
}
| using System;
using System.Windows.Forms;
namespace XComponent.Common.UI.Pdf
{
public partial class WinFormPdfHost : UserControl
{
public WinFormPdfHost()
{
InitializeComponent();
if(!DesignMode)
axAcroPDF1.setShowToolbar(true);
}
public void LoadFile(string path)
{
if (path != null)
{
try
{
axAcroPDF1.LoadFile(path);
axAcroPDF1.src = path;
axAcroPDF1.setViewScroll("FitH", 0);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
}
public void SetShowToolBar(bool on)
{
axAcroPDF1.setShowToolbar(on);
}
}
}
|
Move call to UseFluentActions before UseMvc in api test project | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
namespace SimpleApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
services.AddTransient<IUserService, UserService>();
services.AddTransient<INoteService, NoteService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
actions.Add(UserActions.All);
actions.Add(NoteActions.All);
});
app.UseMvc();
}
}
}
|
Fix Log4Net path for loading config file | // Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Log4NetIntegration.Logging
{
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
} | // Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Log4NetIntegration.Logging
{
using System;
using System.IO;
using MassTransit.Logging;
using log4net;
using log4net.Config;
public class Log4NetLogger :
ILogger
{
public MassTransit.Logging.ILog Get(string name)
{
return new Log4NetLog(LogManager.GetLogger(name));
}
public static void Use()
{
Logger.UseLogger(new Log4NetLogger());
}
public static void Use(string file)
{
Logger.UseLogger(new Log4NetLogger());
file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
var configFile = new FileInfo(file);
XmlConfigurator.Configure(configFile);
}
}
} |
Sort properties vs. methods; whitespace. | namespace StraightSql
{
using System;
using System.Data.Common;
public interface IReader
{
Object Read(DbDataReader reader);
Type Type { get; }
}
}
| namespace StraightSql
{
using System;
using System.Data.Common;
public interface IReader
{
Type Type { get; }
Object Read(DbDataReader reader);
}
}
|
Add using lines and namespaces | public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Shane";
public string LastName => "O'Neill";
public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... ";
public string StateOrRegion => "Ireland";
public string EmailAddress => string.Empty;
public string TwitterHandle => "SOZDBA";
public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510";
public string GitHubHandle => "shaneis";
public GeoPosition Position => new GeoPosition(53.2707, 9.0568);
public Uri WebSite => new Uri("https://nocolumnname.blog/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Shane";
public string LastName => "O'Neill";
public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... ";
public string StateOrRegion => "Ireland";
public string EmailAddress => string.Empty;
public string TwitterHandle => "SOZDBA";
public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510";
public string GitHubHandle => "shaneis";
public GeoPosition Position => new GeoPosition(53.2707, 9.0568);
public Uri WebSite => new Uri("https://nocolumnname.blog/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
}
|
Add test for new properties feature. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
namespace Log4NetlyTesting {
class Program {
static void Main(string[] args) {
log4net.Config.XmlConfigurator.Configure();
var logger = LogManager.GetLogger(typeof(Program));
////logger.Info("I know he can get the job, but can he do the job?");
////logger.Debug("I'm not arguing that with you.");
////logger.Warn("Be careful!");
logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!")));
try {
var hi = 1/int.Parse("0");
} catch (Exception ex) {
logger.Error("I'm afraid I can't do that.", ex);
}
////logger.Fatal("That's it. It's over.");
Console.ReadKey();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Core;
namespace Log4NetlyTesting {
class Program {
static void Main(string[] args) {
log4net.Config.XmlConfigurator.Configure();
var logger = LogManager.GetLogger(typeof(Program));
////logger.Info("I know he can get the job, but can he do the job?");
////logger.Debug("I'm not arguing that with you.");
////logger.Warn("Be careful!");
logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!")));
try {
var hi = 1/int.Parse("0");
} catch (Exception ex) {
logger.Error("I'm afraid I can't do that.", ex);
}
var loggingEvent = new LoggingEvent(typeof(LogManager), logger.Logger.Repository, logger.Logger.Name, Level.Fatal, "Fatal properties, here.", new IndexOutOfRangeException());
loggingEvent.Properties["Foo"] = "Bar";
loggingEvent.Properties["Han"] = "Solo";
loggingEvent.Properties["Two Words"] = "Three words here";
logger.Logger.Log(loggingEvent);
Console.ReadKey();
}
}
}
|
Fix request failing due to parameters | // 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;
if (!string.IsNullOrEmpty(Password))
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
| // 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}";
}
}
|
Enable automatic versioning and Nuget packaging of shippable Vipr binaries | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using Vipr.Core;
namespace Vipr
{
internal class Program
{
private static void Main(string[] args)
{
var bootstrapper = new Bootstrapper();
bootstrapper.Start(args);
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
namespace Vipr
{
internal class Program
{
private static void Main(string[] args)
{
var bootstrapper = new Bootstrapper();
bootstrapper.Start(args);
}
}
}
|
Use the RemoveVersion method to clean up the unnecessary first version | namespace Sitecore.FakeDb.Data.Engines.DataCommands
{
using System;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand
{
private readonly DataStorage dataStorage;
public CreateItemCommand(DataStorage dataStorage)
{
Assert.ArgumentNotNull(dataStorage, "dataStorage");
this.dataStorage = dataStorage;
}
public DataStorage DataStorage
{
get { return this.dataStorage; }
}
protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance()
{
throw new NotSupportedException();
}
protected override Item DoExecute()
{
var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID };
this.dataStorage.AddFakeItem(item);
item.VersionsCount.Clear();
return this.dataStorage.GetSitecoreItem(this.ItemId);
}
}
} | namespace Sitecore.FakeDb.Data.Engines.DataCommands
{
using System;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand
{
private readonly DataStorage dataStorage;
public CreateItemCommand(DataStorage dataStorage)
{
Assert.ArgumentNotNull(dataStorage, "dataStorage");
this.dataStorage = dataStorage;
}
public DataStorage DataStorage
{
get { return this.dataStorage; }
}
protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance()
{
throw new NotSupportedException();
}
protected override Item DoExecute()
{
var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID };
this.dataStorage.AddFakeItem(item);
item.RemoveVersion(Language.Current.Name);
return this.dataStorage.GetSitecoreItem(this.ItemId);
}
}
} |
Reword xmldoc to make more sense | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// The usage of this mod to determine its playability.
/// </summary>
public enum ModUsage
{
/// <summary>
/// In a solo gameplay session.
/// </summary>
User,
/// <summary>
/// In a multiplayer match, as a required mod.
/// </summary>
MultiplayerRequired,
/// <summary>
/// In a multiplayer match, as a "free" mod.
/// </summary>
MultiplayerFree,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// The usage of this mod to determine whether it's playable in such context.
/// </summary>
public enum ModUsage
{
/// <summary>
/// Used for a per-user gameplay session. Determines whether the mod is playable by an end user.
/// </summary>
User,
/// <summary>
/// Used as a "required mod" for a multiplayer match.
/// </summary>
MultiplayerRequired,
/// <summary>
/// Used as a "free mod" for a multiplayer match.
/// </summary>
MultiplayerFree,
}
}
|
Remove method from interface because it's only useful for testing. Generates incorrect results if not used right | using System;
using System.Collections.Generic;
using System.Net.Http;
namespace Refit
{
public interface IRequestBuilder
{
IEnumerable<string> InterfaceHttpMethods { get; }
Func<object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = "");
Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName);
}
interface IRequestBuilderFactory
{
IRequestBuilder Create(Type interfaceType, RefitSettings settings);
}
public static class RequestBuilder
{
static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory();
public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings)
{
return platformRequestBuilderFactory.Create(interfaceType, settings);
}
public static IRequestBuilder ForType(Type interfaceType)
{
return platformRequestBuilderFactory.Create(interfaceType, null);
}
public static IRequestBuilder ForType<T>(RefitSettings settings)
{
return ForType(typeof(T), settings);
}
public static IRequestBuilder ForType<T>()
{
return ForType(typeof(T), null);
}
}
#if PORTABLE
class RequestBuilderFactory : IRequestBuilderFactory
{
public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null)
{
throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!");
}
}
#endif
}
| using System;
using System.Collections.Generic;
using System.Net.Http;
namespace Refit
{
public interface IRequestBuilder
{
IEnumerable<string> InterfaceHttpMethods { get; }
Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName);
}
interface IRequestBuilderFactory
{
IRequestBuilder Create(Type interfaceType, RefitSettings settings);
}
public static class RequestBuilder
{
static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory();
public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings)
{
return platformRequestBuilderFactory.Create(interfaceType, settings);
}
public static IRequestBuilder ForType(Type interfaceType)
{
return platformRequestBuilderFactory.Create(interfaceType, null);
}
public static IRequestBuilder ForType<T>(RefitSettings settings)
{
return ForType(typeof(T), settings);
}
public static IRequestBuilder ForType<T>()
{
return ForType(typeof(T), null);
}
}
#if PORTABLE
class RequestBuilderFactory : IRequestBuilderFactory
{
public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null)
{
throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!");
}
}
#endif
}
|
Fix potential NRE in lucene index | using System;
using Lucene.Net.Documents;
using Orchard.Indexing;
namespace Lucene.Models {
public class LuceneSearchHit : ISearchHit {
private readonly Document _doc;
private readonly float _score;
public float Score { get { return _score; } }
public LuceneSearchHit(Document document, float score) {
_doc = document;
_score = score;
}
public int ContentItemId { get { return int.Parse(GetString("id")); } }
public int GetInt(string name) {
var field = _doc.GetField(name);
return field == null ? 0 : Int32.Parse(field.StringValue);
}
public double GetDouble(string name) {
var field = _doc.GetField(name);
return field == null ? 0 : double.Parse(field.StringValue);
}
public bool GetBoolean(string name) {
return GetInt(name) > 0;
}
public string GetString(string name) {
var field = _doc.GetField(name);
return field == null ? null : field.StringValue;
}
public DateTime GetDateTime(string name) {
var field = _doc.GetField(name);
return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue);
}
}
}
| using System;
using Lucene.Net.Documents;
using Orchard.Indexing;
namespace Lucene.Models {
public class LuceneSearchHit : ISearchHit {
private readonly Document _doc;
private readonly float _score;
public float Score { get { return _score; } }
public LuceneSearchHit(Document document, float score) {
_doc = document;
_score = score;
}
public int ContentItemId { get { return GetInt("id"); } }
public int GetInt(string name) {
var field = _doc.GetField(name);
return field == null ? 0 : Int32.Parse(field.StringValue);
}
public double GetDouble(string name) {
var field = _doc.GetField(name);
return field == null ? 0 : double.Parse(field.StringValue);
}
public bool GetBoolean(string name) {
return GetInt(name) > 0;
}
public string GetString(string name) {
var field = _doc.GetField(name);
return field == null ? null : field.StringValue;
}
public DateTime GetDateTime(string name) {
var field = _doc.GetField(name);
return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue);
}
}
}
|
Apply same fix to legacy accuracy counter | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() => (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText));
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText()
=> (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText))
?.With(s => s.Anchor = s.Origin = Anchor.TopRight);
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.