Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Reset commit to not break backwards compatibility mode | namespace Umbraco.Core.Models
{
public enum TagCacheStorageType
{
Json,
Csv
}
}
| namespace Umbraco.Core.Models
{
public enum TagCacheStorageType
{
Csv,
Json
}
} |
Fix bug where quest NPC dialog caused a crash because the requested NPC was never set | using AutomaticTypeMapper;
using EOLib.Domain.NPC;
using EOLib.IO.Repositories;
using EOLib.Net;
using EOLib.Net.Communication;
namespace EOLib.Domain.Interact
{
[AutoMappedType]
public class MapNPCActions : IMapNPCActions
{
private readonly IPacketSendService _packetSendService;
private readonly IENFFileProvider _enfFileProvider;
public MapNPCActions(IPacketSendService packetSendService,
IENFFileProvider enfFileProvider)
{
_packetSendService = packetSendService;
_enfFileProvider = enfFileProvider;
}
public void RequestShop(INPC npc)
{
var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open)
.AddShort(npc.Index)
.Build();
_packetSendService.SendPacket(packet);
}
public void RequestQuest(INPC npc)
{
var data = _enfFileProvider.ENFFile[npc.ID];
var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use)
.AddShort(npc.Index)
.AddShort(data.VendorID)
.Build();
_packetSendService.SendPacket(packet);
}
}
public interface IMapNPCActions
{
void RequestShop(INPC npc);
void RequestQuest(INPC npc);
}
}
| using AutomaticTypeMapper;
using EOLib.Domain.Interact.Quest;
using EOLib.Domain.NPC;
using EOLib.IO.Repositories;
using EOLib.Net;
using EOLib.Net.Communication;
namespace EOLib.Domain.Interact
{
[AutoMappedType]
public class MapNPCActions : IMapNPCActions
{
private readonly IPacketSendService _packetSendService;
private readonly IENFFileProvider _enfFileProvider;
private readonly IQuestDataRepository _questDataRepository;
public MapNPCActions(IPacketSendService packetSendService,
IENFFileProvider enfFileProvider,
IQuestDataRepository questDataRepository)
{
_packetSendService = packetSendService;
_enfFileProvider = enfFileProvider;
_questDataRepository = questDataRepository;
}
public void RequestShop(INPC npc)
{
var packet = new PacketBuilder(PacketFamily.Shop, PacketAction.Open)
.AddShort(npc.Index)
.Build();
_packetSendService.SendPacket(packet);
}
public void RequestQuest(INPC npc)
{
_questDataRepository.RequestedNPC = npc;
var data = _enfFileProvider.ENFFile[npc.ID];
var packet = new PacketBuilder(PacketFamily.Quest, PacketAction.Use)
.AddShort(npc.Index)
.AddShort(data.VendorID)
.Build();
_packetSendService.SendPacket(packet);
}
}
public interface IMapNPCActions
{
void RequestShop(INPC npc);
void RequestQuest(INPC npc);
}
}
|
Switch the load order so that metadata comes first in the dom | namespace Glimpse.Core2.Extensibility
{
public enum ScriptOrder
{
IncludeBeforeClientInterfaceScript,
ClientInterfaceScript,
IncludeAfterClientInterfaceScript,
IncludeBeforeRequestDataScript,
RequestDataScript,
RequestMetadataScript,
IncludeAfterRequestDataScript,
}
} | namespace Glimpse.Core2.Extensibility
{
public enum ScriptOrder
{
IncludeBeforeClientInterfaceScript,
ClientInterfaceScript,
IncludeAfterClientInterfaceScript,
IncludeBeforeRequestDataScript,
RequestMetadataScript,
RequestDataScript,
IncludeAfterRequestDataScript,
}
} |
Make the FNF exception light up more robust | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
namespace Roslyn.Utilities
{
/// <summary>
/// This is a bridge for APIs that are only available on Desktop
/// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR
/// so this shim is necessary for switching on the dependent behavior.
/// </summary>
internal static class DesktopShim
{
internal static class FileNotFoundException
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.IO.FileNotFoundException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog");
internal static string TryGetFusionLog(object obj) => s_fusionLog.GetValue(obj) as string;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
namespace Roslyn.Utilities
{
/// <summary>
/// This is a bridge for APIs that are only available on Desktop
/// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR
/// so this shim is necessary for switching on the dependent behavior.
/// </summary>
internal static class DesktopShim
{
internal static class FileNotFoundException
{
internal static readonly Type Type = typeof(FileNotFoundException);
private static PropertyInfo s_fusionLog = Type?.GetTypeInfo().GetDeclaredProperty("FusionLog");
internal static string TryGetFusionLog(object obj) => s_fusionLog?.GetValue(obj) as string;
}
}
}
|
Fix bug: Clearing the cache says "All items have been cleared from the recent packages list." Work items: 986 | using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearPackageCache, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
} |
Change a-Z to a-zA-Z as reccomended | namespace dotless.Core.Parser.Tree
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using Exceptions;
public class Url : Node
{
public Node Value { get; set; }
public Url(Node value, IEnumerable<string> paths)
{
if (value is TextNode)
{
var textValue = value as TextNode;
if (!Regex.IsMatch(textValue.Value, @"^(([A-z]+:)|(\/))") && paths.Any())
{
textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths();
}
}
Value = value;
}
public Url(Node value)
{
Value = value;
}
public string GetUrl()
{
if (Value is TextNode)
return (Value as TextNode).Value;
throw new ParserException("Imports do not allow expressions");
}
public override Node Evaluate(Env env)
{
return new Url(Value.Evaluate(env));
}
public override void AppendCSS(Env env)
{
env.Output
.Append("url(")
.Append(Value)
.Append(")");
}
}
} | namespace dotless.Core.Parser.Tree
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Infrastructure;
using Infrastructure.Nodes;
using Utils;
using Exceptions;
public class Url : Node
{
public Node Value { get; set; }
public Url(Node value, IEnumerable<string> paths)
{
if (value is TextNode)
{
var textValue = value as TextNode;
if (!Regex.IsMatch(textValue.Value, @"^(([a-zA-Z]+:)|(\/))") && paths.Any())
{
textValue.Value = paths.Concat(new[] { textValue.Value }).AggregatePaths();
}
}
Value = value;
}
public Url(Node value)
{
Value = value;
}
public string GetUrl()
{
if (Value is TextNode)
return (Value as TextNode).Value;
throw new ParserException("Imports do not allow expressions");
}
public override Node Evaluate(Env env)
{
return new Url(Value.Evaluate(env));
}
public override void AppendCSS(Env env)
{
env.Output
.Append("url(")
.Append(Value)
.Append(")");
}
}
} |
Comment out the environment message for the time being | using System;
using Glimpse.Agent.AspNet.Messages;
using Glimpse.Agent.Inspectors;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet
{
public class EnvironmentInspector : Inspector
{
private readonly IAgentBroker _broker;
private EnvironmentMessage _message;
public EnvironmentInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void Before(HttpContext context)
{
if (_message == null)
{
_message = new EnvironmentMessage
{
Server = Environment.MachineName,
OperatingSystem = Environment.OSVersion.VersionString,
ProcessorCount = Environment.ProcessorCount,
Is64Bit = Environment.Is64BitOperatingSystem,
CommandLineArgs = Environment.GetCommandLineArgs(),
EnvironmentVariables = Environment.GetEnvironmentVariables()
};
}
_broker.SendMessage(_message);
}
}
}
| using System;
using Glimpse.Agent.AspNet.Messages;
using Glimpse.Agent.Inspectors;
using Microsoft.AspNet.Http;
namespace Glimpse.Agent.AspNet.Internal.Inspectors.AspNet
{
public class EnvironmentInspector : Inspector
{
private readonly IAgentBroker _broker;
private EnvironmentMessage _message;
public EnvironmentInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void Before(HttpContext context)
{
//if (_message == null)
//{
// _message = new EnvironmentMessage
// {
// Server = Environment.MachineName,
// OperatingSystem = Environment.OSVersion.VersionString,
// ProcessorCount = Environment.ProcessorCount,
// Is64Bit = Environment.Is64BitOperatingSystem,
// CommandLineArgs = Environment.GetCommandLineArgs(),
// EnvironmentVariables = Environment.GetEnvironmentVariables()
// };
//}
//_broker.SendMessage(_message);
}
}
}
|
Fix unit test by making the Data property writable | using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; }
public object Json { get; set; }
}
}
| using System.Collections.Generic;
namespace RestSharp.Portable.Test.HttpBin
{
public class HttpBinResponse
{
public Dictionary<string, string> Args { get; set; }
public Dictionary<string, string> Form { get; set; }
public Dictionary<string, string> Headers { get; set; }
public string Data { get; set; }
public object Json { get; set; }
}
}
|
Drop in a note for later. | using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
} | using System;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace SparkPost.RequestSenders
{
public class AsyncRequestSender : IRequestSender
{
private readonly IClient client;
public AsyncRequestSender(IClient client)
{
this.client = client;
}
public async virtual Task<Response> Send(Request request)
{
using (var httpClient = client.CustomSettings.CreateANewHttpClient())
{
httpClient.BaseAddress = new Uri(client.ApiHost);
// I don't think this is the right spot for this
//httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("Authorization", client.ApiKey);
if (client.SubaccountId != 0)
{
httpClient.DefaultRequestHeaders.Add("X-MSYS-SUBACCOUNT", client.SubaccountId.ToString(CultureInfo.InvariantCulture));
}
var result = await GetTheResponse(request, httpClient);
return new Response
{
StatusCode = result.StatusCode,
ReasonPhrase = result.ReasonPhrase,
Content = await result.Content.ReadAsStringAsync()
};
}
}
protected virtual async Task<HttpResponseMessage> GetTheResponse(Request request, HttpClient httpClient)
{
return await new RequestMethodFinder(httpClient)
.FindFor(request)
.Execute(request);
}
}
} |
Implement GetSchedule functionality for Rooms | using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
return Enumerable.Empty<RoomSessionSchedule>();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using ISTS.Domain.Rooms;
using ISTS.Domain.Schedules;
using ISTS.Infrastructure.Model;
namespace ISTS.Infrastructure.Repository
{
public class RoomRepository : IRoomRepository
{
private readonly IstsContext _context;
public RoomRepository(
IstsContext context)
{
_context = context;
}
public Room Get(Guid id)
{
return null;
}
public RoomSession GetSession(Guid id)
{
return null;
}
public RoomSession CreateSession(Guid roomId, RoomSession entity)
{
return null;
}
public RoomSession RescheduleSession(Guid id, DateRange schedule)
{
return null;
}
public RoomSession StartSession(Guid id, DateTime time)
{
return null;
}
public RoomSession EndSession(Guid id, DateTime time)
{
return null;
}
public IEnumerable<RoomSessionSchedule> GetSchedule(Guid id, DateRange range)
{
var sessions = _context.Sessions
.Where(s => s.RoomId == id)
.ToList();
var schedule = sessions
.Select(s => RoomSessionSchedule.Create(s.Id, s.Schedule));
return schedule;
}
}
} |
Add invalid message + aria tags to login | <div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text">
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password">
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div> | @model bool
@{
var invalidAttributes = Model ? "aria-invalid=\"true\" aria-labeledby=\"invalidMessage\"" : "";
}
<div class="grid-row">
<div class="column-half">
<h1 class="heading-large">Sign in</h1>
@if (Model)
{
<div class="error" style="margin-bottom: 10px;" id="invalidMessage">
<p class="error-message">Invalid Email address / Password</p>
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<div class="form-group">
<label class="form-label" for="email-address">Email address</label>
<input class="form-control form-control-3-4" id="email-address" name="EmailAddress" type="text"
autofocus="autofocus" aria-required="true" @invalidAttributes>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-control form-control-3-4" id="password" name="Password" type="password"
aria-required="true" @invalidAttributes>
<p>
<a href="#">I can't access my account</a>
</p>
</div>
<div class="form-group">
<button type="submit" class="button">Sign in</button>
</div>
</form>
</div>
<div class="column-half">
<h1 class="heading-large">New to this service?</h1>
<p>If you haven’t used this service before you must <a href="@Url.Action("Register", "Account")">create an account</a></p>
</div>
</div> |
Improve debug string representation of MacroDefinition. | namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return Expression;
}
}
}
| namespace CppSharp.AST
{
public enum MacroLocation
{
Unknown,
ClassHead,
ClassBody,
FunctionHead,
FunctionParameters,
FunctionBody,
};
/// <summary>
/// Base class that describes a preprocessed entity, which may
/// be a preprocessor directive or macro expansion.
/// </summary>
public abstract class PreprocessedEntity : Declaration
{
public MacroLocation MacroLocation = MacroLocation.Unknown;
}
/// <summary>
/// Represents a C preprocessor macro expansion.
/// </summary>
public class MacroExpansion : PreprocessedEntity
{
// Contains the macro expansion text.
public string Text;
public MacroDefinition Definition;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
//return visitor.VisitMacroExpansion(this);
return default(T);
}
public override string ToString()
{
return Text;
}
}
/// <summary>
/// Represents a C preprocessor macro definition.
/// </summary>
public class MacroDefinition : PreprocessedEntity
{
// Contains the macro definition text.
public string Expression;
// Backing enumeration if one was generated.
public Enumeration Enumeration;
public override T Visit<T>(IDeclVisitor<T> visitor)
{
return visitor.VisitMacroDefinition(this);
}
public override string ToString()
{
return string.Format("{0} = {1}", Name, Expression);
}
}
}
|
Add more unit test filestorage | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
db.FileStorage.Upload("Core.dll", "Core.dll");
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Linq;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class FileStorage_Test
{
[TestMethod]
public void FileStorage_InsertDelete()
{
// create a dump file
File.WriteAllText("Core.dll", "FileCoreContent");
using (var db = new LiteDatabase(new MemoryStream()))
{
// upload
db.FileStorage.Upload("Core.dll", "Core.dll");
// exits
var exists = db.FileStorage.Exists("Core.dll");
Assert.AreEqual(true, exists);
// find
var files = db.FileStorage.Find("Core");
Assert.AreEqual(1, files.Count());
Assert.AreEqual("Core.dll", files.First().Id);
// find by id
var core = db.FileStorage.FindById("Core.dll");
Assert.IsNotNull(core);
Assert.AreEqual("Core.dll", core.Id);
// download
var mem = new MemoryStream();
db.FileStorage.Download("Core.dll", mem);
var content = Encoding.UTF8.GetString(mem.ToArray());
Assert.AreEqual("FileCoreContent", content);
// delete
var deleted = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(true, deleted);
// not found deleted
var deleted2 = db.FileStorage.Delete("Core.dll");
Assert.AreEqual(false, deleted2);
}
File.Delete("Core.dll");
}
}
} |
Fix serialization of the zoneemphasis | using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonIgnore]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public string ZoneEmphasisString { get; set; }
}
}
| using Newtonsoft.Json;
namespace OfficeDevPnP.Core.Pages
{
public class ClientSideSectionEmphasis
{
[JsonProperty(PropertyName = "zoneEmphasis", NullValueHandling = NullValueHandling.Ignore)]
public int ZoneEmphasis
{
get
{
if (!string.IsNullOrWhiteSpace(ZoneEmphasisString) && int.TryParse(ZoneEmphasisString, out int result))
{
return result;
}
return 0;
}
set { ZoneEmphasisString = value.ToString(); }
}
[JsonIgnore]
public string ZoneEmphasisString { get; set; }
}
}
|
Add http path under http.uri tag | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
if (!extractor.TryExtract(context.Request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, context.Request.Method))
{
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} | using System;
using Microsoft.AspNetCore.Builder;
using Criteo.Profiling.Tracing;
using Criteo.Profiling.Tracing.Utils;
namespace Criteo.Profiling.Tracing.Middleware
{
public static class TracingMiddleware
{
public static void UseTracing(this IApplicationBuilder app, string serviceName)
{
var extractor = new Middleware.ZipkinHttpTraceExtractor();
app.Use(async (context, next) =>
{
Trace trace;
var request = context.Request;
if (!extractor.TryExtract(request.Headers, out trace))
{
trace = Trace.Create();
}
Trace.Current = trace;
using (new ServerTrace(serviceName, request.Method))
{
trace.Record(Annotations.Tag("http.uri", request.Path));
await TraceHelper.TracedActionAsync(next());
}
});
}
}
} |
Refactor Divide Doubles operation to use GetValues and CloneWithValues | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
Tensor<double> result = new Tensor<double>();
result.SetValue(tensor1.GetValue() / tensor2.GetValue());
return result;
}
}
}
| namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DivideDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
double[] values1 = tensor1.GetValues();
int l = values1.Length;
double value2 = tensor2.GetValue();
double[] newvalues = new double[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] / value2;
return tensor1.CloneWithNewValues(newvalues);
}
}
}
|
Add IRequestTarget.Cast instead of BoundActorTarget.* | namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this BoundActorTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
| namespace Akka.Interfaced
{
public static class InterfacedActorRefExtensions
{
// Cast (not type-safe)
public static TRef Cast<TRef>(this InterfacedActorRef actorRef)
where TRef : InterfacedActorRef, new()
{
if (actorRef == null)
return null;
return new TRef()
{
Target = actorRef.Target,
RequestWaiter = actorRef.RequestWaiter,
Timeout = actorRef.Timeout
};
}
// Wrap target into TRef (not type-safe)
public static TRef Cast<TRef>(this IRequestTarget target)
where TRef : InterfacedActorRef, new()
{
if (target == null)
return null;
return new TRef()
{
Target = target,
RequestWaiter = target.DefaultRequestWaiter
};
}
}
}
|
Add error checking to basic auth header | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
private static string EncodeCredential(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName));
if (password == null) password = "";
Encoding encoding = Encoding.UTF8;
string credential = String.Format("{0}:{1}", userName, password);
return Convert.ToBase64String(encoding.GetBytes(credential));
}
}
} |
Fix for get current user on anon page | using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
| using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace BatteryCommander.Web.Queries
{
public class GetCurrentUser : IRequest<Soldier>
{
private class Handler : IRequestHandler<GetCurrentUser, Soldier>
{
private readonly Database db;
private readonly IHttpContextAccessor http;
public Handler(Database db, IHttpContextAccessor http)
{
this.db = db;
this.http = http;
}
public async Task<Soldier> Handle(GetCurrentUser request, CancellationToken cancellationToken)
{
var email =
http
.HttpContext
.User?
.Identity?
.Name;
if (string.IsNullOrWhiteSpace(email)) return default(Soldier);
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.CivilianEmail == email)
.AsNoTracking()
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
}
|
Update enum for VS 2017 | // 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 Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14
}
} | // 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 Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14,
/// <summary>
/// MSBuildVersion : <c>15</c>
/// </summary>
MSBuild15 = 15
}
} |
Fix spelling of SuccessfulShards in CatSnapshots | using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="succesful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccesfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
| using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="successful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccessfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
|
Comment code that should be commented | namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
} | namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
//string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
} |
Adjust namespaces for Data.NHibernate4 unit tests. | using System;
using System.Data;
using System.Linq;
using Cobweb.Data;
using Cobweb.Data.NHibernate;
using NHibernate;
namespace Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
| using System;
using System.Data;
using System.Linq;
using NHibernate;
namespace Cobweb.Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
|
Extend the boxing/unboxing test with a primitive value unbox | using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
}
}
| using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
object i = 42;
Console.WriteLine((int)i);
}
}
|
Fix issue with test class | using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
public class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
| using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
internal class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
|
Repair error in Console Writeline | using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, C#!");
}
}
| using System;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now);
}
}
|
Add remarks about non-UI thread | using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
event EventHandler StatusChanged;
}
}
| using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
/// <remarks>
/// This property might be changed by a non-UI thread.
/// </remarks>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
/// <remarks>
/// This event might fire on a non-UI thread.
/// </remarks>
event EventHandler StatusChanged;
}
}
|
Add bindings in settings viewmodel for user alert | using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.Quality = Selected;
Close();
}
}
} | using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
private bool _checked;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
Checked = _settings.UserAlert;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public bool Checked
{
get { return _checked; }
set
{
_checked = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.UserAlert = Checked;
_settings.Quality = Selected;
Close();
}
}
} |
Use regular test steps rather than one-time set up and scheduling | // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[SetUp]
public void SetUp() => Schedule(() =>
{
StarRatingDisplay changingStarRating;
Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
};
Scheduler.AddDelayed(() =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 500, true);
});
}
}
| // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Screens.Ranking.Expanded;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStarRatingDisplay : OsuTestScene
{
[Test]
public void TestDisplay()
{
StarRatingDisplay changingStarRating = null;
AddStep("load displays", () => Child = new FillFlowContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Children = new Drawable[]
{
new StarRatingDisplay(new StarDifficulty(1.23, 0)),
new StarRatingDisplay(new StarDifficulty(2.34, 0)),
new StarRatingDisplay(new StarDifficulty(3.45, 0)),
new StarRatingDisplay(new StarDifficulty(4.56, 0)),
new StarRatingDisplay(new StarDifficulty(5.67, 0)),
new StarRatingDisplay(new StarDifficulty(6.78, 0)),
new StarRatingDisplay(new StarDifficulty(10.11, 0)),
changingStarRating = new StarRatingDisplay(),
}
});
AddRepeatStep("change bottom rating", () =>
{
changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next());
}, 10);
}
}
}
|
Make global categories colors are display only | @using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options
@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultures = LocOptions.Value.SupportedUICultures
.Skip(1)
.Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
.ToArray();
}
<h2>Global categories</h2>
<table class="table">
<thead>
<tr>
<th>Default name</th>
@foreach (var culture in cultures)
{
<th>@culture.Name translate</th>
}
</tr>
</thead>
<tbody>
@foreach (var category in Model)
{
<tr>
<td>
@category.Name
<div class="input-group colorpicker colorpicker-component" data-id="@category.Id">
<input type="text" value="name" class="form-control" />
<input type="hidden" value="#@category.Color.ToString("X6")" />
<span class="input-group-addon"><i></i></span>
</div>
</td>
@foreach (var culture in cultures)
{
var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
if (locName != null)
{
<td>@locName.Name</td>
}
else
{
<td class="empty">@category.Name</td>
}
}
</tr>
}
</tbody>
</table> | @using Microsoft.AspNetCore.Builder
@using Microsoft.Extensions.Options
@model IEnumerable<Category>
@inject IOptions<RequestLocalizationOptions> LocOptions
@{
var cultures = LocOptions.Value.SupportedUICultures
.Skip(1)
.Select(culture => new { Culture = culture.Name, Name = culture.EnglishName })
.ToArray();
}
<h2>Global categories</h2>
<table class="table">
<thead>
<tr>
<th class="fit"></th>
<th>Default name</th>
@foreach (var culture in cultures)
{
<th>@culture.Name translate</th>
}
</tr>
</thead>
<tbody>
@foreach (var category in Model)
{
<tr>
<td>
<span class="label category-color" style="background-color: #@(category.Color.ToString("X6"))"> </span>
</td>
<td>
@category.Name
</td>
@foreach (var culture in cultures)
{
var locName = category.Localizations.SingleOrDefault(loc => loc.Culture == culture.Culture);
if (locName != null)
{
<td>@locName.Name</td>
}
else
{
<td class="empty">@category.Name</td>
}
}
</tr>
}
</tbody>
</table> |
Add new plugin repository URL | using FogCreek.Plugins;
[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FBExtendedEvents")]
| using FogCreek.Plugins;
[assembly: AssemblyFogCreekPluginId("FBExtendedEvents@goit.io")]
[assembly: AssemblyFogCreekMajorVersion(3)]
[assembly: AssemblyFogCreekMinorVersionMin(5)]
[assembly: AssemblyFogCreekEmailAddress("jozef.izso@gmail.com")]
[assembly: AssemblyFogCreekWebsite("https://github.com/jozefizso/FogBugz-ExtendedEvents")]
|
Add simple JSON endpoint for soldiers with access | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
namespace BatteryCommander.Web.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Jobs()
{
return View(JobManager.AllSchedules);
}
}
} | using BatteryCommander.Web.Models;
using FluentScheduler;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Jobs()
{
return View(JobManager.AllSchedules);
}
public async Task<IActionResult> Users()
{
var soldiers_with_access =
await db
.Soldiers
.Where(soldier => soldier.CanLogin)
.Select(soldier => new
{
soldier.FirstName,
soldier.LastName,
soldier.CivilianEmail
})
.ToListAsync();
return Json(soldiers_with_access);
}
}
} |
Fix of not unsubscribing to characteristics on disconnect | using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
namespace BleLab.Services
{
public class CharacteristicSubscriptionService
{
private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();
public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;
public bool Subscribe(GattCharacteristic characteristic)
{
if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
return false;
characteristic.ValueChanged += CharacteristicOnValueChanged;
_subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
return true;
}
public bool Unsubscribe(GattCharacteristic characteristic)
{
if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
return false;
characteristic.ValueChanged -= CharacteristicOnValueChanged;
_subscribedCharacteristics.Remove(characteristic.Uuid);
return true;
}
public bool IsSubscribed(GattCharacteristic characteristic)
{
return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
}
public void DeviceDisconnected(BluetoothLEDevice device)
{
if (device == null)
return;
var deviceId = device.DeviceId;
var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.DeviceId == deviceId).ToList();
foreach (var characteristic in characteristics)
{
try
{
Unsubscribe(characteristic);
}
catch
{
}
}
}
private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
ValueChanged?.Invoke(sender, args);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Foundation;
namespace BleLab.Services
{
public class CharacteristicSubscriptionService
{
private readonly Dictionary<Guid, GattCharacteristic> _subscribedCharacteristics = new Dictionary<Guid, GattCharacteristic>();
public event TypedEventHandler<GattCharacteristic, GattValueChangedEventArgs> ValueChanged;
public bool Subscribe(GattCharacteristic characteristic)
{
if (_subscribedCharacteristics.ContainsKey(characteristic.Uuid))
return false;
characteristic.ValueChanged += CharacteristicOnValueChanged;
_subscribedCharacteristics.Add(characteristic.Uuid, characteristic);
return true;
}
public bool Unsubscribe(GattCharacteristic characteristic)
{
if (!_subscribedCharacteristics.TryGetValue(characteristic.Uuid, out characteristic))
return false;
characteristic.ValueChanged -= CharacteristicOnValueChanged;
_subscribedCharacteristics.Remove(characteristic.Uuid);
return true;
}
public bool IsSubscribed(GattCharacteristic characteristic)
{
return _subscribedCharacteristics.ContainsKey(characteristic.Uuid);
}
public void DeviceDisconnected(BluetoothLEDevice device)
{
if (device == null)
return;
var deviceId = device.DeviceId;
var characteristics = _subscribedCharacteristics.Values.Where(t => t.Service.Device.DeviceId == deviceId).ToList();
foreach (var characteristic in characteristics)
{
try
{
Unsubscribe(characteristic);
}
catch
{
}
}
}
private void CharacteristicOnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
ValueChanged?.Invoke(sender, args);
}
}
}
|
Switch direct handling by a syncrhonous dispatching in console sample | using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var registry = new Registry();
registry.IncludeRegistry<InfrastructureRegistry>();
var container = new Container(registry);
var createPersonCommandHandler = container.GetInstance<IHandler<CreatePersonCommand>>();
createPersonCommandHandler.Handle(new CreatePersonCommand());
var getPersonQueryHandler = container.GetInstance<IHandler<GetPersonQuery, GetPersonReadModel>>();
var person = getPersonQueryHandler.Handle(new GetPersonQuery());
Console.WriteLine($"Hello {person.Name} !");
Console.ReadKey();
}
}
}
| using System;
using Bartender;
using ConsoleApplication.Domain.Personne.Create;
using ConsoleApplication.Domain.Personne.Read;
using ConsoleApplication.Registries;
using StructureMap;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
var registry = new Registry();
registry.IncludeRegistry<InfrastructureRegistry>();
var container = new Container(registry);
var dispatcher = container.GetInstance<IDispatcher>();
dispatcher.Dispatch(new CreatePersonCommand());
var person = dispatcher.Dispatch<GetPersonQuery, GetPersonReadModel>(new GetPersonQuery());
Console.WriteLine($"Hello {person.Name} !");
Console.ReadKey();
}
}
}
|
Add agent to the web middleware | using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
public GlimpseMiddleware(RequestDelegate innerNext)
{
_innerNext = innerNext;
}
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context);
await _innerNext(context);
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Glimpse.Host.Web.AspNet.Framework;
using Glimpse.Agent.Web;
namespace Glimpse.Host.Web.AspNet
{
public class GlimpseMiddleware
{
private readonly RequestDelegate _innerNext;
private readonly WebAgentRuntime _runtime;
public GlimpseMiddleware(RequestDelegate innerNext)
{
_innerNext = innerNext;
_runtime = new WebAgentRuntime(); // TODO: This shouldn't have this direct depedency
}
public async Task Invoke(Microsoft.AspNet.Http.HttpContext context)
{
var newContext = new HttpContext(context);
_runtime.Begin(newContext);
await _innerNext(context);
_runtime.End(newContext);
}
}
} |
Adjust paddings to feel better now that backgrounds are visible of toolboxes | // 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.
#nullable disable
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public class ExpandingToolboxContainer : ExpandingContainer
{
protected override double HoverExpansionDelay => 250;
public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
: base(contractedWidth, expandedWidth)
{
RelativeSizeAxes = Axes.Y;
FillFlow.Spacing = new Vector2(10);
}
protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);
private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);
protected override bool OnMouseDown(MouseDownEvent e) => true;
protected override bool OnClick(ClickEvent e) => true;
}
}
| // 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.
#nullable disable
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Rulesets.Edit
{
public class ExpandingToolboxContainer : ExpandingContainer
{
protected override double HoverExpansionDelay => 250;
public ExpandingToolboxContainer(float contractedWidth, float expandedWidth)
: base(contractedWidth, expandedWidth)
{
RelativeSizeAxes = Axes.Y;
FillFlow.Spacing = new Vector2(5);
Padding = new MarginPadding { Vertical = 5 };
}
protected override bool ReceivePositionalInputAtSubTree(Vector2 screenSpacePos) => base.ReceivePositionalInputAtSubTree(screenSpacePos) && anyToolboxHovered(screenSpacePos);
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => base.ReceivePositionalInputAt(screenSpacePos) && anyToolboxHovered(screenSpacePos);
private bool anyToolboxHovered(Vector2 screenSpacePos) => FillFlow.ScreenSpaceDrawQuad.Contains(screenSpacePos);
protected override bool OnMouseDown(MouseDownEvent e) => true;
protected override bool OnClick(ClickEvent e) => true;
}
}
|
Add link to MemoryStream.CopyToAsync source link. | using System.IO;
namespace AWTY.Http.IntegrationTests
{
/// <summary>
/// A non-optimised version of <see cref="MemoryStream"/> for use in tests.
/// </summary>
/// <remarks>
/// <see cref="MemoryStream"/> performs a bunch of optimisations unless subclassed.
///
/// Unfortunately, these optimisations break the tests.
/// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
/// </remarks>
public sealed class DumbMemoryStream
: MemoryStream
{
public DumbMemoryStream()
: base()
{
}
}
} | using System.IO;
namespace AWTY.Http.IntegrationTests
{
/// <summary>
/// A non-optimised version of <see cref="MemoryStream"/> for use in tests.
/// </summary>
/// <remarks>
/// <see cref="MemoryStream"/>'s CopyToAsync performs a bunch of optimisations unless subclassed.
/// https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/memorystream.cs#L450
///
/// Unfortunately, these optimisations break some of our tests.
/// Although you obviously wouldn't use a MemoryStream in real life, it's the simplest options for these tests.
/// </remarks>
public sealed class DumbMemoryStream
: MemoryStream
{
public DumbMemoryStream()
: base()
{
}
}
} |
Initialize git repo on startup. | // -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
/// <summary>
/// The GitReview application.
/// </summary>
public class GitReviewApplication : HttpApplication
{
/// <summary>
/// Gets the path of the shared repository.
/// </summary>
public static string RepositoryPath
{
get { return ConfigurationManager.AppSettings["RepositoryPath"]; }
}
/// <summary>
/// Starts the application.
/// </summary>
protected virtual void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview
{
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using LibGit2Sharp;
/// <summary>
/// The GitReview application.
/// </summary>
public class GitReviewApplication : HttpApplication
{
/// <summary>
/// Gets the path of the shared repository.
/// </summary>
public static string RepositoryPath
{
get { return HostingEnvironment.MapPath(ConfigurationManager.AppSettings["RepositoryPath"]); }
}
/// <summary>
/// Starts the application.
/// </summary>
protected virtual void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
var path = GitReviewApplication.RepositoryPath;
if (!Directory.Exists(path))
{
Repository.Init(path, isBare: true);
}
}
}
}
|
Remove Canadian Styling of bool | @using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>
<div class="tab-pane active" id="Transactions">
<table id="table-Transactions">
<thead>
<tr>
<th></th>
<th>Transaction</th>
<th>Quantity</th>
<th>Amount</th>
<th>Payment Type</th>
<th>Paid</th>
<th>Active Eh</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Where(a => a.ParentTransaction == null))
{
<tr>
<td>
@using (Html.BeginForm<ItemManagementController>
(x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
{
@Html.AntiForgeryToken()
<a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a>
}
</td>
<td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td>
<td>@Html.DisplayFor(modelItem => item.Quantity)</td>
<td>@Html.DisplayFor(modelItem => item.Amount)</td>
<td>@Html.DisplayFor(modelItem => item.Credit)</td>
<td>@Html.DisplayFor(modelItem => item.Paid)</td>
<td>@Html.DisplayFor(modelItem => item.IsActive)</td>
</tr>
}
</tbody>
</table>
</div>
| @using CRP.Controllers
@using Microsoft.Web.Mvc
@model IEnumerable<CRP.Core.Domain.Transaction>
<div class="tab-pane active" id="Transactions">
<table id="table-Transactions">
<thead>
<tr>
<th></th>
<th>Transaction</th>
<th>Quantity</th>
<th>Amount</th>
<th>Payment Type</th>
<th>Paid</th>
<th>Active</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Where(a => a.ParentTransaction == null))
{
<tr>
<td>
@using (Html.BeginForm<ItemManagementController>
(x => x.ToggleTransactionIsActive(item.Id, Request.QueryString["Transactions-orderBy"], Request.QueryString["Transactions-page"])))
{
@Html.AntiForgeryToken()
<a href="javascript:;" class="FormSubmit">@(item.IsActive ? "Deactivate" : "Activate")</a>
}
</td>
<td>@Html.DisplayFor(modelItem => item.TransactionNumber)</td>
<td>@Html.DisplayFor(modelItem => item.Quantity)</td>
<td>@Html.DisplayFor(modelItem => item.Amount)</td>
<td>@Html.DisplayFor(modelItem => item.Credit)</td>
<td>@Html.DisplayFor(modelItem => item.Paid)</td>
<td>@Html.DisplayFor(modelItem => item.IsActive)</td>
</tr>
}
</tbody>
</table>
</div>
|
Add new user constructor tests | using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class UserConstructorTests
{
[Test]
public void Constructor_Should_InitializeUserCorrectly()
{
var user = new User();
Assert.IsNotNull(user);
}
[Test]
public void Constructor_Should_BeInstanceOfIdentityUser()
{
var user = new User();
Assert.IsInstanceOf<IdentityUser>(user);
}
}
}
| using Microsoft.AspNet.Identity.EntityFramework;
using NUnit.Framework;
using ZobShop.Models;
namespace ZobShop.Tests.Models.UserTests
{
[TestFixture]
public class UserConstructorTests
{
[Test]
public void Constructor_Should_InitializeUserCorrectly()
{
var user = new User();
Assert.IsNotNull(user);
}
[Test]
public void Constructor_Should_BeInstanceOfIdentityUser()
{
var user = new User();
Assert.IsInstanceOf<IdentityUser>(user);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetUsernameCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(username, user.UserName);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetNameCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(name, user.Name);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSeEmailCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(email, user.Email);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetPhoneNumberCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(phoneNumber, user.PhoneNumber);
}
[TestCase("pesho", "pesho@pesho.com", "Peter", "0881768356", "1 Peshova street")]
public void Constructor_ShouldSetAddressCorrectly(string username, string email, string name, string phoneNumber, string address)
{
var user = new User(username, email, name, phoneNumber, address);
Assert.AreEqual(address, user.Address);
}
}
}
|
Fix issue where the file name wasn't getting specified. | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.MessageBus.Handlers
{
using System;
using Its.Configuration;
using Naos.Database.MessageBus.Contract;
using Naos.Database.Tools;
using Naos.Database.Tools.Backup;
using Naos.MessageBus.HandlingContract;
/// <summary>
/// Naos.MessageBus handler for BackupMessages.
/// </summary>
public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
{
/// <inheritdoc />
public void Handle(BackupDatabaseMessage message)
{
Action<string> logAction = s => { };
var settings = Settings.Get<MessageHandlerSettings>();
var backupDetails = new BackupDetails()
{
Name = message.BackupName,
BackupTo = new Uri(settings.BackupDirectory),
ChecksumOption = ChecksumOption.Checksum,
Cipher = Cipher.NoEncryption,
CompressionOption = CompressionOption.NoCompression,
Description = message.Description,
Device = Device.Disk,
ErrorHandling = ErrorHandling.StopOnError,
};
DatabaseManager.BackupFull(
settings.LocalhostConnectionString,
message.DatabaseName,
backupDetails,
settings.DefaultTimeout,
logAction);
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="BackupMessageHandler.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.MessageBus.Handlers
{
using System;
using System.IO;
using Its.Configuration;
using Naos.Database.MessageBus.Contract;
using Naos.Database.Tools;
using Naos.Database.Tools.Backup;
using Naos.MessageBus.HandlingContract;
/// <summary>
/// Naos.MessageBus handler for BackupMessages.
/// </summary>
public class BackupMessageHandler : IHandleMessages<BackupDatabaseMessage>
{
/// <inheritdoc />
public void Handle(BackupDatabaseMessage message)
{
Action<string> logAction = s => { };
var settings = Settings.Get<MessageHandlerSettings>();
var backupFileName = Path.Combine(settings.BackupDirectory, message.BackupName) + ".bak";
var backupDetails = new BackupDetails()
{
Name = message.BackupName,
BackupTo = new Uri(backupFileName),
ChecksumOption = ChecksumOption.Checksum,
Cipher = Cipher.NoEncryption,
CompressionOption = CompressionOption.NoCompression,
Description = message.Description,
Device = Device.Disk,
ErrorHandling = ErrorHandling.StopOnError,
};
DatabaseManager.BackupFull(
settings.LocalhostConnectionString,
message.DatabaseName,
backupDetails,
settings.DefaultTimeout,
logAction);
}
}
}
|
Add method to subtract points from player | using System;
using System.Runtime.InteropServices;
namespace PlayerRank
{
public class PlayerScore
{
public string Name { get; set; }
public Points Points { get; internal set; }
public PlayerScore(string name)
{
Name = name;
Points = new Points(0);
}
internal void AddPoints(Points points)
{
Points += points;
}
/// Obsolete V1 API
[Obsolete("Please use Points instead")]
public double Score
{
get { return Points.GetValue(); }
internal set { Points = new Points(value); }
}
}
} | using System;
using System.Runtime.InteropServices;
namespace PlayerRank
{
public class PlayerScore
{
public string Name { get; set; }
public Points Points { get; internal set; }
public PlayerScore(string name)
{
Name = name;
Points = new Points(0);
}
internal void AddPoints(Points points)
{
Points += points;
}
internal void SubtractPoints(Points points)
{
Points -= points;
}
/// Obsolete V1 API
[Obsolete("Please use Points instead")]
public double Score
{
get { return Points.GetValue(); }
internal set { Points = new Points(value); }
}
}
} |
Disable test parallelization for PerfView tests | 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("PerfView.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PerfView.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// 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("PerfView.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PerfView.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
Handle system wide installs of chrome | using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace Admo.Utilities
{
public class SoftwareUtils
{
public static string GetChromeVersion()
{
var path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
if (path != null)
return FileVersionInfo.GetVersionInfo(path.ToString()).FileVersion;
return String.Empty;
}
}
}
| using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace Admo.Utilities
{
public class SoftwareUtils
{
public static string GetChromeVersion()
{
//Handle both system wide and user installs of chrome
var pathLocal = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
var pathMachine = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "", null);
if (pathLocal != null)
{
return FileVersionInfo.GetVersionInfo(pathLocal.ToString()).FileVersion;
}
if (pathMachine != null)
{
return FileVersionInfo.GetVersionInfo(pathMachine.ToString()).FileVersion;
}
return String.Empty;
}
}
}
|
Remove fileStream used for debugging | using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public ExecutionResult Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
using (var fileStream = new FileStream("C:\\output2.dll", FileMode.Truncate))
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return new ExecutionResult { Result = "[Compilation failed]" };
}
compilation.Emit(fileStream);
compiledAssembly = stream.ToArray();
}
using (var sandbox = new Sandbox(compiledAssembly))
{
return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
}
}
}
| using System;
using System.IO;
using Compilify.Models;
namespace Compilify.Services
{
public class CSharpExecutor
{
public CSharpExecutor()
: this(new CSharpCompilationProvider()) { }
public CSharpExecutor(ICSharpCompilationProvider compilationProvider)
{
compiler = compilationProvider;
}
private readonly ICSharpCompilationProvider compiler;
public ExecutionResult Execute(Post post)
{
var compilation = compiler.Compile(post);
byte[] compiledAssembly;
using (var stream = new MemoryStream())
{
var emitResult = compilation.Emit(stream);
if (!emitResult.Success)
{
return new ExecutionResult { Result = "[Compilation failed]" };
}
compiledAssembly = stream.ToArray();
}
using (var sandbox = new Sandbox(compiledAssembly))
{
return sandbox.Run("EntryPoint", "Result", TimeSpan.FromSeconds(5));
}
}
}
}
|
Remove second parameter, bug not picked up by compiler | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Owin;
namespace JSNLog
{
public static class AppBuilderExtensions
{
public static void UseJSNLog(this IAppBuilder app, string loggerUrlRegex = null)
{
app.Use<JsnlogMiddlewareComponent>(loggerUrlRegex);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Owin;
namespace JSNLog
{
public static class AppBuilderExtensions
{
public static void UseJSNLog(this IAppBuilder app)
{
app.Use<JsnlogMiddlewareComponent>();
}
}
}
|
Set nuget package version to 1.0.0 | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta05")] | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")] |
Load Confirmation plugin in PageBuilder | @Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")
@if (UserHelper.IsAdmin)
{
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
} | @Scripts.Render("~/Resources/JavaScript/Bootstrap")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Confirmation")
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Popover")
@Scripts.Render("~/Resources/JavaScript/Framework")
@if (UserHelper.IsAdmin)
{
@Scripts.Render("~/Resources/JavaScript/Bootstrap/Tour")
} |
Add benchmark of updating transforms when none are added | // 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.
#nullable disable
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTransformUpdate : BenchmarkTest
{
private TestBox target;
public override void SetUp()
{
base.SetUp();
const int transforms_count = 10000;
ManualClock clock;
target = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };
// transform one target member over a long period
target.RotateTo(360, transforms_count * 2);
// transform another over the same period many times
for (int i = 0; i < transforms_count; i++)
target.Delay(i).MoveTo(new Vector2(0.01f), 1f);
clock.CurrentTime = target.LatestTransformEndTime;
target.Clock.ProcessFrame();
}
[Benchmark]
public void UpdateTransformsWithManyPresent()
{
for (int i = 0; i < 10000; i++)
target.UpdateTransforms();
}
private class TestBox : Box
{
public override bool RemoveCompletedTransforms => false;
public new void UpdateTransforms() => base.UpdateTransforms();
}
}
}
| // 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.
#nullable disable
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osuTK;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTransformUpdate : BenchmarkTest
{
private TestBox target;
private TestBox targetNoTransforms;
public override void SetUp()
{
base.SetUp();
const int transforms_count = 10000;
ManualClock clock;
targetNoTransforms = new TestBox { Clock = new FramedClock(clock = new ManualClock()) };
target = new TestBox { Clock = new FramedClock(clock) };
// transform one target member over a long period
target.RotateTo(360, transforms_count * 2);
// transform another over the same period many times
for (int i = 0; i < transforms_count; i++)
target.Delay(i).MoveTo(new Vector2(0.01f), 1f);
clock.CurrentTime = target.LatestTransformEndTime;
target.Clock.ProcessFrame();
}
[Benchmark]
public void UpdateTransformsWithNonePresent()
{
for (int i = 0; i < 10000; i++)
targetNoTransforms.UpdateTransforms();
}
[Benchmark]
public void UpdateTransformsWithManyPresent()
{
for (int i = 0; i < 10000; i++)
target.UpdateTransforms();
}
private class TestBox : Box
{
public override bool RemoveCompletedTransforms => false;
public new void UpdateTransforms() => base.UpdateTransforms();
}
}
}
|
Fix node lookup not adding saved computers to dict | using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(object __result)
{
ComputerLookup.PopulateLookups((Computer) __result);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(Computer), nameof(Computer.load))]
internal static void PopulateOnComputerLoad(Computer __result)
{
ComputerLookup.PopulateLookups(__result);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
} | using Hacknet;
using HarmonyLib;
using Pathfinder.Event;
using Pathfinder.Event.Loading;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[Util.Initialize]
internal static void Initialize()
{
EventManager<SaveComputerLoadedEvent>.AddHandler(PopulateOnComputerLoad);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(object __result)
{
if (__result == null)
return;
ComputerLookup.PopulateLookups((Computer) __result);
}
internal static void PopulateOnComputerLoad(SaveComputerLoadedEvent args)
{
ComputerLookup.PopulateLookups(args.Comp);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
} |
Fix hitcircle selections not responding to stacking changes | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Edit.Masks
{
public class HitCircleSelectionMask : SelectionMask
{
public HitCircleSelectionMask(DrawableHitCircle hitCircle)
: base(hitCircle)
{
Origin = Anchor.Centre;
AutoSizeAxes = Axes.Both;
Position = hitCircle.Position;
InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);
hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.Position;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Edit.Masks
{
public class HitCircleSelectionMask : SelectionMask
{
public HitCircleSelectionMask(DrawableHitCircle hitCircle)
: base(hitCircle)
{
Origin = Anchor.Centre;
AutoSizeAxes = Axes.Both;
Position = hitCircle.Position;
InternalChild = new HitCircleMask((HitCircle)hitCircle.HitObject);
hitCircle.HitObject.PositionChanged += _ => Position = hitCircle.HitObject.StackedPosition;
hitCircle.HitObject.StackHeightChanged += _ => Position = hitCircle.HitObject.StackedPosition;
}
}
}
|
Put MD5CryptoServiceProvider into using clause | using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace FFImageLoading.Helpers
{
public class MD5Helper : IMD5Helper
{
public string MD5(Stream stream)
{
var hashProvider = new MD5CryptoServiceProvider();
var bytes = hashProvider.ComputeHash(stream);
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
public string MD5(string input)
{
var hashProvider = new MD5CryptoServiceProvider();
var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
} | using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace FFImageLoading.Helpers
{
public class MD5Helper : IMD5Helper
{
public string MD5(Stream stream)
{
using (var hashProvider = new MD5CryptoServiceProvider())
{
var bytes = hashProvider.ComputeHash(stream);
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
public string MD5(string input)
{
using (var hashProvider = new MD5CryptoServiceProvider())
{
var bytes = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(bytes)?.ToSanitizedKey();
}
}
}
} |
Update code references: extension -> contact | using System.Collections.Generic;
public class Person
{
//---------------------------------------------------------------------------
public int Id { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public List<Status> Status { get; set; }
//---------------------------------------------------------------------------
public Person()
{
Status = new List<Status>();
}
//---------------------------------------------------------------------------
} | using System.Collections.Generic;
public class Person
{
//---------------------------------------------------------------------------
public int Id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public List<Status> Status { get; set; }
//---------------------------------------------------------------------------
public Person()
{
Status = new List<Status>();
}
//---------------------------------------------------------------------------
} |
Return empty result when there are no credentials on the system. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
namespace poshring
{
public class CredentialsManager
{
public IEnumerable<Credential> GetCredentials()
{
int count;
IntPtr ptr;
if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var credentials = Enumerable.Range(0, count)
.Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
.Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
return credentials;
}
public void AddPasswordCredential(string targetName, string userName, string password, string comment)
{
using (var credential = new Credential
{
TargetName = targetName,
UserName = userName,
CredentialBlob = password,
Comment = comment
})
{
credential.Save();
}
}
public void DeleteCredential(Credential credential)
{
if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
{
var error = (CredentialErrors)Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not delete credential.");
}
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
namespace poshring
{
public class CredentialsManager
{
public IEnumerable<Credential> GetCredentials()
{
int count;
IntPtr ptr;
if (!UnsafeAdvapi32.CredEnumerateW(null, 0x1, out count, out ptr))
{
var error = (CredentialErrors) Marshal.GetLastWin32Error();
switch (error)
{
case CredentialErrors.NotFound:
return Enumerable.Empty<Credential>();
case CredentialErrors.NoSuchLogonSession:
case CredentialErrors.InvalidFlags:
throw new Win32Exception((int)error);
default:
throw new InvalidOperationException("Unexpected error while fetching credentials.");
}
}
var credentials = Enumerable.Range(0, count)
.Select(i => Marshal.ReadIntPtr(ptr, i*IntPtr.Size))
.Select(p => new Credential((NativeCredential)Marshal.PtrToStructure(p, typeof(NativeCredential))));
return credentials;
}
public void AddPasswordCredential(string targetName, string userName, string password, string comment)
{
using (var credential = new Credential
{
TargetName = targetName,
UserName = userName,
CredentialBlob = password,
Comment = comment
})
{
credential.Save();
}
}
public void DeleteCredential(Credential credential)
{
if (!UnsafeAdvapi32.CredDeleteW(credential.TargetName, credential.Type, 0))
{
var error = (CredentialErrors)Marshal.GetLastWin32Error();
throw new CredentialManagerException(error, "Could not delete credential.");
}
}
}
} |
Fix Module1 to run as independent app | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Module1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Modules;
namespace Module1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(services =>
{
services.AddSingleton(new ModuleInstanceIdProvider("Module1"));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
|
CLean a potential hole in entityliving | using Voxalia.ServerGame.WorldSystem;
namespace Voxalia.ServerGame.EntitySystem
{
public abstract class EntityLiving: PhysicsEntity, EntityDamageable
{
public EntityLiving(Region tregion, bool ticks, float maxhealth)
: base(tregion, ticks)
{
MaxHealth = maxhealth;
Health = maxhealth;
}
public float Health = 100;
public float MaxHealth = 100;
public virtual float GetHealth()
{
return Health;
}
public virtual float GetMaxHealth()
{
return MaxHealth;
}
public virtual void SetHealth(float health)
{
Health = health;
if (MaxHealth != 0 && Health <= 0)
{
Die();
}
}
public virtual void Damage(float amount)
{
SetHealth(GetHealth() - amount);
}
public virtual void SetMaxHealth(float maxhealth)
{
MaxHealth = maxhealth;
}
public abstract void Die();
}
}
| using System;
using Voxalia.ServerGame.WorldSystem;
namespace Voxalia.ServerGame.EntitySystem
{
public abstract class EntityLiving: PhysicsEntity, EntityDamageable
{
public EntityLiving(Region tregion, bool ticks, float maxhealth)
: base(tregion, ticks)
{
MaxHealth = maxhealth;
Health = maxhealth;
}
public float Health = 100;
public float MaxHealth = 100;
public virtual float GetHealth()
{
return Health;
}
public virtual float GetMaxHealth()
{
return MaxHealth;
}
public virtual void SetHealth(float health)
{
Health = Math.Min(health, MaxHealth);
if (MaxHealth != 0 && Health <= 0)
{
Die();
}
}
public virtual void Damage(float amount)
{
SetHealth(GetHealth() - amount);
}
public virtual void SetMaxHealth(float maxhealth)
{
MaxHealth = maxhealth;
}
public abstract void Die();
}
}
|
Throw error if installer returns a non-zero exist code. | using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;
namespace AppGet.Installers
{
public abstract class InstallerWhispererBase : IInstallerWhisperer
{
private readonly IProcessController _processController;
private readonly Logger _logger;
protected InstallerWhispererBase(IProcessController processController, Logger logger)
{
_processController = processController;
_logger = logger;
}
public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
public abstract bool CanHandle(InstallMethodType installMethod);
protected virtual int Execute(string exectuable, string args)
{
var process = _processController.Start(exectuable, args, OnOutputDataReceived, OnErrorDataReceived);
_processController.WaitForExit(process);
return process.ExitCode;
}
protected virtual void OnOutputDataReceived(string message)
{
_logger.Info(message);
}
protected virtual void OnErrorDataReceived(string message)
{
_logger.Error(message);
}
}
}
| using System.ComponentModel;
using AppGet.Commands.Install;
using AppGet.Commands.Uninstall;
using AppGet.Exceptions;
using AppGet.Manifests;
using AppGet.Processes;
using NLog;
namespace AppGet.Installers
{
public abstract class InstallerWhispererBase : IInstallerWhisperer
{
private readonly IProcessController _processController;
private readonly Logger _logger;
protected InstallerWhispererBase(IProcessController processController, Logger logger)
{
_processController = processController;
_logger = logger;
}
public abstract void Install(string installerLocation, PackageManifest packageManifest, InstallOptions installOptions);
public abstract void Uninstall(PackageManifest packageManifest, UninstallOptions installOptions);
public abstract bool CanHandle(InstallMethodType installMethod);
protected virtual void Execute(string executable, string args)
{
try
{
var process = _processController.Start(executable, args, OnOutputDataReceived, OnErrorDataReceived);
_processController.WaitForExit(process);
if (process.ExitCode != 0)
{
throw new AppGetException($"Installer '{process.ProcessName}' returned with a non-zero exit code. code: {process.ExitCode}");
}
}
catch (Win32Exception e)
{
_logger.Error($"{e.Message}, try running AppGet as an administartor");
throw;
}
}
protected virtual void OnOutputDataReceived(string message)
{
_logger.Info(message);
}
protected virtual void OnErrorDataReceived(string message)
{
_logger.Error(message);
}
}
}
|
Enable offline mode by default. | using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class NetworkManager : MonoBehaviour {
public List<string> ChatMessages;
// Goal #1: Create a reasonable chat system using the NEW UI System
public void AddChatMessage(string message) {
PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
}
[RPC]
private void AddChatMessageRPC(string message) {
// TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
while (ChatMessages.Count >= maxChatMessages) {
ChatMessages.RemoveAt(0);
}
ChatMessages.Add(message);
}
void Start() {
PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
ChatMessages = new List<string>();
Connect();
}
void Update() {
}
void Connect() {
PhotonNetwork.ConnectUsingSettings("FPS Test v001");
}
void OnGUI() {
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}
void OnJoinedLobby() {
Debug.Log("OnJoinedLobby");
PhotonNetwork.JoinRandomRoom();
}
void OnPhotonRandomJoinFailed() {
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null);
}
void OnJoinedRoom() {
Debug.Log("OnJoinedRoom");
AddChatMessage("[SYSTEM] OnJoinedRoom!");
}
const int maxChatMessages = 7;
}
| using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class NetworkManager : MonoBehaviour {
public List<string> ChatMessages;
public bool IsOfflineMode;
// Goal #1: Create a reasonable chat system using the NEW UI System
public void AddChatMessage(string message) {
PhotonView.Get(this).RPC("AddChatMessageRPC", PhotonTargets.All, message);
}
[RPC]
private void AddChatMessageRPC(string message) {
// TODO: If message is longer than x characters, split it into multiple messages so that it fits inside the textbox
while (ChatMessages.Count >= maxChatMessages) {
ChatMessages.RemoveAt(0);
}
ChatMessages.Add(message);
}
void Start() {
PhotonNetwork.player.name = PlayerPrefs.GetString("Username", "Matt");
ChatMessages = new List<string>();
if (IsOfflineMode) {
PhotonNetwork.offlineMode = true;
OnJoinedLobby();
} else {
Connect();
}
}
void Update() {
}
void Connect() {
PhotonNetwork.ConnectUsingSettings("FPS Test v001");
}
void OnGUI() {
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}
void OnJoinedLobby() {
Debug.Log("OnJoinedLobby");
PhotonNetwork.JoinRandomRoom();
}
void OnPhotonRandomJoinFailed() {
Debug.Log("OnPhotonRandomJoinFailed");
PhotonNetwork.CreateRoom(null);
}
void OnJoinedRoom() {
Debug.Log("OnJoinedRoom");
AddChatMessage("[SYSTEM] OnJoinedRoom!");
}
const int maxChatMessages = 7;
}
|
Add extra properties to experience model | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerHub.Client.API.Students.Experiences {
public class ExperienceModel {
public int ID { get; set; }
public string Title { get; set; }
public string Organisation { get; set; }
public string Description { get; set; }
public string ContactName { get; set; }
public string ContactEmail { get; set; }
public string ContactPhone { get; set; }
public DateTime StartUtc { get; set; }
public DateTime? EndUtc { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public string Type { get; set; }
public string Hours { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerHub.Client.API.Students.Experiences {
public class ExperienceModel {
public int ID { get; set; }
public string Title { get; set; }
public string Organisation { get; set; }
public string Description { get; set; }
public string ContactName { get; set; }
public string ContactEmail { get; set; }
public string ContactPhone { get; set; }
public DateTime StartUtc { get; set; }
public DateTime? EndUtc { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
public int? TypeID { get; set; }
public string Type { get; set; }
public int? HoursID { get; set; }
public string Hours { get; set; }
}
}
|
Add global exception handle, not enable. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;
namespace Phoebe.FormClient
{
static class Program
{
/// <summary>
/// 全局操作
/// </summary>
public static GlobalControl GC = new GlobalControl();
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginForm login = new LoginForm();
if (login.ShowDialog() == DialogResult.OK)
{
Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息
Application.Run(new MainForm());
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Phoebe.Base;
using Phoebe.Common;
using Phoebe.Model;
namespace Phoebe.FormClient
{
static class Program
{
/// <summary>
/// 全局操作
/// </summary>
public static GlobalControl GC = new GlobalControl();
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
LoginForm login = new LoginForm();
if (login.ShowDialog() == DialogResult.OK)
{
Program.GC.CurrentUser = Program.GC.ConvertToLoginUser(login.User);
Cache.Instance.Add("CurrentUser", Program.GC.CurrentUser); //缓存用户信息
Application.Run(new MainForm());
}
}
/// <summary>
/// 异常消息处理
/// </summary>
/// <param name="sender"></param>
/// <param name="ex"></param>
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
{
string message = string.Format("{0}\r\n操作发生错误,您需要退出系统么?", ex.Exception.Message);
if (MessageUtil.ConfirmYesNo(message) == DialogResult.Yes)
{
Application.Exit();
}
}
}
}
|
Clarify FudgeDie special case's formatting | using UnityEngine;
public class RollFudgeDie : RollSpecialDie
{
public override string Examine(Vector3 worldPos = default)
{
return $"It is showing side {GetFudgeMessage()}";
}
protected override string GetMessage()
{
return $"The {dieName} lands a {GetFudgeMessage()}";
}
private string GetFudgeMessage()
{
if (result == 2)
{
return specialFaces[1].ToString();
}
return $"{specialFaces[result - 1]}.";
}
}
| using UnityEngine;
public class RollFudgeDie : RollSpecialDie
{
public override string Examine(Vector3 worldPos = default)
{
return $"It is showing {GetFudgeMessage()}";
}
protected override string GetMessage()
{
return $"The {dieName} lands {GetFudgeMessage()}";
}
private string GetFudgeMessage()
{
// Result 2 is a strange side, we modify the formatting such that it reads "a... what?".
if (result == 2)
{
return $"a{specialFaces[1]}";
}
return $"a {specialFaces[result - 1]}.";
}
}
|
Simplify file enumeration and correctly handle path too long exceptions when enumerating sub directories | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
allFiles = allFiles.Concat(GetFiles(current, pattern));
foreach (var subdirectory in GetSubdirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
}
return allFiles;
}
private IEnumerable<string> GetFiles(string path, string pattern)
{
try
{
return Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
private IEnumerable<string> GetSubdirectories(string path)
{
try
{
return Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", path));
return Enumerable.Empty<string>();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Framework.Logging;
namespace OmniSharp.Utilities
{
public class DirectoryEnumerator
{
private ILogger _logger;
public DirectoryEnumerator(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<DirectoryEnumerator>();
}
public IEnumerable<string> SafeEnumerateFiles(string target, string pattern = "*.*")
{
var allFiles = Enumerable.Empty<string>();
var directoryStack = new Stack<string>();
directoryStack.Push(target);
while (directoryStack.Any())
{
var current = directoryStack.Pop();
try
{
var files = Directory.GetFiles(current, pattern);
allFiles = allFiles.Concat(files);
foreach (var subdirectory in Directory.EnumerateDirectories(current))
{
directoryStack.Push(subdirectory);
}
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning(string.Format("Unauthorized access to {0}, skipping", current));
}
catch (PathTooLongException)
{
_logger.LogWarning(string.Format("Path {0} is too long, skipping", current));
}
}
return allFiles;
}
}
}
|
Use separate task to queue sound effects so they can be played when they're loaded | using System;
using System.IO;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;
namespace MonoHaven
{
public class Audio : IDisposable
{
private readonly AudioContext context;
private readonly OggStreamer streamer;
public Audio()
{
context = new AudioContext();
streamer = new OggStreamer();
}
public void Play(Delayed<Resource> res)
{
if (res.Value == null)
return;
var audio = res.Value.GetLayer<AudioData>();
var ms = new MemoryStream(audio.Bytes);
var oggStream = new OggStream(ms);
oggStream.Play();
}
public void Dispose()
{
if (streamer != null)
streamer.Dispose();
if (context != null)
context.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using MonoHaven.Resources;
using MonoHaven.Resources.Layers;
using MonoHaven.Utils;
using NVorbis.OpenTKSupport;
using OpenTK.Audio;
namespace MonoHaven
{
public class Audio : IDisposable
{
private readonly AudioContext context;
private readonly OggStreamer streamer;
private readonly AudioPlayer player;
public Audio()
{
context = new AudioContext();
streamer = new OggStreamer();
player = new AudioPlayer();
player.Run();
}
public void Play(Delayed<Resource> res)
{
player.Queue(res);
}
public void Dispose()
{
player.Stop();
if (streamer != null)
streamer.Dispose();
if (context != null)
context.Dispose();
}
private class AudioPlayer : BackgroundTask
{
private readonly Queue<Delayed<Resource>> queue;
public AudioPlayer() : base("Audio Player")
{
queue = new Queue<Delayed<Resource>>();
}
protected override void OnStart()
{
while (!IsCancelled)
{
lock (queue)
{
var item = queue.Count > 0 ? queue.Peek() : null;
if (item != null && item.Value != null)
{
queue.Dequeue();
var audio = item.Value.GetLayer<AudioData>();
if (audio != null)
{
var ms = new MemoryStream(audio.Bytes);
var oggStream = new OggStream(ms);
oggStream.Play();
}
}
Monitor.Wait(queue, TimeSpan.FromMilliseconds(100));
}
}
}
public void Queue(Delayed<Resource> res)
{
lock (queue)
{
queue.Enqueue(res);
Monitor.PulseAll(queue);
}
}
}
}
}
|
Add mock changes to new Venmo class | using System;
namespace Braintree
{
public class VenmoAccount : PaymentMethod
{
public string Token { get; protected set; }
public string Username { get; protected set; }
public string VenmoUserId { get; protected set; }
public string SourceDescription { get; protected set; }
public string ImageUrl { get; protected set; }
public bool? IsDefault { get; protected set; }
public string CustomerId { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Subscription[] Subscriptions { get; protected set; }
protected internal VenmoAccount(NodeWrapper node, BraintreeGateway gateway)
{
Token = node.GetString("token");
Username = node.GetString("username");
VenmoUserId = node.GetString("venmo-user-id");
SourceDescription = node.GetString("source-description");
ImageUrl = node.GetString("image-url");
IsDefault = node.GetBoolean("default");
CustomerId = node.GetString("customer-id");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
}
}
}
}
| using System;
namespace Braintree
{
public class VenmoAccount : PaymentMethod
{
public string Token { get; protected set; }
public string Username { get; protected set; }
public string VenmoUserId { get; protected set; }
public string SourceDescription { get; protected set; }
public string ImageUrl { get; protected set; }
public bool? IsDefault { get; protected set; }
public string CustomerId { get; protected set; }
public DateTime? CreatedAt { get; protected set; }
public DateTime? UpdatedAt { get; protected set; }
public Subscription[] Subscriptions { get; protected set; }
protected internal VenmoAccount(NodeWrapper node, IBraintreeGateway gateway)
{
Token = node.GetString("token");
Username = node.GetString("username");
VenmoUserId = node.GetString("venmo-user-id");
SourceDescription = node.GetString("source-description");
ImageUrl = node.GetString("image-url");
IsDefault = node.GetBoolean("default");
CustomerId = node.GetString("customer-id");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
}
}
[Obsolete("Mock Use Only")]
protected internal VenmoAccount() { }
}
}
|
Remove underscore from parameter name | namespace ChessDotNet
{
public enum Event
{
Check,
Checkmate,
Stalemate,
Draw,
Custom,
Resign,
VariantEnd, // to be used for chess variants, which can be derived from ChessGame
None
}
public class GameStatus
{
public Event Event
{
get;
private set;
}
public Player PlayerWhoCausedEvent
{
get;
private set;
}
public string EventExplanation
{
get;
private set;
}
public GameStatus(Event _event, Player whoCausedEvent, string eventExplanation)
{
Event = _event;
PlayerWhoCausedEvent = whoCausedEvent;
EventExplanation = eventExplanation;
}
}
}
| namespace ChessDotNet
{
public enum Event
{
Check,
Checkmate,
Stalemate,
Draw,
Custom,
Resign,
VariantEnd, // to be used for chess variants, which can be derived from ChessGame
None
}
public class GameStatus
{
public Event Event
{
get;
private set;
}
public Player PlayerWhoCausedEvent
{
get;
private set;
}
public string EventExplanation
{
get;
private set;
}
public GameStatus(Event @event, Player whoCausedEvent, string eventExplanation)
{
Event = @event;
PlayerWhoCausedEvent = whoCausedEvent;
EventExplanation = eventExplanation;
}
}
}
|
Add basic blocking migration, move not copy | // 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.Logging;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Game.IO
{
public class OsuStorage : WrappedStorage
{
public OsuStorage(GameHost host)
: base(host.Storage, string.Empty)
{
var storageConfig = new StorageConfigManager(host.Storage);
var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);
if (!string.IsNullOrEmpty(customStoragePath))
{
ChangeTargetStorage(host.GetStorage(customStoragePath));
Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Game.Configuration;
namespace osu.Game.IO
{
public class OsuStorage : WrappedStorage
{
private readonly GameHost host;
private readonly StorageConfigManager storageConfig;
public OsuStorage(GameHost host)
: base(host.Storage, string.Empty)
{
this.host = host;
storageConfig = new StorageConfigManager(host.Storage);
var customStoragePath = storageConfig.Get<string>(StorageConfig.FullPath);
if (!string.IsNullOrEmpty(customStoragePath))
{
ChangeTargetStorage(host.GetStorage(customStoragePath));
Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs");
}
}
public void Migrate(string newLocation)
{
string oldLocation = GetFullPath(".");
// ensure the new location has no files present, else hard abort
if (Directory.Exists(newLocation))
{
if (Directory.GetFiles(newLocation).Length > 0)
throw new InvalidOperationException("Migration destination already has files present");
Directory.Delete(newLocation, true);
}
Directory.Move(oldLocation, newLocation);
Directory.CreateDirectory(newLocation);
// temporary
Directory.CreateDirectory(oldLocation);
// move back exceptions for now
Directory.Move(Path.Combine(newLocation, "cache"), Path.Combine(oldLocation, "cache"));
File.Move(Path.Combine(newLocation, "framework.ini"), Path.Combine(oldLocation, "framework.ini"));
ChangeTargetStorage(host.GetStorage(newLocation));
storageConfig.Set(StorageConfig.FullPath, newLocation);
storageConfig.Save();
}
}
}
|
Make test run multiple times | // 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneParticleExplosion : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
AddStep(@"display", () =>
{
Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200)
};
});
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Graphics;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneParticleExplosion : OsuTestScene
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
AddRepeatStep(@"display", () =>
{
Child = new ParticleExplosion(textures.Get("Cursor/cursortrail"), 150, 1200)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(400)
};
}, 10);
}
}
}
|
Change namespace to avoid conflict | // 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.
namespace System.IO.Pipelines
{
public class DuplexPipe : IDuplexPipe
{
public DuplexPipe(PipeReader reader, PipeWriter writer)
{
Input = reader;
Output = writer;
}
public PipeReader Input { get; }
public PipeWriter Output { get; }
public void Dispose()
{
}
public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions)
{
var input = new Pipe(inputOptions);
var output = new Pipe(outputOptions);
var transportToApplication = new DuplexPipe(output.Reader, input.Writer);
var applicationToTransport = new DuplexPipe(input.Reader, output.Writer);
return new DuplexPipePair(applicationToTransport, transportToApplication);
}
// This class exists to work around issues with value tuple on .NET Framework
public struct DuplexPipePair
{
public IDuplexPipe Transport { get; private set; }
public IDuplexPipe Application { get; private set; }
public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application)
{
Transport = transport;
Application = application;
}
}
}
}
| // 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.IO.Pipelines;
namespace Microsoft.AspNetCore.Sockets
{
public class DuplexPipe : IDuplexPipe
{
public DuplexPipe(PipeReader reader, PipeWriter writer)
{
Input = reader;
Output = writer;
}
public PipeReader Input { get; }
public PipeWriter Output { get; }
public void Dispose()
{
}
public static DuplexPipePair CreateConnectionPair(PipeOptions inputOptions, PipeOptions outputOptions)
{
var input = new Pipe(inputOptions);
var output = new Pipe(outputOptions);
var transportToApplication = new DuplexPipe(output.Reader, input.Writer);
var applicationToTransport = new DuplexPipe(input.Reader, output.Writer);
return new DuplexPipePair(applicationToTransport, transportToApplication);
}
// This class exists to work around issues with value tuple on .NET Framework
public struct DuplexPipePair
{
public IDuplexPipe Transport { get; private set; }
public IDuplexPipe Application { get; private set; }
public DuplexPipePair(IDuplexPipe transport, IDuplexPipe application)
{
Transport = transport;
Application = application;
}
}
}
}
|
Fix bug not able to install packages to JS Metro project. Work items: 1986 | using System.IO;
using EnvDTE;
namespace NuGet.VisualStudio
{
/// <summary>
/// This project system represents the JavaScript Metro project in Windows8
/// </summary>
public class JsProjectSystem : VsProjectSystem
{
public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) :
base(project, fileSystemProvider)
{
}
public override string ProjectName
{
get
{
return Project.GetName();
}
}
public override void AddFile(string path, Stream stream)
{
Project.GetProjectItems(path, createIfNotExists: true);
base.AddFile(path, stream);
}
protected override void AddFileToContainer(string fullPath, ProjectItems container)
{
container.AddFromFile(fullPath);
}
}
} | using System.IO;
using EnvDTE;
namespace NuGet.VisualStudio
{
/// <summary>
/// This project system represents the JavaScript Metro project in Windows8
/// </summary>
public class JsProjectSystem : VsProjectSystem
{
public JsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) :
base(project, fileSystemProvider)
{
}
public override string ProjectName
{
get
{
return Project.GetName();
}
}
public override void AddFile(string path, Stream stream)
{
// ensure the parent folder is created before adding file to the project
Project.GetProjectItems(Path.GetDirectoryName(path), createIfNotExists: true);
base.AddFile(path, stream);
}
protected override void AddFileToContainer(string fullPath, ProjectItems container)
{
container.AddFromFile(fullPath);
}
}
} |
Make published books "motion book"s | using System.Collections.Generic;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel
{
public class Body
{
[XmlAttribute("bookcreationtype")]
public string BookCreationType;
[XmlAttribute("class")]
public string Class;
[XmlElement("div")]
public List<Div> Divs;
}
} | using System.Collections.Generic;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.BloomModel.BloomHtmlModel
{
public class Body
{
// REVIEW: I don't think these two are necessary/useful
[XmlAttribute("bookcreationtype")]
public string BookCreationType;
[XmlAttribute("class")]
public string Class;
// Features used to make this a "motion book"
[XmlAttribute("data-bfautoadvance")]
public string BloomFeature_AutoAdvance = "landscape;bloomReader";
[XmlAttribute("data-bfcanrotate")]
public string BloomFeature_CanRotate = "allOrientations;bloomReader";
[XmlAttribute("data-bfplayanimations")]
public string BloomFeature_PlayAnimations = "landscape;bloomReader";
[XmlAttribute("data-bfplaymusic")]
public string BloomFeature_PlayMusic = "landscape;bloomReader";
[XmlAttribute("data-bfplaynarration")]
public string BloomFeature_PlayNarration = "landscape;bloomReader";
[XmlAttribute("data-bffullscreenpicture")]
public string BloomFeature_FullScreenPicture = "landscape;bloomReader";
[XmlElement("div")]
public List<Div> Divs;
}
}
|
Add deprecated 'tree list' type to formatter, because that's what __base templates still is :) | using System;
using System.Collections.Generic;
using Rainbow.Model;
using Sitecore.Data;
namespace Rainbow.Formatting.FieldFormatters
{
public class MultilistFormatter : FieldTypeBasedFormatter
{
public override string[] SupportedFieldTypes
{
get
{
return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx" };
}
}
public override string Format(IItemFieldValue field)
{
var values = ID.ParseArray(field.Value);
if (values.Length == 0 && field.Value.Length > 0)
return field.Value;
return string.Join(Environment.NewLine, (IEnumerable<ID>)values);
}
public override string Unformat(string value)
{
if (value == null) return null;
return value.Trim().Replace(Environment.NewLine, "|");
}
}
}
| using System;
using System.Collections.Generic;
using Rainbow.Model;
using Sitecore.Data;
namespace Rainbow.Formatting.FieldFormatters
{
public class MultilistFormatter : FieldTypeBasedFormatter
{
public override string[] SupportedFieldTypes
{
get
{
return new[] { "Checklist", "Multilist", "Multilist with Search", "Treelist", "Treelist with Search", "TreelistEx", "tree list" };
}
}
public override string Format(IItemFieldValue field)
{
var values = ID.ParseArray(field.Value);
if (values.Length == 0 && field.Value.Length > 0)
return field.Value;
return string.Join(Environment.NewLine, (IEnumerable<ID>)values);
}
public override string Unformat(string value)
{
if (value == null) return null;
return value.Trim().Replace(Environment.NewLine, "|");
}
}
}
|
Correct test client endpoint address. It worked! |
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8000/HelloIndigo/HelloIndigoService");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(), endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
|
using System;
using System.Diagnostics;
using System.ServiceModel;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace Host.Specs
{
/// <summary>
/// An **copy** of the interface specifying the contract for this service.
/// </summary>
[ServiceContract(
Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
[Binding]
public class RunServiceHostSteps
{
[Given(@"that I have started the host")]
public void GivenThatIHaveStartedTheHost()
{
Process.Start(@"..\..\..\Host\bin\Debug\Host.exe");
}
[When(@"I execute the ""(.*)"" method of the service")]
public void WhenIExecuteTheMethodOfTheService(string p0)
{
var endPointAddress =
new EndpointAddress(
"http://localhost:8733/Design_Time_Addresses/Host/HelloIndigoService");
var proxy =
ChannelFactory<IHelloIndigoService>.CreateChannel(
new BasicHttpBinding(), endPointAddress);
ScenarioContext.Current.Set(proxy);
}
[Then(@"I receive ""(.*)"" as a result")]
public void ThenIReceiveAsAResult(string p0)
{
var proxy = ScenarioContext.Current.Get<IHelloIndigoService>();
var result = proxy.HelloIndigo();
Assert.That(result, Is.EqualTo("Hello Indigo"));
}
}
}
|
Remove underline from breadcrumb display | // 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.Graphics.UserInterface;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value);
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
Text.Font = Text.Font.With(size: 14);
Chevron.Y = 3;
}
}
}
}
| // 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.Graphics.UserInterface;
using osu.Framework.Graphics;
using osu.Framework.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public class OverlayHeaderBreadcrumbControl : BreadcrumbControl<string>
{
public OverlayHeaderBreadcrumbControl()
{
RelativeSizeAxes = Axes.X;
}
protected override TabItem<string> CreateTabItem(string value) => new ControlTabItem(value);
private class ControlTabItem : BreadcrumbTabItem
{
protected override float ChevronSize => 8;
public ControlTabItem(string value)
: base(value)
{
Text.Font = Text.Font.With(size: 14);
Chevron.Y = 3;
Bar.Height = 0;
}
}
}
}
|
Fix button colors in beatmap options test | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Screens.Select.Options;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null);
overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, Color4.Pink, null);
overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Screens.Select.Options;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
var colours = new OsuColour();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, null);
overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, null);
overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, colours.Yellow, null);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
|
Fix migration test - use correct database from v2 fixture. | namespace SqlStreamStore
{
using System.Threading;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Streams;
using Xunit;
public class MigrationTests
{
[Fact]
public async Task Can_migrate()
{
// Set up an old schema + data.
var schema = "baz";
var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false);
var v2Store = await v2Fixture.GetMsSqlStreamStore();
await v2Store.AppendToStream("stream-1",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.AppendToStream("stream-2",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20);
v2Store.Dispose();
v2Fixture.Dispose();
// Migrate with V3 schema.
var v3Fixture = new MsSqlStreamStoreV3Fixture(schema, databaseNameOverride: v2Fixture.DatabaseName);
var v3Store = await v3Fixture.GetMsSqlStreamStore();
var checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeFalse();
await v3Store.Migrate(CancellationToken.None);
checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeTrue();
v3Store.Dispose();
v3Fixture.Dispose();
}
}
} | namespace SqlStreamStore
{
using System.Threading;
using System.Threading.Tasks;
using Shouldly;
using SqlStreamStore.Streams;
using Xunit;
public class MigrationTests
{
[Fact]
public async Task Can_migrate()
{
// Set up an old schema + data.
var schema = "baz";
var v2Fixture = new MsSqlStreamStoreFixture(schema, deleteDatabaseOnDispose: false);
var v2Store = await v2Fixture.GetMsSqlStreamStore();
await v2Store.AppendToStream("stream-1",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.AppendToStream("stream-2",
ExpectedVersion.NoStream,
StreamStoreAcceptanceTests.CreateNewStreamMessages(1, 2, 3));
await v2Store.SetStreamMetadata("stream-1", ExpectedVersion.Any, maxAge: 10, maxCount: 20);
v2Store.Dispose();
v2Fixture.Dispose();
var settings = new MsSqlStreamStoreV3Settings(v2Fixture.ConnectionString)
{
Schema = schema,
};
var v3Store = new MsSqlStreamStoreV3(settings);
var checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeFalse();
await v3Store.Migrate(CancellationToken.None);
checkSchemaResult = await v3Store.CheckSchema();
checkSchemaResult.IsMatch().ShouldBeTrue();
v3Store.Dispose();
}
}
} |
Disable "select all mods" button if all are selected | // 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.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Overlays.Mods
{
public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction>
{
public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.SelectAll;
Action = modSelectOverlay.SelectAll;
}
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat || e.Action != PlatformAction.SelectAll)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
}
}
| // 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 osu.Framework.Bindables;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Overlays.Mods
{
public class SelectAllModsButton : ShearedButton, IKeyBindingHandler<PlatformAction>
{
private readonly Bindable<IReadOnlyList<Mod>> selectedMods = new Bindable<IReadOnlyList<Mod>>();
private readonly Bindable<Dictionary<ModType, IReadOnlyList<ModState>>> availableMods = new Bindable<Dictionary<ModType, IReadOnlyList<ModState>>>();
public SelectAllModsButton(FreeModSelectOverlay modSelectOverlay)
: base(ModSelectOverlay.BUTTON_WIDTH)
{
Text = CommonStrings.SelectAll;
Action = modSelectOverlay.SelectAll;
selectedMods.BindTo(modSelectOverlay.SelectedMods);
availableMods.BindTo(modSelectOverlay.AvailableMods);
}
protected override void LoadComplete()
{
base.LoadComplete();
selectedMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState));
availableMods.BindValueChanged(_ => Scheduler.AddOnce(updateEnabledState));
updateEnabledState();
}
private void updateEnabledState()
{
Enabled.Value = availableMods.Value
.SelectMany(pair => pair.Value)
.Any(modState => !modState.Active.Value && !modState.Filtered.Value);
}
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat || e.Action != PlatformAction.SelectAll)
return false;
TriggerClick();
return true;
}
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
}
}
|
Fix build error with mirroring | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
public readonly partial struct DateTime
{
public static DateTime UtcNow
{
get
{
// For performance, use a private constructor that does not validate arguments.
return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + TicksTo1970)) | KindUtc);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
public readonly partial struct DateTime
{
public static DateTime UtcNow
{
get
{
// For performance, use a private constructor that does not validate arguments.
return new DateTime(((ulong)(Interop.Sys.GetSystemTimeAsTicks() + DateTime.UnixEpochTicks)) | KindUtc);
}
}
}
}
|
Check voor CLS-compliante code verwijderd uit project CodeProject.Data | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CodeProject - EF Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AREBIS")]
[assembly: AssemblyProduct("CodeProject - EF")]
[assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: System.CLSCompliant(true)] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CodeProject - EF Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AREBIS")]
[assembly: AssemblyProduct("CodeProject - EF")]
[assembly: AssemblyCopyright("Copyright © Rudi Breedenraedt 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// voorlopig geen CLS-compliante code.
// [assembly: System.CLSCompliant(true)] |
Update Json tests to reflect change to IEnumerable | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
ObservableCollection<TestClass> expected = new ObservableCollection<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
ObservableCollection<TestClass> result = sut.DeserializeCollection<TestClass>(testData);
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
[Fact]
public void ShouldReturnValue()
{
var sut = new JsonService();
string expected = "value";
string testData = "{ \"key\": \"value\" }";
string result = sut.GetValue<string>(testData, "key");
Assert.Equal(expected, result);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
List<TestClass> expected = new List<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
List<TestClass> result = sut.DeserializeCollection<TestClass>(testData).ToList();
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
[Fact]
public void ShouldReturnValue()
{
var sut = new JsonService();
string expected = "value";
string testData = "{ \"key\": \"value\" }";
string result = sut.GetValue<string>(testData, "key");
Assert.Equal(expected, result);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
|
Extend character set of function names (including ".") | using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w](?<functionName>\w*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
| using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
|
Fix the problem that the web request is displayed twice when -Verbosity is set to detailed. |
namespace NuGet.Common
{
public class CommandLineRepositoryFactory : PackageRepositoryFactory
{
public static readonly string UserAgent = "NuGet Command Line";
private readonly IConsole _console;
public CommandLineRepositoryFactory(IConsole console)
{
_console = console;
}
public override IPackageRepository CreateRepository(string packageSource)
{
var repository = base.CreateRepository(packageSource);
var httpClientEvents = repository as IHttpClientEvents;
if (httpClientEvents != null)
{
httpClientEvents.SendingRequest += (sender, args) =>
{
if (_console.Verbosity == Verbosity.Detailed)
{
_console.WriteLine(
System.ConsoleColor.Green,
"{0} {1}", args.Request.Method, args.Request.RequestUri);
}
string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
HttpUtility.SetUserAgent(args.Request, userAgent);
};
}
return repository;
}
}
} |
using System.Windows;
namespace NuGet.Common
{
public class CommandLineRepositoryFactory : PackageRepositoryFactory, IWeakEventListener
{
public static readonly string UserAgent = "NuGet Command Line";
private readonly IConsole _console;
public CommandLineRepositoryFactory(IConsole console)
{
_console = console;
}
public override IPackageRepository CreateRepository(string packageSource)
{
var repository = base.CreateRepository(packageSource);
var httpClientEvents = repository as IHttpClientEvents;
if (httpClientEvents != null)
{
SendingRequestEventManager.AddListener(httpClientEvents, this);
}
return repository;
}
public bool ReceiveWeakEvent(System.Type managerType, object sender, System.EventArgs e)
{
if (managerType == typeof(SendingRequestEventManager))
{
var args = (WebRequestEventArgs)e;
if (_console.Verbosity == Verbosity.Detailed)
{
_console.WriteLine(
System.ConsoleColor.Green,
"{0} {1}", args.Request.Method, args.Request.RequestUri);
}
string userAgent = HttpUtility.CreateUserAgentString(CommandLineConstants.UserAgent);
HttpUtility.SetUserAgent(args.Request, userAgent);
return true;
}
else
{
return false;
}
}
}
} |
Make the application and its window come in front when launched | using System;
using MonoMac.AppKit;
namespace macdoc
{
public class AppleDocWizardDelegate : NSApplicationDelegate
{
AppleDocWizardController wizard;
public override bool ApplicationShouldOpenUntitledFile (NSApplication sender)
{
return false;
}
public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification)
{
wizard = new AppleDocWizardController ();
wizard.Window.Center ();
NSApplication.SharedApplication.ArrangeInFront (this);
NSApplication.SharedApplication.RunModalForWindow (wizard.Window);
}
}
}
| using System;
using MonoMac.AppKit;
namespace macdoc
{
public class AppleDocWizardDelegate : NSApplicationDelegate
{
AppleDocWizardController wizard;
public override bool ApplicationShouldOpenUntitledFile (NSApplication sender)
{
return false;
}
public override void DidFinishLaunching (MonoMac.Foundation.NSNotification notification)
{
wizard = new AppleDocWizardController ();
NSApplication.SharedApplication.ActivateIgnoringOtherApps (true);
wizard.Window.MakeMainWindow ();
wizard.Window.MakeKeyWindow ();
wizard.Window.MakeKeyAndOrderFront (this);
wizard.Window.Center ();
wizard.VerifyFreshnessAndLaunchDocProcess ();
NSApplication.SharedApplication.RunModalForWindow (wizard.Window);
}
}
}
|
Use SetAnchorPreset instead of manually setting each anchor | using Content.Client.GameObjects.Components.Construction;
using Robust.Client.Interfaces.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Content.Client.Construction
{
public class ConstructionButton : Button
{
private readonly IDisplayManager _displayManager;
public ConstructorComponent Owner
{
get => Menu.Owner;
set => Menu.Owner = value;
}
ConstructionMenu Menu;
public ConstructionButton(IDisplayManager displayManager)
{
_displayManager = displayManager;
PerformLayout();
}
protected override void Initialize()
{
base.Initialize();
AnchorLeft = 1.0f;
AnchorTop = 1.0f;
AnchorRight = 1.0f;
AnchorBottom = 1.0f;
MarginLeft = -110.0f;
MarginTop = -70.0f;
MarginRight = -50.0f;
MarginBottom = -50.0f;
Text = "Crafting";
OnPressed += IWasPressed;
}
private void PerformLayout()
{
Menu = new ConstructionMenu(_displayManager);
Menu.AddToScreen();
}
void IWasPressed(ButtonEventArgs args)
{
Menu.Open();
}
public void AddToScreen()
{
UserInterfaceManager.StateRoot.AddChild(this);
}
public void RemoveFromScreen()
{
if (Parent != null)
{
Parent.RemoveChild(this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Menu.Dispose();
}
base.Dispose(disposing);
}
}
}
| using Content.Client.GameObjects.Components.Construction;
using Robust.Client.Interfaces.Graphics;
using Robust.Client.UserInterface.Controls;
using Robust.Shared.Maths;
using Robust.Shared.Utility;
namespace Content.Client.Construction
{
public class ConstructionButton : Button
{
private readonly IDisplayManager _displayManager;
public ConstructorComponent Owner
{
get => Menu.Owner;
set => Menu.Owner = value;
}
ConstructionMenu Menu;
public ConstructionButton(IDisplayManager displayManager)
{
_displayManager = displayManager;
PerformLayout();
}
protected override void Initialize()
{
base.Initialize();
SetAnchorPreset(LayoutPreset.BottomRight);
MarginLeft = -110.0f;
MarginTop = -70.0f;
MarginRight = -50.0f;
MarginBottom = -50.0f;
Text = "Crafting";
OnPressed += IWasPressed;
}
private void PerformLayout()
{
Menu = new ConstructionMenu(_displayManager);
Menu.AddToScreen();
}
void IWasPressed(ButtonEventArgs args)
{
Menu.Open();
}
public void AddToScreen()
{
UserInterfaceManager.StateRoot.AddChild(this);
}
public void RemoveFromScreen()
{
if (Parent != null)
{
Parent.RemoveChild(this);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Menu.Dispose();
}
base.Dispose(disposing);
}
}
}
|
Handle PS3 covers with no text | using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.PS3Model
{
[XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")]
public class PhotoStoryProject
{
[XmlAttribute("schemaVersion")]
public string SchemaVersion;
[XmlAttribute("appVersion")]
public string AppVersion;
[XmlAttribute("linkOnly")]
public bool LinkOnly;
[XmlAttribute("defaultImageDuration")]
public int DefaultImageDuration;
[XmlAttribute("visualUnitCount")]
public int VisualUnitCount;
[XmlAttribute("codecVersion")]
public string CodecVersion;
[XmlAttribute("sessionSeed")]
public int SessionSeed;
[XmlElement("VisualUnit")]
public VisualUnit[] VisualUnits;
public string GetProjectName()
{
var bookName = "";
foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null))
{
foreach (var edit in vunit.Image.Edits)
{
if (edit.TextOverlays.Length <= 0)
continue;
bookName = edit.TextOverlays[0].Text.Trim();
bookName = Regex.Replace(bookName, @"\s+", " ");
break;
}
if (bookName != "")
break;
}
return bookName;
}
}
}
| using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace PhotoStoryToBloomConverter.PS3Model
{
[XmlRoot("MSPhotoStoryProject", Namespace="MSPhotoStory")]
public class PhotoStoryProject
{
[XmlAttribute("schemaVersion")]
public string SchemaVersion;
[XmlAttribute("appVersion")]
public string AppVersion;
[XmlAttribute("linkOnly")]
public bool LinkOnly;
[XmlAttribute("defaultImageDuration")]
public int DefaultImageDuration;
[XmlAttribute("visualUnitCount")]
public int VisualUnitCount;
[XmlAttribute("codecVersion")]
public string CodecVersion;
[XmlAttribute("sessionSeed")]
public int SessionSeed;
[XmlElement("VisualUnit")]
public VisualUnit[] VisualUnits;
public string GetProjectName()
{
var bookName = "";
foreach (var vunit in VisualUnits.Where(vu => vu.Image?.Edits != null))
{
foreach (var edit in vunit.Image.Edits)
{
if (edit.TextOverlays == null || edit.TextOverlays.Length <= 0)
continue;
bookName = edit.TextOverlays[0].Text.Trim();
bookName = Regex.Replace(bookName, @"\s+", " ");
break;
}
if (bookName != "")
break;
}
return bookName;
}
}
}
|
Add test for returning empty list from script | using System.Linq;
using NUnit.Framework;
namespace Rant.Tests.Richard
{
[TestFixture]
public class Lists
{
private readonly RantEngine rant = new RantEngine();
[Test]
public void ListInitBare()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main);
}
[Test]
public void ListInitBrackets()
{
Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main);
}
[Test]
public void ListInitConcat()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main);
}
[Test]
public void ListAsBlock()
{
string[] possibleResults = new string[] { "1", "2", "3", "4" };
Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0);
}
[Test]
public void ListInitializer()
{
Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main);
}
}
}
| using System.Linq;
using NUnit.Framework;
namespace Rant.Tests.Richard
{
[TestFixture]
public class Lists
{
private readonly RantEngine rant = new RantEngine();
[Test]
public void ListInitBare()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3, 4, 5; x.length ]").Main);
}
[Test]
public void ListInitBrackets()
{
Assert.AreEqual("5", rant.Do("[@ x = [1, 2, 3, 4, 5]; x.length ]").Main);
}
[Test]
public void ListInitConcat()
{
Assert.AreEqual("5", rant.Do("[@ x = 1, 2, 3; y = x, 4, 5; y.length ]").Main);
}
[Test]
public void ListAsBlock()
{
string[] possibleResults = new string[] { "1", "2", "3", "4" };
Assert.GreaterOrEqual(possibleResults.ToList().IndexOf(rant.Do("[@ 1, 2, 3, 4 ]").Main), 0);
}
[Test]
public void ListInitializer()
{
Assert.AreEqual("12", rant.Do("[@ x = list 12; x.length ]").Main);
}
[Test]
public void ListEmptyAsBlock()
{
Assert.AreEqual("", rant.Do(@"[@ [] ]"));
}
}
}
|
Print results of running tests | using System;
namespace TDDUnit {
class TestTestCase : TestCase {
public TestTestCase(string name) : base(name) {
}
public void TestTemplateMethod() {
WasRunObj test = new WasRunObj("TestMethod");
test.Run();
Assert.That(test.Log == "SetUp TestMethod TearDown ");
}
public void TestResult() {
WasRunObj test = new WasRunObj("TestMethod");
TestResult result = test.Run();
Assert.That("1 run, 0 failed" == result.Summary);
}
public void TestFailedResult() {
WasRunObj test = new WasRunObj("TestBrokenMethod");
TestResult result = test.Run();
Assert.That("1 run, 1 failed" == result.Summary);
}
public void TestFailedResultFormatting() {
TestResult result = new TestResult();
result.TestStarted();
result.TestFailed();
Assert.That("1 run, 1 failed" == result.Summary);
}
}
class Program {
static void Main() {
new TestTestCase("TestTemplateMethod").Run();
new TestTestCase("TestResult").Run();
new TestTestCase("TestFailedResult").Run();
new TestTestCase("TestFailedResultFormatting").Run();
}
}
}
| using System;
namespace TDDUnit {
class TestTestCase : TestCase {
public TestTestCase(string name) : base(name) {
}
public void TestTemplateMethod() {
WasRunObj test = new WasRunObj("TestMethod");
test.Run();
Assert.That(test.Log == "SetUp TestMethod TearDown ");
}
public void TestResult() {
WasRunObj test = new WasRunObj("TestMethod");
TestResult result = test.Run();
Assert.That("1 run, 0 failed" == result.Summary);
}
public void TestFailedResult() {
WasRunObj test = new WasRunObj("TestBrokenMethod");
TestResult result = test.Run();
Assert.That("1 run, 1 failed" == result.Summary);
}
public void TestFailedResultFormatting() {
TestResult result = new TestResult();
result.TestStarted();
result.TestFailed();
Assert.That("1 run, 1 failed" == result.Summary);
}
}
class Program {
static void Main() {
Console.WriteLine(new TestTestCase("TestTemplateMethod").Run().Summary);
Console.WriteLine(new TestTestCase("TestResult").Run().Summary);
Console.WriteLine(new TestTestCase("TestFailedResult").Run().Summary);
Console.WriteLine(new TestTestCase("TestFailedResultFormatting").Run().Summary);
}
}
}
|
Add a bracket that somehow did not get comitted | // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class UserInputManagerTest : TestCase
{
[Test]
public void IsAliveTest()
{
AddAssert("UserInputManager is alive", () =>
{
using (var client = new TestHeadlessGameHost(@"client", true))
{
return client.CurrentRoot.IsAlive;
}
});
}
private class TestHeadlessGameHost : HeadlessGameHost
{
public Drawable CurrentRoot => Root;
public TestHeadlessGameHost(string hostname, bool bindIPC)
: base(hostname, bindIPC)
{
using (var game = new TestGame())
{
Root = game.CreateUserInputManager();
}
}
}
}
}
|
Fix missing API key error on AppVeyor | using System.Collections.Generic;
using Stormpath.Configuration.Abstractions;
using Stormpath.Owin.Abstractions.Configuration;
namespace Stormpath.Owin.UnitTest
{
public static class ConfigurationHelper
{
public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config)
{
var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config);
var integrationConfig = new IntegrationConfiguration(
compiledConfig,
new TenantConfiguration("foo", false, false),
new KeyValuePair<string, ProviderConfiguration>[0]);
return integrationConfig;
}
}
}
| using System.Collections.Generic;
using Stormpath.Configuration.Abstractions;
using Stormpath.Owin.Abstractions.Configuration;
namespace Stormpath.Owin.UnitTest
{
public static class ConfigurationHelper
{
public static IntegrationConfiguration CreateFakeConfiguration(StormpathConfiguration config)
{
if (config.Client?.ApiKey == null)
{
if (config.Client == null)
{
config.Client = new ClientConfiguration();
}
config.Client.ApiKey = new ClientApiKeyConfiguration()
{
Id = "foo",
Secret = "bar"
};
};
var compiledConfig = Configuration.ConfigurationLoader.Initialize().Load(config);
var integrationConfig = new IntegrationConfiguration(
compiledConfig,
new TenantConfiguration("foo", false, false),
new KeyValuePair<string, ProviderConfiguration>[0]);
return integrationConfig;
}
}
}
|
Remove dependency of home controller since it is no longer needed | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Oogstplanner.Common;
using Oogstplanner.Models;
using Oogstplanner.Services;
namespace Oogstplanner.Web.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
readonly ICalendarService calendarService;
public HomeController(ICalendarService calendarService)
{
if (calendarService == null)
{
throw new ArgumentNullException("calendarService");
}
this.calendarService = calendarService;
}
//
// GET: /welkom
public ActionResult Index()
{
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Oogstplanner.Common;
using Oogstplanner.Models;
using Oogstplanner.Services;
namespace Oogstplanner.Web.Controllers
{
[AllowAnonymous]
public class HomeController : Controller
{
readonly ICalendarService calendarService;
public HomeController()
{ }
//
// GET: /welkom
public ActionResult Index()
{
return View();
}
//
// GET: /veelgesteldevragen
public ActionResult Faq()
{
return View();
}
}
}
|
Make sure that the stream passed in ctor can be seeked and read | using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
} | using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
if (!fileStream.CanSeek) throw new ArgumentException("Stream must be seekable", "fileStream");
if (!fileStream.CanRead) throw new ArgumentException("Stream must be readable", "fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
} |
Add ToString to help with debuggign... :-) | using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
}
}
| using System;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Utils;
namespace LINQToTTreeLib.Variables
{
/// <summary>
/// A simple variable (like int, etc.).
/// </summary>
public class VarSimple : IVariable
{
public string VariableName { get; private set; }
public string RawValue { get; private set; }
public Type Type { get; private set; }
public VarSimple(System.Type type)
{
if (type == null)
throw new ArgumentNullException("Must have a good type!");
Type = type;
VariableName = type.CreateUniqueVariableName();
RawValue = VariableName;
}
public IValue InitialValue { get; set; }
/// <summary>
/// Get/Set if this variable needs to be declared.
/// </summary>
public bool Declare { get; set; }
/// <summary>
/// TO help with debugging...
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "(" + Type.Name + ") " + RawValue;
}
}
}
|
Add protected copy constructor to avoid breaking changes | // 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.
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A set of parameters that control the way strings are localised.
/// </summary>
public class LocalisationParameters
{
/// <summary>
/// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.
/// </summary>
public readonly ILocalisationStore? Store;
/// <summary>
/// Whether to prefer the "original" script of <see cref="RomanisableString"/>s.
/// </summary>
public readonly bool PreferOriginalScript;
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param>
/// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param>
public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript)
{
Store = store;
PreferOriginalScript = preferOriginalScript;
}
}
}
| // 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.
#nullable enable
namespace osu.Framework.Localisation
{
/// <summary>
/// A set of parameters that control the way strings are localised.
/// </summary>
public class LocalisationParameters
{
/// <summary>
/// The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.
/// </summary>
public readonly ILocalisationStore? Store;
/// <summary>
/// Whether to prefer the "original" script of <see cref="RomanisableString"/>s.
/// </summary>
public readonly bool PreferOriginalScript;
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/> based off another <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="parameters">The <see cref="LocalisationParameters"/> to copy values from.</param>
protected LocalisationParameters(LocalisationParameters parameters)
: this(parameters.Store, parameters.PreferOriginalScript)
{
}
/// <summary>
/// Creates a new instance of <see cref="LocalisationParameters"/>.
/// </summary>
/// <param name="store">The <see cref="ILocalisationStore"/> to be used for string lookups and culture-specific formatting.</param>
/// <param name="preferOriginalScript">Whether to prefer the "original" script of <see cref="RomanisableString"/>s.</param>
public LocalisationParameters(ILocalisationStore? store, bool preferOriginalScript)
{
Store = store;
PreferOriginalScript = preferOriginalScript;
}
}
}
|
Check if there are any Clients on the list page | @model IEnumerable<BankingManagementClient.ProjectionStore.Projections.Client.ClientProjection>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientId)
</th>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientName)
</th>
<th></th>
</tr>
@foreach (var clientProjection in Model)
{
<tr>
<td>
@Html.ActionLink(clientProjection.ClientId.ToString(), "Details", new { id = clientProjection.ClientId })
</td>
<td>
@Html.DisplayFor(modelItem => clientProjection.ClientName)
</td>
</tr>
}
</table> | @model IEnumerable<BankingManagementClient.ProjectionStore.Projections.Client.ClientProjection>
@{
ViewBag.Title = "Index";
}
<h2>Clients</h2>
@if (Model.Any())
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientId)
</th>
<th>
@Html.DisplayNameFor(model => model.ElementAt(0)
.ClientName)
</th>
<th></th>
</tr>
@foreach (var clientProjection in Model)
{
<tr>
<td>
@Html.ActionLink(clientProjection.ClientId.ToString(), "Details", new {id = clientProjection.ClientId})
</td>
<td>
@Html.DisplayFor(modelItem => clientProjection.ClientName)
</td>
</tr>
}
</table>
}
else
{
<p>No clients found.</p>
} |
Handle null arrays when MSBuild doesn't initialize task properties | using System.IO;
using ApiContractGenerator.AssemblyReferenceResolvers;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Source;
using Microsoft.Build.Framework;
namespace ApiContractGenerator.MSBuild
{
public sealed class GenerateApiContract : ITask
{
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
[Required]
public ITaskItem[] Assemblies { get; set; }
public string[] IgnoredNamespaces { get; set; }
public bool Execute()
{
if (Assemblies.Length == 0) return true;
var generator = new ApiContractGenerator();
generator.IgnoredNamespaces.UnionWith(IgnoredNamespaces);
foreach (var assembly in Assemblies)
{
var assemblyPath = assembly.GetMetadata("ResolvedAssemblyPath");
var outputPath = assembly.GetMetadata("ResolvedOutputPath");
var assemblyResolver = new CompositeAssemblyReferenceResolver(
new GacAssemblyReferenceResolver(),
new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(assemblyPath)));
using (var metadataReferenceResolver = new MetadataReaderReferenceResolver(() => File.OpenRead(assemblyPath), assemblyResolver))
using (var source = new MetadataReaderSource(File.OpenRead(assemblyPath), metadataReferenceResolver))
using (var outputFile = File.CreateText(outputPath))
generator.Generate(source, new CSharpTextFormatter(outputFile, metadataReferenceResolver));
}
return true;
}
}
}
| using System.IO;
using ApiContractGenerator.AssemblyReferenceResolvers;
using ApiContractGenerator.MetadataReferenceResolvers;
using ApiContractGenerator.Source;
using Microsoft.Build.Framework;
namespace ApiContractGenerator.MSBuild
{
public sealed class GenerateApiContract : ITask
{
public IBuildEngine BuildEngine { get; set; }
public ITaskHost HostObject { get; set; }
[Required]
public ITaskItem[] Assemblies { get; set; }
public string[] IgnoredNamespaces { get; set; }
public bool Execute()
{
if (Assemblies == null || Assemblies.Length == 0) return true;
var generator = new ApiContractGenerator();
if (IgnoredNamespaces != null) generator.IgnoredNamespaces.UnionWith(IgnoredNamespaces);
foreach (var assembly in Assemblies)
{
var assemblyPath = assembly.GetMetadata("ResolvedAssemblyPath");
var outputPath = assembly.GetMetadata("ResolvedOutputPath");
var assemblyResolver = new CompositeAssemblyReferenceResolver(
new GacAssemblyReferenceResolver(),
new SameDirectoryAssemblyReferenceResolver(Path.GetDirectoryName(assemblyPath)));
using (var metadataReferenceResolver = new MetadataReaderReferenceResolver(() => File.OpenRead(assemblyPath), assemblyResolver))
using (var source = new MetadataReaderSource(File.OpenRead(assemblyPath), metadataReferenceResolver))
using (var outputFile = File.CreateText(outputPath))
generator.Generate(source, new CSharpTextFormatter(outputFile, metadataReferenceResolver));
}
return true;
}
}
}
|
Change "Countdown" "End Sync" properties order | using System;
using System.Collections.Generic;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public Settings()
{
DateTimeFormat = new List<string> {"{dd}d {hh}h {mm}m"};
}
[Category("End")]
[DisplayName("Date/Time")]
public DateTime EndDateTime { get; set; } = DateTime.Now;
[Browsable(false)]
[DisplayName("Last End Date/Time")]
public DateTime LastEndDateTime { get; set; } = DateTime.Now;
[Category("Style")]
[DisplayName("Continue Counting")]
public bool EndContinueCounting { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Year")]
public bool SyncYear { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Month")]
public bool SyncMonth { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Day")]
public bool SyncDay { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Hour")]
public bool SyncHour { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Minute")]
public bool SyncMinute { get; set; } = false;
[Category("End Sync")]
[DisplayName("Sync Next Second")]
public bool SyncSecond { get; set; } = false;
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using DesktopWidgets.WidgetBase.Settings;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public Settings()
{
DateTimeFormat = new List<string> {"{dd}d {hh}h {mm}m"};
}
[Category("End")]
[DisplayName("Date/Time")]
public DateTime EndDateTime { get; set; } = DateTime.Now;
[Browsable(false)]
[DisplayName("Last End Date/Time")]
public DateTime LastEndDateTime { get; set; } = DateTime.Now;
[Category("Style")]
[DisplayName("Continue Counting")]
public bool EndContinueCounting { get; set; } = false;
[PropertyOrder(0)]
[Category("End Sync")]
[DisplayName("Sync Next Year")]
public bool SyncYear { get; set; } = false;
[PropertyOrder(1)]
[Category("End Sync")]
[DisplayName("Sync Next Month")]
public bool SyncMonth { get; set; } = false;
[PropertyOrder(2)]
[Category("End Sync")]
[DisplayName("Sync Next Day")]
public bool SyncDay { get; set; } = false;
[PropertyOrder(3)]
[Category("End Sync")]
[DisplayName("Sync Next Hour")]
public bool SyncHour { get; set; } = false;
[PropertyOrder(4)]
[Category("End Sync")]
[DisplayName("Sync Next Minute")]
public bool SyncMinute { get; set; } = false;
[PropertyOrder(5)]
[Category("End Sync")]
[DisplayName("Sync Next Second")]
public bool SyncSecond { get; set; } = false;
}
} |
Fix cref attribute in XML comment | using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
/// <summary>
/// Base class to map classes derived from <see cref="AbpTenant{TTenant,TUser}"/>
/// </summary>
/// <typeparam name="TTenant">Tenant type</typeparam>
/// <typeparam name="TUser">User type</typeparam>
public abstract class AbpTenantMap<TTenant, TUser> : EntityMap<TTenant>
where TTenant : AbpTenant<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Constructor.
/// </summary>
protected AbpTenantMap()
: base("AbpTenants")
{
References(x => x.Edition).Column("EditionId").Nullable();
Map(x => x.TenancyName);
Map(x => x.Name);
Map(x => x.IsActive);
this.MapFullAudited();
Polymorphism.Explicit();
}
}
} | using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
/// <summary>
/// Base class to map classes derived from <see cref="AbpTenant{TUser}"/>
/// </summary>
/// <typeparam name="TTenant">Tenant type</typeparam>
/// <typeparam name="TUser">User type</typeparam>
public abstract class AbpTenantMap<TTenant, TUser> : EntityMap<TTenant>
where TTenant : AbpTenant<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Constructor.
/// </summary>
protected AbpTenantMap()
: base("AbpTenants")
{
References(x => x.Edition).Column("EditionId").Nullable();
Map(x => x.TenancyName);
Map(x => x.Name);
Map(x => x.IsActive);
this.MapFullAudited();
Polymorphism.Explicit();
}
}
} |
Update Assert call and mute the test | using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Octokit.Reactive;
using Xunit;
namespace Octokit.Tests.Integration
{
public class ObservableRepositoriesClientTests
{
public class TheGetMethod
{
[IntegrationTest]
public async Task ReturnsSpecifiedRepository()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var observable = client.Get("haacked", "seegit");
var repository = await observable;
var repository2 = await observable;
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository.CloneUrl);
Assert.False(repository.Private);
Assert.False(repository.Fork);
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository2.CloneUrl);
Assert.False(repository2.Private);
Assert.False(repository2.Fork);
}
}
public class TheGetAllPublicSinceMethod
{
[IntegrationTest]
public async Task ReturnsAllPublicReposSinceLastSeen()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var request = new PublicRepositoryRequest
{
Since = 32732250
};
var repositories = await client.GetAllPublic(request).ToArray();
Assert.NotNull(repositories);
Assert.True(repositories.Any());
Assert.Equal(32732252, repositories[0].Id);
Assert.False(repositories[0].Private);
Assert.Equal("zad19", repositories[0].Name);
}
}
}
}
| using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Octokit.Reactive;
using Xunit;
namespace Octokit.Tests.Integration
{
public class ObservableRepositoriesClientTests
{
public class TheGetMethod
{
[IntegrationTest]
public async Task ReturnsSpecifiedRepository()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var observable = client.Get("haacked", "seegit");
var repository = await observable;
var repository2 = await observable;
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository.CloneUrl);
Assert.False(repository.Private);
Assert.False(repository.Fork);
Assert.Equal("https://github.com/Haacked/SeeGit.git", repository2.CloneUrl);
Assert.False(repository2.Private);
Assert.False(repository2.Fork);
}
}
public class TheGetAllPublicSinceMethod
{
[IntegrationTest(Skip = "This will take a very long time to return, so will skip it for now.")]
public async Task ReturnsAllPublicReposSinceLastSeen()
{
var github = Helper.GetAuthenticatedClient();
var client = new ObservableRepositoriesClient(github);
var request = new PublicRepositoryRequest
{
Since = 32732250
};
var repositories = await client.GetAllPublic(request).ToArray();
Assert.NotEmpty(repositories);
Assert.Equal(32732252, repositories[0].Id);
Assert.False(repositories[0].Private);
Assert.Equal("zad19", repositories[0].Name);
}
}
}
}
|
Add mutability test to StripNamespaces | using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tyrrrz.Extensions.Tests
{
[TestClass]
public class XmlTests
{
[TestMethod]
public void StripNamespacesTest()
{
var ns = XNamespace.Get("http://schemas.domain.com/orders");
var xml =
new XElement(ns + "order",
new XElement(ns + "customer", "Foo", new XAttribute(ns + "hello", "world")),
new XElement("purchases",
new XElement(ns + "purchase", "Unicycle", new XAttribute("price", "100.00")),
new XElement("purchase", "Bicycle"),
new XElement(ns + "purchase", "Tricycle",
new XAttribute("price", "300.00"),
new XAttribute(XNamespace.Xml.GetName("space"), "preserve")
)
)
);
var stripped = xml.StripNamespaces();
var xCustomer = stripped.Element("customer");
var xHello = xCustomer?.Attribute("hello");
Assert.IsNotNull(xCustomer);
Assert.IsNotNull(xHello);
Assert.AreEqual("world", xHello.Value);
}
}
} | using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tyrrrz.Extensions.Tests
{
[TestClass]
public class XmlTests
{
[TestMethod]
public void StripNamespacesTest()
{
var ns = XNamespace.Get("http://schemas.domain.com/orders");
var xml =
new XElement(ns + "order",
new XElement(ns + "customer", "Foo", new XAttribute(ns + "hello", "world")),
new XElement("purchases",
new XElement(ns + "purchase", "Unicycle", new XAttribute("price", "100.00")),
new XElement("purchase", "Bicycle"),
new XElement(ns + "purchase", "Tricycle",
new XAttribute("price", "300.00"),
new XAttribute(XNamespace.Xml.GetName("space"), "preserve")
)
)
);
var stripped = xml.StripNamespaces();
var xCustomer = stripped.Element("customer");
var xHello = xCustomer?.Attribute("hello");
Assert.AreNotSame(xml, stripped);
Assert.IsNotNull(xCustomer);
Assert.IsNotNull(xHello);
Assert.AreEqual("world", xHello.Value);
}
}
} |
Add basic integration test skeleton | //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace LockSample
{
using System;
internal sealed class Program
{
private static void Main(string[] args)
{
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace LockSample
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
internal sealed class Program
{
private static void Main(string[] args)
{
Random random = new Random();
ExclusiveLock l = new ExclusiveLock();
List<int> list = new List<int>();
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Task task = LoopAsync(random, l, list, cts.Token);
Thread.Sleep(1000);
cts.Cancel();
task.Wait();
}
}
private static async Task LoopAsync(Random random, ExclusiveLock l, IList<int> list, CancellationToken token)
{
while (!token.IsCancellationRequested)
{
switch (random.Next(1))
{
case 0:
await EnumerateListAsync(l, list);
break;
}
}
}
private static async Task EnumerateListAsync(ExclusiveLock l, IList<int> list)
{
ExclusiveLock.Token token = await l.AcquireAsync();
await Task.Yield();
try
{
int lastItem = 0;
foreach (int item in list)
{
if (lastItem != (item - 1))
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"State corruption detected; expected {0} but saw {1} in next list entry.",
lastItem + 1,
item));
}
await Task.Yield();
}
}
finally
{
l.Release(token);
}
}
}
}
|
Return 403 instead of 401 | using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CVaS.Web.Filters
{
/// <summary>
/// Exception filter that catch exception of known type
/// and transform them into specific HTTP status code with
/// error message
/// </summary>
public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
switch (context.Exception)
{
case ApiException apiException:
var apiError = new ApiError(apiException.Message);
context.ExceptionHandled = true;
context.HttpContext.Response.StatusCode = apiException.StatusCode;
context.Result = new ObjectResult(apiError);
break;
case NotImplementedException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
context.ExceptionHandled = true;
break;
case UnauthorizedAccessException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.ExceptionHandled = true;
break;
}
base.OnException(context);
}
}
}
| using System;
using System.Net;
using CVaS.Shared.Exceptions;
using CVaS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CVaS.Web.Filters
{
/// <summary>
/// Exception filter that catch exception of known type
/// and transform them into specific HTTP status code with
/// error message
/// </summary>
public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
switch (context.Exception)
{
case ApiException apiException:
var apiError = new ApiError(apiException.Message);
context.ExceptionHandled = true;
context.HttpContext.Response.StatusCode = apiException.StatusCode;
context.Result = new ObjectResult(apiError);
break;
case NotImplementedException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
context.ExceptionHandled = true;
break;
case UnauthorizedAccessException _:
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
context.ExceptionHandled = true;
break;
}
base.OnException(context);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.