Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set incoming webhook usename to /todo. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SlashTodo.Core;
using SlashTodo.Infrastructure.Slack;
namespace SlashTodo.Web.Api
{
public class DefaultSlashCommandHandler : ISlashCommandHandler
{
private readonly IRepository<Core.Domain.Todo> _todoRepository;
private readonly ISlackIncomingWebhookApi _slackIncomingWebhookApi;
public DefaultSlashCommandHandler(
IRepository<Core.Domain.Todo> todoRepository,
ISlackIncomingWebhookApi slackIncomingWebhookApi)
{
_todoRepository = todoRepository;
_slackIncomingWebhookApi = slackIncomingWebhookApi;
}
public Task<string> Handle(SlashCommand command, Uri teamIncomingWebhookUrl)
{
_slackIncomingWebhookApi.Send(teamIncomingWebhookUrl, new SlackIncomingWebhookMessage
{
ConversationId = command.ConversationId,
Text = string.Format("*Echo:* {0} {1}", command.Command, command.Text)
});
return Task.FromResult<string>(null);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using SlashTodo.Core;
using SlashTodo.Infrastructure.Slack;
namespace SlashTodo.Web.Api
{
public class DefaultSlashCommandHandler : ISlashCommandHandler
{
private readonly IRepository<Core.Domain.Todo> _todoRepository;
private readonly ISlackIncomingWebhookApi _slackIncomingWebhookApi;
public DefaultSlashCommandHandler(
IRepository<Core.Domain.Todo> todoRepository,
ISlackIncomingWebhookApi slackIncomingWebhookApi)
{
_todoRepository = todoRepository;
_slackIncomingWebhookApi = slackIncomingWebhookApi;
}
public Task<string> Handle(SlashCommand command, Uri teamIncomingWebhookUrl)
{
_slackIncomingWebhookApi.Send(teamIncomingWebhookUrl, new SlackIncomingWebhookMessage
{
UserName = "/todo",
ConversationId = command.ConversationId,
Text = string.Format("*Echo:* {0} {1}", command.Command, command.Text)
});
return Task.FromResult<string>(null);
}
}
} |
Use parallelism for puzzle 10 | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = 0;
for (int n = 2; n < max; n++)
{
if (Maths.IsPrime(n))
{
sum += n;
}
}
Answer = sum;
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
Answer = Enumerable.Range(2, max - 2)
.AsParallel()
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
return 0;
}
}
}
|
Add ikey placeholder to setup() call | using System;
using Xamarin.Forms;
using AI.XamarinSDK.Abstractions;
namespace XamarinTest
{
public class App : Application
{
public App ()
{
var mainNav = new NavigationPage (new XamarinTestMasterView ());
MainPage = mainNav;
}
protected override void OnStart ()
{
ApplicationInsights.Setup ("");
//ApplicationInsights.Setup ("ijhch");
ApplicationInsights.Start ();
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
| using System;
using Xamarin.Forms;
using AI.XamarinSDK.Abstractions;
namespace XamarinTest
{
public class App : Application
{
public App ()
{
var mainNav = new NavigationPage (new XamarinTestMasterView ());
MainPage = mainNav;
}
protected override void OnStart ()
{
ApplicationInsights.Setup ("<YOUR-INSTRUMENTATION-KEY>");
ApplicationInsights.Start ();
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
|
Use IDtoModelMapper instead of IMapper in change sets controller | using System.Linq;
using BitChangeSetManager.DataAccess;
using BitChangeSetManager.Dto;
using BitChangeSetManager.Model;
using Foundation.Api.ApiControllers;
using AutoMapper;
using AutoMapper.QueryableExtensions;
namespace BitChangeSetManager.Api
{
public class ChangeSetsController : DefaultDtoSetController<ChangeSet, ChangeSetDto>
{
private readonly IBitChangeSetManagerRepository<ChangeSet> _changeSetsRepository;
public ChangeSetsController(IBitChangeSetManagerRepository<ChangeSet> changeSetsRepository)
: base(changeSetsRepository)
{
_changeSetsRepository = changeSetsRepository;
}
public IMapper Mapper { get; set; }
public IBitChangeSetManagerRepository<Customer> CustomersRepository { get; set; }
public override IQueryable<ChangeSetDto> GetAll()
{
IQueryable<Customer> customersQuery = CustomersRepository.GetAll();
return _changeSetsRepository
.GetAll()
.ProjectTo<ChangeSetDto>(configuration: Mapper.ConfigurationProvider, parameters: new { customersQuery = customersQuery });
}
}
} | using System.Linq;
using BitChangeSetManager.DataAccess;
using BitChangeSetManager.Dto;
using BitChangeSetManager.Model;
using Foundation.Api.ApiControllers;
namespace BitChangeSetManager.Api
{
public class ChangeSetsController : DefaultDtoSetController<ChangeSet, ChangeSetDto>
{
private readonly IBitChangeSetManagerRepository<ChangeSet> _changeSetsRepository;
public ChangeSetsController(IBitChangeSetManagerRepository<ChangeSet> changeSetsRepository)
: base(changeSetsRepository)
{
_changeSetsRepository = changeSetsRepository;
}
public IBitChangeSetManagerRepository<Customer> CustomersRepository { get; set; }
public override IQueryable<ChangeSetDto> GetAll()
{
IQueryable<Customer> customersQuery = CustomersRepository.GetAll();
return DtoModelMapper.FromModelQueryToDtoQuery(_changeSetsRepository.GetAll(), parameters: new { customersQuery = customersQuery });
}
}
} |
Change properties to getters only | using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace Skarp.HubSpotClient
{
[Serializable]
public class HubSpotException : Exception
{
private HttpResponseMessage response;
public string RawJsonResponse { get; set; }
public HubSpotException()
{
}
public HubSpotException(string message) : base(message)
{
}
public HubSpotException(string message, string jsonResponse) : base(message)
{
RawJsonResponse = jsonResponse;
}
public HubSpotException(string message, Exception innerException) : base(message, innerException)
{
}
public HubSpotException(string message, string jsonResponse, HttpResponseMessage response) : this(message, jsonResponse)
{
this.response = response;
}
public override String Message
{
get
{
return base.Message + $", JSONResponse={RawJsonResponse??"Empty"}";
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace Skarp.HubSpotClient
{
[Serializable]
public class HubSpotException : Exception
{
public HttpResponseMessage Response { get; }
public string RawJsonResponse { get; }
public HubSpotException()
{
}
public HubSpotException(string message) : base(message)
{
}
public HubSpotException(string message, string jsonResponse) : base(message)
{
RawJsonResponse = jsonResponse;
}
public HubSpotException(string message, Exception innerException) : base(message, innerException)
{
}
public HubSpotException(string message, string jsonResponse, HttpResponseMessage response) : this(message, jsonResponse)
{
this.Response = response;
}
public override String Message
{
get
{
return base.Message + $", JSONResponse={RawJsonResponse??"Empty"}";
}
}
}
}
|
Remove pointless line from functionality test | using CSharpTo2600.Framework;
using static CSharpTo2600.Framework.TIARegisters;
namespace CSharpTo2600.FunctionalitySamples
{
[Atari2600Game]
static class SingleChangeBkColor
{
[SpecialMethod(MethodType.Initialize)]
[System.Obsolete(CSharpTo2600.Framework.Assembly.Symbols.AUDC0, true)]
static void Initialize()
{
BackgroundColor = 0x5E;
}
}
}
| using CSharpTo2600.Framework;
using static CSharpTo2600.Framework.TIARegisters;
namespace CSharpTo2600.FunctionalitySamples
{
[Atari2600Game]
static class SingleChangeBkColor
{
[SpecialMethod(MethodType.Initialize)]
static void Initialize()
{
BackgroundColor = 0x5E;
}
}
}
|
Revert "Created the Regex outside of the method, with a MatchTimeout property." | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BlogTemplate._1.Models;
namespace BlogTemplate._1.Services
{
public class SlugGenerator
{
private BlogDataStore _dataStore;
private static Regex AllowList = new Regex("([^A-Za-z0-9-])", RegexOptions.None, TimeSpan.FromSeconds(1));
public SlugGenerator(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public string CreateSlug(string title)
{
string tempTitle = title;
tempTitle = tempTitle.Replace(" ", "-");
string slug = AllowList.Replace(tempTitle, "");
return slug;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BlogTemplate._1.Models;
namespace BlogTemplate._1.Services
{
public class SlugGenerator
{
private BlogDataStore _dataStore;
public SlugGenerator(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public string CreateSlug(string title)
{
string tempTitle = title;
tempTitle = tempTitle.Replace(" ", "-");
Regex allowList = new Regex("([^A-Za-z0-9-])");
string slug = allowList.Replace(tempTitle, "");
return slug;
}
}
}
|
Fix not disposing frame object when handling key events | using System.Windows.Forms;
using CefSharp;
using TweetDuck.Utils;
namespace TweetDuck.Browser.Handling {
class KeyboardHandlerBase : IKeyboardHandler {
protected virtual bool HandleRawKey(IWebBrowser browserControl, Keys key, CefEventFlags modifiers) {
if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I) {
browserControl.OpenDevToolsCustom();
return true;
}
return false;
}
bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut) {
if (type == KeyType.RawKeyDown && !browser.FocusedFrame.Url.StartsWith("devtools://")) {
return HandleRawKey(browserControl, (Keys) windowsKeyCode, modifiers);
}
return false;
}
bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey) {
return false;
}
}
}
| using System.Windows.Forms;
using CefSharp;
using TweetDuck.Utils;
namespace TweetDuck.Browser.Handling {
class KeyboardHandlerBase : IKeyboardHandler {
protected virtual bool HandleRawKey(IWebBrowser browserControl, Keys key, CefEventFlags modifiers) {
if (modifiers == (CefEventFlags.ControlDown | CefEventFlags.ShiftDown) && key == Keys.I) {
browserControl.OpenDevToolsCustom();
return true;
}
return false;
}
bool IKeyboardHandler.OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut) {
if (type == KeyType.RawKeyDown) {
using var frame = browser.FocusedFrame;
if (!frame.Url.StartsWith("devtools://")) {
return HandleRawKey(browserControl, (Keys) windowsKeyCode, modifiers);
}
}
return false;
}
bool IKeyboardHandler.OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey) {
return false;
}
}
}
|
Update GetEnumerator binding for more one run support. | using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Moq;
namespace Mox
{
public static class DbSetMockingExtensions
{
public static DbSet<T> MockWithList<T>(this DbSet<T> dbSet, IList<T> data) where T : class
{
var queryable = data.AsQueryable();
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
return dbSet;
}
}
}
| using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Moq;
namespace Mox
{
public static class DbSetMockingExtensions
{
public static DbSet<T> MockWithList<T>(this DbSet<T> dbSet, IList<T> data) where T : class
{
var queryable = data.AsQueryable();
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
Mock.Get(dbSet).As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
return dbSet;
}
}
}
|
Set interaction priority of PlacableSurfaceComponent to 1 | using Content.Server.GameObjects.Components.GUI;
using Content.Shared.GameObjects.Components;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Server.GameObjects.Components
{
[RegisterComponent]
public class PlaceableSurfaceComponent : SharedPlaceableSurfaceComponent, IInteractUsing
{
private bool _isPlaceable;
public bool IsPlaceable { get => _isPlaceable; set => _isPlaceable = value; }
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _isPlaceable, "IsPlaceable", true);
}
public bool InteractUsing(InteractUsingEventArgs eventArgs)
{
if (!IsPlaceable)
return false;
if(!eventArgs.User.TryGetComponent<HandsComponent>(out var handComponent))
{
return false;
}
handComponent.Drop(eventArgs.Using);
eventArgs.Using.Transform.WorldPosition = eventArgs.ClickLocation.Position;
return true;
}
}
}
| using Content.Server.GameObjects.Components.GUI;
using Content.Shared.GameObjects.Components;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Server.GameObjects.Components
{
[RegisterComponent]
public class PlaceableSurfaceComponent : SharedPlaceableSurfaceComponent, IInteractUsing
{
private bool _isPlaceable;
public bool IsPlaceable { get => _isPlaceable; set => _isPlaceable = value; }
int IInteractUsing.Priority { get => 1; }
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _isPlaceable, "IsPlaceable", true);
}
public bool InteractUsing(InteractUsingEventArgs eventArgs)
{
if (!IsPlaceable)
return false;
if(!eventArgs.User.TryGetComponent<HandsComponent>(out var handComponent))
{
return false;
}
handComponent.Drop(eventArgs.Using);
eventArgs.Using.Transform.WorldPosition = eventArgs.ClickLocation.Position;
return true;
}
}
}
|
Use `Unknown` instead of `default` | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Database;
using osu.Game.Users;
using osu.Game.Utils;
using Realms;
namespace osu.Game.Models
{
public class RealmUser : EmbeddedObject, IUser, IEquatable<RealmUser>, IDeepCloneable<RealmUser>
{
public int OnlineID { get; set; } = 1;
public string Username { get; set; } = string.Empty;
[Ignored]
public CountryCode CountryCode
{
get => Enum.TryParse(CountryString, out CountryCode country) ? country : default;
set => CountryString = value.ToString();
}
[MapTo(nameof(CountryCode))]
public string CountryString { get; set; } = default(CountryCode).ToString();
public bool IsBot => false;
public bool Equals(RealmUser other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return OnlineID == other.OnlineID && Username == other.Username;
}
public RealmUser DeepClone() => (RealmUser)this.Detach().MemberwiseClone();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Database;
using osu.Game.Users;
using osu.Game.Utils;
using Realms;
namespace osu.Game.Models
{
public class RealmUser : EmbeddedObject, IUser, IEquatable<RealmUser>, IDeepCloneable<RealmUser>
{
public int OnlineID { get; set; } = 1;
public string Username { get; set; } = string.Empty;
[Ignored]
public CountryCode CountryCode
{
get => Enum.TryParse(CountryString, out CountryCode country) ? country : CountryCode.Unknown;
set => CountryString = value.ToString();
}
[MapTo(nameof(CountryCode))]
public string CountryString { get; set; } = default(CountryCode).ToString();
public bool IsBot => false;
public bool Equals(RealmUser other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return OnlineID == other.OnlineID && Username == other.Username;
}
public RealmUser DeepClone() => (RealmUser)this.Detach().MemberwiseClone();
}
}
|
Allow formatted telephone numbers on iOS (e.g. 1800 111 222 333 instead of 1800111222333) | using System;
#if __UNIFIED__
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif
namespace Plugin.Messaging
{
internal class PhoneCallTask : IPhoneCallTask
{
public PhoneCallTask()
{
}
#region IPhoneCallTask Members
public bool CanMakePhoneCall
{
get { return true; }
}
public void MakePhoneCall(string number, string name = null)
{
if (string.IsNullOrWhiteSpace(number))
throw new ArgumentNullException("number");
if (CanMakePhoneCall)
{
var nsurl = new NSUrl("tel://" + number);
UIApplication.SharedApplication.OpenUrl(nsurl);
}
}
#endregion
}
} | using System;
#if __UNIFIED__
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif
namespace Plugin.Messaging
{
internal class PhoneCallTask : IPhoneCallTask
{
public PhoneCallTask()
{
}
#region IPhoneCallTask Members
public bool CanMakePhoneCall
{
get { return true; }
}
public void MakePhoneCall(string number, string name = null)
{
if (string.IsNullOrWhiteSpace(number))
throw new ArgumentNullException("number");
if (CanMakePhoneCall)
{
var nsurl = CreateNSUrl(number);
UIApplication.SharedApplication.OpenUrl(nsurl);
}
}
private NSUrl CreateNSUrl(string number)
{
return new NSUrl(new Uri($"tel:{number}").AbsoluteUri);
}
#endregion
}
} |
Add id of slave to slave configuration. | using System.Runtime.Serialization;
namespace Orationi.CommunicationCore.Model
{
/// <summary>
/// Provide information about slave configuration.
/// </summary>
[DataContract]
public class SlaveConfiguration
{
/// <summary>
/// Versions of slave-assigned modules.
/// </summary>
[DataMember]
public ModuleVersionItem[] Modules { get; set; }
}
}
| using System;
using System.Runtime.Serialization;
namespace Orationi.CommunicationCore.Model
{
/// <summary>
/// Provide information about slave configuration.
/// </summary>
[DataContract]
public class SlaveConfiguration
{
/// <summary>
/// Global slave Id.
/// </summary>
[DataMember]
public Guid Id { get; set; }
/// <summary>
/// Versions of slave-assigned modules.
/// </summary>
[DataMember]
public ModuleVersionItem[] Modules { get; set; }
}
}
|
Change to AddOrUpdate for the feature to make it visible what the method is doing | using AutoMapper.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace AutoMapper.Internal
{
public class FeatureCollectionBase<TValue> : IEnumerable<KeyValuePair<Type, TValue>>
{
private IDictionary<Type, TValue> _features = new Dictionary<Type, TValue>();
public TValue this[Type key]
{
get => _features.GetOrDefault(key);
set
{
if (value == null)
{
_features.Remove(key);
}
else
{
_features[key] = value;
}
}
}
/// <summary>
/// Gets the feature of type <typeparamref name="TFeature"/>.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
/// <returns>The feature or null if feature not exists.</returns>
public TFeature Get<TFeature>() where TFeature : TValue => (TFeature)this[typeof(TFeature)];
/// <summary>
/// Add the feature for type <typeparamref name="TFeature"/>. Existing feature of the same type will be replaces.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
/// <param name="feature">The feature.</param>
public void Add<TFeature>(TFeature feature) where TFeature : TValue => this[typeof(TFeature)] = feature;
public IEnumerator<KeyValuePair<Type, TValue>> GetEnumerator() => _features.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
protected void MakeReadOnly() => _features = new ReadOnlyDictionary<Type, TValue>(_features);
}
}
| using AutoMapper.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace AutoMapper.Internal
{
public class FeatureCollectionBase<TValue> : IEnumerable<KeyValuePair<Type, TValue>>
{
private IDictionary<Type, TValue> _features = new Dictionary<Type, TValue>();
public TValue this[Type key]
{
get => _features.GetOrDefault(key);
set
{
if (value == null)
{
_features.Remove(key);
}
else
{
_features[key] = value;
}
}
}
/// <summary>
/// Gets the feature of type <typeparamref name="TFeature"/>.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
/// <returns>The feature or null if feature not exists.</returns>
public TFeature Get<TFeature>() where TFeature : TValue => (TFeature)this[typeof(TFeature)];
/// <summary>
/// Add or update the feature for type <typeparamref name="TFeature"/>. Existing feature of the same type will be replaces.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
/// <param name="feature">The feature.</param>
public void AddOrUpdate<TFeature>(TFeature feature) where TFeature : TValue => this[typeof(TFeature)] = feature;
public IEnumerator<KeyValuePair<Type, TValue>> GetEnumerator() => _features.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
protected void MakeReadOnly() => _features = new ReadOnlyDictionary<Type, TValue>(_features);
}
}
|
Add ToSlug and ToFileNameSlug string extensions | using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace JabbR.Infrastructure
{
public static class StringExtensions
{
public static string ToMD5(this string value)
{
if (String.IsNullOrEmpty(value))
{
return null;
}
return String.Join("", MD5.Create()
.ComputeHash(Encoding.Default.GetBytes(value))
.Select(b => b.ToString("x2")));
}
public static string ToSha256(this string value, string salt)
{
string saltedValue = ((salt ?? "") + value);
return String.Join("", SHA256.Create()
.ComputeHash(Encoding.Default.GetBytes(saltedValue))
.Select(b => b.ToString("x2")));
}
}
} | using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace JabbR.Infrastructure
{
public static class StringExtensions
{
public static string ToMD5(this string value)
{
if (String.IsNullOrEmpty(value))
{
return null;
}
return String.Join("", MD5.Create()
.ComputeHash(Encoding.Default.GetBytes(value))
.Select(b => b.ToString("x2")));
}
public static string ToSha256(this string value, string salt)
{
string saltedValue = ((salt ?? "") + value);
return String.Join("", SHA256.Create()
.ComputeHash(Encoding.Default.GetBytes(saltedValue))
.Select(b => b.ToString("x2")));
}
public static string ToSlug(this string value)
{
string result = value;
// Remove non-ASCII characters
result = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(result));
result = result.Trim();
// Remove Invalid Characters
result = Regex.Replace(result, @"[^A-z0-9\s-]", string.Empty);
// Reduce spaces and convert to underscore
result = Regex.Replace(result, @"\s+", "_");
return result;
}
public static string ToFileNameSlug(this string value)
{
string result = value;
// Trim Slashes
result = result.TrimEnd('/', '\\', '.');
// Remove Path (included by IE in Intranet Mode)
result = result.Contains(@"/") ? result.Substring(result.LastIndexOf(@"/") + 1) : result;
result = result.Contains(@"\") ? result.Substring(result.LastIndexOf(@"\") + 1) : result;
if (result.Contains('.'))
{
// ToSlug Filename Component
string fileNameSlug = result.Substring(0, result.LastIndexOf('.')).ToSlug();
// ToSlug Extension Component
string fileExtensionSlug = result.Substring(result.LastIndexOf('.') + 1).ToSlug();
// Combine Filename Slug
result = string.Concat(fileNameSlug, ".", fileExtensionSlug);
}
else
{
// No Extension
result = result.ToSlug();
}
return result;
}
}
} |
Remove NUnit.Framework.Constraint (unused - accident) | using System.Web.Mvc;
using NUnit.Framework.Constraints;
namespace MvcRouteTester.Test.Areas.SomeArea
{
public class SomeAreaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "SomeArea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SomeArea_TestController",
"SomeArea/{action}/{id}",
defaults: new { action = "Index", controller = "Test", id = UrlParameter.Optional },
constraints: new { action = "Index|About" }
);
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { action = "Index", controller = "Test", id = UrlParameter.Optional }
);
}
}
}
| using System.Web.Mvc;
namespace MvcRouteTester.Test.Areas.SomeArea
{
public class SomeAreaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "SomeArea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SomeArea_TestController",
"SomeArea/{action}/{id}",
defaults: new { action = "Index", controller = "Test", id = UrlParameter.Optional },
constraints: new { action = "Index|About" }
);
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { action = "Index", controller = "Test", id = UrlParameter.Optional }
);
}
}
}
|
Include app info in legal notice and privacy page | <h1>Legal Notice & Privacy</h1>
<p>Dangl.<strong>Docu</strong> hosts all documentation and help pages for products and services offered by Dangl<strong>IT</strong> as well as for multiple open source projects.</p>
<p>
This website is operated and hosted by <a href="https://www.dangl-it.com/legal-notice/">Dangl<strong>IT</strong> GmbH</a>.
Please <a href="mailto:info@dangl-it.com">contact us</a> for any further questions.
</p>
<p>
<strong>
The source code for this website is completely open and available at
<a href="https://github.com/GeorgDangl/WebDocu">GitHub</a>.
</strong>
</p>
<h2>Privacy Information</h2>
<p>If you have no user account, no information about you is stored.</p>
<p>
For user accounts, the only personal identifiable information stored about you
is your email address. You will not receive automated newsletters, we will not
give your information to anyone and we will not use your information for anything
else than providing this documentation website.
</p>
<p>
You only need your own user account if you are a customer of Dangl<strong>IT</strong>
and want to get access to internal, non-public information.
</p>
| <h1>Legal Notice & Privacy</h1>
<p>Dangl.<strong>Docu</strong> hosts all documentation and help pages for products and services offered by Dangl<strong>IT</strong> as well as for multiple open source projects.</p>
<p>
This website is operated and hosted by <a href="https://www.dangl-it.com/legal-notice/">Dangl<strong>IT</strong> GmbH</a>.
Please <a href="mailto:info@dangl-it.com">contact us</a> for any further questions.
</p>
<p>
<strong>
The source code for this website is completely open and available at
<a href="https://github.com/GeorgDangl/WebDocu">GitHub</a>.
</strong>
</p>
<h2>Privacy Information</h2>
<p>If you have no user account, no information about you is stored.</p>
<p>
For user accounts, the only personal identifiable information stored about you
is your email address. You will not receive automated newsletters, we will not
give your information to anyone and we will not use your information for anything
else than providing this documentation website.
</p>
<p>
You only need your own user account if you are a customer of Dangl<strong>IT</strong>
and want to get access to internal, non-public information.
</p>
<hr />
<p>Dangl<strong>Docu</strong> @Dangl.WebDocumentation.Services.VersionsService.Version, built @Dangl.WebDocumentation.Services.VersionsService.BuildDateUtc.ToString("dd.MM.yyyy HH:mm") (UTC)</p>
|
Check before trying to deserialize transform | using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class Autopilot : NetworkBehaviour {
public string serverUrl;
public float smoothing;
private SerializableTransform targetTransform;
private void Start ()
{
if (isLocalPlayer)
StartCoroutine(SendTransformToServer ());
else
StartCoroutine(UpdateTransformFromServer ());
}
private void Update ()
{
if (isLocalPlayer)
return;
if (targetTransform != null)
{
transform.position = Vector3.Lerp (transform.position, targetTransform.position, smoothing);
transform.rotation = Quaternion.Lerp (transform.rotation, targetTransform.rotation, smoothing);
}
}
private IEnumerator SendTransformToServer()
{
while (true)
{
WWWForm form = new WWWForm ();
form.AddField("transform", SerializableTransform.ToJson (transform));
WWW postRequest = new WWW(serverUrl + netId, form);
yield return postRequest;
}
}
private IEnumerator UpdateTransformFromServer()
{
while (true)
{
WWW getRequest = new WWW(serverUrl + netId);
yield return getRequest;
targetTransform = SerializableTransform.FromJson (getRequest.text);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class Autopilot : NetworkBehaviour {
public string serverUrl;
public float smoothing;
private SerializableTransform targetTransform;
private void Start ()
{
if (isLocalPlayer)
StartCoroutine(SendTransformToServer ());
else
StartCoroutine(UpdateTransformFromServer ());
}
private void Update ()
{
if (isLocalPlayer)
return;
if (targetTransform != null)
{
transform.position = Vector3.Lerp (transform.position, targetTransform.position, smoothing);
transform.rotation = Quaternion.Lerp (transform.rotation, targetTransform.rotation, smoothing);
}
}
private IEnumerator SendTransformToServer()
{
while (true)
{
WWWForm form = new WWWForm ();
form.AddField("transform", SerializableTransform.ToJson (transform));
WWW postRequest = new WWW(serverUrl + netId, form);
yield return postRequest;
}
}
private IEnumerator UpdateTransformFromServer()
{
while (true)
{
WWW getRequest = new WWW(serverUrl + netId);
yield return getRequest;
if (string.IsNullOrEmpty (getRequest.error))
{
targetTransform = SerializableTransform.FromJson (getRequest.text);
}
}
}
}
|
Make "add account" button nonexecutable when running. | // Copyright (c) 2016 The btcsuite developers
// Copyright (c) 2016 The Decred developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using Paymetheus.Framework;
using System;
using System.Windows;
using System.Windows.Input;
namespace Paymetheus.ViewModels
{
public sealed class CreateAccountDialogViewModel : DialogViewModelBase
{
public CreateAccountDialogViewModel(ShellViewModel shell) : base(shell)
{
Execute = new DelegateCommand(ExecuteAction);
}
public string AccountName { get; set; } = "";
public string Passphrase { private get; set; } = "";
public ICommand Execute { get; }
private async void ExecuteAction()
{
try
{
await App.Current.Synchronizer.WalletRpcClient.NextAccountAsync(Passphrase, AccountName);
HideDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
| // Copyright (c) 2016 The btcsuite developers
// Copyright (c) 2016 The Decred developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using Grpc.Core;
using Paymetheus.Framework;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace Paymetheus.ViewModels
{
public sealed class CreateAccountDialogViewModel : DialogViewModelBase
{
public CreateAccountDialogViewModel(ShellViewModel shell) : base(shell)
{
Execute = new DelegateCommandAsync(ExecuteAction);
}
public string AccountName { get; set; } = "";
public string Passphrase { private get; set; } = "";
public ICommand Execute { get; }
private async Task ExecuteAction()
{
try
{
await App.Current.Synchronizer.WalletRpcClient.NextAccountAsync(Passphrase, AccountName);
HideDialog();
}
catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.AlreadyExists)
{
MessageBox.Show("Account name already exists");
}
catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.InvalidArgument)
{
// Since there is no client-side validation of account name user input, this might be an
// invalid account name or the wrong passphrase. Just show the detail for now.
MessageBox.Show(ex.Status.Detail);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
}
|
Change default find country code | using System.Configuration;
using System.Linq;
using System.Web.Mvc;
namespace MAB.PCAPredictCapturePlus.TestHarness.Controllers
{
public class HomeController : Controller
{
private CapturePlusClient _client = new CapturePlusClient(
apiVersion: "2.10",
key: ConfigurationManager.AppSettings["PCAPredictCapturePlusKey"],
defaultFindCountry: "GBR",
defaultLanguage: "EN"
);
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Find(string term)
{
var result = _client.Find(term);
if(result.Error != null)
return Json(result.Error);
return Json(result.Items);
}
[HttpPost]
public ActionResult Retrieve(string id)
{
var result = _client.Retrieve(id);
if(result.Error != null)
return Json(result.Error);
var model = result.Items.Select(a => new {
Company = a.Company,
BuildingName = a.BuildingName,
Street = a.Street,
Line1 = a.Line1,
Line2 = a.Line2,
Line3 = a.Line3,
Line4 = a.Line4,
Line5 = a.Line5,
City = a.City,
County = a.Province,
Postcode = a.PostalCode
}).First();
return Json(model);
}
}
} | using System.Configuration;
using System.Linq;
using System.Web.Mvc;
namespace MAB.PCAPredictCapturePlus.TestHarness.Controllers
{
public class HomeController : Controller
{
private CapturePlusClient _client = new CapturePlusClient(
apiVersion: "2.10",
key: ConfigurationManager.AppSettings["PCAPredictCapturePlusKey"],
defaultFindCountry: "GB",
defaultLanguage: "EN"
);
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Find(string term)
{
var result = _client.Find(term);
if(result.Error != null)
return Json(result.Error);
return Json(result.Items);
}
[HttpPost]
public ActionResult Retrieve(string id)
{
var result = _client.Retrieve(id);
if(result.Error != null)
return Json(result.Error);
var model = result.Items.Select(a => new {
Company = a.Company,
BuildingName = a.BuildingName,
Street = a.Street,
Line1 = a.Line1,
Line2 = a.Line2,
Line3 = a.Line3,
Line4 = a.Line4,
Line5 = a.Line5,
City = a.City,
County = a.Province,
Postcode = a.PostalCode
}).First();
return Json(model);
}
}
} |
Allow player to walk through unlocked doors | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Game_Algo
{
class Tile
{
/// <summary>
/// 0 - Floor
/// 1 - Wall
/// </summary>
public int TypeId { get; set; }
public Tile(int MapCellId)
{
this.TypeId = MapCellId;
}
public bool Walkable
{
get
{
return (TypeId == GameSetting.TileType.Wall) ? false : true;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Game_Algo
{
class Tile
{
/// <summary>
/// 0 - Floor
/// 1 - Wall
/// </summary>
public int TypeId { get; set; }
public Tile(int MapCellId)
{
this.TypeId = MapCellId;
}
public bool Walkable
{
get
{
return (TypeId == GameSetting.TileType.Floor || TypeId == GameSetting.TileType.DoorUnlocked);
}
}
}
}
|
Make logging configurable by external consumers | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuantConnect.ToolBox
{
/// <summary>
/// Provides time stamped writing to the console
/// </summary>
public static class Log
{
/// <summary>
/// Writes the message in normal text
/// </summary>
public static void Trace(string format, params object[] args)
{
Console.WriteLine("{0}: {1}", DateTime.UtcNow.ToString("o"), string.Format(format, args));
}
/// <summary>
/// Writes the message in red
/// </summary>
public static void Error(string format, params object[] args)
{
var foregroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("{0}: ERROR:: {1}", DateTime.UtcNow.ToString("o"), string.Format(format, args));
Console.ForegroundColor = foregroundColor;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuantConnect.ToolBox
{
/// <summary>
/// Provides time stamped writing to the console
/// </summary>
public static class Log
{
/// <summary>
/// Defines the delegate used to perform trace logging, this allows other application
/// users of the toolbox projects to intercept their logging
/// </summary>
public static Action<string> TraceHandler = TraceHandlerImpl;
/// <summary>
/// Defines the delegate used to perform error logging, this allows other application
/// users of the toolbox projects to intercept their logging
/// </summary>
public static Action<string> ErrorHandler = ErrorHandlerImpl;
/// <summary>
/// Writes the message in normal text
/// </summary>
public static void Trace(string format, params object[] args)
{
TraceHandler(string.Format(format, args));
}
/// <summary>
/// Writes the message in red
/// </summary>
public static void Error(string format, params object[] args)
{
ErrorHandler(string.Format(format, args));
}
private static void TraceHandlerImpl(string msg)
{
Console.WriteLine("{0}: {1}", DateTime.UtcNow.ToString("o"), msg);
}
private static void ErrorHandlerImpl(string msg)
{
var foregroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("{0}: ERROR:: {1}", DateTime.UtcNow.ToString("o"), msg);
Console.ForegroundColor = foregroundColor;
}
}
}
|
Remove properties from interface as they are no longer needed | // The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow.EventStores
{
public interface ICommittedDomainEvent
{
string AggregateId { get; set; }
string Data { get; set; }
string Metadata { get; set; }
int AggregateSequenceNumber { get; set; }
}
}
| // The MIT License (MIT)
//
// Copyright (c) 2015 Rasmus Mikkelsen
// https://github.com/rasmus/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace EventFlow.EventStores
{
public interface ICommittedDomainEvent
{
string Data { get; set; }
string Metadata { get; set; }
}
}
|
Update the appdelegate to make sure FreshEssentials is deployed | using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace ExcelFormsTest.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace ExcelFormsTest.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
new FreshEssentials.iOS.AdvancedFrameRendereriOS();
return base.FinishedLaunching(app, options);
}
}
}
|
Use net4+ validation API on SimpleConfig, so we have detailed error messages. | using System;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Text;
namespace HermaFx.SimpleConfig
{
internal class CompositeConfigurationValidator : ConfigurationValidatorBase
{
private readonly ValidationAttribute[] _validationAttributes;
private readonly string _propertyName;
public CompositeConfigurationValidator(ValidationAttribute[] validationAttributes, string propertyName)
{
_validationAttributes = validationAttributes;
_propertyName = propertyName;
}
public override bool CanValidate(Type type)
{
return true;
}
public override void Validate(object value)
{
var validationErrors = (from validation in _validationAttributes
where validation.IsValid(value) == false
select validation.FormatErrorMessage(_propertyName)).ToList();
if(validationErrors.Any())
{
var errorMsgs = new StringBuilder("Validation Errors:");
var fullMsg = validationErrors.Aggregate(errorMsgs, (sb, cur) => sb.AppendLine(cur)).ToString();
throw new ArgumentException(fullMsg);
}
}
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Text;
namespace HermaFx.SimpleConfig
{
internal class CompositeConfigurationValidator : ConfigurationValidatorBase
{
private readonly ValidationAttribute[] _validationAttributes;
private readonly string _propertyName;
public CompositeConfigurationValidator(ValidationAttribute[] validationAttributes, string propertyName)
{
_validationAttributes = validationAttributes;
_propertyName = propertyName;
}
public override bool CanValidate(Type type)
{
return true;
}
public override void Validate(object value)
{
var context = new ValidationContext(value) { MemberName = _propertyName };
var errors = _validationAttributes
.Select(x => x.GetValidationResult(value, context))
.Where(x => x != ValidationResult.Success)
.ToArray();
if(errors.Any())
{
var errorMsgs = new StringBuilder("Validation Errors:");
var fullMsg = errors.Select(x => x.ErrorMessage).Aggregate(errorMsgs, (sb, cur) => sb.AppendLine(cur)).ToString();
throw new ArgumentException(fullMsg);
}
}
}
}
|
Add fields related to 5b3c493 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic.KTHPlaces
{
[DataContract]
public class RoomDataContract
{
[DataMember(Name = "floorUid")]
public string FloorUId { get; set; }
[DataMember(Name = "buildingName")]
public string BuildingName { get; set; }
[DataMember(Name = "campus")]
public string Campus { get; set; }
[DataMember(Name = "typeName")]
public string TypeName { get; set; }
[DataMember(Name = "placeName")]
public string PlaceName { get; set; }
[DataMember(Name = "uid")]
public string UId { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.Logic.KTHPlaces
{
[DataContract]
public class RoomDataContract
{
[DataMember(Name = "floorUid")]
public string FloorUId { get; set; }
[DataMember(Name = "buildingName")]
public string BuildingName { get; set; }
[DataMember(Name = "campus")]
public string Campus { get; set; }
[DataMember(Name = "typeName")]
public string TypeName { get; set; }
[DataMember(Name = "placeName")]
public string PlaceName { get; set; }
[DataMember(Name = "uid")]
public string UId { get; set; }
[DataMember(Name = "equipment")]
public Equipment[] Equipment { get; set; }
}
[DataContract]
public class Equipment
{
[DataMember(Name = "name")]
public Name Name { get; set; }
}
[DataContract]
public class Name
{
[DataMember(Name = "en")]
public string En { get; set; }
}
} |
Fix for persisting the known devices. | using ChromeCast.Desktop.AudioStreamer.Application;
namespace ChromeCast.Desktop.AudioStreamer.Discover
{
public class DiscoveredDevice
{
private const string GroupIdentifier = "\"md=Google Cast Group\"";
public string Name { get; set; }
public string IPAddress { get; set; }
public int Port { get; set; }
public string Protocol { get; set; }
public string Usn { get; set; }
public string Headers { get; set; }
public bool AddedByDeviceInfo { get; internal set; }
public DeviceEureka Eureka { get; internal set; }
public Group Group { get; internal set; }
public bool IsGroup {
get
{
if (Headers != null && Headers.IndexOf(GroupIdentifier) >= 0)
return true;
return false;
}
set
{
if (value)
Headers = GroupIdentifier;
}
}
}
}
| using ChromeCast.Desktop.AudioStreamer.Application;
using System.Xml.Serialization;
namespace ChromeCast.Desktop.AudioStreamer.Discover
{
public class DiscoveredDevice
{
private const string GroupIdentifier = "\"md=Google Cast Group\"";
public string Name { get; set; }
public string IPAddress { get; set; }
public int Port { get; set; }
public string Protocol { get; set; }
public string Usn { get; set; }
public string Headers { get; set; }
public bool AddedByDeviceInfo { get; set; }
[XmlIgnore]
public DeviceEureka Eureka { get; set; }
[XmlIgnore]
public Group Group { get; set; }
public bool IsGroup {
get
{
if (Headers != null && Headers.IndexOf(GroupIdentifier) >= 0)
return true;
return false;
}
set
{
if (value)
Headers = GroupIdentifier;
}
}
}
}
|
Change the padding on the exception message | using StructuredXmlEditor.View;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace StructuredXmlEditor
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
if (!Debugger.IsAttached) this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
VersionInfo.DeleteUpdater();
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string errorMessage = "An unhandled exception occurred!\n" + e.Exception.Message + "\n\nThe app has attempted to recover and carry on, but you may experience some weirdness. Report error?.";
File.WriteAllText("error.log", e.Exception.ToString());
var choice = Message.Show(errorMessage, "Error", "Report", "Ignore");
if (choice == "Report")
{
Email.SendEmail("Crash Report", "Editor crashed on " + DateTime.Now + ".\nEditor Version: " + VersionInfo.Version, e.Exception.ToString());
Message.Show("Error Reported, I shall fix as soon as possible.", "Error reported", "Ok");
}
e.Handled = true;
}
}
}
| using StructuredXmlEditor.View;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace StructuredXmlEditor
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
if (!Debugger.IsAttached) this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
VersionInfo.DeleteUpdater();
}
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string errorMessage = "An unhandled exception occurred!\n\n" + e.Exception.Message + "\n\nThe app has attempted to recover and carry on, but you may experience some weirdness. Report error?";
File.WriteAllText("error.log", e.Exception.ToString());
var choice = Message.Show(errorMessage, "Error", "Report", "Ignore");
if (choice == "Report")
{
Email.SendEmail("Crash Report", "Editor crashed on " + DateTime.Now + ".\nEditor Version: " + VersionInfo.Version, e.Exception.ToString());
Message.Show("Error Reported, I shall fix as soon as possible.", "Error reported", "Ok");
}
e.Handled = true;
}
}
}
|
Add a link to "about trac" on the trac version number at the end | <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <strong>Trac <?cs var:trac.version ?></strong><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
| <script type="text/javascript">searchHighlight()</script>
<?cs if:len(links.alternate) ?>
<div id="altlinks">
<h3>Download in other formats:</h3>
<ul><?cs each:link = links.alternate ?>
<li<?cs if:name(link) == len(links.alternate) - #1 ?> class="last"<?cs /if ?>>
<a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs
var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a>
</li><?cs /each ?>
</ul>
</div>
<?cs /if ?>
</div>
<div id="footer">
<hr />
<a id="tracpowered" href="http://trac.edgewall.com/"><img src="<?cs
var:$htdocs_location ?>trac_logo_mini.png" height="30" width="107"
alt="Trac Powered"/></a>
<p class="left">
Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs
var:trac.version ?></strong></a><br />
By <a href="http://www.edgewall.com/">Edgewall Software</a>.
</p>
<p class="right">
<?cs var $project.footer ?>
</p>
</div>
<?cs include "site_footer.cs" ?>
</body>
</html>
|
Add HTTP request verb and url to echo response | using System;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using Newtonsoft.Json;
namespace WebServer
{
public class RequestInformation
{
public NameValueCollection Headers { get; private set; }
public string BodyContent { get; private set; }
public int BodyLength { get; private set; }
public bool SecureConnection { get; private set; }
public bool ClientCertificatePresent { get; private set; }
public HttpClientCertificate ClientCertificate { get; private set; }
public static RequestInformation Create(HttpRequest request)
{
var info = new RequestInformation();
info.Headers = request.Headers;
Stream stream = request.GetBufferedInputStream();
using (var reader = new StreamReader(stream))
{
string body = reader.ReadToEnd();
info.BodyContent = body;
info.BodyLength = body.Length;
}
info.SecureConnection = request.IsSecureConnection;
var cs = request.ClientCertificate;
info.ClientCertificatePresent = cs.IsPresent;
if (cs.IsPresent)
{
info.ClientCertificate = request.ClientCertificate;
}
return info;
}
public static RequestInformation DeSerializeFromJson(string json)
{
return (RequestInformation)JsonConvert.DeserializeObject(
json,
typeof(RequestInformation),
new NameValueCollectionConverter());
}
public string SerializeToJson()
{
return JsonConvert.SerializeObject(this, new NameValueCollectionConverter());
}
private RequestInformation()
{
}
}
}
| using System;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using Newtonsoft.Json;
namespace WebServer
{
public class RequestInformation
{
public string Verb { get; private set; }
public string Url { get; private set; }
public NameValueCollection Headers { get; private set; }
public string BodyContent { get; private set; }
public int BodyLength { get; private set; }
public bool SecureConnection { get; private set; }
public bool ClientCertificatePresent { get; private set; }
public HttpClientCertificate ClientCertificate { get; private set; }
public static RequestInformation Create(HttpRequest request)
{
var info = new RequestInformation();
info.Verb = request.HttpMethod;
info.Url = request.RawUrl;
info.Headers = request.Headers;
Stream stream = request.GetBufferedInputStream();
using (var reader = new StreamReader(stream))
{
string body = reader.ReadToEnd();
info.BodyContent = body;
info.BodyLength = body.Length;
}
info.SecureConnection = request.IsSecureConnection;
var cs = request.ClientCertificate;
info.ClientCertificatePresent = cs.IsPresent;
if (cs.IsPresent)
{
info.ClientCertificate = request.ClientCertificate;
}
return info;
}
public static RequestInformation DeSerializeFromJson(string json)
{
return (RequestInformation)JsonConvert.DeserializeObject(
json,
typeof(RequestInformation),
new NameValueCollectionConverter());
}
public string SerializeToJson()
{
return JsonConvert.SerializeObject(this, new NameValueCollectionConverter());
}
private RequestInformation()
{
}
}
}
|
Add sending of all http header values | using System.Collections.Generic;
namespace DotVVM.Framework.Diagnostics.Models
{
public class HttpHeaderItem
{
public string Key { get; set; }
public string Value { get; set; }
public static HttpHeaderItem FromKeyValuePair(KeyValuePair<string, string[]> pair)
{
return new HttpHeaderItem
{
Key = pair.Key,
Value = pair.Value[0]
};
}
}
} | using System.Collections.Generic;
namespace DotVVM.Framework.Diagnostics.Models
{
public class HttpHeaderItem
{
public string Key { get; set; }
public string Value { get; set; }
public static HttpHeaderItem FromKeyValuePair(KeyValuePair<string, string[]> pair)
{
return new HttpHeaderItem
{
Key = pair.Key,
Value = string.Join("; ", pair.Value)
};
}
}
} |
Fix up menu for IE |
@if (Request.IsAuthenticated)
{
<div class="btn-group">
<a class="btn btn-inverse" href="#"><i class="icon-user icon-white"></i> @User.Identity.Name</a>
<a class="btn btn-inverse dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "User", "Account")</li>
<li><a href="javascript:document.getElementById('logoutMenuForm').submit()">Logout</a></li>
</ul>
</div>
using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutMenuForm", @class="hidden" }))
{
@Html.AntiForgeryToken()
}
}
else
{
<a class="btn btn-info" href="@Url.Action("Login", "Account")" > <i class="icon-user icon-white"></i> Login</a>
} |
@if (Request.IsAuthenticated)
{
<li>
<div class="btn-group">
<a class="btn btn-inverse" href="#"><i class="icon-user icon-white"></i> @User.Identity.Name</a>
<a class="btn btn-inverse dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "User", "Account")</li>
<li><a href="javascript:document.getElementById('logoutMenuForm').submit()">Logout</a></li>
</ul>
</div>
</li>
using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutMenuForm", @class="hidden" }))
{
@Html.AntiForgeryToken()
}
}
else
{
<li><a class="btn btn-info" href="@Url.Action("Login", "Account")" > <i class="icon-user icon-white"></i> Login</a></li>
} |
Fix some spacing in class | using System;
using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc
{
internal class ActionSelectedMessage : IMessage
{
public Guid Id { get; } = Guid.NewGuid();
public DateTime Time { get; } = DateTime.Now;
public string ActionId { get; set; }
public string DisplayName { get; set; }
public RouteData RouteData { get; set; }
}
internal class RouteData
{
public string Name { get; set; }
public string Pattern { get; set; }
public IList<RouteResolutionData> Data { get; set; }
}
internal class RouteResolutionData
{
public string Tag { get; set; }
public string Match { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc
{
internal class ActionSelectedMessage : IMessage
{
public Guid Id { get; } = Guid.NewGuid();
public DateTime Time { get; } = DateTime.Now;
public string ActionId { get; set; }
public string DisplayName { get; set; }
public RouteData RouteData { get; set; }
}
internal class RouteData
{
public string Name { get; set; }
public string Pattern { get; set; }
public IList<RouteResolutionData> Data { get; set; }
}
internal class RouteResolutionData
{
public string Tag { get; set; }
public string Match { get; set; }
}
} |
Add more tests for get by id | using Moq;
using NUnit.Framework;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
namespace PhotoLife.Services.Tests.UserServiceTests
{
[TestFixture]
public class GetById_Should
{
[TestCase("some id")]
[TestCase("other id")]
public void _CallRepository_GetByIdMethod(string id)
{
//Arrange
var mockedRepository = new Mock<IRepository<User>>();
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
//Act
userService.GetUserById(id);
//Assert
mockedRepository.Verify(r => r.GetById(id), Times.Once);
}
}
}
| using Moq;
using NUnit.Framework;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
namespace PhotoLife.Services.Tests.UserServiceTests
{
[TestFixture]
public class GetById_Should
{
[TestCase("some id")]
[TestCase("other id")]
public void _CallRepository_GetByIdMethod(string id)
{
//Arrange
var mockedRepository = new Mock<IRepository<User>>();
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
//Act
userService.GetUserById(id);
//Assert
mockedRepository.Verify(r => r.GetById(id), Times.Once);
}
[TestCase("some id")]
[TestCase("other id")]
public void _Return_Correctly(string id)
{
//Arrange
var mockedUser = new Mock<User>();
var mockedRepository = new Mock<IRepository<User>>();
mockedRepository.Setup(r=>r.GetById(It.IsAny<string>())).Returns(mockedUser.Object);
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var userService = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
//Act
var res = userService.GetUserById(id);
//Assert
Assert.AreSame(mockedUser.Object, res);
}
}
}
|
Fix issue to throw exception when wallpaper isn't set. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using SylphyHorn.Services;
namespace SylphyHorn.UI.Controls
{
public class UnlockImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null;
using (var stream = new FileStream((string)value, FileMode.Open))
{
var decoder = BitmapDecoder.Create(
stream,
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
var bitmap = new WriteableBitmap(decoder.Frames[0]);
bitmap.Freeze();
return bitmap;
}
}
catch (Exception ex)
{
LoggingService.Instance.Register(ex);
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using SylphyHorn.Services;
namespace SylphyHorn.UI.Controls
{
public class UnlockImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) return null;
var filename = (string)value;
if (string.IsNullOrEmpty(filename)) return null;
using (var stream = new FileStream(filename, FileMode.Open))
{
var decoder = BitmapDecoder.Create(
stream,
BitmapCreateOptions.None,
BitmapCacheOption.OnLoad);
var bitmap = new WriteableBitmap(decoder.Frames[0]);
bitmap.Freeze();
return bitmap;
}
}
catch (Exception ex)
{
LoggingService.Instance.Register(ex);
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
Add regex for associating work items | using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
}
}
| using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
// e.g. git-tfs-work-item: 24 associate
public static readonly Regex TfsWorkItemRegex =
new Regex(@"^\s*"+ GitTfsPrefix + @"-work-item:\s+(?<item_id>\d+)\s(?<action>.+)");
}
}
|
Use proper input instead of log message to request manual DNS change | using PKISharp.WACS.Services;
namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
class Manual : DnsValidation<ManualOptions, Manual>
{
private IInputService _input;
public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) : base(log, options, identifier)
{
// Usually it's a big no-no to rely on user input in validation plugin
// because this should be able to run unattended. This plugin is for testing
// only and therefor we will allow it. Future versions might be more advanced,
// e.g. shoot an email to an admin and complete the order later.
_input = input;
}
public override void CreateRecord(string recordName, string token)
{
_log.Warning("Create record {recordName} for domain {identifier} with content {token}", recordName, _identifier, token);
_input.Wait();
}
public override void DeleteRecord(string recordName, string token)
{
_log.Warning("Delete record {recordName} for domain {identifier}", recordName, _identifier);
_input.Wait();
}
}
}
| using PKISharp.WACS.Services;
namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns
{
class Manual : DnsValidation<ManualOptions, Manual>
{
private IInputService _input;
public Manual(ILogService log, IInputService input, ManualOptions options, string identifier) : base(log, options, identifier)
{
// Usually it's a big no-no to rely on user input in validation plugin
// because this should be able to run unattended. This plugin is for testing
// only and therefor we will allow it. Future versions might be more advanced,
// e.g. shoot an email to an admin and complete the order later.
_input = input;
}
public override void CreateRecord(string recordName, string token)
{
_input.Wait($"Create record {recordName} for domain {_identifier} with content {token} and press enter to continue...");
}
public override void DeleteRecord(string recordName, string token)
{
_input.Wait($"Delete record {recordName} for domain {_identifier}");
}
}
}
|
Fix compiler warning and rename test to be more clear. | using System;
using NUnit.Framework;
namespace MongoDB.Driver.Connections
{
[TestFixture]
public class TestConnectionFactory
{
[TearDown]
public void TearDown (){
ConnectionFactory.Shutdown ();
}
[Test]
public void TestGetConnection (){
var connection1 = ConnectionFactory.GetConnection (string.Empty);
var connection2 = ConnectionFactory.GetConnection (string.Empty);
Assert.IsNotNull (connection1);
Assert.IsNotNull (connection2);
Assert.AreEqual (1, ConnectionFactory.PoolCount);
}
[Test]
public void TestCreatePoolForEachUniqeConnectionString (){
ConnectionFactory.GetConnection (string.Empty);
ConnectionFactory.GetConnection (string.Empty);
ConnectionFactory.GetConnection ("Username=test");
ConnectionFactory.GetConnection ("Username=test");
ConnectionFactory.GetConnection ("Server=localhost");
Assert.AreEqual (3, ConnectionFactory.PoolCount);
}
[Test]
public void TestGetInvalidConnection (){
bool thrown = false;
try{
ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
}catch(ArgumentException){
thrown = true;
}catch(Exception){
Assert.Fail("Wrong exception thrown");
}
}
}
}
| using System;
using NUnit.Framework;
namespace MongoDB.Driver.Connections
{
[TestFixture]
public class TestConnectionFactory
{
[TearDown]
public void TearDown (){
ConnectionFactory.Shutdown ();
}
[Test]
public void TestGetConnection (){
var connection1 = ConnectionFactory.GetConnection (string.Empty);
var connection2 = ConnectionFactory.GetConnection (string.Empty);
Assert.IsNotNull (connection1);
Assert.IsNotNull (connection2);
Assert.AreEqual (1, ConnectionFactory.PoolCount);
}
[Test]
public void TestCreatePoolForEachUniqeConnectionString (){
ConnectionFactory.GetConnection (string.Empty);
ConnectionFactory.GetConnection (string.Empty);
ConnectionFactory.GetConnection ("Username=test");
ConnectionFactory.GetConnection ("Username=test");
ConnectionFactory.GetConnection ("Server=localhost");
Assert.AreEqual (3, ConnectionFactory.PoolCount);
}
[Test]
public void TestExceptionWhenMinimumPoolSizeIsGreaterThenMaximumPoolSize (){
try{
ConnectionFactory.GetConnection("MinimumPoolSize=50; MaximumPoolSize=10");
}catch(ArgumentException){
}catch(Exception){
Assert.Fail("Wrong exception thrown");
}
}
}
}
|
Use UserName instead of UserDomainName | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using OneWayMirror.Core;
namespace OneWayMirror
{
internal sealed class ReportingConsoleHost : ConsoleHost
{
private readonly string _reportEmailAddress;
internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose)
{
_reportEmailAddress = reportEmailAddress;
}
private void SendMail(string body)
{
using (var msg = new MailMessage())
{
msg.To.Add(new MailAddress(_reportEmailAddress));
msg.From = new MailAddress(Environment.UserDomainName + @"@microsoft.com");
msg.IsBodyHtml = false;
msg.Subject = "Git to TFS Mirror Error";
msg.Body = body;
var client = new SmtpClient("smtphost");
client.UseDefaultCredentials = true;
client.Send(msg);
}
}
public override void Error(string format, params object[] args)
{
base.Error(format, args);
SendMail(string.Format(format, args));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using OneWayMirror.Core;
namespace OneWayMirror
{
internal sealed class ReportingConsoleHost : ConsoleHost
{
private readonly string _reportEmailAddress;
internal ReportingConsoleHost(bool verbose, string reportEmailAddress) : base(verbose)
{
_reportEmailAddress = reportEmailAddress;
}
private void SendMail(string body)
{
using (var msg = new MailMessage())
{
msg.To.Add(new MailAddress(_reportEmailAddress));
msg.From = new MailAddress(Environment.UserName + @"@microsoft.com");
msg.IsBodyHtml = false;
msg.Subject = "Git to TFS Mirror Error";
msg.Body = body;
var client = new SmtpClient("smtphost");
client.UseDefaultCredentials = true;
client.Send(msg);
}
}
public override void Error(string format, params object[] args)
{
base.Error(format, args);
SendMail(string.Format(format, args));
}
}
}
|
Disable commands while they are executing | using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Fotografix
{
public sealed class DelegateCommand : ICommand
{
private readonly Func<bool> canExecute;
private readonly Func<Task> execute;
private bool executing;
public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; })
{
}
public DelegateCommand(Func<Task> execute) : this(() => true, execute)
{
}
public DelegateCommand(Func<bool> canExecute, Func<Task> execute)
{
this.canExecute = canExecute;
this.execute = execute;
}
public event EventHandler CanExecuteChanged
{
add { }
remove { }
}
public bool CanExecute(object parameter)
{
return canExecute();
}
public async void Execute(object parameter)
{
if (executing)
{
/*
* This scenario can occur in two situations:
* 1. The user invokes the command again before the previous async execution has completed.
* 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator.
*/
Debug.WriteLine("Skipping command execution since previous execution has not completed yet");
return;
}
try
{
this.executing = true;
await execute();
}
finally
{
this.executing = false;
}
}
}
}
| using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Fotografix
{
public sealed class DelegateCommand : ICommand
{
private readonly Func<bool> canExecute;
private readonly Func<Task> execute;
private bool executing;
public DelegateCommand(Action execute) : this(() => true, () => { execute(); return Task.CompletedTask; })
{
}
public DelegateCommand(Func<Task> execute) : this(() => true, execute)
{
}
public DelegateCommand(Func<bool> canExecute, Func<Task> execute)
{
this.canExecute = canExecute;
this.execute = execute;
}
public bool IsExecuting
{
get => executing;
private set
{
this.executing = value;
RaiseCanExecuteChanged();
}
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
public bool CanExecute(object parameter)
{
return !executing && canExecute();
}
public async void Execute(object parameter)
{
if (IsExecuting)
{
/*
* This scenario can occur in two situations:
* 1. The user invokes the command again before the previous async execution has completed.
* 2. A bug in the XAML framework that sometimes triggers a command twice when using a keyboard accelerator.
*/
Debug.WriteLine("Skipping command execution since previous execution has not completed yet");
return;
}
try
{
this.IsExecuting = true;
await execute();
}
finally
{
this.IsExecuting = false;
}
}
}
}
|
Add description indicating retrieval method | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Extensions.TypeExtensions;
namespace osu.Framework.Localisation
{
/// <summary>
/// Indicates that the members of an enum can be localised.
/// </summary>
[AttributeUsage(AttributeTargets.Enum)]
public sealed class LocalisableEnumAttribute : Attribute
{
/// <summary>
/// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.
/// </summary>
public readonly Type MapperType;
/// <summary>
/// Creates a new <see cref="LocalisableEnumAttribute"/>.
/// </summary>
/// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param>
public LocalisableEnumAttribute(Type mapperType)
{
MapperType = mapperType;
if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType))
throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Extensions;
using osu.Framework.Extensions.TypeExtensions;
namespace osu.Framework.Localisation
{
/// <summary>
/// Indicates that the values of an enum have <see cref="LocalisableString"/> descriptions.
/// The descriptions can be returned through <see cref="ExtensionMethods.GetLocalisableDescription{T}"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Enum)]
public sealed class LocalisableEnumAttribute : Attribute
{
/// <summary>
/// The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.
/// </summary>
public readonly Type MapperType;
/// <summary>
/// Creates a new <see cref="LocalisableEnumAttribute"/>.
/// </summary>
/// <param name="mapperType">The <see cref="EnumLocalisationMapper{T}"/> type that maps enum values to <see cref="LocalisableString"/>s.</param>
public LocalisableEnumAttribute(Type mapperType)
{
MapperType = mapperType;
if (!typeof(IEnumLocalisationMapper).IsAssignableFrom(mapperType))
throw new ArgumentException($"Type \"{mapperType.ReadableName()}\" must inherit from {nameof(EnumLocalisationMapper<Enum>)}.", nameof(mapperType));
}
}
}
|
Load the service in the main thread, once more. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Common;
using Hadouken.Hosting;
namespace Hadouken.Hosts.WindowsService
{
public class HdknService : ServiceBase
{
private IHadoukenHost _host;
public HdknService()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.AutoLog = true;
this.ServiceName = "Hadouken";
}
protected override void OnStart(string[] args)
{
Task.Factory.StartNew(() =>
{
_host = Kernel.Get<IHadoukenHost>();
_host.Load();
});
}
protected override void OnStop()
{
if (_host != null)
_host.Unload();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Common;
using Hadouken.Hosting;
using System.Threading;
namespace Hadouken.Hosts.WindowsService
{
public class HdknService : ServiceBase
{
private IHadoukenHost _host;
public HdknService()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.AutoLog = true;
this.ServiceName = "Hadouken";
}
protected override void OnStart(string[] args)
{
Load();
}
private void Load()
{
_host = Kernel.Get<IHadoukenHost>();
_host.Load();
}
protected override void OnStop()
{
if (_host != null)
_host.Unload();
}
}
}
|
Create Display/Editor location settings for Parts and Fields | using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Common.Fields;
namespace Orchard.Core.Common.Drivers {
[UsedImplicitly]
public class TextFieldDriver : ContentFieldDriver<TextField> {
public IOrchardServices Services { get; set; }
private const string TemplateName = "Fields/Common.TextField";
public TextFieldDriver(IOrchardServices services) {
Services = services;
}
private static string GetPrefix(TextField field, ContentPart part) {
return part.PartDefinition.Name + "." + field.Name;
}
protected override DriverResult Display(ContentPart part, TextField field, string displayType) {
return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part));
}
protected override DriverResult Editor(ContentPart part, TextField field) {
return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part)).Location("primary", "5");
}
protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) {
updater.TryUpdateModel(field, GetPrefix(field, part), null, null);
return Editor(part, field);
}
}
}
| using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Common.Fields;
using Orchard.Core.Common.Settings;
namespace Orchard.Core.Common.Drivers {
[UsedImplicitly]
public class TextFieldDriver : ContentFieldDriver<TextField> {
public IOrchardServices Services { get; set; }
private const string TemplateName = "Fields/Common.TextField";
public TextFieldDriver(IOrchardServices services) {
Services = services;
}
private static string GetPrefix(TextField field, ContentPart part) {
return part.PartDefinition.Name + "." + field.Name;
}
protected override DriverResult Display(ContentPart part, TextField field, string displayType) {
var locationSettings =
field.PartFieldDefinition.Settings.GetModel<LocationSettings>("DisplayLocation") ??
new LocationSettings { Zone = "primary", Position = "5" };
return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part))
.Location(locationSettings.Zone, locationSettings.Position);
}
protected override DriverResult Editor(ContentPart part, TextField field) {
var locationSettings =
field.PartFieldDefinition.Settings.GetModel<LocationSettings>("EditorLocation") ??
new LocationSettings { Zone = "primary", Position = "5" };
return ContentFieldTemplate(field, TemplateName, GetPrefix(field, part))
.Location(locationSettings.Zone, locationSettings.Position);
}
protected override DriverResult Editor(ContentPart part, TextField field, IUpdateModel updater) {
updater.TryUpdateModel(field, GetPrefix(field, part), null, null);
return Editor(part, field);
}
}
}
|
Fix intermittent Style unit test failures. | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
[assembly: AssemblyTitle("Perspex.Styling.UnitTests")]
| // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Reflection;
using Xunit;
[assembly: AssemblyTitle("Perspex.Styling.UnitTests")]
// Don't run tests in parallel.
[assembly: CollectionBehavior(DisableTestParallelization = true)] |
Fix dumb in torch mod | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using VRage.Game.Components;
namespace Torch.Mod
{
[MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
public class TorchModCore : MySessionComponentBase
{
public const ulong MOD_ID = 1406994352;
private static bool _init;
public static bool Debug;
public override void UpdateAfterSimulation()
{
if (_init)
return;
_init = true;
ModCommunication.Register();
MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered;
}
private void Utilities_MessageEntered(string messageText, ref bool sendToOthers)
{
if (messageText == "@!debug")
{
Debug = !Debug;
MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}");
sendToOthers = false;
}
}
protected override void UnloadData()
{
try
{
ModCommunication.Unregister();
}
catch
{
//session unloading, don't care
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox.ModAPI;
using VRage.Game.Components;
namespace Torch.Mod
{
[MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
public class TorchModCore : MySessionComponentBase
{
public const ulong MOD_ID = 1406994352;
private static bool _init;
public static bool Debug;
public override void UpdateAfterSimulation()
{
if (_init)
return;
_init = true;
ModCommunication.Register();
MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered;
}
private void Utilities_MessageEntered(string messageText, ref bool sendToOthers)
{
if (messageText == "@!debug")
{
Debug = !Debug;
MyAPIGateway.Utilities.ShowMessage("Torch", $"Debug: {Debug}");
sendToOthers = false;
}
}
protected override void UnloadData()
{
try
{
MyAPIGateway.Utilities.MessageEntered -= Utilities_MessageEntered;
ModCommunication.Unregister();
}
catch
{
//session unloading, don't care
}
}
}
}
|
Add slider test step for visual inspection purposes | // 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.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneStarCounter : OsuTestScene
{
private readonly StarCounter starCounter;
private readonly OsuSpriteText starsLabel;
public TestSceneStarCounter()
{
starCounter = new StarCounter
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
};
Add(starCounter);
starsLabel = new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Scale = new Vector2(2),
Y = 50,
};
Add(starsLabel);
setStars(5);
AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10);
AddStep("stop animation", () => starCounter.StopAnimation());
AddStep("reset", () => setStars(0));
}
private void setStars(float stars)
{
starCounter.Current = stars;
starsLabel.Text = starCounter.Current.ToString("0.00");
}
}
}
| // 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.Utils;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[TestFixture]
public class TestSceneStarCounter : OsuTestScene
{
private readonly StarCounter starCounter;
private readonly OsuSpriteText starsLabel;
public TestSceneStarCounter()
{
starCounter = new StarCounter
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
};
Add(starCounter);
starsLabel = new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Scale = new Vector2(2),
Y = 50,
};
Add(starsLabel);
setStars(5);
AddRepeatStep("random value", () => setStars(RNG.NextSingle() * (starCounter.StarCount + 1)), 10);
AddSliderStep("exact value", 0f, 10f, 5f, setStars);
AddStep("stop animation", () => starCounter.StopAnimation());
AddStep("reset", () => setStars(0));
}
private void setStars(float stars)
{
starCounter.Current = stars;
starsLabel.Text = starCounter.Current.ToString("0.00");
}
}
}
|
Check if _soundData is null before attempting to play the sound | using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;
namespace Win32
{
public static class Winmm
{
public static void PlayMessageNotify()
{
if (_soundData == null)
{
using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop)
{
_soundData = new byte[sound.Length];
sound.Read(_soundData, 0, (int)sound.Length);
}
}
PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
}
private static byte[] _soundData;
private const UInt32 SND_ASYNC = 1;
private const UInt32 SND_MEMORY = 4;
[DllImport("Winmm.dll")]
private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
}
}
| using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;
namespace Win32
{
public static class Winmm
{
public static void PlayMessageNotify()
{
if (_soundData == null)
{
using (UnmanagedMemoryStream sound = Toxy.Properties.Resources.Blop)
{
_soundData = new byte[sound.Length];
sound.Read(_soundData, 0, (int)sound.Length);
}
}
if (_soundData != null)
{
PlaySound(_soundData, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
}
}
private static byte[] _soundData;
private const UInt32 SND_ASYNC = 1;
private const UInt32 SND_MEMORY = 4;
[DllImport("Winmm.dll")]
private static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
}
}
|
Use local definition of ArchiveTypes to validate metadata systemtypes | using System;
namespace Arkivverket.Arkade.Metadata
{
public static class MetsTranslationHelper
{
public static bool IsValidSystemType(string systemType)
{
// TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema
return Enum.IsDefined(typeof(ExternalModels.Info.type), systemType);
}
public static bool IsSystemTypeNoark5(string systemType)
{
// TODO: Use Enum ExternalModels.Mets.type (not ExternalModels.Info.type) when/if supported in built in mets schema
ExternalModels.Info.type enumSystemType;
bool isParsableSystemType = Enum.TryParse(systemType, out enumSystemType);
return isParsableSystemType && enumSystemType == ExternalModels.Info.type.Noark5;
}
}
}
| using System;
using Arkivverket.Arkade.Core;
namespace Arkivverket.Arkade.Metadata
{
public static class MetsTranslationHelper
{
public static bool IsValidSystemType(string systemType)
{
return Enum.IsDefined(typeof(ArchiveType), systemType);
}
public static bool IsSystemTypeNoark5(string systemType)
{
ArchiveType archiveType;
bool isParsableSystemType = Enum.TryParse(systemType, out archiveType);
return isParsableSystemType && archiveType == ArchiveType.Noark5;
}
}
}
|
Remove userGuid on ValidateUser method | using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "DiallerService")]
public interface IDiallerService
{
[OperationContract]
ValidUserInfoDto ValidateUser(Guid userGuid, Guid mothershipSessionGuid);
[OperationContract]
Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe);
[OperationContract]
Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe);
[OperationContract]
SipAccountDetailsDto GetSipAccountDetails(Guid userGuid);
[OperationContract(IsOneWay = true)]
List<InboundQueueDetailsDto> GetInboundQueueDetails();
[OperationContract(IsOneWay = true)]
List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);
[OperationContract]
void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid);
}
}
| using System;
using System.Collections.Generic;
using System.ServiceModel;
using PS.Mothership.Core.Common.Dto;
namespace PS.Mothership.Core.Common.Contracts
{
[ServiceContract(Name = "DiallerService")]
public interface IDiallerService
{
[OperationContract]
ValidUserInfoDto ValidateUser(Guid mothershipSessionGuid);
[OperationContract]
Guid LogDiallerSessionSubscribe(DiallerSessionSubscribeDto diallerSessionSubscribe);
[OperationContract]
Guid LogDiallerSessionUnsubscribe(DiallerSessionUnsubscribeDto diallerSessionUnsubscribe);
[OperationContract]
SipAccountDetailsDto GetSipAccountDetails(Guid userGuid);
[OperationContract(IsOneWay = true)]
List<InboundQueueDetailsDto> GetInboundQueueDetails();
[OperationContract(IsOneWay = true)]
List<MissingCallRecordingsDto> GetMissingCallRecordings(DateTime dateStart, DateTime dateEnd);
[OperationContract]
void UpdateRecorderCallIdForCallGuid(Guid callGuid, int recorderCallId, Guid userGuid);
}
}
|
Fix a niggle from the wiki: display donation amounts to two decimal places. Also format them as a currency, and respect the current culture. | @model IEnumerable<GiveCRM.Models.Donation>
@{
Layout = null;
}
<table>
<tr>
<th>Date</th><th>Amount</th>
</tr>
@foreach (var donation in Model)
{
<tr>
<td>@donation.Date.ToLongDateString()</td>
<td>@donation.Amount</td>
</tr>
}
</table> | @using System.Globalization
@model IEnumerable<GiveCRM.Models.Donation>
@{
Layout = null;
}
<table>
<tr>
<th>Date</th><th>Amount</th>
</tr>
@foreach (var donation in Model)
{
<tr>
<td>@donation.Date.ToLongDateString()</td>
<td>@donation.Amount.ToString("C2", NumberFormatInfo.CurrentInfo)</td>
</tr>
}
</table> |
Remove CoreCLR pull 6423, run msbuild System.ObjectModel.Tests.csproj /t:BuildAndTest, succeeded. | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
public partial class KeyedCollection_Serialization
{
public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData()
{
yield return new object[] { new TestCollection() };
yield return new object[] { new TestCollection() { "hello" } };
yield return new object[] { new TestCollection() { "hello", "world" } };
}
[ActiveIssue("https://github.com/dotnet/coreclr/pull/7966")]
[Theory]
[MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))]
public void SerializeDeserialize_Roundtrips(TestCollection c)
{
TestCollection clone = BinaryFormatterHelpers.Clone(c);
Assert.NotSame(c, clone);
Assert.Equal(c, clone);
}
[Serializable]
public sealed class TestCollection : KeyedCollection<string, string>
{
protected override string GetKeyForItem(string item) => item;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
public partial class KeyedCollection_Serialization
{
public static IEnumerable<object[]> SerializeDeserialize_Roundtrips_MemberData()
{
yield return new object[] { new TestCollection() };
yield return new object[] { new TestCollection() { "hello" } };
yield return new object[] { new TestCollection() { "hello", "world" } };
}
[Theory]
[MemberData(nameof(SerializeDeserialize_Roundtrips_MemberData))]
public void SerializeDeserialize_Roundtrips(TestCollection c)
{
TestCollection clone = BinaryFormatterHelpers.Clone(c);
Assert.NotSame(c, clone);
Assert.Equal(c, clone);
}
[Serializable]
public sealed class TestCollection : KeyedCollection<string, string>
{
protected override string GetKeyForItem(string item) => item;
}
}
}
|
Remove JsonProperty Mapping for "file" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Contentful.Core.Models
{
/// <summary>
/// Represents a single asset of a <see cref="Space"/>.
/// </summary>
public class Asset : IContentfulResource
{
/// <summary>
/// Common system managed metadata properties.
/// </summary>
[JsonProperty("sys")]
public SystemProperties SystemProperties { get; set; }
/// <summary>
/// The description of the asset.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The title of the asset.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Encapsulates information about the binary file of the asset.
/// </summary>
public File File { get; set; }
/// <summary>
/// The titles of the asset per locale.
/// </summary>
public Dictionary<string, string> TitleLocalized { get; set; }
/// <summary>
/// The descriptions of the asset per locale.
/// </summary>
public Dictionary<string, string> DescriptionLocalized { get; set; }
/// <summary>
/// Information about the file in respective language.
/// </summary>
[JsonProperty("file")]
public Dictionary<string, File> FilesLocalized { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Contentful.Core.Models
{
/// <summary>
/// Represents a single asset of a <see cref="Space"/>.
/// </summary>
public class Asset : IContentfulResource
{
/// <summary>
/// Common system managed metadata properties.
/// </summary>
[JsonProperty("sys")]
public SystemProperties SystemProperties { get; set; }
/// <summary>
/// The description of the asset.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The title of the asset.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Encapsulates information about the binary file of the asset.
/// </summary>
public File File { get; set; }
/// <summary>
/// The titles of the asset per locale.
/// </summary>
public Dictionary<string, string> TitleLocalized { get; set; }
/// <summary>
/// The descriptions of the asset per locale.
/// </summary>
public Dictionary<string, string> DescriptionLocalized { get; set; }
/// <summary>
/// Information about the file in respective language.
/// </summary>
public Dictionary<string, File> FilesLocalized { get; set; }
}
}
|
Add throw error on Neo exception in ExecuteCore | namespace CypherTwo.Core
{
using System;
using System.Linq;
using System.Threading.Tasks;
public class NeoClient : INeoClient
{
private readonly ISendRestCommandsToNeo neoApi;
public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper()))
{
}
internal NeoClient(ISendRestCommandsToNeo neoApi)
{
this.neoApi = neoApi;
}
public async Task InitialiseAsync()
{
try
{
await this.neoApi.LoadServiceRootAsync();
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public async Task<ICypherDataReader> QueryAsync(string cypher)
{
var neoResponse = await this.neoApi.SendCommandAsync(cypher);
if (neoResponse.errors != null && neoResponse.errors.Any())
{
throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>())));
}
return new CypherDataReader(neoResponse);
}
public async Task ExecuteAsync(string cypher)
{
await this.neoApi.SendCommandAsync(cypher);
}
}
} | namespace CypherTwo.Core
{
using System;
using System.Linq;
using System.Threading.Tasks;
public class NeoClient : INeoClient
{
private readonly ISendRestCommandsToNeo neoApi;
public NeoClient(string baseUrl) : this(new ApiClientFactory(baseUrl, new JsonHttpClientWrapper()))
{
}
internal NeoClient(ISendRestCommandsToNeo neoApi)
{
this.neoApi = neoApi;
}
public async Task InitialiseAsync()
{
try
{
await this.neoApi.LoadServiceRootAsync();
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public async Task<ICypherDataReader> QueryAsync(string cypher)
{
var neoResponse = await this.ExecuteCore(cypher);
return new CypherDataReader(neoResponse);
}
public async Task ExecuteAsync(string cypher)
{
await this.ExecuteCore(cypher);
}
private async Task<NeoResponse> ExecuteCore(string cypher)
{
var neoResponse = await this.neoApi.SendCommandAsync(cypher);
if (neoResponse.errors != null && neoResponse.errors.Any())
{
throw new Exception(string.Join(Environment.NewLine, neoResponse.errors.Select(error => error.ToObject<string>())));
}
return neoResponse;
}
}
} |
Comment out the code in Hangman that uses Table | using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
Table table = new Table(2, 3);
string output = table.Draw();
Console.WriteLine(output);
}
}
}
| using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
|
Add client method for notifying about host 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.
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining a spectator client instance.
/// </summary>
public interface IMultiplayerClient
{
/// <summary>
/// Signals that the room has changed state.
/// </summary>
/// <param name="state">The state of the room.</param>
Task RoomStateChanged(MultiplayerRoomState state);
/// <summary>
/// Signals that a user has joined the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserJoined(MultiplayerRoomUser user);
/// <summary>
/// Signals that a user has left the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserLeft(MultiplayerRoomUser user);
/// <summary>
/// Signals that the settings for this room have changed.
/// </summary>
/// <param name="newSettings">The updated room settings.</param>
Task SettingsChanged(MultiplayerRoomSettings newSettings);
}
}
| // 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.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining a spectator client instance.
/// </summary>
public interface IMultiplayerClient
{
/// <summary>
/// Signals that the room has changed state.
/// </summary>
/// <param name="state">The state of the room.</param>
Task RoomStateChanged(MultiplayerRoomState state);
/// <summary>
/// Signals that a user has joined the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserJoined(MultiplayerRoomUser user);
/// <summary>
/// Signals that a user has left the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserLeft(MultiplayerRoomUser user);
/// <summary>
/// Signal that the host of the room has changed.
/// </summary>
/// <param name="userId">The user ID of the new host.</param>
Task HostChanged(long userId);
/// <summary>
/// Signals that the settings for this room have changed.
/// </summary>
/// <param name="newSettings">The updated room settings.</param>
Task SettingsChanged(MultiplayerRoomSettings newSettings);
}
}
|
Add parameter-less defaults for Start, Toggle, Reset. | using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Stop();
Start(0);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
}
}
}
| using System;
using System.Threading;
using Microsoft.SPOT;
namespace AgentIntervals
{
public delegate void HeartBeatEventHandler(object sender, EventArgs e);
public class HeartBeat
{
private Timer _timer;
private int _period;
public event HeartBeatEventHandler OnHeartBeat;
public HeartBeat(int period)
{
_period = period;
}
private void TimerCallback(object state)
{
if (OnHeartBeat != null)
{
OnHeartBeat(this, new EventArgs());
}
}
public void Start()
{
Start(0);
}
public void Start(int delay)
{
if (_timer != null) return;
_timer = new Timer(TimerCallback, null, delay, _period);
}
public void Stop()
{
if (_timer == null) return;
_timer.Dispose();
_timer = null;
}
public bool Toggle()
{
return Toggle(0);
}
public bool Toggle(int delay)
{
bool started;
if (_timer == null)
{
Start(delay);
started = true;
}
else
{
Stop();
started = false;
}
return started;
}
public void Reset()
{
Reset(0);
}
public void Reset(int delay)
{
Stop();
Start(delay);
}
public void ChangePeriod(int newPeriod)
{
_period = newPeriod;
}
}
}
|
Use the defined max value | using System;
using System.Linq;
namespace FibCSharp
{
class Program
{
static void Main(string[] args)
{
var max = 50;
Enumerable.Range(0, int.MaxValue)
.Select(Fib)
.TakeWhile(x => x <= 50)
.ToList()
.ForEach(Console.WriteLine);
}
static int Fib(int arg) =>
arg == 0 ? 0
: arg == 1 ? 1
: Fib(arg - 2) + Fib(arg - 1);
}
}
| using System;
using System.Linq;
namespace FibCSharp
{
class Program
{
static void Main(string[] args)
{
var max = 50;
Enumerable.Range(0, int.MaxValue)
.Select(Fib)
.TakeWhile(x => x <= max)
.ToList()
.ForEach(Console.WriteLine);
}
static int Fib(int arg) =>
arg == 0 ? 0
: arg == 1 ? 1
: Fib(arg - 2) + Fib(arg - 1);
}
}
|
Add the option of specifying a comparer. | using System;
using System.Collections.Generic;
namespace IvionSoft
{
public class History<T>
{
int length;
HashSet<T> hashes;
Queue<T> queue;
object _locker;
public History(int length)
{
if (length < 1)
throw new ArgumentException("Must be 1 or larger", "length");
this.length = length;
hashes = new HashSet<T>();
queue = new Queue<T>(length + 1);
_locker = new object();
}
public bool Contains(T item)
{
return hashes.Contains(item);
}
public bool Add(T item)
{
bool added;
lock (_locker)
{
added = hashes.Add(item);
if (added)
{
queue.Enqueue(item);
if (queue.Count > length)
{
T toRemove = queue.Dequeue();
hashes.Remove(toRemove);
}
}
}
return added;
}
}
} | using System;
using System.Collections.Generic;
namespace IvionSoft
{
public class History<T>
{
public int Length { get; private set; }
HashSet<T> hashes;
Queue<T> queue;
object _locker = new object();
public History(int length) : this(length, null)
{}
public History(int length, IEqualityComparer<T> comparer)
{
if (length < 1)
throw new ArgumentException("Must be 1 or larger", "length");
Length = length;
queue = new Queue<T>(length + 1);
if (comparer != null)
hashes = new HashSet<T>(comparer);
else
hashes = new HashSet<T>();
}
public bool Contains(T item)
{
return hashes.Contains(item);
}
public bool Add(T item)
{
bool added;
lock (_locker)
{
added = hashes.Add(item);
if (added)
{
queue.Enqueue(item);
if (queue.Count > Length)
{
T toRemove = queue.Dequeue();
hashes.Remove(toRemove);
}
}
}
return added;
}
}
} |
Update colour of spotlights playlist to match new specs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
public class RoomSpecialCategoryPill : OnlinePlayComposite
{
private SpriteText text;
public RoomSpecialCategoryPill()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChild = new PillContainer
{
Background =
{
Colour = colours.Pink,
Alpha = 1
},
Child = text = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12),
Colour = Color4.Black
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Category.BindValueChanged(c => text.Text = c.NewValue.ToString(), 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 osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Rooms;
using osuTK.Graphics;
namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
public class RoomSpecialCategoryPill : OnlinePlayComposite
{
private SpriteText text;
private PillContainer pill;
[Resolved]
private OsuColour colours { get; set; }
public RoomSpecialCategoryPill()
{
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = pill = new PillContainer
{
Background =
{
Colour = colours.Pink,
Alpha = 1
},
Child = text = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Font = OsuFont.GetFont(weight: FontWeight.SemiBold, size: 12),
Colour = Color4.Black
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Category.BindValueChanged(c =>
{
text.Text = c.NewValue.GetLocalisableDescription();
switch (c.NewValue)
{
case RoomCategory.Spotlight:
pill.Background.Colour = colours.Green2;
break;
case RoomCategory.FeaturedArtist:
pill.Background.Colour = colours.Blue2;
break;
}
}, true);
}
}
}
|
Add blocks not in order | namespace PegSharp.External
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BlockChain
{
private List<BlockData> blocks = new List<BlockData>();
private List<BlockData> others = new List<BlockData>();
public long Height { get { return blocks.Count; } }
public BlockData BestBlock
{
get
{
return this.blocks.Last();
}
}
public bool Add(BlockData block)
{
if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash)))
{
this.blocks.Add(block);
var children = this.others.Where(b => b.ParentHash.Equals(block.Hash));
foreach (var child in children) {
this.others.Remove(child);
this.Add(child);
}
return true;
}
others.Add(block);
return false;
}
}
}
| namespace PegSharp.External
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class BlockChain
{
private List<BlockData> blocks = new List<BlockData>();
private List<BlockData> others = new List<BlockData>();
public long Height { get { return blocks.Count; } }
public BlockData BestBlock
{
get
{
return this.blocks.Last();
}
}
public bool Add(BlockData block)
{
if ((this.blocks.Count == 0 && block.Number == 0) || (this.blocks.Count > 0 && this.BestBlock.Hash.Equals(block.ParentHash)))
{
this.blocks.Add(block);
var children = this.others.Where(b => b.ParentHash.Equals(block.Hash)).ToList();
foreach (var child in children) {
this.others.Remove(child);
this.Add(child);
}
return true;
}
others.Add(block);
return false;
}
}
}
|
Use one way function protocol for bit commitment | using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages.
/// </summary>
public class BitCommitmentEngine
{
#region properties
public byte[] BobRandBytesR { get; set; }
public byte[] AliceEncryptedMessage { get; set; }
#endregion
}
}
| using System;
namespace BitCommitment
{
/// <summary>
/// A class to perform bit commitment. It does not care what the input is; it's just a
/// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
/// function method for committing bits
/// </summary>
public class BitCommitmentEngine
{
public byte[] AliceRandBytes1 { get; set; }
public byte[] AliceRandBytes2 { get; set; }
public byte[] AliceMessageBytesBytes { get; set; }
public BitCommitmentEngine(byte[] one, byte[] two, byte[] messageBytes)
{
AliceRandBytes1 = one;
AliceRandBytes2 = two;
AliceMessageBytesBytes = messageBytes;
}
}
}
|
Make a proper view model | /*
* Created by SharpDevelop.
* User: Lars Magnus
* Date: 12.06.2014
* Time: 20:54
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Text;
using Nancy;
using SubmittedData;
namespace Modules
{
/// <summary>
/// Description of WebService.
/// </summary>
public class RootMenuModule : NancyModule
{
private ITournament _tournament;
public RootMenuModule(ITournament tournament)
{
_tournament = tournament;
var groups = new Groups() { Tournament = _tournament.GetName() };
Get["/"] = _ => {
return View["groups.sshtml", groups];
};
}
private string PrintGroups()
{
StringBuilder s = new StringBuilder();
s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName());
char gn = 'A';
foreach (object[] group in _tournament.GetGroups())
{
s.AppendLine("Group " + gn);
foreach (var team in group)
{
s.AppendLine(team.ToString());
}
gn++;
}
return s.ToString();
}
}
class Groups
{
public string Tournament { get; set; }
}
}
| /*
* Created by SharpDevelop.
* User: Lars Magnus
* Date: 12.06.2014
* Time: 20:54
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Text;
using Nancy;
using SubmittedData;
namespace Modules
{
/// <summary>
/// Description of WebService.
/// </summary>
public class RootMenuModule : NancyModule
{
public RootMenuModule(ITournament tournament)
{
Get["/"] = _ => {
return View["groups.sshtml", new GroupsViewModel(tournament)];
};
}
}
public class GroupsViewModel
{
public string Tournament
{
get { return _tournament.GetName(); }
}
ITournament _tournament;
public GroupsViewModel(ITournament t)
{
_tournament = t;
}
private string PrintGroups()
{
StringBuilder s = new StringBuilder();
s.AppendFormat("Welcome to {0} betting scores\n", _tournament.GetName());
char gn = 'A';
foreach (object[] group in _tournament.GetGroups())
{
s.AppendLine("Group " + gn);
foreach (var team in group)
{
s.AppendLine(team.ToString());
}
gn++;
}
return s.ToString();
}
}
}
|
Change some intro settings property names | using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Classes
{
[ExpandableObject]
[DisplayName("Intro Settings")]
public class IntroData
{
[DisplayName("Duration")]
public int Duration { get; set; } = -1;
[DisplayName("Reversable")]
public bool Reversable { get; set; } = false;
[DisplayName("Activate")]
public bool Activate { get; set; } = false;
[DisplayName("Hide On Finish")]
public bool HideOnFinish { get; set; } = true;
[DisplayName("Execute Finish Action")]
public bool ExecuteFinishAction { get; set; } = true;
}
} | using System.ComponentModel;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
namespace DesktopWidgets.Classes
{
[ExpandableObject]
[DisplayName("Intro Settings")]
public class IntroData
{
[DisplayName("Duration")]
public int Duration { get; set; } = -1;
[DisplayName("Reversable")]
public bool Reversable { get; set; } = false;
[DisplayName("Activate")]
public bool Activate { get; set; } = false;
[DisplayName("Hide On End")]
public bool HideOnFinish { get; set; } = true;
[DisplayName("Trigger End Event")]
public bool ExecuteFinishAction { get; set; } = true;
}
} |
Use timer rather than blocking sleep | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
public class Chat : Hub
{
public void SayHello()
{
while (true)
{
Clients.All.addMessage("Date time : "+DateTime.Now);
Thread.Sleep(500);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using System.Web;
using Microsoft.AspNet.SignalR;
using Timer = System.Timers.Timer;
namespace SignalRDemo.Hubs
{
public class Chat : Hub
{
static string messageToSend = DateTime.Now.ToString();
Timer t = new Timer(500);
public void SayHello()
{
t.Elapsed +=t_Elapsed;
t.Start();
}
private void t_Elapsed(object sender, ElapsedEventArgs e)
{
Clients.All.addMessage("Date time : " + messageToSend);
messageToSend = DateTime.Now.ToString();
}
}
} |
Switch to not serialize the full embed object | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers.API
{
public class EmbedsController : ApiController
{
public EmbedsController(Database db) : base(db)
{
// Nothing to do here
}
[HttpGet]
public IEnumerable<Embed> List()
{
return db.Embeds.ToList();
}
[HttpPost]
public async Task<IActionResult> Create([FromBody]Embed embed)
{
db.Embeds.Add(embed);
await db.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id);
db.Embeds.Remove(embed);
await db.SaveChangesAsync();
return Ok();
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Controllers.API
{
public class EmbedsController : ApiController
{
public EmbedsController(Database db) : base(db)
{
// Nothing to do here
}
[HttpGet]
public async Task<IEnumerable<dynamic>> List()
{
return
await db
.Embeds
.Select(embed => new
{
embed.Id,
embed.UnitId,
embed.Name,
embed.Route,
embed.Source
})
.ToListAsync();
}
[HttpPost]
public async Task<IActionResult> Create([FromBody]Embed embed)
{
db.Embeds.Add(embed);
await db.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var embed = await db.Embeds.SingleOrDefaultAsync(_ => _.Id == id);
db.Embeds.Remove(embed);
await db.SaveChangesAsync();
return Ok();
}
}
} |
Add a 5% chance for attacks to be critical hits, which ignore defense. | using Roguelike.UI;
using System;
namespace Roguelike.Entities.Components
{
public class FighterComponent : Component
{
public int MaximumHealth { get; set; }
public int CurrentHealth { get; set; }
public int Power { get; set; }
public int Defense { get; set; }
public Action<Entity> DeathFunction { get; set; }
public void Damage(int amount)
{
CurrentHealth -= amount;
if (CurrentHealth <= 0)
{
DeathFunction?.Invoke(Entity);
}
}
public void Attack(Entity target)
{
if (target.GetComponent<FighterComponent>() == null)
{
return;
}
var damage = Power - target.GetComponent<FighterComponent>().Defense;
if (damage > 0)
{
MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP.");
target.GetComponent<FighterComponent>().Damage(damage);
}
else
{
MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!");
}
}
}
}
| using Roguelike.UI;
using System;
namespace Roguelike.Entities.Components
{
public class FighterComponent : Component
{
public const float CriticalHitChance = 0.05f;
public int MaximumHealth { get; set; }
public int CurrentHealth { get; set; }
public int Power { get; set; }
public int Defense { get; set; }
public Action<Entity> DeathFunction { get; set; }
public void Damage(int amount)
{
CurrentHealth -= amount;
if (CurrentHealth <= 0)
{
DeathFunction?.Invoke(Entity);
}
}
public void Attack(Entity target)
{
if (target.GetComponent<FighterComponent>() == null)
{
return;
}
int damage = 0;
if (Program.Random.NextDouble() < CriticalHitChance)
{
damage = Power;
}
else
{
damage = Power - target.GetComponent<FighterComponent>().Defense;
}
if (damage > 0)
{
MessageLog.Add($"{Entity.Name} attacks {target.Name} for {damage} HP.");
target.GetComponent<FighterComponent>().Damage(damage);
}
else
{
MessageLog.Add($"{Entity.Name} attacks {target.Name} but it has no effect!");
}
}
}
}
|
Change model and EF errors with schema change | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstMigrations
{
public class Address
{
public Int32 Id { get; set; }
public Int32 HouseNumber { get; set; }
public String Street { get; set; }
public String City { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstMigrations
{
public class Address
{
public Int32 Id { get; set; }
public Int32 HouseNumber { get; set; }
public String Street { get; set; }
public String City { get; set; }
public String Postcode { get; set; }
}
}
|
Change the order of the columns in CSV export | using BSParser.Data;
using CsvHelper;
using System.IO;
using System.Text;
namespace BSParser.Writers
{
public class StrictCSVWriter : Writer
{
private string _fileName;
public StrictCSVWriter(string fileName)
{
_fileName = fileName;
}
public override bool Write(StatementTable data)
{
using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8))
{
var csv = new CsvWriter(sw);
csv.Configuration.Delimiter = ";";
csv.WriteRecords(data);
}
return true;
}
}
}
| using BSParser.Data;
using CsvHelper;
using System.IO;
using System.Linq;
using System.Text;
namespace BSParser.Writers
{
public class StrictCSVWriter : Writer
{
private string _fileName;
public StrictCSVWriter(string fileName)
{
_fileName = fileName;
}
public override bool Write(StatementTable data)
{
if (!data.Any()) return false;
var orderedData = data.Select(x => new
{
x.Category,
x.RefNum,
x.DocNum,
x.Amount,
x.Direction,
x.RegisteredOn,
x.Description,
x.PayerINN,
x.PayerName,
x.ReceiverINN,
x.ReceiverName
});
using (var sw = new StreamWriter(_fileName, false, Encoding.UTF8))
{
var csv = new CsvWriter(sw);
csv.Configuration.Delimiter = ";";
csv.WriteRecords(orderedData);
}
return true;
}
}
}
|
Add game version to the results (for e.g. heavy rain) | using CompatApiClient.Utils;
using DSharpPlus.Entities;
using IrdLibraryClient;
using IrdLibraryClient.POCOs;
namespace CompatBot.Utils.ResultFormatters
{
public static class IrdSearchResultFormattercs
{
public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult)
{
var result = new DiscordEmbedBuilder
{
//Title = "IRD Library Search Result",
Color = Config.Colors.DownloadLinks,
};
if (searchResult.Data.Count == 0)
{
result.Color = Config.Colors.LogResultFailed;
result.Description = "No matches were found";
return result;
}
foreach (var item in searchResult.Data)
{
var parts = item.Filename?.Split('-');
if (parts == null)
parts = new string[] {null, null};
else if (parts.Length == 1)
parts = new[] {null, item.Filename};
result.AddField(
$"[{parts?[0]}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}",
$"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)}) ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})"
);
}
return result;
}
}
}
| using CompatApiClient.Utils;
using DSharpPlus.Entities;
using IrdLibraryClient;
using IrdLibraryClient.POCOs;
namespace CompatBot.Utils.ResultFormatters
{
public static class IrdSearchResultFormattercs
{
public static DiscordEmbedBuilder AsEmbed(this SearchResult searchResult)
{
var result = new DiscordEmbedBuilder
{
//Title = "IRD Library Search Result",
Color = Config.Colors.DownloadLinks,
};
if (searchResult.Data.Count == 0)
{
result.Color = Config.Colors.LogResultFailed;
result.Description = "No matches were found";
return result;
}
foreach (var item in searchResult.Data)
{
var parts = item.Filename?.Split('-');
if (parts == null)
parts = new string[] {null, null};
else if (parts.Length == 1)
parts = new[] {null, item.Filename};
result.AddField(
$"[{parts?[0]} v{item.GameVersion}] {item.Title?.Sanitize().Trim(EmbedPager.MaxFieldTitleLength)}",
$"⏬ [`{parts[1]?.Sanitize().Trim(200)}`]({IrdClient.GetDownloadLink(item.Filename)}) ℹ [Info]({IrdClient.GetInfoLink(item.Filename)})"
);
}
return result;
}
}
}
|
Add test for ListaAutores method | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Livraria;
namespace LivrariaTest
{
[TestClass]
public class AutorTest
{
[TestMethod]
public void TestProperties()
{
Autor autor = new Autor();
autor.CodAutor = 999;
autor.Nome = "George R. R. Martin";
autor.Cpf = "012.345.678.90";
autor.DtNascimento = new DateTime(1948, 9, 20);
Assert.AreEqual(autor.CodAutor, 999);
Assert.AreEqual(autor.Nome, "George R. R. Martin");
Assert.AreEqual(autor.Cpf, "012.345.678.90");
Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Livraria;
using System.Collections.Generic;
namespace LivrariaTest
{
[TestClass]
public class AutorTest
{
[TestMethod]
public void TestProperties()
{
Autor autor = new Autor();
autor.CodAutor = 999;
autor.Nome = "George R. R. Martin";
autor.Cpf = "012.345.678.90";
autor.DtNascimento = new DateTime(1948, 9, 20);
Assert.AreEqual(autor.CodAutor, 999);
Assert.AreEqual(autor.Nome, "George R. R. Martin");
Assert.AreEqual(autor.Cpf, "012.345.678.90");
Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20));
}
[TestMethod]
public void TestListaAutores()
{
Autor autor = new Autor();
List<Autor> lstAutores = autor.ListaAutores();
foreach (var aut in lstAutores)
{
Assert.IsInstanceOfType(aut, typeof(Autor));
}
}
}
}
|
Use correct TBT_LINEAR_TARGET shader feature keyword. | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
namespace TiltBrushToolkit {
[InitializeOnLoad]
public class GammaSettings : EditorWindow {
static ColorSpace m_LastColorSpace;
static GammaSettings() {
EditorApplication.update += OnUpdate;
SetKeywords();
m_LastColorSpace = PlayerSettings.colorSpace;
}
static void OnUpdate() {
if (m_LastColorSpace != PlayerSettings.colorSpace) {
SetKeywords();
m_LastColorSpace = PlayerSettings.colorSpace;
}
}
static void SetKeywords() {
bool linear = PlayerSettings.colorSpace == ColorSpace.Linear;
if (linear) {
Shader.DisableKeyword("FORCE_SRGB");
} else {
Shader.EnableKeyword("FORCE_SRGB");
}
}
}
} | // Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
namespace TiltBrushToolkit {
[InitializeOnLoad]
public class GammaSettings : EditorWindow {
static ColorSpace m_LastColorSpace;
static GammaSettings() {
EditorApplication.update += OnUpdate;
SetKeywords();
m_LastColorSpace = PlayerSettings.colorSpace;
}
static void OnUpdate() {
if (m_LastColorSpace != PlayerSettings.colorSpace) {
SetKeywords();
m_LastColorSpace = PlayerSettings.colorSpace;
}
}
static void SetKeywords() {
bool linear = PlayerSettings.colorSpace == ColorSpace.Linear;
if (linear) {
Shader.EnableKeyword("TBT_LINEAR_TARGET");
} else {
Shader.DisableKeyword("TBT_LINEAR_TARGET");
}
}
}
} |
Allow bass sample channels to overwrite older ones by default. | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using ManagedBass;
using System;
using System.Collections.Concurrent;
namespace osu.Framework.Audio.Sample
{
internal class SampleBass : Sample, IBassAudio
{
private volatile int sampleId;
public override bool IsLoaded => sampleId != 0;
public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null)
{
if (customPendingActions != null)
PendingActions = customPendingActions;
PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default); });
}
protected override void Dispose(bool disposing)
{
Bass.SampleFree(sampleId);
base.Dispose(disposing);
}
void IBassAudio.UpdateDevice(int deviceIndex)
{
if (IsLoaded)
// counter-intuitively, this is the correct API to use to migrate a sample to a new device.
Bass.ChannelSetDevice(sampleId, deviceIndex);
}
public int CreateChannel() => Bass.SampleGetChannel(sampleId);
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using ManagedBass;
using System;
using System.Collections.Concurrent;
namespace osu.Framework.Audio.Sample
{
internal class SampleBass : Sample, IBassAudio
{
private volatile int sampleId;
public override bool IsLoaded => sampleId != 0;
public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null)
{
if (customPendingActions != null)
PendingActions = customPendingActions;
PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default | BassFlags.SampleOverrideLongestPlaying); });
}
protected override void Dispose(bool disposing)
{
Bass.SampleFree(sampleId);
base.Dispose(disposing);
}
void IBassAudio.UpdateDevice(int deviceIndex)
{
if (IsLoaded)
// counter-intuitively, this is the correct API to use to migrate a sample to a new device.
Bass.ChannelSetDevice(sampleId, deviceIndex);
}
public int CreateChannel() => Bass.SampleGetChannel(sampleId);
}
}
|
Fix - Modificata notifica delete utente | using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
| using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
//await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
//await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
|
Add explanation of why having 2 yield return | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Wangkanai.Detection.Hosting
{
public class ResponsivePageLocationExpander : IViewLocationExpander
{
private const string ValueKey = "device";
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
context.Values.TryGetValue(ValueKey, out var device);
if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
return viewLocations;
if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
return viewLocations;
var expandLocations = ExpandPageHierarchy().ToList();
return expandLocations;
IEnumerable<string> ExpandPageHierarchy()
{
foreach (var location in viewLocations)
{
if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
{
yield return location;
continue;
}
yield return location.Replace("{0}", "{0}." + device);
yield return location;
}
}
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
}
}
} | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Wangkanai.Detection.Hosting
{
public class ResponsivePageLocationExpander : IViewLocationExpander
{
private const string ValueKey = "device";
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
context.Values.TryGetValue(ValueKey, out var device);
if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
return viewLocations;
if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
return viewLocations;
var expandLocations = ExpandPageHierarchy().ToList();
return expandLocations;
IEnumerable<string> ExpandPageHierarchy()
{
foreach (var location in viewLocations)
{
if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
{
yield return location;
continue;
}
// Device View if exist on disk
yield return location.Replace("{0}", "{0}." + device);
// Fallback to the original default view
yield return location;
}
}
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
}
}
} |
Remove Seq compact flag, default now | namespace BatteryCommander.Web
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
| namespace BatteryCommander.Web
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
|
Allow reading numbers from strings in JSON | using System;
using System.Data;
using System.Text.Json;
using Dapper;
namespace Dommel.Json
{
internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
{
private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};
public void SetValue(IDbDataParameter parameter, object? value)
{
parameter.Value = value is null || value is DBNull
? (object)DBNull.Value
: JsonSerializer.Serialize(value, JsonOptions);
parameter.DbType = DbType.String;
}
public object? Parse(Type destinationType, object? value) =>
value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
}
}
| using System;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Dapper;
namespace Dommel.Json
{
internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};
public void SetValue(IDbDataParameter parameter, object? value)
{
parameter.Value = value is null || value is DBNull
? DBNull.Value
: JsonSerializer.Serialize(value, JsonOptions);
parameter.DbType = DbType.String;
}
public object? Parse(Type destinationType, object? value) =>
value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
}
}
|
Fix plugin script generator causing JS syntax error | using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("});");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
| using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("};");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
|
Add empty to null check | using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreecraftCore.Serializer.Tests
{
[TestFixture]
public class StringTests
{
[Test]
public static void Test_String_Serializer_Serializes()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));
//assert
Assert.AreEqual(value, "Hello!");
}
}
}
| using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreecraftCore.Serializer.Tests
{
[TestFixture]
public class StringTests
{
[Test]
public static void Test_String_Serializer_Serializes()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));
//assert
Assert.AreEqual(value, "Hello!");
}
[Test]
public static void Test_String_Serializer_Can_Serialize_Empty_String()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize(""));
//assert
Assert.Null(value);
}
}
}
|
Resolve binding exception on netfx. | using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace AudioWorks.Extensions
{
abstract class ExtensionContainerBase
{
static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
"Extensions"));
protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
.WithAssemblies(_extensionRoot
.EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
.Select(f => f.FullName)
.Select(Assembly.LoadFrom))
.CreateContainer();
static ExtensionContainerBase()
{
// Search all extension directories for unresolved references
// .NET Core
AssemblyLoadContext.Default.Resolving += (context, name) =>
AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
// Full Framework
AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
Assembly.LoadFrom(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
}
}
}
| using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
namespace AudioWorks.Extensions
{
abstract class ExtensionContainerBase
{
static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
"Extensions"));
protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
.WithAssemblies(_extensionRoot
.EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
.Select(f => f.FullName)
.Select(Assembly.LoadFrom))
.CreateContainer();
static ExtensionContainerBase()
{
// Search all extension directories for unresolved references
// Assembly.LoadFrom only works on the full framework
if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework",
StringComparison.Ordinal))
AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
Assembly.LoadFrom(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
// Use AssemblyLoadContext on .NET Core
else
UseAssemblyLoadContext();
}
static void UseAssemblyLoadContext()
{
// Workaround - this needs to reside in a separate method to avoid a binding exception with the desktop
// framework, as System.Runtime.Loader does not include a net462 library.
AssemblyLoadContext.Default.Resolving += (context, name) =>
AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
}
}
}
|
Add link to Markdown help | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
} | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
} |
Switch to OrdinalIgnoreCase comparison for PackageReference deduplication | using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Microsoft.NET.Build.Tasks
{
public class CheckForImplicitPackageReferenceOverrides : TaskBase
{
const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";
[Required]
public ITaskItem [] PackageReferenceItems { get; set; }
[Required]
public string MoreInformationLink { get; set; }
[Output]
public ITaskItem[] ItemsToRemove { get; set; }
protected override void ExecuteCore()
{
var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec.ToLowerInvariant()).Where(g => g.Count() > 1);
var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));
ItemsToRemove = duplicateItemsToRemove.ToArray();
foreach (var itemToRemove in ItemsToRemove)
{
string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
itemToRemove.ItemSpec,
MoreInformationLink);
Log.LogWarning(message);
}
}
}
}
| using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Microsoft.NET.Build.Tasks
{
public class CheckForImplicitPackageReferenceOverrides : TaskBase
{
const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";
[Required]
public ITaskItem [] PackageReferenceItems { get; set; }
[Required]
public string MoreInformationLink { get; set; }
[Output]
public ITaskItem[] ItemsToRemove { get; set; }
protected override void ExecuteCore()
{
var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1);
var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));
ItemsToRemove = duplicateItemsToRemove.ToArray();
foreach (var itemToRemove in ItemsToRemove)
{
string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
itemToRemove.ItemSpec,
MoreInformationLink);
Log.LogWarning(message);
}
}
}
}
|
Remove extra tab in the script template. | using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
| using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
|
Fix closing tag on iframe | namespace Ooui
{
public class Iframe : Element
{
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
public Iframe ()
: base ("iframe")
{
}
}
}
| namespace Ooui
{
public class Iframe : Element
{
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
public Iframe ()
: base ("iframe")
{
}
protected override bool HtmlNeedsFullEndElement => true;
}
}
|
Make decal on despawn script use void. | using UnityEngine;
namespace Weapons.Projectiles.Behaviours
{
/// <summary>
/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
/// </summary>
public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
{
[SerializeField] private GameObject decal = null;
[Tooltip("Living time of decal.")]
[SerializeField] private float animationTime = 0;
[Tooltip("Spawn decal on collision?")]
[SerializeField] private bool isTriggeredOnHit = true;
public void OnDespawn(RaycastHit2D hit, Vector2 point)
{
if (isTriggeredOnHit && hit.collider != null)
{
OnBeamEnd(hit.point);
}
else
{
OnBeamEnd(point);
}
}
private bool OnBeamEnd(Vector2 position)
{
var newDecal = Spawn.ClientPrefab(decal.name,
position).GameObject;
var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
timeLimitedDecal.SetUpDecal(animationTime);
return false;
}
}
} | using UnityEngine;
namespace Weapons.Projectiles.Behaviours
{
/// <summary>
/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
/// </summary>
public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
{
[SerializeField] private GameObject decal = null;
[Tooltip("Living time of decal.")]
[SerializeField] private float animationTime = 0;
[Tooltip("Spawn decal on collision?")]
[SerializeField] private bool isTriggeredOnHit = true;
public void OnDespawn(RaycastHit2D hit, Vector2 point)
{
if (isTriggeredOnHit && hit.collider != null)
{
OnBeamEnd(hit.point);
}
else
{
OnBeamEnd(point);
}
}
private void OnBeamEnd(Vector2 position)
{
var newDecal = Spawn.ClientPrefab(decal.name,
position).GameObject;
var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
timeLimitedDecal.SetUpDecal(animationTime);
}
}
} |
Fix search result when returning multiple results | @using Hops.Models;
@model ListModel<HopModel>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Search results - Hops";
}
@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{
<h3>Search results for "@Model.Pagination.SearchTerm":</h3>
}
@Html.Partial("~/Views/Hop/List", Model) | @using Hops.Models;
@model ListModel<HopModel>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Search results - Hops";
}
@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{
<h3>Search results for "@Model.Pagination.SearchTerm":</h3>
}
@Html.Partial("~/Views/Hop/List.cshtml", Model) |
Return an empty string for / on markdig webapi | using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;
namespace Markdig.WebApp
{
public class ApiController : Controller
{
// GET api/to_html?text=xxx&extensions=advanced
[Route("api/to_html")]
[HttpGet()]
public object Get([FromQuery] string text, [FromQuery] string extension)
{
try
{
if (text == null)
{
text = string.Empty;
}
if (text.Length > 1000)
{
text = text.Substring(0, 1000);
}
var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
var result = Markdown.ToHtml(text, pipeline);
return new {name = "markdig", html = result, version = Markdown.Version};
}
catch (Exception ex)
{
return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
}
}
private static string GetPrettyMessageFromException(Exception exception)
{
var builder = new StringBuilder();
while (exception != null)
{
builder.Append(exception.Message);
exception = exception.InnerException;
}
return builder.ToString();
}
}
}
| using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;
namespace Markdig.WebApp
{
public class ApiController : Controller
{
[HttpGet()]
[Route("")]
public string Empty()
{
return string.Empty;
}
// GET api/to_html?text=xxx&extensions=advanced
[Route("api/to_html")]
[HttpGet()]
public object Get([FromQuery] string text, [FromQuery] string extension)
{
try
{
if (text == null)
{
text = string.Empty;
}
if (text.Length > 1000)
{
text = text.Substring(0, 1000);
}
var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
var result = Markdown.ToHtml(text, pipeline);
return new {name = "markdig", html = result, version = Markdown.Version};
}
catch (Exception ex)
{
return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
}
}
private static string GetPrettyMessageFromException(Exception exception)
{
var builder = new StringBuilder();
while (exception != null)
{
builder.Append(exception.Message);
exception = exception.InnerException;
}
return builder.ToString();
}
}
}
|
Allow conversion of UInt64 based enums | using System;
namespace Python.Runtime.Codecs
{
[Obsolete]
public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder
{
public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec();
public bool CanDecode(PyType objectType, Type targetType)
{
return targetType.IsEnum
&& objectType.IsSubclass(Runtime.PyLongType);
}
public bool CanEncode(Type type)
{
return type == typeof(object) || type == typeof(ValueType) || type.IsEnum;
}
public bool TryDecode<T>(PyObject pyObj, out T? value)
{
value = default;
if (!typeof(T).IsEnum) return false;
Type etype = Enum.GetUnderlyingType(typeof(T));
if (!PyInt.IsIntType(pyObj)) return false;
object? result;
try
{
result = pyObj.AsManagedObject(etype);
}
catch (InvalidCastException)
{
return false;
}
if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum())
{
value = (T)Enum.ToObject(typeof(T), result);
return true;
}
return false;
}
public PyObject? TryEncode(object value)
{
if (value is null) return null;
var enumType = value.GetType();
if (!enumType.IsEnum) return null;
return new PyInt(Convert.ToInt64(value));
}
private EnumPyIntCodec() { }
}
}
| using System;
namespace Python.Runtime.Codecs
{
[Obsolete]
public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder
{
public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec();
public bool CanDecode(PyType objectType, Type targetType)
{
return targetType.IsEnum
&& objectType.IsSubclass(Runtime.PyLongType);
}
public bool CanEncode(Type type)
{
return type == typeof(object) || type == typeof(ValueType) || type.IsEnum;
}
public bool TryDecode<T>(PyObject pyObj, out T? value)
{
value = default;
if (!typeof(T).IsEnum) return false;
Type etype = Enum.GetUnderlyingType(typeof(T));
if (!PyInt.IsIntType(pyObj)) return false;
object? result;
try
{
result = pyObj.AsManagedObject(etype);
}
catch (InvalidCastException)
{
return false;
}
if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum())
{
value = (T)Enum.ToObject(typeof(T), result);
return true;
}
return false;
}
public PyObject? TryEncode(object value)
{
if (value is null) return null;
var enumType = value.GetType();
if (!enumType.IsEnum) return null;
try
{
return new PyInt(Convert.ToInt64(value));
}
catch (OverflowException)
{
return new PyInt(Convert.ToUInt64(value));
}
}
private EnumPyIntCodec() { }
}
}
|
Remove DebuggerDisplay attribute not applicable anymore | using System;
using System.Diagnostics;
namespace Nett
{
[DebuggerDisplay("{FromType} -> {ToType}")]
internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo>
{
private readonly Func<TFrom, TTo> convert;
public TomlConverter(Func<TFrom, TTo> convert)
{
if (convert == null) { throw new ArgumentNullException(nameof(convert)); }
this.convert = convert;
}
public override TTo Convert(TFrom from, Type targetType) => this.convert(from);
}
}
| using System;
namespace Nett
{
internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo>
{
private readonly Func<TFrom, TTo> convert;
public TomlConverter(Func<TFrom, TTo> convert)
{
if (convert == null) { throw new ArgumentNullException(nameof(convert)); }
this.convert = convert;
}
public override TTo Convert(TFrom from, Type targetType) => this.convert(from);
}
}
|
Make all strings in loaded TdfNodes lowercase | namespace TAUtil.Tdf
{
using System.Collections.Generic;
public class TdfNodeAdapter : ITdfNodeAdapter
{
private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>();
public TdfNodeAdapter()
{
this.RootNode = new TdfNode();
this.nodeStack.Push(this.RootNode);
}
public TdfNode RootNode { get; private set; }
public void BeginBlock(string name)
{
TdfNode n = new TdfNode(name);
this.nodeStack.Peek().Keys[name] = n;
this.nodeStack.Push(n);
}
public void AddProperty(string name, string value)
{
this.nodeStack.Peek().Entries[name] = value;
}
public void EndBlock()
{
this.nodeStack.Pop();
}
}
}
| namespace TAUtil.Tdf
{
using System.Collections.Generic;
public class TdfNodeAdapter : ITdfNodeAdapter
{
private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>();
public TdfNodeAdapter()
{
this.RootNode = new TdfNode();
this.nodeStack.Push(this.RootNode);
}
public TdfNode RootNode { get; private set; }
public void BeginBlock(string name)
{
name = name.ToLowerInvariant();
TdfNode n = new TdfNode(name);
this.nodeStack.Peek().Keys[name] = n;
this.nodeStack.Push(n);
}
public void AddProperty(string name, string value)
{
name = name.ToLowerInvariant();
value = value.ToLowerInvariant();
this.nodeStack.Peek().Entries[name] = value;
}
public void EndBlock()
{
this.nodeStack.Pop();
}
}
}
|
Update UI look and feel | @model ChatApp.Controllers.ChatMessagesViewModel
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using ChatApp.Models
<!DOCTYPE html>
<html>
<head>
<title>ChatApp</title>
</head>
<body>
<table>
@foreach (Message msg in Model.OldMessages)
{
<tr>
<td class="author">@msg.Author</td>
<td class="text">@msg.Text</td>
<td class="timestamp">@msg.Timestamp</td>
</tr>
}
</table>
<form asp-action="SendNewMessage" method="post">
<input asp-for="NewMessage.Author"/>
<input asp-for="NewMessage.Text"/>
<input type="submit" value="Send"/>
</form>
</body>
</html>
| @model ChatApp.Controllers.ChatMessagesViewModel
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using ChatApp.Models
<!DOCTYPE html>
<html>
<head>
<title>ChatApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" async>
</head>
<body>
<table class="w3-table w3-striped">
@foreach (Message msg in Model.OldMessages)
{
<tr>
<td name="author" class="w3-right-align" style="width: 10em;">@msg.Author:</td>
<td name="text">@msg.Text</td>
<td name="timestamp" class="w3-right-align">@msg.Timestamp</td>
</tr>
}
</table>
<form asp-action="SendNewMessage" method="post" class="w3-row">
<input asp-for="NewMessage.Author" class="w3-input w3-border w3-col m2" placeholder="Name"/>
<input asp-for="NewMessage.Text" class="w3-input w3-border w3-col m8" placeholder="Message"/>
<input type="submit" value="Send" class="w3-btn w3-blue w3-col w3-large m2"/>
</form>
</body>
</html>
|
Align XSD Doc version number with SHFB | using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright(XsdDocMetadata.Copyright)]
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("XML Schema Documenter")]
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion(XsdDocMetadata.Version)]
[assembly: AssemblyFileVersion(XsdDocMetadata.Version)]
internal static class XsdDocMetadata
{
public const string Version = "15.10.10.0";
public const string Copyright = "Copyright 2009-2015 Immo Landwerth";
} | using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCopyright(XsdDocMetadata.Copyright)]
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("XML Schema Documenter")]
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion(XsdDocMetadata.Version)]
[assembly: AssemblyFileVersion(XsdDocMetadata.Version)]
internal static class XsdDocMetadata
{
public const string Version = "16.9.17.0";
public const string Copyright = "Copyright 2009-2015 Immo Landwerth";
} |
Increment copyright year of projects to 2019 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2018")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
|
Add support for XOR in PostgreSQL | using SimpleStack.Orm.Expressions;
namespace SimpleStack.Orm.PostgreSQL
{
/// <summary>A postgre SQL expression visitor.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T>
{
public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider)
{
}
/// <summary>Gets the limit expression.</summary>
/// <value>The limit expression.</value>
public override string LimitExpression{
get{
if(!Rows.HasValue) return "";
string offset;
if(Skip.HasValue){
offset= string.Format(" OFFSET {0}", Skip.Value );
}
else{
offset=string.Empty;
}
return string.Format("LIMIT {0}{1}", Rows.Value, offset);
}
}
}
} | using System.Linq.Expressions;
using SimpleStack.Orm.Expressions;
namespace SimpleStack.Orm.PostgreSQL
{
/// <summary>A postgre SQL expression visitor.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T>
{
public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider)
{
}
protected override string BindOperant(ExpressionType e)
{
switch (e)
{
case ExpressionType.ExclusiveOr:
return "#";
}
return base.BindOperant(e);
}
/// <summary>Gets the limit expression.</summary>
/// <value>The limit expression.</value>
public override string LimitExpression{
get{
if(!Rows.HasValue) return "";
string offset;
if(Skip.HasValue){
offset= string.Format(" OFFSET {0}", Skip.Value );
}
else{
offset=string.Empty;
}
return string.Format("LIMIT {0}{1}", Rows.Value, offset);
}
}
}
} |
Update to Problem 3. Check for a Play Card | /*Problem 3. Check for a Play Card
Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A.
Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples:
character Valid card sign?
5 yes
1 no
Q yes
q no
P no
10 yes
500 no
*/
using System;
class CheckPlayCard
{
static void Main()
{
Console.Title = "Check for a Play Card"; //Changing the title of the console.
Console.Write("Please, enter a play card sign to check if it is valid: ");
string cardSign = Console.ReadLine();
switch (cardSign)
{
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "10":
case "J":
case "Q":
case "K":
case "A": Console.WriteLine("\nValid card sign?\nyes"); break;
default: Console.WriteLine("\nValid card sign?\nno"); break;
}
Console.ReadKey(); // Keeping the console opened.
}
} | /*Problem 3. Check for a Play Card
Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A.
Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples:
character Valid card sign?
5 yes
1 no
Q yes
q no
P no
10 yes
500 no
*/
using System;
class CheckPlayCard
{
static void Main()
{
Console.Title = "Check for a Play Card"; //Changing the title of the console.
Console.Write("Please, enter a play card sign to check if it is valid: ");
string cardSign = Console.ReadLine();
switch (cardSign)
{
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "10":
case "J":
case "Q":
case "K":
case "A": Console.WriteLine("\r\nValid card sign?\r\nyes"); break;
default: Console.WriteLine("\r\nValid card sign?\r\nno"); break;
}
Console.ReadKey(); // Keeping the console opened.
}
} |
Use AndroidClientHandler for android & NSUrlSessionHandler for iOS by default in bit cs client | using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Bit.ViewModel.Implementations
{
public class BitHttpClientHandler : HttpClientHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// ToDo:
// Current-Time-Zone
// Desired-Time-Zone
// Client-App-Version
// Client-Culture
// Client-Route
// Client-Theme
// Client-Debug-Mode
// System-Language
// Client-Sys-Language
// Client-Platform
// ToDo: Use IDeviceService & IDateTimeProvider
request.Headers.Add("Client-Type", "Xamarin");
if (Device.Idiom != TargetIdiom.Unsupported)
request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet");
request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o"));
request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString());
request.Headers.Add("Bit-Client-Type", "CS-Client");
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
}
| using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Bit.ViewModel.Implementations
{
public class BitHttpClientHandler :
#if Android
Xamarin.Android.Net.AndroidClientHandler
#elif iOS
NSUrlSessionHandler
#else
HttpClientHandler
#endif
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// ToDo:
// Current-Time-Zone
// Desired-Time-Zone
// Client-App-Version
// Client-Culture
// Client-Route
// Client-Theme
// Client-Debug-Mode
// System-Language
// Client-Sys-Language
// Client-Platform
// ToDo: Use IDeviceService & IDateTimeProvider
request.Headers.Add("Client-Type", "Xamarin");
if (Device.Idiom != TargetIdiom.Unsupported)
request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet");
request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o"));
request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString());
request.Headers.Add("Bit-Client-Type", "CS-Client");
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
}
|
Make sure GetIdValue returns a unique value per object. | using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla;
namespace DataBindingApp
{
[Serializable()]
public class ListObject : BusinessListBase<ListObject, ListObject.DataObject>
{
[Serializable()]
public class DataObject : BusinessBase<DataObject>
{
private int _ID;
private string _data;
private int _number;
public int Number
{
get { return _number; }
set { _number = value; }
}
public string Data
{
get { return _data; }
set { _data = value; }
}
public int ID
{
get { return _ID; }
set { _ID = value; }
}
protected override object GetIdValue()
{
return _ID;
}
public DataObject(string data, int number)
{
this.MarkAsChild();
_data = data;
_number = number;
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged);
}
public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Console.WriteLine("Property has changed");
}
}
private ListObject()
{ }
public static ListObject GetList()
{
ListObject list = new ListObject();
for (int i = 0; i < 5; i++)
{
list.Add(new DataObject("element" + i, i));
}
return list;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla;
namespace DataBindingApp
{
[Serializable()]
public class ListObject : BusinessListBase<ListObject, ListObject.DataObject>
{
[Serializable()]
public class DataObject : BusinessBase<DataObject>
{
private int _ID;
private string _data;
private int _number;
public int Number
{
get { return _number; }
set { _number = value; }
}
public string Data
{
get { return _data; }
set { _data = value; }
}
public int ID
{
get { return _ID; }
set { _ID = value; }
}
protected override object GetIdValue()
{
return _number;
}
public DataObject(string data, int number)
{
this.MarkAsChild();
_data = data;
_number = number;
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged);
}
public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
Console.WriteLine("Property has changed");
}
}
private ListObject()
{ }
public static ListObject GetList()
{
ListObject list = new ListObject();
for (int i = 0; i < 5; i++)
{
list.Add(new DataObject("element" + i, i));
}
return list;
}
}
}
|
Fix namespace & class name | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
writer.Write(@"namespace Cucu
{
[Migration(");
writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
writer.WriteLine(@")]
public class Vaca : Migration
{
public override void Up()
{");
writer.Write($" Create.Table(\"{tableName}\")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{");
writer.Write($" Delete.Table(\"{tableName}\");");
writer.WriteLine(@"
}
}
}");
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApp
{
public class Table
{
private readonly string tableName;
private readonly IEnumerable<Column> columns;
public Table(string tableName, IEnumerable<Column> columns)
{
this.tableName = tableName;
this.columns = columns;
}
public void OutputMigrationCode(TextWriter writer)
{
const string format = "yyyyMMddHHmmss";
writer.WriteLine(@"namespace Migrations
{");
writer.WriteLine($" [Migration(\"{DateTime.Now.ToString(format)}\")]");
writer.Write($" public class {tableName}Migration : Migration");
writer.WriteLine(@"
{
public override void Up()
{");
writer.Write($" Create.Table(\"{tableName}\")");
columns.ToList().ForEach(c =>
{
writer.WriteLine();
writer.Write(c.FluentMigratorCode());
});
writer.WriteLine(@";
}
public override void Down()
{");
writer.Write($" Delete.Table(\"{tableName}\");");
writer.WriteLine(@"
}
}
}");
}
}
} |
Bring back integration test for CosmosDb. | using System;
using System.Linq;
using ExRam.Gremlinq.Core.Tests;
using FluentAssertions;
using Xunit;
using static ExRam.Gremlinq.Core.GremlinQuerySource;
namespace ExRam.Gremlinq.Providers.CosmosDb.Tests
{
public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor>
{
[Fact]
public void Limit_overflow()
{
g
.V()
.Limit((long)int.MaxValue + 1)
.Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x))
.Should()
.Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void Where_property_array_intersects_empty_array2()
{
g
.V<User>()
.Where(t => t.PhoneNumbers.Intersect(new string[0]).Any())
.Should()
.SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
.WithParameters("User");
}
}
}
| using System;
using System.Linq;
using ExRam.Gremlinq.Core.Tests;
using FluentAssertions;
using Xunit;
using static ExRam.Gremlinq.Core.GremlinQuerySource;
namespace ExRam.Gremlinq.Providers.CosmosDb.Tests
{
public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor>
{
[Fact]
public void Limit_overflow()
{
g
.V()
.Limit((long)int.MaxValue + 1)
.Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x))
.Should()
.Throw<ArgumentOutOfRangeException>();
}
[Fact]
public void Where_property_array_intersects_empty_array()
{
g
.V<User>()
.Where(t => t.PhoneNumbers.Intersect(new string[0]).Any())
.Should()
.SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
.WithParameters("User");
}
[Fact]
public void Where_property_is_contained_in_empty_enumerable()
{
var enumerable = Enumerable.Empty<int>();
g
.V<User>()
.Where(t => enumerable.Contains(t.Age))
.Should()
.SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())")
.WithParameters("User");
}
}
}
|
Add back in the reflection namespace | using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Octokit.Internal;
namespace Octokit
{
static class EnumExtensions
{
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
internal static string ToParameter(this Enum prop)
{
if (prop == null) return null;
var propString = prop.ToString();
var member = prop.GetType().GetMember(propString).FirstOrDefault();
if (member == null) return null;
var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false)
.Cast<ParameterAttribute>()
.FirstOrDefault();
return attribute != null ? attribute.Value : propString.ToLowerInvariant();
}
}
}
| using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Octokit.Internal;
namespace Octokit
{
static class EnumExtensions
{
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
internal static string ToParameter(this Enum prop)
{
if (prop == null) return null;
var propString = prop.ToString();
var member = prop.GetType().GetMember(propString).FirstOrDefault();
if (member == null) return null;
var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false)
.Cast<ParameterAttribute>()
.FirstOrDefault();
return attribute != null ? attribute.Value : propString.ToLowerInvariant();
}
}
}
|
Update default encoding to utf8 for supporting non-us symbols | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MailChimp.Net.Api
{
class PostHelpers
{
public static string PostJson(string url, string data)
{
var bytes = Encoding.Default.GetBytes(data);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
var response = client.UploadData(url, "POST", bytes);
return Encoding.Default.GetString(response);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace MailChimp.Net.Api
{
class PostHelpers
{
public static string PostJson(string url, string data)
{
var bytes = Encoding.UTF8.GetBytes(data);
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
var response = client.UploadData(url, "POST", bytes);
return Encoding.Default.GetString(response);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.