Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update tests to pass with the new API.
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using MonoTorrent.Client; using System.Net; using System.Net.Sockets; namespace MonoTorrent.Client.Tests { [TestFixture] public class ConnectionListenerTests { private SocketListener listener; private IPEndPoint endpoint; [SetUp] public void Setup() { endpoint = new IPEndPoint(IPAddress.Loopback, 55652); listener = new SocketListener(endpoint); listener.Start(); System.Threading.Thread.Sleep(100); } [TearDown] public void Teardown() { listener.Stop(); } [Test] public void AcceptThree() { using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); } [Test] public void ChangePortThree() { endpoint.Port++; listener.ChangeEndpoint(new IPEndPoint(IPAddress.Any, endpoint.Port)); AcceptThree(); endpoint.Port++; listener.ChangeEndpoint(new IPEndPoint(IPAddress.Any, endpoint.Port)); AcceptThree(); endpoint.Port++; listener.ChangeEndpoint(new IPEndPoint(IPAddress.Any, endpoint.Port)); AcceptThree(); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using MonoTorrent.Client; using System.Net; using System.Net.Sockets; namespace MonoTorrent.Client.Tests { [TestFixture] public class ConnectionListenerTests { //static void Main(string[] args) //{ // ConnectionListenerTests t = new ConnectionListenerTests(); // t.Setup(); // t.AcceptThree(); // t.Teardown(); //} private SocketListener listener; private IPEndPoint endpoint; [SetUp] public void Setup() { endpoint = new IPEndPoint(IPAddress.Loopback, 55652); listener = new SocketListener(endpoint); listener.Start(); System.Threading.Thread.Sleep(100); } [TearDown] public void Teardown() { listener.Stop(); } [Test] public void AcceptThree() { using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); using (TcpClient c = new TcpClient(AddressFamily.InterNetwork)) c.Connect(endpoint); } [Test] public void ChangePortThree() { endpoint.Port++; listener.ChangeEndpoint(endpoint); AcceptThree(); endpoint.Port++; listener.ChangeEndpoint(endpoint); AcceptThree(); endpoint.Port++; listener.ChangeEndpoint(endpoint); AcceptThree(); } } }
Make Advanced context inherit from normal context
using System; namespace RawRabbit.Context { public class AdvancedMessageContext : IAdvancedMessageContext { public Guid GlobalRequestId { get; set; } public Action Nack { get; set; } } }
using System; namespace RawRabbit.Context { public class AdvancedMessageContext : MessageContext, IAdvancedMessageContext { public Action Nack { get; set; } } }
Fix hard crash due to spinner spin requirement being zero
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects.Types; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); // spinning doesn't match 1:1 with stable, so let's fudge them easier for the time being. SpinsRequired = (int)(SpinsRequired * 0.6); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects.Types; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Osu.Objects { public class Spinner : OsuHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; /// <summary> /// Number of spins required to finish the spinner without miss. /// </summary> public int SpinsRequired { get; protected set; } = 1; public override bool NewCombo => true; protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty) { base.ApplyDefaultsToSelf(controlPointInfo, difficulty); SpinsRequired = (int)(Duration / 1000 * BeatmapDifficulty.DifficultyRange(difficulty.OverallDifficulty, 3, 5, 7.5)); // spinning doesn't match 1:1 with stable, so let's fudge them easier for the time being. SpinsRequired = (int)Math.Max(1, SpinsRequired * 0.6); } } }
Check for NullReference - CodeMashSettings.
using System; using System.Collections.Generic; using CodeMash.Interfaces; namespace CodeMash.Notifications.Email { public class EmailService : IEmailService { public ICodeMashSettings CodeMashSettings { get; set; } public bool SendMail(string[] recipients, string templateName, Dictionary<string, object> tokens = null, Guid? accountId = null) { // TODO : use FluentValidation instead if (recipients == null) { throw new ArgumentNullException(); } var response = CodeMashSettings.Client.Post<SendEmailResponse>("/email/send", new SendEmail { Recipients = recipients, TemplateName = templateName, Tokens = tokens, AccountId = accountId }); return response != null && response.Result; } } }
using System; using System.Collections.Generic; using CodeMash.Interfaces; namespace CodeMash.Notifications.Email { public class EmailService : IEmailService { public ICodeMashSettings CodeMashSettings { get; set; } public bool SendMail(string[] recipients, string templateName, Dictionary<string, object> tokens = null, Guid? accountId = null) { // TODO : use FluentValidation instead if (recipients == null) { throw new ArgumentNullException(); } if (CodeMashSettings == null) { throw new ArgumentNullException("CodeMashSettings", "CodeMash settings is not set"); } var response = CodeMashSettings.Client.Post<SendEmailResponse>("/email/send", new SendEmail { Recipients = recipients, TemplateName = templateName, Tokens = tokens, AccountId = accountId }); return response != null && response.Result; } } }
Change the QueueTime to an hour again
using Quartz; using System; using System.Threading.Tasks; using Discord; using Microsoft.Extensions.DependencyInjection; using NLog; namespace NoAdsHere.Services.Penalties { public static class JobQueue { private static IScheduler _scheduler; public static Task Install(IServiceProvider provider) { _scheduler = provider.GetService<IScheduler>(); return Task.CompletedTask; } public static async Task QueueTrigger(IUserMessage message) { var job = JobBuilder.Create<DeleteMessageJob>() .StoreDurably() .Build(); var trigger = TriggerBuilder.Create() .StartAt(DateTimeOffset.Now.AddSeconds(10)) .ForJob(job) .Build(); trigger.JobDataMap["message"] = message; await _scheduler.ScheduleJob(job, trigger); } } public class DeleteMessageJob : IJob { private readonly Logger _logger = LogManager.GetLogger("AntiAds"); public async Task Execute(IJobExecutionContext context) { var datamap = context.Trigger.JobDataMap; var message = (IUserMessage)datamap["message"]; try { await message.DeleteAsync(); } catch (Exception e) { _logger.Warn(e, $"Unable to delete Message {message.Id}."); } } } }
using Quartz; using System; using System.Threading.Tasks; using Discord; using Microsoft.Extensions.DependencyInjection; using NLog; namespace NoAdsHere.Services.Penalties { public static class JobQueue { private static IScheduler _scheduler; public static Task Install(IServiceProvider provider) { _scheduler = provider.GetService<IScheduler>(); return Task.CompletedTask; } public static async Task QueueTrigger(IUserMessage message) { var job = JobBuilder.Create<DeleteMessageJob>() .StoreDurably() .Build(); var trigger = TriggerBuilder.Create() .StartAt(DateTimeOffset.Now.AddHours(1)) .ForJob(job) .Build(); trigger.JobDataMap["message"] = message; await _scheduler.ScheduleJob(job, trigger); } } public class DeleteMessageJob : IJob { private readonly Logger _logger = LogManager.GetLogger("AntiAds"); public async Task Execute(IJobExecutionContext context) { var datamap = context.Trigger.JobDataMap; var message = (IUserMessage)datamap["message"]; try { await message.DeleteAsync(); } catch (Exception e) { _logger.Warn(e, $"Unable to delete Message {message.Id}."); } } } }
Fix for Visual Studio 2008
// Needed for NET40 using System; using System.Collections; using System.Collections.Generic; using Theraot.Core; namespace Theraot.Collections.Specialized { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "By Design")] public class EnumerableFromDelegate<T> : IEnumerable<T> { private readonly Func<IEnumerator<T>> _getEnumerator; public EnumerableFromDelegate(Func<IEnumerator> getEnumerator) { _getEnumerator = getEnumerator.ChainConversion(ConvertEnumerator); } public IEnumerator<T> GetEnumerator() { return _getEnumerator.Invoke(); } IEnumerator IEnumerable.GetEnumerator() { return _getEnumerator.Invoke(); } private static IEnumerator<T> ConvertEnumerator(IEnumerator enumerator) { if (enumerator == null) { return null; } var genericEnumerator = enumerator as IEnumerator<T>; if (genericEnumerator != null) { return genericEnumerator; } return ConvertEnumeratorExtracted(enumerator); } private static IEnumerator<T> ConvertEnumeratorExtracted(IEnumerator enumerator) { try { while (enumerator.MoveNext()) { var element = enumerator.Current; if (element is T) { yield return (T)element; } } } finally { var disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } } }
// Needed for NET40 using System; using System.Collections; using System.Collections.Generic; using Theraot.Core; namespace Theraot.Collections.Specialized { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "By Design")] public class EnumerableFromDelegate<T> : IEnumerable<T> { private readonly Func<IEnumerator<T>> _getEnumerator; public EnumerableFromDelegate(Func<IEnumerator> getEnumerator) { // Specify the type arguments explicitly _getEnumerator = getEnumerator.ChainConversion<IEnumerator, IEnumerator<T>>(ConvertEnumerator); } public IEnumerator<T> GetEnumerator() { return _getEnumerator.Invoke(); } IEnumerator IEnumerable.GetEnumerator() { return _getEnumerator.Invoke(); } private static IEnumerator<T> ConvertEnumerator(IEnumerator enumerator) { if (enumerator == null) { return null; } var genericEnumerator = enumerator as IEnumerator<T>; if (genericEnumerator != null) { return genericEnumerator; } return ConvertEnumeratorExtracted(enumerator); } private static IEnumerator<T> ConvertEnumeratorExtracted(IEnumerator enumerator) { try { while (enumerator.MoveNext()) { var element = enumerator.Current; if (element is T) { yield return (T)element; } } } finally { var disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } } }
Add Beta property on FleaHeader event
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EDDiscovery.EliteDangerous.JournalEvents { public class JournalFileHeader : JournalEntry { public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader) { GameVersion = Tools.GetStringDef(evt["gameversion"]); Build = Tools.GetStringDef(evt["build"]); Language = Tools.GetStringDef(evt["language"]); } public string GameVersion { get; set; } public string Build { get; set; } public string Language { get; set; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EDDiscovery.EliteDangerous.JournalEvents { public class JournalFileHeader : JournalEntry { public JournalFileHeader(JObject evt ) : base(evt, JournalTypeEnum.FileHeader) { GameVersion = Tools.GetStringDef(evt["gameversion"]); Build = Tools.GetStringDef(evt["build"]); Language = Tools.GetStringDef(evt["language"]); } public string GameVersion { get; set; } public string Build { get; set; } public string Language { get; set; } public bool Beta { get { if (GameVersion.Contains("Beta")) return true; if (GameVersion.Equals("2.2") && Build.Contains("r121645/r0")) return true; return false; } } } }
Add method CancelTransaction to service interface
using Cielo.Requests; using Cielo.Responses; namespace Cielo { public interface ICieloService { CreateTransactionResponse CreateTransaction(CreateTransactionRequest request); CheckTransactionResponse CheckTransaction(CheckTransactionRequest request); } }
using Cielo.Requests; using Cielo.Responses; namespace Cielo { public interface ICieloService { CreateTransactionResponse CreateTransaction(CreateTransactionRequest request); CheckTransactionResponse CheckTransaction(CheckTransactionRequest request); CancelTransactionResponse CancelTransaction(CancelTransactionRequest request); } }
Correct errors in .cs file
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MikeFRobbins : IAmAMicrosoftMVP, IFilterMyBlogPosts { public string FirstName => "Tommy"; public string LastName => "Maynard"; public string ShortBioOrTagLine => "Information Technology Professional (PowerShell Enthusiast)"; public string StateOrRegion => "Arizona, USA"; public string EmailAddress => "tommy@tommymaynard.com"; public string TwitterHandle => "thetommymaynard"; public string GitHubHandle => "tommymaynard"; public string GravatarHash => "e809f9f3d1f46f219c3a28b2fd7dbf83"; public GeoPosition Position => new GeoPosition(32.2217, 110.9265); public Uri WebSite => new Uri("http://tommymaynard.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://tommymaynard.com/feed/"); } } public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class TommyMaynard : IAmACommunityMember { public string FirstName => "Tommy"; public string LastName => "Maynard"; public string ShortBioOrTagLine => "Information Technology Professional (PowerShell Enthusiast)"; public string StateOrRegion => "Arizona, USA"; public string EmailAddress => "tommy@tommymaynard.com"; public string TwitterHandle => "thetommymaynard"; public string GitHubHandle => "tommymaynard"; public string GravatarHash => "e809f9f3d1f46f219c3a28b2fd7dbf83"; public GeoPosition Position => new GeoPosition(32.2217, 110.9265); public Uri WebSite => new Uri("http://tommymaynard.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://tommymaynard.com/feed/"); } } public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
Add impl method for Play.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [RequireComponent(typeof(ObjectPool))] public class AudioController : MonoBehaviour { #region Serialized Data [SerializeField] private GameObject _defaultPrefab; #endregion #region Private fields private ObjectPool _pool; #endregion #region Public methods and properties [HideInInspector] public string _dbName; // This Path starts relatively to Assets folder. [HideInInspector] public string _dbPath; public AudioControllerData _database; public GameObject defaultPrefab { set { _defaultPrefab = value; } } public void Play(string name) { //TODO: Add Implementation } #endregion #region MonoBehaviour methods void Awake() { _pool = GetComponent<ObjectPool>(); } void OnEnable() { } #endregion }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [RequireComponent(typeof(ObjectPool))] public class AudioController : MonoBehaviour { #region Serialized Data [SerializeField] private GameObject _defaultPrefab; #endregion #region Private fields private ObjectPool _pool; #endregion #region Public methods and properties [HideInInspector] public string _dbName; // This Path starts relatively to Assets folder. [HideInInspector] public string _dbPath; public AudioControllerData _database; public GameObject defaultPrefab { set { _defaultPrefab = value; } } public void Play(string name) { PlayImpl(name); } #endregion #region Private methods private void PlayImpl(string name) { //TODO: Add Implementation } #endregion #region MonoBehaviour methods void Awake() { _pool = GetComponent<ObjectPool>(); } void OnEnable() { } #endregion }
Revert "Hack for new version of RunTextWithXmlResults which returns multiple results"
using System; using System.Data.SqlClient; namespace tSQLt.Client.Net.Gateways { public interface ISqlServerGateway { string RunWithXmlResult(string query); void RunWithNoResult(string query); } public class SqlServerGateway : ISqlServerGateway { private readonly string _connectionString; private readonly int _runTimeout; public SqlServerGateway(string connectionString, int runTimeout) { _connectionString = connectionString; _runTimeout = runTimeout; } public void RunWithNoResult(string query) { using (var con = new SqlConnection(_connectionString)) { con.Open(); using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = query; cmd.CommandTimeout = _runTimeout; cmd.ExecuteNonQuery(); } } } public string RunWithXmlResult(string query) { using (var con = new SqlConnection(_connectionString)) { con.Open(); using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = query; cmd.CommandTimeout = _runTimeout; SqlDataReader reader = cmd.ExecuteReader(); if (!reader.Read()) { throw new InvalidOperationException( string.Format("Expecting to get a data reader with the response to: \"{0}\" ", query)); } var result = reader[0] as string; var testCount = 0; if (Int32.TryParse(result, out testCount)) { if (reader.NextResult()) { if (reader.Read()) { return reader[0] as string; } } } return result; } } } } }
using System; using System.Data.SqlClient; namespace tSQLt.Client.Net.Gateways { public interface ISqlServerGateway { string RunWithXmlResult(string query); void RunWithNoResult(string query); } public class SqlServerGateway : ISqlServerGateway { private readonly string _connectionString; private readonly int _runTimeout; public SqlServerGateway(string connectionString, int runTimeout) { _connectionString = connectionString; _runTimeout = runTimeout; } public void RunWithNoResult(string query) { using (var con = new SqlConnection(_connectionString)) { con.Open(); using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = query; cmd.CommandTimeout = _runTimeout; cmd.ExecuteNonQuery(); } } } public string RunWithXmlResult(string query) { using (var con = new SqlConnection(_connectionString)) { con.Open(); using (SqlCommand cmd = con.CreateCommand()) { cmd.CommandText = query; cmd.CommandTimeout = _runTimeout; SqlDataReader reader = cmd.ExecuteReader(); if (!reader.Read()) { throw new InvalidOperationException( string.Format("Expecting to get a data reader with the response to: \"{0}\" ", query)); } return reader[0] as string; } } } } }
Rename client trace to git-push-date.
using System; namespace Kudu.TestHarness { public static class ApplicationManagerExtensions { public static GitDeploymentResult GitDeploy(this ApplicationManager appManager, string localRepoPath, string localBranchName = "master", string remoteBranchName = "master") { GitDeploymentResult result = Git.GitDeploy(appManager.DeploymentManager, appManager.ServiceUrl, localRepoPath, appManager.GitUrl, localBranchName, remoteBranchName); string traceFile = String.Format("git-{0:MM-dd-H-mm-ss}.txt", DateTime.Now); appManager.Save(traceFile, result.GitTrace); return result; } } }
using System; namespace Kudu.TestHarness { public static class ApplicationManagerExtensions { public static GitDeploymentResult GitDeploy(this ApplicationManager appManager, string localRepoPath, string localBranchName = "master", string remoteBranchName = "master") { GitDeploymentResult result = Git.GitDeploy(appManager.DeploymentManager, appManager.ServiceUrl, localRepoPath, appManager.GitUrl, localBranchName, remoteBranchName); string traceFile = String.Format("git-push-{0:MM-dd-H-mm-ss}.txt", DateTime.Now); appManager.Save(traceFile, result.GitTrace); return result; } } }
Read appSettings on construction to throw early.
using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { // ReSharper disable once InconsistentNaming private static readonly AppSettingsLibratoSettings settings = new AppSettingsLibratoSettings(); private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public static AppSettingsLibratoSettings Settings { get { return settings; } } public string Username { get { var username = ConfigurationManager.AppSettings["Librato.Username"]; if (string.IsNullOrEmpty(username)) { throw new ConfigurationErrorsException("Librato.Username is required and cannot be empty"); } return username; } } public string ApiKey { get { var apiKey = ConfigurationManager.AppSettings["Librato.ApiKey"]; if (string.IsNullOrEmpty(apiKey)) { throw new ConfigurationErrorsException("Librato.ApiKey is required and cannot be empty"); } return apiKey; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }
using System; using System.Configuration; namespace librato4net { public class AppSettingsLibratoSettings : ILibratoSettings { private const string DefaultApiEndPoint = "https://metrics-api.librato.com/v1/"; public AppSettingsLibratoSettings() { var _ = Username; _ = ApiKey; } public string Username { get { var username = ConfigurationManager.AppSettings["Librato.Username"]; if (string.IsNullOrEmpty(username)) { throw new ConfigurationErrorsException("Librato.Username is required and cannot be empty"); } return username; } } public string ApiKey { get { var apiKey = ConfigurationManager.AppSettings["Librato.ApiKey"]; if (string.IsNullOrEmpty(apiKey)) { throw new ConfigurationErrorsException("Librato.ApiKey is required and cannot be empty"); } return apiKey; } } public Uri ApiEndpoint { get { return new Uri(ConfigurationManager.AppSettings["Librato.ApiEndpoint"] ?? DefaultApiEndPoint); } } public TimeSpan SendInterval { get { return TimeSpan.Parse(ConfigurationManager.AppSettings["Librato.SendInterval"] ?? "00:00:05"); } } } }
Use dynamic layout for simple app
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Eto.Forms; namespace Eto.Test.Android { [Activity(Label = "Eto.Test.Android", MainLauncher = true)] public class MainActivity : Activity { public class SimpleApplication : Forms.Application { public SimpleApplication(Generator generator = null) : base(generator) { } public override void OnInitialized(EventArgs e) { base.OnInitialized(e); MainForm = new Form { Content = new Label { Text = "Hello world", VerticalAlign = VerticalAlign.Middle, HorizontalAlign = HorizontalAlign.Center } }; MainForm.Show(); } } protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var generator = new Eto.Platform.Android.Generator(); //new TestApplication(generator).Attach(this); new SimpleApplication(generator).Attach(this).Run(); // Set our view from the "main" layout resource //SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it /*Button button = FindViewById<Button>(Resource.Id.myButton); button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };*/ } } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Eto.Forms; namespace Eto.Test.Android { [Activity(Label = "Eto.Test.Android", MainLauncher = true)] public class MainActivity : Activity { public class SimpleApplication : Forms.Application { public SimpleApplication(Generator generator = null) : base(generator) { } public override void OnInitialized(EventArgs e) { base.OnInitialized(e); var layout = new DynamicLayout(); layout.Add(new Label { Text = "Hello world", VerticalAlign = VerticalAlign.Middle, HorizontalAlign = HorizontalAlign.Center }); layout.Add(new Label { Text = "Hello world2", VerticalAlign = VerticalAlign.Middle, HorizontalAlign = HorizontalAlign.Center }); MainForm = new Form { Content = layout }; MainForm.Show(); } } protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); var generator = new Eto.Platform.Android.Generator(); //new TestApplication(generator).Attach(this); new SimpleApplication(generator).Attach(this).Run(); } } }
Fix injection script loading from GUI.
using Infusion.Commands; using Infusion.LegacyApi.Injection; using InjectionScript.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infusion.Injection.Avalonia.Scripts { public class ScriptServices : IScriptServices { private readonly InjectionRuntime injectionRuntime; private readonly InjectionHost injectionHost; public event Action AvailableScriptsChanged { add => injectionHost.ScriptLoaded += value; remove => injectionHost.ScriptLoaded -= value; } public event Action RunningScriptsChanged { add => injectionHost.RunningCommandsChanged += value; remove => injectionHost.RunningCommandsChanged -= value; } public ScriptServices(InjectionRuntime injectionRuntime, InjectionHost injectionHost) { this.injectionRuntime = injectionRuntime; this.injectionHost = injectionHost; } public IEnumerable<string> RunningScripts => injectionHost.RunningCommands; public IEnumerable<string> AvailableScripts => injectionRuntime.Metadata.Subrutines.Select(x => x.Name); public void Load(string scriptFileName) => injectionRuntime.Load(scriptFileName); public void Run(string name) => injectionHost.ExecSubrutine(name); public void Terminate(string name) => injectionRuntime.Api.UO.Terminate(name); } }
using Infusion.Commands; using Infusion.LegacyApi.Injection; using InjectionScript.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infusion.Injection.Avalonia.Scripts { public class ScriptServices : IScriptServices { private readonly InjectionRuntime injectionRuntime; private readonly InjectionHost injectionHost; public event Action AvailableScriptsChanged { add => injectionHost.ScriptLoaded += value; remove => injectionHost.ScriptLoaded -= value; } public event Action RunningScriptsChanged { add => injectionHost.RunningCommandsChanged += value; remove => injectionHost.RunningCommandsChanged -= value; } public ScriptServices(InjectionRuntime injectionRuntime, InjectionHost injectionHost) { this.injectionRuntime = injectionRuntime; this.injectionHost = injectionHost; } public IEnumerable<string> RunningScripts => injectionHost.RunningCommands; public IEnumerable<string> AvailableScripts => injectionRuntime.Metadata.Subrutines.Select(x => x.Name); public void Load(string scriptFileName) => injectionHost.LoadScript(scriptFileName); public void Run(string name) => injectionHost.ExecSubrutine(name); public void Terminate(string name) => injectionRuntime.Api.UO.Terminate(name); } }
Introduce OnNext + push result in
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace rx { class Program { static void Main(string[] args) { var subject = new Subject<string>(); using (subject.Subscribe(result => Console.WriteLine(result))) { var wc = new WebClient(); var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt"); task.ContinueWith(t => Console.WriteLine(t.Result)); // Wait for the async call Console.ReadLine(); } } } public class Subject<T> { private readonly IList<Action<T>> observers = new List<Action<T>>(); public IDisposable Subscribe(Action<T> observer) { observers.Add(observer); return new Disposable(() => observers.Remove(observer)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace rx { class Program { static void Main(string[] args) { var subject = new Subject<string>(); using (subject.Subscribe(result => Console.WriteLine(result))) { var wc = new WebClient(); var task = wc.DownloadStringTaskAsync("http://www.google.com/robots.txt"); task.ContinueWith(t => subject.OnNext(t.Result)); // Wait for the async call Console.ReadLine(); } } } public class Subject<T> { private readonly IList<Action<T>> observers = new List<Action<T>>(); public IDisposable Subscribe(Action<T> observer) { observers.Add(observer); return new Disposable(() => observers.Remove(observer)); } public void OnNext(T result) { foreach (var observer in observers) { observer(result); } } } }
Add a menu to make the dev tools not show up by default
using System; using System.ComponentModel; using System.IO; using System.Reflection; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; using Knockout.Binding.ExtensionMethods; namespace Knockout.Binding.Sample { public partial class MainForm : Form { private readonly WebView m_WebView; private readonly SimpleViewModel m_SimpleViewModel = new SimpleViewModel(); public MainForm() { CEF.Initialize(new Settings()); m_WebView = new WebView(GetPageLocation(), new BrowserSettings()) { Dock = DockStyle.Fill }; m_WebView.RegisterForKnockout(m_SimpleViewModel); m_WebView.PropertyChanged += OnWebBrowserInitialized; Controls.Add(m_WebView); } private void OnWebBrowserInitialized(object sender, PropertyChangedEventArgs args) { if (String.Equals(args.PropertyName, "IsBrowserInitialized", StringComparison.OrdinalIgnoreCase)) { m_WebView.Load(GetPageLocation()); m_WebView.ShowDevTools(); } } private static string GetPageLocation() { var runtimeDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; return Path.Combine(runtimeDirectory, "SomePage.htm"); } } }
using System; using System.ComponentModel; using System.IO; using System.Reflection; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; using Knockout.Binding.ExtensionMethods; namespace Knockout.Binding.Sample { public partial class MainForm : Form { private readonly WebView m_WebView; private readonly SimpleViewModel m_SimpleViewModel = new SimpleViewModel(); public MainForm() { CEF.Initialize(new Settings()); m_WebView = new WebView(GetPageLocation(), new BrowserSettings()) { Dock = DockStyle.Fill }; m_WebView.RegisterForKnockout(m_SimpleViewModel); m_WebView.PropertyChanged += OnWebBrowserInitialized; Controls.Add(m_WebView); Menu = GetMenu(); } private void OnWebBrowserInitialized(object sender, PropertyChangedEventArgs args) { if (String.Equals(args.PropertyName, "IsBrowserInitialized", StringComparison.OrdinalIgnoreCase)) { m_WebView.Load(GetPageLocation()); } } private static string GetPageLocation() { var runtimeDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName; return Path.Combine(runtimeDirectory, "SomePage.htm"); } private MainMenu GetMenu() { var showDevToolsItem = new MenuItem("Show Dev Tools"); showDevToolsItem.Click += (sender, args) => m_WebView.ShowDevTools(); var fileMenu = new MenuItem("File"); fileMenu.MenuItems.Add(showDevToolsItem); return new MainMenu(new[] { fileMenu, }); } } }
Add supression for generated xaml class
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")]
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.Providers")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "NuPack.Dialog.ToolsOptionsUI")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "XamlGeneratedNamespace")]
Add default setting it's missing.
using System; using System.Data.SqlClient; using TeamTracker; public partial class SettingsLogin : System.Web.UI.Page { //--------------------------------------------------------------------------- public static readonly string SES_SETTINGS_LOGGED_IN = "SesSettingsLoggedIn"; protected string DbConnectionString = Database.DB_CONNECTION_STRING; //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { } //--------------------------------------------------------------------------- protected void OnLoginClick( object sender, EventArgs e ) { string password = Request.Form[ "password" ]; if( ValidatePassword( password ) ) { Session[ SES_SETTINGS_LOGGED_IN ] = true; Response.Redirect( "Settings.aspx" ); } } //--------------------------------------------------------------------------- bool ValidatePassword( string password ) { using( SqlConnection connection = new SqlConnection( Database.DB_CONNECTION_STRING ) ) { connection.Open(); int rowCount = (int) new SqlCommand( string.Format( "SELECT COUNT(*) " + "FROM Setting " + "WHERE [Key]='SettingsPassword' AND Value='{0}'", password ), connection ).ExecuteScalar(); return rowCount == 1; } } //--------------------------------------------------------------------------- }
using System; using System.Data.SqlClient; using TeamTracker; public partial class SettingsLogin : System.Web.UI.Page { //--------------------------------------------------------------------------- public static readonly string SES_SETTINGS_LOGGED_IN = "SesSettingsLoggedIn"; protected string DbConnectionString = Database.DB_CONNECTION_STRING; //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { if( Database.ExecSql( "SELECT id FROM Settings WHERE [Key]='SettingsPassword'" ) == 0 ) { Database.ExecSql( "INSERT INTO Settings ( [Key], Value ) VALUES ( 'SettingsPassword', 'admin' )" ); } } //--------------------------------------------------------------------------- protected void OnLoginClick( object sender, EventArgs e ) { string password = Request.Form[ "password" ]; if( ValidatePassword( password ) ) { Session[ SES_SETTINGS_LOGGED_IN ] = true; Response.Redirect( "Settings.aspx" ); } } //--------------------------------------------------------------------------- bool ValidatePassword( string password ) { using( SqlConnection connection = new SqlConnection( Database.DB_CONNECTION_STRING ) ) { connection.Open(); int rowCount = (int) new SqlCommand( string.Format( "SELECT COUNT(*) " + "FROM Setting " + "WHERE [Key]='SettingsPassword' AND Value='{0}'", password ), connection ).ExecuteScalar(); return rowCount == 1; } } //--------------------------------------------------------------------------- }
Set error type depending on severity (squiggle color)
using jwldnr.VisualLinter.Linting; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace jwldnr.VisualLinter.Tagging { internal class LinterTag : IErrorTag { public string ErrorType { get; } public object ToolTipContent { get; } internal LinterTag(LinterMessage message) { ErrorType = GetErrorType(message.IsFatal); ToolTipContent = GetToolTipContent(message.IsFatal, message.Message, message.RuleId); } private static string GetErrorType(bool isFatal) { return isFatal ? PredefinedErrorTypeNames.SyntaxError : PredefinedErrorTypeNames.Warning; } private static object GetToolTipContent(bool isFatal, string message, string ruleId) { return isFatal ? message : $"{message} ({ruleId})"; } } }
using jwldnr.VisualLinter.Linting; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace jwldnr.VisualLinter.Tagging { internal class LinterTag : IErrorTag { public string ErrorType { get; } public object ToolTipContent { get; } internal LinterTag(LinterMessage message) { ErrorType = GetErrorType(message); ToolTipContent = GetToolTipContent(message.IsFatal, message.Message, message.RuleId); } private static string GetErrorType(LinterMessage message) { if (message.IsFatal) return PredefinedErrorTypeNames.SyntaxError; return RuleSeverity.Error == message.Severity ? PredefinedErrorTypeNames.SyntaxError : PredefinedErrorTypeNames.Warning; } private static object GetToolTipContent(bool isFatal, string message, string ruleId) { return isFatal ? message : $"{message} ({ruleId})"; } } }
Apply window placement second time to override possible WM_DPICHANGED reaction
using LordJZ.WinAPI; namespace WindowPositions { public class WindowPosition { public string Title { get; set; } public string ClassName { get; set; } public WindowPlacement Placement { get; set; } public bool Matches(WindowDTO dto) { if (this.Title != null) { if (this.Title != dto.Title) return false; } if (dto.ClassName != this.ClassName) return false; return true; } public void Apply(NativeWindow window) { WindowPlacement placement = this.Placement; window.Placement = placement; } } }
using LordJZ.WinAPI; namespace WindowPositions { public class WindowPosition { public string Title { get; set; } public string ClassName { get; set; } public WindowPlacement Placement { get; set; } public bool Matches(WindowDTO dto) { if (this.Title != null) { if (this.Title != dto.Title) return false; } if (dto.ClassName != this.ClassName) return false; return true; } public void Apply(NativeWindow window) { WindowPlacement placement = this.Placement; window.Placement = placement; // apply second time to override possible WM_DPICHANGED reaction window.Placement = placement; } } }
Fix region name and comments
#region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserMenuHandler : IMenuHandler { #region Internal Methods /* * Handler for the browser context menu. */ public bool OnBeforeContextMenu(IWebBrowser browser) { // Disable the context menu return false; } #endregion } }
#region Copyright © 2014 Ricardo Amaral /* * Use of this source code is governed by an MIT-style license that can be found in the LICENSE file. */ #endregion using CefSharp; namespace SlackUI { internal class BrowserMenuHandler : IMenuHandler { #region Public Methods /* * Handler for the browser on before context menu event. */ public bool OnBeforeContextMenu(IWebBrowser browser) { // Disable the context menu return false; } #endregion } }
Add sample validation in dummy app
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Http; namespace Swashbuckle.Dummy.Controllers { public class AnnotatedTypesController : ApiController { public int Create(Payment payment) { throw new NotImplementedException(); } } public class Payment { [Required] public decimal Amount { get; set; } [Required, RegularExpression("^[3-6]?\\d{12,15}$")] public string CardNumber { get; set; } [Required, Range(1, 12)] public int ExpMonth { get; set; } [Required, Range(14, 99)] public int ExpYear { get; set; } public string Note { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Http; using System.Net.Http; using System.Net; namespace Swashbuckle.Dummy.Controllers { public class AnnotatedTypesController : ApiController { public int Create(Payment payment) { if (!ModelState.IsValid) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); throw new NotImplementedException(); } } public class Payment { [Required] public decimal Amount { get; set; } [Required, RegularExpression("^[3-6]?\\d{12,15}$")] public string CardNumber { get; set; } [Required, Range(1, 12)] public int ExpMonth { get; set; } [Required, Range(14, 99)] public int ExpYear { get; set; } public string Note { get; set; } } }
Make it just 'sign in' instead of 'sign in / register'
<div class="user-display"> @if (!User.Identity.IsAuthenticated) { string returnUrl = ViewData.ContainsKey(Constants.ReturnUrlViewDataKey) ? (string)ViewData[Constants.ReturnUrlViewDataKey] : Request.RawUrl; <span class="welcome"> <a href="@Url.LogOn(returnUrl)">Sign in / Register</a> </span> } else { <span class="welcome"><a href="@Url.Action(MVC.Users.Account())">@(User.Identity.Name)</a></span> <text>/</text> <span class="user-actions"> <a href="@Url.LogOff()">Sign out</a> </span> } </div>
<div class="user-display"> @if (!User.Identity.IsAuthenticated) { string returnUrl = ViewData.ContainsKey(Constants.ReturnUrlViewDataKey) ? (string)ViewData[Constants.ReturnUrlViewDataKey] : Request.RawUrl; <span class="welcome"> <a href="@Url.LogOn(returnUrl)">Sign in</a> </span> } else { <span class="welcome"><a href="@Url.Action(MVC.Users.Account())">@(User.Identity.Name)</a></span> <text>/</text> <span class="user-actions"> <a href="@Url.LogOff()">Sign out</a> </span> } </div>
Fix for "PSInvalidOperationException: Nested pipeline should run only from a running pipeline." when using PowerShell v3
using System; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace PowerBridge.Internal { internal interface IPowerShellCommandParameterProvider { string[] GetDefaultParameterSetParameterNames(string command); } internal class PowerShellCommandParameterProvider : IPowerShellCommandParameterProvider { public string[] GetDefaultParameterSetParameterNames(string commandName) { using (var powerShell = PowerShell.Create(RunspaceMode.CurrentRunspace)) { var command = new Command("Get-Command"); command.Parameters.Add("Name", commandName); powerShell.Commands.AddCommand(command); var commandInfo = powerShell.Invoke<CommandInfo>()[0]; var parameterSet = commandInfo.ParameterSets.Count == 1 ? commandInfo.ParameterSets[0] : commandInfo.ParameterSets.FirstOrDefault(x => x.IsDefault); if (parameterSet == null) { throw new InvalidOperationException(commandName + " does not have a default parameter set."); } return parameterSet.Parameters.Select(x => x.Name).ToArray(); } } } }
using System; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace PowerBridge.Internal { internal interface IPowerShellCommandParameterProvider { string[] GetDefaultParameterSetParameterNames(string command); } internal class PowerShellCommandParameterProvider : IPowerShellCommandParameterProvider { public string[] GetDefaultParameterSetParameterNames(string commandName) { using (var powerShell = PowerShell.Create(RunspaceMode.NewRunspace)) { var command = new Command("Get-Command"); command.Parameters.Add("Name", commandName); powerShell.Commands.AddCommand(command); var commandInfo = powerShell.Invoke<CommandInfo>()[0]; var parameterSet = commandInfo.ParameterSets.Count == 1 ? commandInfo.ParameterSets[0] : commandInfo.ParameterSets.FirstOrDefault(x => x.IsDefault); if (parameterSet == null) { throw new InvalidOperationException(commandName + " does not have a default parameter set."); } return parameterSet.Parameters.Select(x => x.Name).ToArray(); } } } }
Revert "Fixed formatter which changes Uri to Url which was creating subject as a literal which made it difficult to do do related queries such as the following:"
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LinkedData.Helpers; using Sitecore.Links; using VDS.RDF; namespace LinkedData.Formatters { public class UriToDynamicUrlFormatter : ITripleFormatter { public Triple FormatTriple(Triple triple) { var subjectItem = SitecoreTripleHelper.UriToItem(triple.Subject.ToString()); var objectItem = SitecoreTripleHelper.UriToItem(triple.Object.ToString()); if (subjectItem == null || objectItem == null) { return triple; } var urlOptions = new UrlOptions() {AlwaysIncludeServerUrl = true, AddAspxExtension = false, LowercaseUrls = true, LanguageEmbedding = LanguageEmbedding.Never}; var subjectUrl = LinkManager.GetItemUrl(subjectItem, urlOptions); var objectUrl = LinkManager.GetItemUrl(objectItem, urlOptions); var g = new Graph(); IUriNode sub = g.CreateUriNode(new Uri(subjectUrl)); IUriNode pred = g.CreateUriNode(new Uri(triple.Predicate.ToString().Split('#')[0])); IUriNode obj = g.CreateUriNode(new Uri(objectUrl)); triple = new Triple(sub, pred, obj); return triple; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LinkedData.Helpers; using Sitecore.Links; using VDS.RDF; namespace LinkedData.Formatters { public class UriToDynamicUrlFormatter : ITripleFormatter { public Triple FormatTriple(Triple triple) { var subjectItem = SitecoreTripleHelper.UriToItem(triple.Subject.ToString()); var objectItem = SitecoreTripleHelper.UriToItem(triple.Object.ToString()); if (subjectItem == null || objectItem == null) { return triple; } var urlOptions = new UrlOptions() {AlwaysIncludeServerUrl = true, AddAspxExtension = false, LowercaseUrls = true, LanguageEmbedding = LanguageEmbedding.Never}; var subjectUrl = LinkManager.GetItemUrl(subjectItem, urlOptions); var objectUrl = LinkManager.GetItemUrl(objectItem, urlOptions); var g = new Graph(); IUriNode sub = g.CreateUriNode(new Uri(subjectUrl)); IUriNode pred = g.CreateUriNode(new Uri(triple.Predicate.ToString().Split('#')[0])); ILiteralNode obj = g.CreateLiteralNode(objectUrl); triple = new Triple(sub, pred, obj); return triple; } } }
Fix marshalling of Winstation name
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; /// <content> /// Exported functions from the WtsApi32.dll Windows library /// that are available to Desktop apps only. /// </content> public static partial class WtsApi32 { /// <summary> /// Contains information about a client session on a Remote Desktop Session Host (RD Session Host) server. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct WTS_SESSION_INFO { public int SessionID; [MarshalAs(UnmanagedType.LPStr)] public string pWinStationName; public WtsConnectStateClass State; } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; /// <content> /// Exported functions from the WtsApi32.dll Windows library /// that are available to Desktop apps only. /// </content> public static partial class WtsApi32 { /// <summary> /// Contains information about a client session on a Remote Desktop Session Host (RD Session Host) server. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct WTS_SESSION_INFO { public int SessionID; [MarshalAs(UnmanagedType.LPTStr)] public string pWinStationName; public WtsConnectStateClass State; } } }
Fix for Dna parsing: line endings
using UnityEngine; using System.Collections; using Fukami.Helpers; public class Seed : MonoBehaviour { public string Dna; void Start(){ var dnaAsset = Resources.Load<TextAsset>("dna"); Dna = dnaAsset.text.Replace("\n","*"); } void OnSeedDnaStringRequested (Wrap<string> dna) { dna.Value = Dna; dna.ValueSource = "Seed"; } }
using UnityEngine; using System.Collections; using Fukami.Helpers; public class Seed : MonoBehaviour { public string Dna; void Start(){ var dnaAsset = Resources.Load<TextAsset>("dna"); Dna = dnaAsset.text.Replace("\r\n","*"); } void OnSeedDnaStringRequested (Wrap<string> dna) { dna.Value = Dna; dna.ValueSource = "Seed"; } }
Update assembly info for nuget 3.3 release
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Bot.Connector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft Bot Framework")] [assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9f1a81ee-c6fe-474e-a3e2-c581435d55bf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("3.2.1.0")] [assembly: AssemblyFileVersion("3.2.1.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Bot.Connector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft Bot Framework")] [assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9f1a81ee-c6fe-474e-a3e2-c581435d55bf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("3.3.0.0")] [assembly: AssemblyFileVersion("3.3.0.0")]
Fix a problem with 'fixed' variables due to cleanup
// 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.Runtime.InteropServices; namespace Microsoft.Diagnostics.Runtime.Interop { [StructLayout(LayoutKind.Sequential)] public unsafe struct DEBUG_STACK_FRAME_EX { /* DEBUG_STACK_FRAME */ public ulong InstructionOffset; public ulong ReturnOffset; public ulong FrameOffset; public ulong StackOffset; public ulong FuncTableEntry; public fixed ulong Params[4]; public fixed ulong Reserved[6]; public uint Virtual; public uint FrameNumber; /* DEBUG_STACK_FRAME_EX */ public uint InlineFrameContext; public uint Reserved1; public DEBUG_STACK_FRAME_EX(DEBUG_STACK_FRAME dsf) { InstructionOffset = dsf.InstructionOffset; ReturnOffset = dsf.ReturnOffset; FrameOffset = dsf.FrameOffset; StackOffset = dsf.StackOffset; FuncTableEntry = dsf.FuncTableEntry; for (int i = 0; i < 4; ++i) Params[i] = dsf.Params[i]; for (int i = 0; i < 6; ++i) Reserved[i] = dsf.Reserved[i]; Virtual = dsf.Virtual; FrameNumber = dsf.FrameNumber; InlineFrameContext = 0xFFFFFFFF; Reserved1 = 0; } } }
// 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.Runtime.InteropServices; namespace Microsoft.Diagnostics.Runtime.Interop { [StructLayout(LayoutKind.Sequential)] public unsafe struct DEBUG_STACK_FRAME_EX { /* DEBUG_STACK_FRAME */ public ulong InstructionOffset; public ulong ReturnOffset; public ulong FrameOffset; public ulong StackOffset; public ulong FuncTableEntry; public fixed ulong Params[4]; public fixed ulong Reserved[6]; public uint Virtual; public uint FrameNumber; /* DEBUG_STACK_FRAME_EX */ public uint InlineFrameContext; public uint Reserved1; public DEBUG_STACK_FRAME_EX(DEBUG_STACK_FRAME dsf) { InstructionOffset = dsf.InstructionOffset; ReturnOffset = dsf.ReturnOffset; FrameOffset = dsf.FrameOffset; StackOffset = dsf.StackOffset; FuncTableEntry = dsf.FuncTableEntry; fixed (ulong* pParams = Params) for (int i = 0; i < 4; ++i) pParams[i] = dsf.Params[i]; fixed (ulong* pReserved = Params) for (int i = 0; i < 6; ++i) pReserved[i] = dsf.Reserved[i]; Virtual = dsf.Virtual; FrameNumber = dsf.FrameNumber; InlineFrameContext = 0xFFFFFFFF; Reserved1 = 0; } } }
Add the guest system info as push action
namespace Espera.Network { public enum PushAction { UpdateAccessPermission = 0, UpdateCurrentPlaylist = 1, UpdatePlaybackState = 2, UpdateRemainingVotes = 3, UpdateCurrentPlaybackTime = 4 } }
namespace Espera.Network { public enum PushAction { UpdateAccessPermission = 0, UpdateCurrentPlaylist = 1, UpdatePlaybackState = 2, UpdateRemainingVotes = 3, UpdateCurrentPlaybackTime = 4, UpdateGuestSystemInfo = 5 } }
Move ignore up to fixture to kick off new full build for windows and mono.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture] public class WritingSystemTreeItemTests { [Test, Ignore("Not Yet")] public void GetChildren_ShouldBeNoChildren_GivesEmptyList() { } [Test, Ignore("Not Yet")] public void GetChildren_IpaVersionExists_ResultIncludesIpa() { } [Test, Ignore("Not Yet")] public void GetChildren_OpportunityLinksExist_ResultLinks() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Palaso.UI.WindowsForms.WritingSystems; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.WritingSystems { [TestFixture, Ignore("Not Yet")] public class WritingSystemTreeItemTests { [Test, Ignore("Not Yet")] public void GetChildren_ShouldBeNoChildren_GivesEmptyList() { } [Test, Ignore("Not Yet")] public void GetChildren_IpaVersionExists_ResultIncludesIpa() { } [Test, Ignore("Not Yet")] public void GetChildren_OpportunityLinksExist_ResultLinks() { } } }
Use AssemblyName constructor to retrieve assembly version
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace EvilDICOM.Core.Helpers { public static class Constants { public static string EVIL_DICOM_IMP_UID = "1.2.598.0.1.2851334.2.1865.1"; public static string EVIL_DICOM_IMP_VERSION = Assembly.GetCallingAssembly().FullName.Split(new[] { '=', ',' }).ElementAt(2); //APPLICATION CONTEXT public static string DEFAULT_APPLICATION_CONTEXT = "1.2.840.10008.3.1.1.1"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace EvilDICOM.Core.Helpers { public static class Constants { public static string EVIL_DICOM_IMP_UID = "1.2.598.0.1.2851334.2.1865.1"; public static string EVIL_DICOM_IMP_VERSION = new AssemblyName(Assembly.GetCallingAssembly().FullName).Version.ToString(); //APPLICATION CONTEXT public static string DEFAULT_APPLICATION_CONTEXT = "1.2.840.10008.3.1.1.1"; } }
Handle empty properties on fallback
using System.Linq; using EPiServer.Core; namespace Meridium.EPiServer.Migration.Support { public class SourcePage { public string TypeName { get; set; } public PropertyDataCollection Properties { get; set; } public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) where TValue : class { var data = Properties != null ? Properties.Get(propertyName) : null; return (data != null) ? (data.Value as TValue) : @default; } public TValue GetValueWithFallback<TValue>(params string[] properties) where TValue : class { var property = properties.SkipWhile(p => null == Properties.Get(p)).FirstOrDefault(); return (property != null) ? GetValue<TValue>(property) : null; } } }
using System.Linq; using EPiServer.Core; namespace Meridium.EPiServer.Migration.Support { public class SourcePage { public string TypeName { get; set; } public PropertyDataCollection Properties { get; set; } public TValue GetValue<TValue>(string propertyName, TValue @default = default(TValue)) where TValue : class { var data = Properties != null ? Properties.Get(propertyName) : null; return (data != null) ? (data.Value as TValue) : @default; } public TValue GetValueWithFallback<TValue>(params string[] properties) where TValue : class { var property = properties.SkipWhile(p => !Properties.HasValue(p)).FirstOrDefault(); return (property != null) ? GetValue<TValue>(property) : null; } } internal static class PropertyDataExtensions { public static bool HasValue(this PropertyDataCollection self, string key) { var property = self.Get(key); if (property == null) return false; return !(property.IsNull || string.IsNullOrWhiteSpace(property.ToString())); } } }
Fix similar "can see but can't path" crash on sprinters.
using System; using System.Collections.Generic; using Magecrawl.Utilities; namespace Magecrawl.GameEngine.Actors { internal class SprinterMonster : Monster { public SprinterMonster(string name, Point p, int maxHP, int vision, DiceRoll damage, double defense, double evade, double ctIncreaseModifer, double ctMoveCost, double ctActCost, double ctAttackCost) : base(name, p, maxHP, vision, damage, defense, evade, ctIncreaseModifer, ctMoveCost, ctActCost, ctAttackCost) { } public override void Action(CoreGameEngine engine) { if (IsPlayerVisible(engine) && GetPathToPlayer(engine).Count == 2) { UpdateKnownPlayerLocation(engine); if (engine.UseSkill(this, SkillType.Rush, engine.Player.Position)) return; } DefaultAction(engine); } } }
using System; using System.Collections.Generic; using Magecrawl.Utilities; namespace Magecrawl.GameEngine.Actors { internal class SprinterMonster : Monster { public SprinterMonster(string name, Point p, int maxHP, int vision, DiceRoll damage, double defense, double evade, double ctIncreaseModifer, double ctMoveCost, double ctActCost, double ctAttackCost) : base(name, p, maxHP, vision, damage, defense, evade, ctIncreaseModifer, ctMoveCost, ctActCost, ctAttackCost) { } public override void Action(CoreGameEngine engine) { if (IsPlayerVisible(engine)) { UpdateKnownPlayerLocation(engine); List<Point> pathToPlayer = GetPathToPlayer(engine); if (pathToPlayer != null && pathToPlayer.Count == 2) { if (engine.UseSkill(this, SkillType.Rush, engine.Player.Position)) return; } } DefaultAction(engine); } } }
Use a different authentication type
using System; using Hellang.Authentication.JwtBearer.Google; using Microsoft.AspNetCore.Authentication.JwtBearer; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class JwtBearerOptionsExtensions { public static JwtBearerOptions UseGoogle(this JwtBearerOptions options, string clientId) { return options.UseGoogle(clientId, null); } public static JwtBearerOptions UseGoogle(this JwtBearerOptions options, string clientId, string hostedDomain) { if (clientId == null) { throw new ArgumentNullException(nameof(clientId)); } if (clientId.Length == 0) { throw new ArgumentException("ClientId cannot be empty.", nameof(clientId)); } options.Audience = clientId; options.Authority = "https://accounts.google.com"; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new GoogleJwtSecurityTokenHandler()); options.TokenValidationParameters = new GoogleTokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, NameClaimType = GoogleClaimTypes.Name, AuthenticationType = JwtBearerDefaults.AuthenticationScheme, HostedDomain = hostedDomain, ValidIssuers = new[] { options.Authority, "accounts.google.com" }, }; return options; } } }
using System; using Hellang.Authentication.JwtBearer.Google; using Microsoft.AspNetCore.Authentication.JwtBearer; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class JwtBearerOptionsExtensions { public static JwtBearerOptions UseGoogle(this JwtBearerOptions options, string clientId) { return options.UseGoogle(clientId, null); } public static JwtBearerOptions UseGoogle(this JwtBearerOptions options, string clientId, string hostedDomain) { if (clientId == null) { throw new ArgumentNullException(nameof(clientId)); } if (clientId.Length == 0) { throw new ArgumentException("ClientId cannot be empty.", nameof(clientId)); } options.Audience = clientId; options.Authority = "https://accounts.google.com"; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new GoogleJwtSecurityTokenHandler()); options.TokenValidationParameters = new GoogleTokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, NameClaimType = GoogleClaimTypes.Name, AuthenticationType = "Google." + JwtBearerDefaults.AuthenticationScheme, HostedDomain = hostedDomain, ValidIssuers = new[] { options.Authority, "accounts.google.com" }, }; return options; } } }
Add comment about other calculation methods
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType { /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Identifies the method to calculate the result /// </summary> public enum CalculationType { // TODO: We might implement some other calculation methods as needed? // Percent of Special Earnings: Select to calculate the deduction as a percent of a special accumulator, such as 401(k). /// <summary> /// Deduction is taken as a percentage of the gross pay /// </summary> PercentOfGrossPay = 1, /// <summary> /// Deduction is taken as a percentage of the net pay /// </summary> PercentOfNetPay = 2, /// <summary> /// Deduction is taken as a flat, fixed amount /// </summary> FixedAmount = 3, /// <summary> /// Deduction is taken as a fixed amount per hour of work /// </summary> FixedHourlyAmount = 4 } public static class CalculationTypes { public static IEnumerable<CalculationType> Values() { yield return CalculationType.PercentOfGrossPay; yield return CalculationType.PercentOfNetPay; yield return CalculationType.FixedAmount; yield return CalculationType.FixedHourlyAmount; } } }
Add the usage of the .net linked list as an example for comparison in the outcomes
using System; using AlgorithmsAndDataStructures.LinkedList; namespace AlgorithmsAndDataStructures { class Program { static void Main(string[] args) { // +-----+------+ // | 3 | null + // +-----+------+ Node first = new Node {Value = 3}; // +-----+------+ // | 5 | null + // +-----+------+ Node middle = new Node() {Value = 5}; // +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | null + // +-----+------+ +-----+------+ first.Next = middle; // +-----+------+ +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | null + | 7 | null + // +-----+------+ +-----+------+ +-----+------+ Node last = new Node{Value = 7}; // +-----+------+ +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | *---+-->| 7 | null + // +-----+------+ +-----+------+ +-----+------+ middle.Next = last; PrintList(first); } private static void PrintList(Node firstNode) { while (firstNode != null) { Console.WriteLine(firstNode.Value); firstNode = firstNode.Next; } } } }
using System; using AlgorithmsAndDataStructures.LinkedList; namespace AlgorithmsAndDataStructures { class Program { static void Main(string[] args) { // AT FIRST USE THE .NET FRAMEWORK LINKEDLIST CLASS System.Collections.Generic.LinkedList<int> list = new System.Collections.Generic.LinkedList<int>(); list.AddLast(3); list.AddLast(5); list.AddLast(7); foreach (var value in list) { Console.WriteLine(value); } // +-----+------+ // | 3 | null + // +-----+------+ Node first = new Node {Value = 3}; // +-----+------+ // | 5 | null + // +-----+------+ Node middle = new Node() {Value = 5}; // +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | null + // +-----+------+ +-----+------+ first.Next = middle; // +-----+------+ +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | null + | 7 | null + // +-----+------+ +-----+------+ +-----+------+ Node last = new Node{Value = 7}; // +-----+------+ +-----+------+ +-----+------+ // | 3 | *---+--->| 5 | *---+-->| 7 | null + // +-----+------+ +-----+------+ +-----+------+ middle.Next = last; PrintList(first); } private static void PrintList(Node firstNode) { while (firstNode != null) { Console.WriteLine(firstNode.Value); firstNode = firstNode.Next; } } } }
Add icon for needs measure
@model IEnumerable<ABCP> <h2>ABCP @Html.ActionLink("Add New", "New", "ABCP", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td>@Html.DisplayFor(_ => model.Date)</td> <td> @if (model.IsPassing) { <span class="label label-danger">Failure</span> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
@model IEnumerable<ABCP> <h2>ABCP @Html.ActionLink("Add New", "New", "ABCP", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th></th> </tr> </thead> <tbody> @foreach (var model in Model) { <tr> <td>@Html.DisplayFor(_ => model.Soldier)</td> <td>@Html.DisplayFor(_ => model.Date)</td> <td> @if (model.IsPassing) { <span class="label label-danger">Failure</span> } </td> <td> @if (model.RequiresTape && !model.Measurements.Any()) { <a href="@Url.Action("Measurements", new { model.Id })"> <span class="label label-warning">Requires Measurement</span> </a> } </td> <td>@Html.ActionLink("Details", "Details", new { model.Id })</td> </tr> } </tbody> </table>
Use yield return instead of allocating new list.
using Newtonsoft.Json; using ReactiveUI; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using WalletWasabi.Gui.ViewModels.Validation; using WalletWasabi.Models; namespace WalletWasabi.Gui.ViewModels { public class ViewModelBase : ReactiveObject, INotifyDataErrorInfo { private List<(string propertyName, MethodInfo mInfo)> ValidationMethodCache; public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; public ViewModelBase() { var vmc = Validator.PropertiesWithValidation(this).ToList(); if (vmc.Count == 0) return; ValidationMethodCache = vmc; } public bool HasErrors => Validator.ValidateAllProperties(this, ValidationMethodCache).HasErrors; public IEnumerable GetErrors(string propertyName) { var error = Validator.ValidateProperty(this, propertyName, ValidationMethodCache); if (!error.HasErrors) return null; // HACK: Need to serialize this in order to pass through IndeiValidationPlugin on Avalonia 0.8.2. // Should be removed when Avalonia has the hotfix update. return new List<string>() { JsonConvert.SerializeObject(error) }; } protected void NotifyErrorsChanged(string propertyName) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } }
using Newtonsoft.Json; using ReactiveUI; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using WalletWasabi.Gui.ViewModels.Validation; using WalletWasabi.Models; namespace WalletWasabi.Gui.ViewModels { public class ViewModelBase : ReactiveObject, INotifyDataErrorInfo { private List<(string propertyName, MethodInfo mInfo)> ValidationMethodCache; public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; public ViewModelBase() { var vmc = Validator.PropertiesWithValidation(this).ToList(); if (vmc.Count == 0) return; ValidationMethodCache = vmc; } public bool HasErrors => Validator.ValidateAllProperties(this, ValidationMethodCache).HasErrors; public IEnumerable GetErrors(string propertyName) { var error = Validator.ValidateProperty(this, propertyName, ValidationMethodCache); // HACK: Need to serialize this in order to pass through IndeiValidationPlugin on Avalonia 0.8.2. // Should be removed when Avalonia has the hotfix update. if (error.HasErrors) yield return JsonConvert.SerializeObject(error); } protected void NotifyErrorsChanged(string propertyName) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } }
Fix checkbox change not raising settings update
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Misc; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public partial class TcpSocketSettings : UserControl { private readonly Settings _settings; private readonly SettingNames _names = SettingNames.Instance; public TcpSocketSettings(Settings settings) { _settings = settings; InitializeComponent(); checkBox_EnableTcpOutput.Checked = _settings.Get<bool>(_names.tcpSocketEnabled); checkBox_EnableTcpOutput.CheckedChanged += checkBox_EnableTcpOutput_CheckedChanged; } private void checkBox_EnableTcpOutput_CheckedChanged(object sender, EventArgs e) { _settings.Add(_names.tcpSocketEnabled.Name, checkBox_EnableTcpOutput.Checked); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Misc; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public partial class TcpSocketSettings : UserControl { private readonly Settings _settings; private readonly SettingNames _names = SettingNames.Instance; public TcpSocketSettings(Settings settings) { _settings = settings; InitializeComponent(); checkBox_EnableTcpOutput.Checked = _settings.Get<bool>(_names.tcpSocketEnabled); checkBox_EnableTcpOutput.CheckedChanged += checkBox_EnableTcpOutput_CheckedChanged; } private void checkBox_EnableTcpOutput_CheckedChanged(object sender, EventArgs e) { _settings.Add(_names.tcpSocketEnabled.Name, checkBox_EnableTcpOutput.Checked, true); } } }
Fix not compiling, missing import
using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Game.HideHoldOut.Libraries; namespace Oxide.Plugins { public abstract class HideHoldOutPlugin : CSharpPlugin { protected Command cmd; protected HideHoldOut h2o; public override void SetPluginInfo(string name, string path) { base.SetPluginInfo(name, path); cmd = Interface.Oxide.GetLibrary<Command>(); h2o = Interface.Oxide.GetLibrary<HideHoldOut>("H2o"); } public override void HandleAddedToManager(PluginManager manager) { foreach (var method in GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) { var attributes = method.GetCustomAttributes(typeof(ConsoleCommandAttribute), true); if (attributes.Length > 0) { var attribute = attributes[0] as ConsoleCommandAttribute; cmd.AddConsoleCommand(attribute?.Command, this, method.Name); continue; } attributes = method.GetCustomAttributes(typeof(ChatCommandAttribute), true); if (attributes.Length > 0) { var attribute = attributes[0] as ChatCommandAttribute; cmd.AddChatCommand(attribute?.Command, this, method.Name); } } base.HandleAddedToManager(manager); } } }
using System.Reflection; using Oxide.Core; using Oxide.Core.Plugins; using Oxide.Game.HideHoldOut.Libraries; namespace Oxide.Plugins { public abstract class HideHoldOutPlugin : CSharpPlugin { protected Command cmd; protected HideHoldOut h2o; public override void SetPluginInfo(string name, string path) { base.SetPluginInfo(name, path); cmd = Interface.Oxide.GetLibrary<Command>(); h2o = Interface.Oxide.GetLibrary<HideHoldOut>("H2o"); } public override void HandleAddedToManager(PluginManager manager) { foreach (var method in GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) { var attributes = method.GetCustomAttributes(typeof(ConsoleCommandAttribute), true); if (attributes.Length > 0) { var attribute = attributes[0] as ConsoleCommandAttribute; cmd.AddConsoleCommand(attribute?.Command, this, method.Name); continue; } attributes = method.GetCustomAttributes(typeof(ChatCommandAttribute), true); if (attributes.Length > 0) { var attribute = attributes[0] as ChatCommandAttribute; cmd.AddChatCommand(attribute?.Command, this, method.Name); } } base.HandleAddedToManager(manager); } } }
Make Params required (not default)
using CommandLine; using CommandLine.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tailor { public class Options { [Option('a', "appDir", DefaultValue = "app", HelpText = "Directory app is placed in")] public string AppDir { get; set; } [Option('d', "outputDroplet", DefaultValue = "app", HelpText = "the output droplet")] public string OutputDroplet { get; set; } [Option('m', "outputMetadata", DefaultValue = "app", HelpText = "Directory to the output metadata json file")] public string OutputMetadata { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
using CommandLine; using CommandLine.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tailor { public class Options { [Option('a', "appDir", Required = true, HelpText = "Directory app is placed in")] public string AppDir { get; set; } [Option('d', "outputDroplet", Required = true, HelpText = "the output droplet")] public string OutputDroplet { get; set; } [Option('m', "outputMetadata", Required = true, HelpText = "Directory to the output metadata json file")] public string OutputMetadata { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
Add get best id method for user.
namespace TraktApiSharp.Objects.Get.Users { using Newtonsoft.Json; using System; public class TraktUser { [JsonProperty(PropertyName = "username")] public string Username { get; set; } [JsonProperty(PropertyName = "private")] public bool? Private { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "vip")] public bool? VIP { get; set; } [JsonProperty(PropertyName = "vip_ep")] public bool? VIP_EP { get; set; } [JsonProperty(PropertyName = "joined_at")] public DateTime? JoinedAt { get; set; } [JsonProperty(PropertyName = "location")] public string Location { get; set; } [JsonProperty(PropertyName = "about")] public string About { get; set; } [JsonProperty(PropertyName = "gender")] public string Gender { get; set; } [JsonProperty(PropertyName = "age")] public int? Age { get; set; } [JsonProperty(PropertyName = "images")] public TraktUserImages Images { get; set; } } }
namespace TraktApiSharp.Objects.Get.Users { using Newtonsoft.Json; using System; /// <summary>A Trakt user.</summary> public class TraktUser { /// <summary>Gets or sets the user's username.</summary> [JsonProperty(PropertyName = "username")] public string Username { get; set; } /// <summary>Gets or sets the user's privacy status.</summary> [JsonProperty(PropertyName = "private")] public bool? Private { get; set; } /// <summary>Gets or sets the user's name.</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary>Gets or sets the user's VIP status.</summary> [JsonProperty(PropertyName = "vip")] public bool? VIP { get; set; } /// <summary>Gets or sets the user's VIP EP status.</summary> [JsonProperty(PropertyName = "vip_ep")] public bool? VIP_EP { get; set; } /// <summary>Gets or sets the UTC datetime when the user joined Trakt.</summary> [JsonProperty(PropertyName = "joined_at")] public DateTime? JoinedAt { get; set; } /// <summary>Gets or sets the user's location.</summary> [JsonProperty(PropertyName = "location")] public string Location { get; set; } /// <summary>Gets or sets the user's about information.</summary> [JsonProperty(PropertyName = "about")] public string About { get; set; } /// <summary>Gets or sets the user's gender.</summary> [JsonProperty(PropertyName = "gender")] public string Gender { get; set; } /// <summary>Gets or sets the user's age.</summary> [JsonProperty(PropertyName = "age")] public int? Age { get; set; } /// <summary>Gets or sets the collection of images for the user.</summary> [JsonProperty(PropertyName = "images")] public TraktUserImages Images { get; set; } } }
Make tags and fields more thread safe.
using System; using System.Collections.Generic; using System.Linq; namespace Ocelog { public enum LogLevel { Info, Warn, Error } public class LogEvent { private List<string> _tags = new List<string>(); private List<object> _fields= new List<object>(); private object _content; public object Content { get { return _content; } set { EnsureValidType(value, nameof(value)); _content = value; } } public LogLevel Level { get; set; } public CallerInfo CallerInfo { get; set; } public DateTime Timestamp { get; set; } public IEnumerable<string> Tags { get { return _tags; } } public IEnumerable<object> AdditionalFields { get { return _fields; } } public void AddTag(string tag) { _tags.Add(tag); } public void AddField(object additionalFields) { EnsureValidType(additionalFields, nameof(additionalFields)); _fields.Add(additionalFields); } private void EnsureValidType(object value, string nameof) { if (value.GetType().IsPrimitive) throw new InvalidLogMessageTypeException(nameof, $"{nameof} cannot be a primitive type."); if (value is string) throw new InvalidLogMessageTypeException(nameof, $"{nameof} cannot be a string."); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Ocelog { public enum LogLevel { Info, Warn, Error } public class LogEvent { private ConcurrentQueue<string> _tags = new ConcurrentQueue<string>(); private ConcurrentQueue<object> _fields= new ConcurrentQueue<object>(); private object _content; public object Content { get { return _content; } set { EnsureValidType(value, nameof(value)); _content = value; } } public LogLevel Level { get; set; } public CallerInfo CallerInfo { get; set; } public DateTime Timestamp { get; set; } public IEnumerable<string> Tags { get { return _tags; } } public IEnumerable<object> AdditionalFields { get { return _fields; } } public void AddTag(string tag) { _tags.Enqueue(tag); } public void AddField(object additionalFields) { EnsureValidType(additionalFields, nameof(additionalFields)); _fields.Enqueue(additionalFields); } private void EnsureValidType(object value, string nameof) { if (value.GetType().IsPrimitive) throw new InvalidLogMessageTypeException(nameof, $"{nameof} cannot be a primitive type."); if (value is string) throw new InvalidLogMessageTypeException(nameof, $"{nameof} cannot be a string."); } } }
Change section title to read better
// 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.Localisation; using osu.Game.Rulesets; namespace osu.Game.Screens.Edit.Setup { public abstract class RulesetSetupSection : SetupSection { public sealed override LocalisableString Title => $"{rulesetInfo.Name}-specific"; private readonly RulesetInfo rulesetInfo; protected RulesetSetupSection(RulesetInfo rulesetInfo) { this.rulesetInfo = rulesetInfo; } } }
// 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.Localisation; using osu.Game.Rulesets; namespace osu.Game.Screens.Edit.Setup { public abstract class RulesetSetupSection : SetupSection { public sealed override LocalisableString Title => $"Ruleset ({rulesetInfo.Name})"; private readonly RulesetInfo rulesetInfo; protected RulesetSetupSection(RulesetInfo rulesetInfo) { this.rulesetInfo = rulesetInfo; } } }
Switch failing test to passing tests (AppVeyor now successfully running xunit tests and failing the build on failing test)
using System; using Xunit; namespace ControlFlow.Test { public class TryTest { [Fact] public void Fail() { throw new Exception(); } } }
using System; using Xunit; namespace ControlFlow.Test { public class TryTest { [Fact] public void Pass() { } } }
Implement parser to get tests passing
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Bugsnag.Common { public class StacktraceLineParser { public string ParseFile(string line) { throw new NotImplementedException(); } public string ParseMethodName(string line) { throw new NotImplementedException(); } public int? ParseLineNumber(string line) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Bugsnag.Common { public class StacktraceLineParser { Regex _fileRegex = new Regex("\\) [^ ]+ (.+):"); public string ParseFile(string line) { var match = _fileRegex.Match(line); if (match.Groups.Count < 2) { return ""; } return match.Groups[1].Value; } Regex _methodNameRegex = new Regex("^ *[^ ]+ (.+\\))"); public string ParseMethodName(string line) { var match = _methodNameRegex.Match(line); if (match.Groups.Count < 2) { return line; } return match.Groups[1].Value; } Regex _lineNumberRegex = new Regex(":.+ ([0-9]+)$"); public int? ParseLineNumber(string line) { var match = _lineNumberRegex.Match(line); if (match.Groups.Count < 2) { return null; } if (int.TryParse(match.Groups[1].Value, out var lineNumber)) { return lineNumber; } else { return null; } } } }
Set "isInitialized" to true, or we don't terminate the analytics
using System; using System.Collections.Generic; using Xamarin; namespace Espera.Core.Analytics { internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint { private bool isInitialized; public void Dispose() { // Xamarin Insights can only be terminated if it has been started before, otherwise it // throws an exception if (this.isInitialized) { Insights.Terminate(); this.isInitialized = false; } } public void Identify(string id, IDictionary<string, string> traits = null) { Insights.Identify(id, traits); } public void Initialize() { Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath); } public void ReportBug(string message) { var exception = new Exception(message); Insights.Report(exception); } public void ReportFatalException(Exception exception) { Insights.Report(exception, ReportSeverity.Error); } public void ReportNonFatalException(Exception exception) { Insights.Report(exception); } public void Track(string key, IDictionary<string, string> traits = null) { Insights.Track(key, traits); } public void UpdateEmail(string email) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Xamarin; namespace Espera.Core.Analytics { internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint { private bool isInitialized; public void Dispose() { // Xamarin Insights can only be terminated if it has been started before, otherwise it // throws an exception if (this.isInitialized) { Insights.Terminate(); this.isInitialized = false; } } public void Identify(string id, IDictionary<string, string> traits = null) { Insights.Identify(id, traits); } public void Initialize() { Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath); this.isInitialized = true; } public void ReportBug(string message) { var exception = new Exception(message); Insights.Report(exception); } public void ReportFatalException(Exception exception) { Insights.Report(exception, ReportSeverity.Error); } public void ReportNonFatalException(Exception exception) { Insights.Report(exception); } public void Track(string key, IDictionary<string, string> traits = null) { Insights.Track(key, traits); } public void UpdateEmail(string email) { throw new NotImplementedException(); } } }
Add an explanatory comment about why the AssemblyVersion and AssemblyFileVersion are different.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("icu.net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL International")] [assembly: AssemblyProduct("icu.net")] [assembly: AssemblyCopyright("Copyright © SIL International 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3439151b-347b-4321-9f2f-d5fa28b46477")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: // (These numbers match the ICU version number we're building against.) [assembly: AssemblyVersion("4.2.1.0")] [assembly: AssemblyFileVersion("5.0.0.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("icu.net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL International")] [assembly: AssemblyProduct("icu.net")] [assembly: AssemblyCopyright("Copyright © SIL International 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3439151b-347b-4321-9f2f-d5fa28b46477")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: // (The AssemblyVersion needs to match the version that Palaso builds against.) // (The AssemblyFileVersion matches the ICU version number we're building against.) [assembly: AssemblyVersion("4.2.1.0")] [assembly: AssemblyFileVersion("5.0.0.2")]
Throw for negative count of marbles condition
using System; using TechTalk.SpecFlow; using Xunit; namespace Web.UI.Tests { [Binding] public class SimpleSteps { private static int MarblesCount; [Given(@"I have (.*) marbles")] public void GivenIHaveMarbles(int count) { MarblesCount = count; } [When(@"I give away (.*) marbles")] public void WhenIGiveAwayMarbles(int count) { MarblesCount = Math.Max(0, MarblesCount - count); } [Then(@"I should have (.*) marbles")] public void ThenIShouldHaveMarbles(int count) { Assert.Equal(count, MarblesCount); } } }
using System; using TechTalk.SpecFlow; using Xunit; namespace Web.UI.Tests { [Binding] public class SimpleSteps { private static int MarblesCount; [Given(@"I have (.*) marbles")] public void GivenIHaveMarbles(int count) { MarblesCount = count; } [When(@"I give away (.*) marbles")] public void WhenIGiveAwayMarbles(int count) { if (count > MarblesCount) throw new ArgumentOutOfRangeException("count must be less than to equal to MarblesCount."); MarblesCount = MarblesCount - count; } [Then(@"I should have (.*) marbles")] public void ThenIShouldHaveMarbles(int count) { Assert.Equal(count, MarblesCount); } } }
Add assertion covering free mod selection mod validity filter
// 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.Containers; using osu.Game.Screens.OnlinePlay; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneFreeModSelectScreen : MultiplayerTestScene { [Test] public void TestFreeModSelect() { FreeModSelectScreen freeModSelectScreen = null; AddStep("create free mod select screen", () => Child = freeModSelectScreen = new FreeModSelectScreen { State = { Value = Visibility.Visible } }); AddToggleStep("toggle visibility", visible => { if (freeModSelectScreen != null) freeModSelectScreen.State.Value = visible ? Visibility.Visible : Visibility.Hidden; }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Overlays.Mods; using osu.Game.Screens.OnlinePlay; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneFreeModSelectScreen : MultiplayerTestScene { [Test] public void TestFreeModSelect() { FreeModSelectScreen freeModSelectScreen = null; AddStep("create free mod select screen", () => Child = freeModSelectScreen = new FreeModSelectScreen { State = { Value = Visibility.Visible } }); AddAssert("all visible mods are playable", () => this.ChildrenOfType<ModPanel>() .Where(panel => panel.IsPresent) .All(panel => panel.Mod.HasImplementation && panel.Mod.UserPlayable)); AddToggleStep("toggle visibility", visible => { if (freeModSelectScreen != null) freeModSelectScreen.State.Value = visible ? Visibility.Visible : Visibility.Hidden; }); } } }
Increase default receive high-water mark
using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 100.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 2; ClosedStateDurationAfterSendFailure = 15.Seconds(); ClosedStateDurationAfterConnectFailure = 2.Minutes(); ReceiveHighWaterMark = 20000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDurationAfterSendFailure { get; set; } public TimeSpan ClosedStateDurationAfterConnectFailure { get; set; } public int ReceiveHighWaterMark { get; set; } } }
using System; using Abc.Zebus.Util; namespace Abc.Zebus.Transport { public class ZmqSocketOptions { public ZmqSocketOptions() { ReadTimeout = 300.Milliseconds(); SendHighWaterMark = 20000; SendTimeout = 100.Milliseconds(); SendRetriesBeforeSwitchingToClosedState = 2; ClosedStateDurationAfterSendFailure = 15.Seconds(); ClosedStateDurationAfterConnectFailure = 2.Minutes(); ReceiveHighWaterMark = 40000; } public TimeSpan ReadTimeout { set; get; } public int SendHighWaterMark { get; set; } public TimeSpan SendTimeout { get; set; } public int SendRetriesBeforeSwitchingToClosedState { get; set; } public TimeSpan ClosedStateDurationAfterSendFailure { get; set; } public TimeSpan ClosedStateDurationAfterConnectFailure { get; set; } public int ReceiveHighWaterMark { get; set; } } }
Add some robustness to FullName test
using Xunit; using Xunit.Extensions; namespace DotNext.RockAndRoll.UnitTests { public class MusicianTestCase { [Theory] [InlineData("foo", "bar", "foo bar")] [InlineData("bar", "baz", "bar baz")] [InlineData("baz", "qux", "baz qux")] public void FullName_Always_ShouldReturnConcatenationOfNames( string firstName, string lastName, string expected) { var sut = new Musician(firstName, lastName); Assert.Equal(expected, sut.FullName); } } }
using Xunit; using Xunit.Extensions; namespace DotNext.RockAndRoll.UnitTests { public class MusicianTestCase { [Theory] [InlineData("foo", "bar")] [InlineData("bar", "baz")] [InlineData("baz", "qux")] public void FullName_Always_ShouldReturnConcatenationOfNames( string firstName, string lastName) { var sut = new Musician(firstName, lastName); Assert.Equal(firstName + " " + lastName, sut.FullName); } } }
Allow automatic migration with data loss for the metadata db.
// ----------------------------------------------------------------------- // <copyright file="Configuration.cs" company=""> // Copyright 2014 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System.Data.Entity.Migrations; using System.Linq; using MySql.Data.Entity; using QDMS; namespace EntityData.Migrations { public class MyDbContextConfiguration : DbMigrationsConfiguration<MyDBContext> { public MyDbContextConfiguration() { AutomaticMigrationsEnabled = true; SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator()); //SetSqlGenerator("System.Data.SqlClient", new SqlServerMigrationSqlGenerator()); //TODO solution? } protected override void Seed(MyDBContext context) { base.Seed(context); } } }
// ----------------------------------------------------------------------- // <copyright file="Configuration.cs" company=""> // Copyright 2014 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System.Data.Entity.Migrations; using System.Linq; using MySql.Data.Entity; using QDMS; namespace EntityData.Migrations { public class MyDbContextConfiguration : DbMigrationsConfiguration<MyDBContext> { public MyDbContextConfiguration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator()); //SetSqlGenerator("System.Data.SqlClient", new SqlServerMigrationSqlGenerator()); //TODO solution? } protected override void Seed(MyDBContext context) { base.Seed(context); } } }
Revert "Making Adjustments for implementation"
using Calendar_Converter.ViewModel; using MVVMObjectLibrary; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace ITATools.ViewModel { public class MainWindowViewModel : ViewModelBase { #region Member Variables private ObservableCollection<ViewModelBase> _currentViewModel; private ViewModelBase _mainView; #endregion #region Default Constructor public MainWindowViewModel() { _mainView = new Calendar_Converter.ViewModel.MainWindowViewModel(); _currentViewModel = new ObservableCollection<ViewModelBase>(); _currentViewModel.Add(_mainView); } #endregion #region Event Handlers #endregion #region Properties /// <summary> /// The CurrentViewModel Property provides the data for the MainWindow that allows the various User Controls to /// be populated, and displayed. /// </summary> public ObservableCollection<ViewModelBase> CurrentViewModel { get { return _currentViewModel; } } #endregion #region Member Methods /// <summary> /// OnDispose Overrides the default OnDispose, and causes the collections /// instantiated to be cleared. /// </summary> protected override void OnDispose() { this.CurrentViewModel.Clear(); } #endregion } }
using Calendar_Converter.ViewModel; using MVVMObjectLibrary; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace ITATools.ViewModel { public class MainWindowViewModel : ViewModelBase { #region Member Variables private ObservableCollection<ViewModelBase> _currentViewModel; private ViewModelBase _mainView; #endregion #region Default Constructor public MainWindowViewModel() { _mainView = new MainViewViewModel(); _currentViewModel = new ObservableCollection<ViewModelBase>(); _currentViewModel.Add(_mainView); } #endregion #region Event Handlers #endregion #region Properties /// <summary> /// The CurrentViewModel Property provides the data for the MainWindow that allows the various User Controls to /// be populated, and displayed. /// </summary> public ObservableCollection<ViewModelBase> CurrentViewModel { get { return _currentViewModel; } } #endregion #region Member Methods /// <summary> /// OnDispose Overrides the default OnDispose, and causes the collections /// instantiated to be cleared. /// </summary> protected override void OnDispose() { this.CurrentViewModel.Clear(); } #endregion } }
Fix unresolved reference to UpdaetManager in the documentation
// Copyright © Dominic Beger 2017 using System; namespace nUpdate.UpdateEventArgs { /// <summary> /// Provides data for the <see cref="UpdateManager.UpdateSearchFinished" />-event. /// </summary> public class UpdateSearchFinishedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="UpdateSearchFinishedEventArgs" />-class. /// </summary> /// <param name="updatesAvailable">A value which indicates whether a new update is available or not.</param> internal UpdateSearchFinishedEventArgs(bool updatesAvailable) { UpdatesAvailable = updatesAvailable; } /// <summary> /// Gets a value indicating whether new updates are available, or not. /// </summary> public bool UpdatesAvailable { get; } } }
// Copyright © Dominic Beger 2017 using System; using nUpdate.Updating; namespace nUpdate.UpdateEventArgs { /// <summary> /// Provides data for the <see cref="UpdateManager.UpdateSearchFinished" />-event. /// </summary> public class UpdateSearchFinishedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref="UpdateSearchFinishedEventArgs" />-class. /// </summary> /// <param name="updatesAvailable">A value which indicates whether a new update is available or not.</param> internal UpdateSearchFinishedEventArgs(bool updatesAvailable) { UpdatesAvailable = updatesAvailable; } /// <summary> /// Gets a value indicating whether new updates are available, or not. /// </summary> public bool UpdatesAvailable { get; } } }
Disable resharper suggestions for return
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main /// executes a FindByTag on the scene, which will get worse and worse with more tagged objects. /// </summary> public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera Main { get { if (cachedCamera == null) { return Refresh(Camera.main); } return cachedCamera; } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main /// executes a FindByTag on the scene, which will get worse and worse with more tagged objects. /// </summary> public static class CameraCache { private static Camera cachedCamera; /// <summary> /// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet. /// </summary> public static Camera Main { get { // ReSharper disable once ConvertIfStatementToReturnStatement if (cachedCamera == null) { return Refresh(Camera.main); } return cachedCamera; } } /// <summary> /// Set the cached camera to a new reference and return it /// </summary> /// <param name="newMain">New main camera to cache</param> public static Camera Refresh(Camera newMain) { return cachedCamera = newMain; } } }
Change "Slideshow" "Max File Size" option default value
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 384; Style.Height = 216; } [Category("General")] [DisplayName("Image Folder Path")] public string RootPath { get; set; } [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 1048576; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Style.Width = 384; Style.Height = 216; } [Category("General")] [DisplayName("Image Folder Path")] public string RootPath { get; set; } [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 5242880; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
Correct class name. Was Mapping
using System; using NHibernate.Type; namespace NHibernate.Engine { /// <summary> /// Defines operations common to "compiled" mappings (ie. <c>SessionFactory</c>) and /// "uncompiled" mappings (ie <c>Configuration</c> that are used by implementors of <c>IType</c> /// </summary> public interface Mapping { IType GetIdentifierType(System.Type persistentType); } }
using System; using NHibernate.Type; namespace NHibernate.Engine { /// <summary> /// Defines operations common to "compiled" mappings (ie. <c>SessionFactory</c>) and /// "uncompiled" mappings (ie <c>Configuration</c> that are used by implementors of <c>IType</c> /// </summary> public interface IMapping { IType GetIdentifierType(System.Type persistentType); } }
Add button-primary-white class to button
<section class="sign-up-alert"> <form action="/subscribe?EmailAlertsTopicId=@ViewData["SignUpAlertsTopicIdTopicId"]" method="POST"> <label for="emailAddress">Sign up to receive our news and email alerts in your inbox</label> <input type="email" name="emailAddress" id="emailAddress" placeholder="Enter your email address"> <button type="submit">Subscribe</button> </form> </section>
<section class="sign-up-alert"> <form action="/subscribe?EmailAlertsTopicId=@ViewData["SignUpAlertsTopicIdTopicId"]" method="POST"> <label for="emailAddress">Sign up to receive our news and email alerts in your inbox</label> <input type="email" name="emailAddress" id="emailAddress" placeholder="Enter your email address"> <button class="button-primary-white" type="submit">Subscribe</button> </form> </section>
Add a specific user-agent to CoinChoose.com requests
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; namespace MultiMiner.Coinchoose.Api { public static class ApiContext { public static List<CoinInformation> GetCoinInformation() { WebClient client = new WebClient(); string jsonString = client.DownloadString("http://www.coinchoose.com/api.php"); JArray jsonArray = JArray.Parse(jsonString); List<CoinInformation> result = new List<CoinInformation>(); foreach (JToken jToken in jsonArray) { CoinInformation coinInformation = new CoinInformation(); coinInformation.PopulateFromJson(jToken); result.Add(coinInformation); } return result; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; namespace MultiMiner.Coinchoose.Api { public static class ApiContext { public static List<CoinInformation> GetCoinInformation() { WebClient client = new WebClient(); const string userAgent = "MultiMiner/V1"; client.Headers.Add("user-agent", userAgent); string jsonString = client.DownloadString("http://www.coinchoose.com/api.php"); JArray jsonArray = JArray.Parse(jsonString); List<CoinInformation> result = new List<CoinInformation>(); foreach (JToken jToken in jsonArray) { CoinInformation coinInformation = new CoinInformation(); coinInformation.PopulateFromJson(jToken); result.Add(coinInformation); } return result; } } }
Move foo type to static member
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class TypeNameMatcherTest { interface IFoo { } class Foo : IFoo { } [Fact] public void ShouldThrowIfInitializedWithUnnasignableType() { var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) })); } [Theory] [InlineData("Foo", typeof(Foo))] [InlineData("foo", typeof(Foo))] public void ShouldGetTypeStartingWithCommandName(string commandName, Type fooType) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { fooType }); Assert.Equal(fooType, matcher.GetMatchedType(commandName)); } [Theory] [InlineData("Bar", typeof(Foo))] public void ShouldThrowWhenNoTypesMatches(string commandName, Type fooType) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { fooType }); Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName)); } } }
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class TypeNameMatcherTest { interface IFoo { } class Foo : IFoo { } private static Type FooType = typeof(Foo); [Fact] public void ShouldThrowIfInitializedWithUnnasignableType() { var exception = Assert.Throws<ArgumentException>(() => new TypeNameMatcher<IFoo>(new List<Type> { typeof(string) })); } [Theory] [InlineData("Foo")] [InlineData("foo")] public void ShouldGetTypeStartingWithCommandName(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Equal(FooType, matcher.GetMatchedType(commandName)); } [Theory] [InlineData("Bar")] public void ShouldThrowWhenNoTypesMatches(string commandName) { var matcher = new TypeNameMatcher<IFoo>(new Type[] { FooType }); Assert.Throws<ArgumentException>(() => matcher.GetMatchedType(commandName)); } } }
Add link to kendo grid title
@using Kendo.Mvc.UI @using VotingSystem.Web.ViewModels.Polls @model List<PublicActivePollsViewModel> @{ ViewBag.Title = "All Public Polls"; } <h1>@ViewBag.Title</h1> @(Html.Kendo().Grid(Model) .Name("pollGrid") .Columns(col => { col.Bound(poll => poll.Id).Hidden(); col.Bound(poll => poll.Title).ClientTemplate("<a href='" + Url.Action("All", "Polls", new { Id_Cliente = "#: Id #" }) + "'>#= Title #</a>"); col.Bound(poll => poll.Description); col.Bound(poll => poll.Author); col.Bound(poll => poll.StartDate); col.Bound(poll => poll.EndDate); }) .Sortable() .Pageable() .Filterable())
@using Kendo.Mvc.UI @using VotingSystem.Web.ViewModels.Polls @model List<PublicActivePollsViewModel> @{ ViewBag.Title = "All Public Polls"; } <h1>@ViewBag.Title</h1> @(Html.Kendo().Grid(Model) .Name("pollGrid") .Columns(col => { col.Bound(poll => poll.Id).Hidden(); col.Bound(p => p.Title).Template(@<text> <strong> <a href="/Polls/All/@item.Id">@item.Title</a></strong> </text>); col.Bound(poll => poll.Title); col.Bound(poll => poll.Description); col.Bound(poll => poll.Author); col.Bound(poll => poll.StartDate); col.Bound(poll => poll.EndDate); }) .Sortable() .Pageable() .Filterable())
Add owner user id for bags
using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace TheCollection.Business.Tea { [JsonConverter(typeof(SearchableConverter))] public class Bag { [Key] [JsonProperty(PropertyName = "id")] public string Id { get; set; } [Searchable] [JsonProperty(PropertyName = "mainid")] public int MainID { get; set; } [Searchable] [JsonProperty(PropertyName = "brand")] public RefValue Brand { get; set; } [Searchable] [JsonProperty(PropertyName = "serie")] public string Serie { get; set; } [Searchable] [JsonProperty(PropertyName = "flavour")] public string Flavour { get; set; } [Searchable] [JsonProperty(PropertyName = "hallmark")] public string Hallmark { get; set; } [Searchable] [JsonProperty(PropertyName = "bagtype")] public RefValue BagType { get; set; } [Searchable] [JsonProperty(PropertyName = "country")] public RefValue Country { get; set; } [Searchable] [JsonProperty(PropertyName = "serialnumber")] public string SerialNumber { get; set; } [JsonProperty(PropertyName = "insertdate")] public string InsertDate { get; set; } [JsonProperty(PropertyName = "imageid")] public string ImageId { get; set; } } }
using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace TheCollection.Business.Tea { [JsonConverter(typeof(SearchableConverter))] public class Bag { [Key] [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "userid")] public string UserId { get; set; } [Searchable] [JsonProperty(PropertyName = "mainid")] public int MainID { get; set; } [Searchable] [JsonProperty(PropertyName = "brand")] public RefValue Brand { get; set; } [Searchable] [JsonProperty(PropertyName = "serie")] public string Serie { get; set; } [Searchable] [JsonProperty(PropertyName = "flavour")] public string Flavour { get; set; } [Searchable] [JsonProperty(PropertyName = "hallmark")] public string Hallmark { get; set; } [Searchable] [JsonProperty(PropertyName = "bagtype")] public RefValue BagType { get; set; } [Searchable] [JsonProperty(PropertyName = "country")] public RefValue Country { get; set; } [Searchable] [JsonProperty(PropertyName = "serialnumber")] public string SerialNumber { get; set; } [JsonProperty(PropertyName = "insertdate")] public string InsertDate { get; set; } [JsonProperty(PropertyName = "imageid")] public string ImageId { get; set; } } }
Fix the solution for Ex05
using System; using System.Threading; namespace Lurchsoft.ParallelWorkshop.Ex05DatedSerial.PossibleSolution { public class LazyDatedSerial { private Lazy<ThreadSafeSerial> serial = new Lazy<ThreadSafeSerial>(LazyThreadSafetyMode.ExecutionAndPublication); public string GetNextSerial() { return serial.Value.GetNextSerial(); } private class ThreadSafeSerial { private readonly string prefix; private int serial; public ThreadSafeSerial(string prefix) { this.prefix = prefix; } public string GetNextSerial() { int thisSerial = Interlocked.Increment(ref serial); return string.Format("{0}-{1}", prefix, thisSerial); } } } }
using System; using System.Threading; namespace Lurchsoft.ParallelWorkshop.Ex05DatedSerial.PossibleSolution { public class LazyDatedSerial { private Lazy<ThreadSafeSerial> serial = new Lazy<ThreadSafeSerial> (() => new ThreadSafeSerial(DateTime.Now.ToShortDateString()), LazyThreadSafetyMode.ExecutionAndPublication); public string GetNextSerial() { return serial.Value.GetNextSerial(); } private class ThreadSafeSerial { private readonly string prefix; private int serial; public ThreadSafeSerial(string prefix) { this.prefix = prefix; } public string GetNextSerial() { int thisSerial = Interlocked.Increment(ref serial); return string.Format("{0}-{1}", prefix, thisSerial); } } } }
Remove now-redundant code previously used for dictionary support
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using System.Linq; namespace Google.Cloud.Spanner.Data { internal static class TypeUtil { public static bool DictionaryEquals(IDictionary d1, IDictionary d2) { if (d1 == null && d2 == null) { return true; } if (d1 == null || d2 == null) { return false; } return d1.Count == d2.Count && d1.Keys.Cast<object>().All(key => d2.Contains(key) && Equals(d2[key], d1[key])); } public static bool DictionaryEquals<TK, TV>(IDictionary<TK, TV> d1, IDictionary<TK, TV> d2) { if (d1 == null && d2 == null) { return true; } if (d1 == null || d2 == null) { return false; } return d1.Count == d2.Count && d1.Keys.All(key => d2.ContainsKey(key) && Equals(d2[key], d1[key])); } } }
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Linq; namespace Google.Cloud.Spanner.Data { internal static class TypeUtil { public static bool DictionaryEquals(IDictionary d1, IDictionary d2) { if (d1 == null && d2 == null) { return true; } if (d1 == null || d2 == null) { return false; } return d1.Count == d2.Count && d1.Keys.Cast<object>().All(key => d2.Contains(key) && Equals(d2[key], d1[key])); } } }
Reduce the amount of 'PersistedCityStatistics'
using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 20800) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }
using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 5200) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }
Add GitHub auth. Hide option in UI
using System; using System.IO; using System.Net; namespace SimpleWAWS.Authentication { public static class AuthUtilities { public static string GetContentFromUrl(string url) { var request = (HttpWebRequest)WebRequest.Create(url); using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.UserAgent = "x-ms-try-appservice"; if (jsonAccept) { request.Accept = "application/json"; } if (addGitHubHeaders) { request.Accept = "application/vnd.github.v3+json"; } if (!String.IsNullOrEmpty(AuthorizationHeader)) { request.Headers.Add("Authorization", AuthorizationHeader); } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } } }
using System; using System.IO; using System.Net; namespace SimpleWAWS.Authentication { public static class AuthUtilities { public static string GetContentFromUrl(string url, string method="GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader ="") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.UserAgent = "Anything"; if (jsonAccept) request.Accept = "application/json"; if (addGitHubHeaders) request.Accept = "application/vnd.github.v3+json"; if (!String.IsNullOrEmpty(AuthorizationHeader)) { request.Headers.Add("Authorization", AuthorizationHeader); } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.UserAgent = "x-ms-try-appservice"; if (jsonAccept) { request.Accept = "application/json"; } if (addGitHubHeaders) { request.Accept = "application/vnd.github.v3+json"; } if (!String.IsNullOrEmpty(AuthorizationHeader)) { request.Headers.Add("Authorization", AuthorizationHeader); } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } } }
Add application title and copyright.
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("dcm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("dcm")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca199dd4-2017-4ee7-808c-3747101e04b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Digital Color Meter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Digital Color Meter")] [assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca199dd4-2017-4ee7-808c-3747101e04b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Allow to set spawn interval public
using UnityEngine; using System.Collections; public class SpawnController : MonoBehaviour { public GameObject enemiesFolder; public GameObject originalEnemy; public int enemiesToSpawn; private int enemiesSpawned; void Start () { enemiesSpawned = 0; InvokeRepeating("SpawnEnemy", 0, 2f); } void SpawnEnemy() { if(enemiesSpawned < enemiesToSpawn) { GameObject anEnemy = Instantiate (originalEnemy); anEnemy.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y + 0.1f, this.transform.position.z); anEnemy.transform.SetParent (enemiesFolder.transform); enemiesSpawned += 1; } } }
using UnityEngine; using System.Collections; public class SpawnController : MonoBehaviour { public GameObject enemiesFolder; public GameObject originalEnemy; public int enemiesToSpawn; public float spawnInterval; private int enemiesSpawned; void Start () { enemiesSpawned = 0; InvokeRepeating("SpawnEnemy", 0, spawnInterval); } void SpawnEnemy() { if(enemiesSpawned < enemiesToSpawn) { GameObject anEnemy = Instantiate (originalEnemy); anEnemy.transform.position = new Vector3 (this.transform.position.x, this.transform.position.y + 0.1f, this.transform.position.z); anEnemy.transform.SetParent (enemiesFolder.transform); enemiesSpawned += 1; } } }
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Web 3.1.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Web 3.1.0")]
Remove TEAK_X_Y_OR_NEWER before adding them again so that in the case of SDK rollback defines are not left in
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; using System.Collections.Generic; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER", "TEAK_2_1_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'); HashSet<string> updatedDefines = new HashSet<string>(existingDefines); updatedDefines.UnionWith(TeakDefines); string[] defines = new string[updatedDefines.Count]; updatedDefines.CopyTo(defines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines)); } }
using UnityEditor; using UnityEditor.Build; #if UNITY_2018_1_OR_NEWER using UnityEditor.Build.Reporting; #endif using UnityEngine; using System.Collections.Generic; class TeakPreProcessDefiner : #if UNITY_2018_1_OR_NEWER IPreprocessBuildWithReport #else IPreprocessBuild #endif { public int callbackOrder { get { return 0; } } public static readonly string[] TeakDefines = new string[] { "TEAK_2_0_OR_NEWER", "TEAK_2_1_OR_NEWER" }; #if UNITY_2018_1_OR_NEWER public void OnPreprocessBuild(BuildReport report) { SetTeakPreprocesorDefines(report.summary.platformGroup); } #else public void OnPreprocessBuild(BuildTarget target, string path) { SetTeakPreprocesorDefines(BuildPipeline.GetBuildTargetGroup(target)); } #endif private void SetTeakPreprocesorDefines(BuildTargetGroup targetGroup) { string[] existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'); HashSet<string> updatedDefines = new HashSet<string>(existingDefines); updatedDefines.RemoveWhere(define => define.StartsWith("TEAK_") && define.EndsWith("_OR_NEWER")); updatedDefines.UnionWith(TeakDefines); string[] defines = new string[updatedDefines.Count]; updatedDefines.CopyTo(defines); PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines)); } }
Update image resolution to UHD
using System; using System.IO; namespace Kfstorm.BingWallpaper { public static class Constants { public static string DataPath { get { string path = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), @"K.F.Storm\BingWallpaper"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } public static string LogFile { get { return "log.log"; } } public static string StateFile { get { return "state.xml"; } } public static string JpgFile { get { return "image.jpg"; } } public static string BmpFile { get { return "image.bmp"; } } public static string WallpaperInfoUrl { get { return string.Format("http://www.bing.com/hpimagearchive.aspx?format=xml&idx={0}&n={1}&mkt={2}", PictureIndex, PictureCount, Market); } } public static int PictureCount { get { return 1; } } public static int PictureIndex { get { return 0; } } public static string Market { get { return "zh-cn"; } } public static string PictureUrlFormat { get { return "http://www.bing.com{0}_1920x1080.jpg"; } } public static TimeZoneInfo TimeZone { get { return TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); } } } }
using System; using System.IO; namespace Kfstorm.BingWallpaper { public static class Constants { public static string DataPath { get { string path = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), @"K.F.Storm\BingWallpaper"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } public static string LogFile { get { return "log.log"; } } public static string StateFile { get { return "state.xml"; } } public static string JpgFile { get { return "image.jpg"; } } public static string BmpFile { get { return "image.bmp"; } } public static string WallpaperInfoUrl { get { return string.Format("http://www.bing.com/hpimagearchive.aspx?format=xml&idx={0}&n={1}&mkt={2}", PictureIndex, PictureCount, Market); } } public static int PictureCount { get { return 1; } } public static int PictureIndex { get { return 0; } } public static string Market { get { return "zh-cn"; } } public static string PictureUrlFormat { get { return "http://www.bing.com{0}_UHD.jpg"; } } public static TimeZoneInfo TimeZone { get { return TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); } } } }
Store ObjectHandle in LogicalCallContext and prevent cross AppDomain Activity usage
// 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.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { // this code is specific to .NET 4.5 and uses CallContext to store Activity.Current which requires Activity to be Serializable. [Serializable] // DO NOT remove public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private [Serializable] // DO NOT remove private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }
// 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.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { ObjectHandle activityHandle = (ObjectHandle)CallContext.LogicalGetData(FieldKey); // Unwrap the Activity if it was set in the same AppDomain (as FieldKey is AppDomain-specific). if (activityHandle != null) { return (Activity)activityHandle.Unwrap(); } return null; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { // Applications may implicitly or explicitly call other AppDomains // that do not have DiagnosticSource DLL, therefore may not be able to resolve Activity type stored in the logical call context. // To avoid it, we wrap Activity with ObjectHandle. CallContext.LogicalSetData(FieldKey, new ObjectHandle(value)); } } #region private private partial class KeyValueListNode { } // Slot name depends on the AppDomain Id in order to prevent AppDomains to use the same Activity // Cross AppDomain calls are considered as 'external' i.e. only Activity Id and Baggage should be propagated and // new Activity should be started for the RPC calls (incoming and outgoing) private static readonly string FieldKey = $"{typeof(Activity).FullName}_{AppDomain.CurrentDomain.Id}"; #endregion } }
Add a control to permit rebase only when Working directory have no changes
using System; using System.Collections.Generic; using System.ComponentModel; using NDesk.Options; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("pull")] [Description("pull [options]")] [RequiresValidGitRepository] public class Pull : GitTfsCommand { private readonly Fetch fetch; private readonly Globals globals; private bool _shouldRebase; public OptionSet OptionSet { get { return fetch.OptionSet .Add("rebase", "rebase your modifications on tfs changes", v => _shouldRebase = v != null ); } } public Pull(Globals globals, Fetch fetch) { this.fetch = fetch; this.globals = globals; } public int Run() { return Run(globals.RemoteId); } public int Run(string remoteId) { var retVal = fetch.Run(remoteId); if (retVal == 0) { var remote = globals.Repository.ReadTfsRemote(remoteId); if (_shouldRebase) globals.Repository.CommandNoisy("rebase", remote.RemoteRef); else globals.Repository.CommandNoisy("merge", remote.RemoteRef); } return retVal; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using NDesk.Options; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("pull")] [Description("pull [options]")] [RequiresValidGitRepository] public class Pull : GitTfsCommand { private readonly Fetch fetch; private readonly Globals globals; private bool _shouldRebase; public OptionSet OptionSet { get { return fetch.OptionSet .Add("rebase", "rebase your modifications on tfs changes", v => _shouldRebase = v != null ); } } public Pull(Globals globals, Fetch fetch) { this.fetch = fetch; this.globals = globals; } public int Run() { return Run(globals.RemoteId); } public int Run(string remoteId) { var retVal = fetch.Run(remoteId); if (retVal == 0) { var remote = globals.Repository.ReadTfsRemote(remoteId); if (_shouldRebase) { if (globals.Repository.WorkingCopyHasUnstagedOrUncommitedChanges) { throw new GitTfsException("error: You have local changes; rebase-workflow only possible with clean working directory.") .WithRecommendation("Try 'git stash' to stash your local changes and pull again."); } globals.Repository.CommandNoisy("rebase", remote.RemoteRef); } else globals.Repository.CommandNoisy("merge", remote.RemoteRef); } return retVal; } } }
Add multiplayer screen test steps.
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using NUnit.Framework; using osu.Game.Screens.Multi; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : OsuTestCase { public TestCaseMultiScreen() { Child = new Multiplayer(); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using NUnit.Framework; using osu.Game.Screens.Multi; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseMultiScreen : OsuTestCase { public TestCaseMultiScreen() { Multiplayer multi = new Multiplayer(); AddStep(@"show", () => Add(multi)); AddWaitStep(5); AddStep(@"exit", multi.Exit); } } }
Add license header to the new file
using System; using System.Collections.Generic; using System.Text; namespace osu.Game.Graphics { public class DrawableJoinDate : DrawableDate { private readonly DateTimeOffset date; public DrawableJoinDate(DateTimeOffset date) : base(date) { this.date = date; } protected override string Format() => Text = string.Format("{0:MMMM yyyy}", date); public override string TooltipText => string.Format("{0:d MMMM yyyy}", date); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Text; namespace osu.Game.Graphics { public class DrawableJoinDate : DrawableDate { private readonly DateTimeOffset date; public DrawableJoinDate(DateTimeOffset date) : base(date) { this.date = date; } protected override string Format() => Text = string.Format("{0:MMMM yyyy}", date); public override string TooltipText => string.Format("{0:d MMMM yyyy}", date); } }
Switch remaining test back to NUnit
using Xunit; using System; using Cake.Core.IO; using Cake.Xamarin.Build; namespace Cake.Xamarin.Build.Tests.Fakes { public class DownloadFileTests : TestFixtureBase { [Fact] public void Download_FacebookSDK () { var url = "https://origincache.facebook.com/developers/resources/?id=FacebookSDKs-iOS-20160210.zip"; var destFile = new FilePath("./fbsdk.zip"); Cake.DownloadFile(url, destFile, new DownloadFileSettings { UserAgent = "curl/7.43.0" }); var fileInfo = new System.IO.FileInfo(destFile.MakeAbsolute(Cake.Environment).FullPath); Assert.True(fileInfo.Exists); Assert.True (fileInfo.Length > 1024); } } }
using System; using Cake.Core.IO; using Cake.Xamarin.Build; using NUnit.Framework; namespace Cake.Xamarin.Build.Tests.Fakes { public class DownloadFileTests : TestFixtureBase { [Test] public void Download_FacebookSDK () { var url = "https://origincache.facebook.com/developers/resources/?id=FacebookSDKs-iOS-20160210.zip"; var destFile = new FilePath("./fbsdk.zip"); Cake.DownloadFile(url, destFile, new DownloadFileSettings { UserAgent = "curl/7.43.0" }); var fileInfo = new System.IO.FileInfo(destFile.MakeAbsolute(Cake.Environment).FullPath); Assert.True(fileInfo.Exists); Assert.True (fileInfo.Length > 1024); } } }
Disable NetworkPlayer extensions in WebGL
using UnityEngine; namespace Extensions { /// <summary> /// Extension methods for UnityEngine.NetworkPlayer. /// </summary> public static class NetworkPlayerExtensions { /// <summary> /// Gets the numeric index of the network player. /// </summary> /// <param name="networkPlayer">Network player.</param> /// <returns>Network player index.</returns> public static int GetIndex(this NetworkPlayer networkPlayer) { return int.Parse(networkPlayer.ToString()); } } }
#if !UNITY_WEBGL using UnityEngine; namespace Extensions { /// <summary> /// Extension methods for UnityEngine.NetworkPlayer. /// </summary> public static class NetworkPlayerExtensions { /// <summary> /// Gets the numeric index of the network player. /// </summary> /// <param name="networkPlayer">Network player.</param> /// <returns>Network player index.</returns> public static int GetIndex(this NetworkPlayer networkPlayer) { return int.Parse(networkPlayer.ToString()); } } } #endif
Simplify firefox title with version selector.
using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using AngleSharp; using AngleSharp.Parser.Html; namespace WebDriverManager.DriverConfigs.Impl { public class FirefoxConfig : IDriverConfig { public virtual string GetName() { return "Firefox"; } public virtual string GetUrl32() { return GetUrl64(); } public virtual string GetUrl64() { return "https://github.com/mozilla/geckodriver/releases/download/v<version>/geckodriver-v<version>-win64.zip"; } public virtual string GetBinaryName() { return "geckodriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/mozilla/geckodriver/releases"); var parser = new HtmlParser(Configuration.Default.WithDefaultLoader()); var document = parser.Parse(htmlCode); var version = document.QuerySelectorAll("[class~='release-title'] a") .Select(element => element.TextContent) .FirstOrDefault() ?.Remove(0, 1); return version; } } } }
using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using AngleSharp; using AngleSharp.Parser.Html; namespace WebDriverManager.DriverConfigs.Impl { public class FirefoxConfig : IDriverConfig { public virtual string GetName() { return "Firefox"; } public virtual string GetUrl32() { return "https://github.com/mozilla/geckodriver/releases/download/v<version>/geckodriver-v<version>-win32.zip"; } public virtual string GetUrl64() { return "https://github.com/mozilla/geckodriver/releases/download/v<version>/geckodriver-v<version>-win64.zip"; } public virtual string GetBinaryName() { return "geckodriver.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/mozilla/geckodriver/releases"); var parser = new HtmlParser(Configuration.Default.WithDefaultLoader()); var document = parser.Parse(htmlCode); var version = document.QuerySelectorAll(".release-title > a") .Select(element => element.TextContent) .FirstOrDefault() ?.Remove(0, 1); return version; } } } }
Add check if data is null
using UnityEngine; using System.Collections; public class Wall : MonoBehaviour { public Sprite dmgSprite; public int hp = 4; public AudioClip chopSound1; public AudioClip chopSound2; //hit points for the wall. private SpriteRenderer spriteRenderer; //Store a component reference to the attached SpriteRenderer. // Use this for initialization void Awakes () { //Get a component reference to the SpriteRenderer. spriteRenderer = GetComponent<SpriteRenderer> (); } //DamageWall is called when the player attacks a wall. public void DamageWall (int loss) { SoundManager.instance.RandomizeSfx (chopSound1, chopSound2); //Set spriteRenderer to the damaged wall sprite. // TODO CHeck the sprite renderer // spriteRenderer.sprite = dmgSprite; //Subtract loss from hit point total. hp -= loss; //If hit points are less than or equal to zero: if(hp <= 0) //Disable the gameObject. gameObject.SetActive (false); } }
using UnityEngine; using System.Collections; public class Wall : MonoBehaviour { public Sprite dmgSprite; public int hp = 4; public AudioClip chopSound1; public AudioClip chopSound2; //hit points for the wall. private SpriteRenderer spriteRenderer; //Store a component reference to the attached SpriteRenderer. // Use this for initialization void Awakes () { //Get a component reference to the SpriteRenderer. spriteRenderer = GetComponent<SpriteRenderer> (); } //DamageWall is called when the player attacks a wall. public void DamageWall (int loss) { SoundManager.instance.RandomizeSfx (chopSound1, chopSound2); //Set spriteRenderer to the damaged wall sprite. // TODO CHeck the sprite renderer if (spriteRenderer != null) { spriteRenderer.sprite = dmgSprite; } //Subtract loss from hit point total. hp -= loss; //If hit points are less than or equal to zero: if(hp <= 0) //Disable the gameObject. gameObject.SetActive (false); } }
Fix possible exceptions in Reflection helper.
using System; using System.Linq; public static class ReflectionHelper { public static Type FindType(string fullName) { return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(t => t.FullName.Equals(fullName)); } public static Type FindType(string fullName, string assemblyName) { return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(t => t.FullName.Equals(fullName) && t.Assembly.GetName().Name.Equals(assemblyName)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class ReflectionHelper { public static Type FindType(string fullName) { return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetSafeTypes()).FirstOrDefault(t => t.FullName != null && t.FullName.Equals(fullName)); } public static Type FindType(string fullName, string assemblyName) { return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetSafeTypes()).FirstOrDefault(t => t.FullName != null && t.FullName.Equals(fullName) && t.Assembly.GetName().Name.Equals(assemblyName)); } private static IEnumerable<Type> GetSafeTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(x => x != null); } catch (Exception) { return new List<Type>(); } } }
Fix broken claims and characters filter
using System.Collections.Generic; using JoinRpg.DataModel; using JoinRpg.Services.Interfaces; namespace JoinRpg.Services.Impl.ClaimProblemFilters { internal class BrokenClaimsAndCharacters : IClaimProblemFilter { public IEnumerable<ClaimProblem> GetProblems(Project project, Claim claim) { if (claim.IsInDiscussion && claim.Character?.ApprovedClaim != null) { yield return new ClaimProblem(claim, ClaimProblemType.ClaimActiveButCharacterHasApprovedClaim); } if (claim.IsActive && (claim.Character == null || !claim.Character.IsActive)) { yield return new ClaimProblem(claim, ClaimProblemType.NoCharacterOnApprovedClaim); } } } }
using System.Collections.Generic; using JoinRpg.DataModel; using JoinRpg.Services.Interfaces; namespace JoinRpg.Services.Impl.ClaimProblemFilters { internal class BrokenClaimsAndCharacters : IClaimProblemFilter { public IEnumerable<ClaimProblem> GetProblems(Project project, Claim claim) { if (claim.IsInDiscussion && claim.Character?.ApprovedClaim != null) { yield return new ClaimProblem(claim, ClaimProblemType.ClaimActiveButCharacterHasApprovedClaim); } if (claim.IsApproved && (claim.Character == null || !claim.Character.IsActive)) { yield return new ClaimProblem(claim, ClaimProblemType.NoCharacterOnApprovedClaim); } } } }
Fix test, we have a custom Exception now that is public.
using AppSettingsByConvention; using FluentAssertions; using NUnit.Framework; namespace AppSettingsByConventionTests { [TestFixture] public class WhenAnalyzingExportedTypes { [Test] public void ShouldMatchWhitelist() { var whiteList = new [] { typeof(SettingsByConvention), typeof(IConnectionString), typeof(IParser) }; var exportedTypes = typeof (SettingsByConvention).Assembly.GetExportedTypes(); exportedTypes.ShouldBeEquivalentTo(whiteList); } } }
using System.Linq; using AppSettingsByConvention; using FluentAssertions; using NUnit.Framework; namespace AppSettingsByConventionTests { [TestFixture] public class WhenAnalyzingExportedTypes { [Test] public void ShouldMatchWhitelist() { var whiteList = new [] { typeof(SettingsByConvention), typeof(IConnectionString), typeof(IParser), typeof(UnsupportedPropertyTypeException) }; var exportedTypes = typeof (SettingsByConvention).Assembly.GetExportedTypes(); exportedTypes.ShouldBeEquivalentTo(whiteList, "that is the whitelist, but found unexpected types "+string.Join(", ", exportedTypes.Except(whiteList))); } } }
Fix bug in SFML mouse wheel
using System; using SFML.Graphics; using SFML.Window; using Point = SadRogue.Primitives.Point; using SFMLMouse = SFML.Window.Mouse; namespace SadConsole.Host { public class Mouse : SadConsole.Input.IMouseState { private int _mouseWheelValue; private RenderWindow _window; public Mouse(RenderWindow window) { window.MouseWheelScrolled += Window_MouseWheelScrolled; _window = window; } ~Mouse() { _window.MouseWheelScrolled -= Window_MouseWheelScrolled; _window = null; } private void Window_MouseWheelScrolled(object sender, MouseWheelScrollEventArgs e) { _mouseWheelValue = (int)e.Delta; } public bool IsLeftButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Left); public bool IsRightButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Right); public bool IsMiddleButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Middle); public Point ScreenPosition { get { SFML.System.Vector2i position = SFMLMouse.GetPosition(_window); return new Point(position.X, position.Y); } } public int MouseWheel => _mouseWheelValue; } }
using System; using SFML.Graphics; using SFML.Window; using Point = SadRogue.Primitives.Point; using SFMLMouse = SFML.Window.Mouse; namespace SadConsole.Host { public class Mouse : SadConsole.Input.IMouseState { private int _mouseWheelValue; private RenderWindow _window; public Mouse(RenderWindow window) { window.MouseWheelScrolled += Window_MouseWheelScrolled; _window = window; } ~Mouse() { _window.MouseWheelScrolled -= Window_MouseWheelScrolled; _window = null; } private void Window_MouseWheelScrolled(object sender, MouseWheelScrollEventArgs e) { _mouseWheelValue += (int)e.Delta; } public bool IsLeftButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Left); public bool IsRightButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Right); public bool IsMiddleButtonDown => SFMLMouse.IsButtonPressed(SFMLMouse.Button.Middle); public Point ScreenPosition { get { SFML.System.Vector2i position = SFMLMouse.GetPosition(_window); return new Point(position.X, position.Y); } } public int MouseWheel => _mouseWheelValue; } }
Format registration a bit better
using Glimpse; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.Collections.Generic; namespace Glimpse { public class GlimpseServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Discovery & Reflection. // yield return describe.Transient<ITypeActivator, DefaultTypeActivator>(); yield return describe.Transient<ITypeSelector, DefaultTypeSelector>(); yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>(); yield return describe.Transient<ITypeService, DefaultTypeService>(); yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>)); // // Messages. // yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>(); // // JSON.Net. // yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } } }
using Glimpse; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.Collections.Generic; using System; using System.Reflection; namespace Glimpse { public class GlimpseServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describe = new ServiceDescriber(configuration); // // Discovery & Reflection. // yield return describe.Transient<ITypeActivator, DefaultTypeActivator>(); yield return describe.Transient<ITypeSelector, DefaultTypeSelector>(); yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>(); yield return describe.Transient<ITypeService, DefaultTypeService>(); yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>)); // // Messages. // yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>(); // // JSON.Net. // yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } } }
Check the state before fetching the thread id
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace System.IO { // Abstract Iterator, borrowed from Linq. Used in anticipation of need for similar enumerables // in the future internal abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TSource> { private int _threadId; internal int state; internal TSource current; public Iterator() { _threadId = Environment.CurrentManagedThreadId; } public TSource Current { get { return current; } } protected abstract Iterator<TSource> Clone(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { current = default(TSource); state = -1; } public IEnumerator<TSource> GetEnumerator() { if (_threadId == Environment.CurrentManagedThreadId && state == 0) { state = 1; return this; } Iterator<TSource> duplicate = Clone(); duplicate.state = 1; return duplicate; } public abstract bool MoveNext(); object IEnumerator.Current { get { return Current; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IEnumerator.Reset() { throw new NotSupportedException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace System.IO { // Abstract Iterator, borrowed from Linq. Used in anticipation of need for similar enumerables // in the future internal abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerator<TSource> { private int _threadId; internal int state; internal TSource current; public Iterator() { _threadId = Environment.CurrentManagedThreadId; } public TSource Current { get { return current; } } protected abstract Iterator<TSource> Clone(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { current = default(TSource); state = -1; } public IEnumerator<TSource> GetEnumerator() { if (state == 0 && _threadId == Environment.CurrentManagedThreadId) { state = 1; return this; } Iterator<TSource> duplicate = Clone(); duplicate.state = 1; return duplicate; } public abstract bool MoveNext(); object IEnumerator.Current { get { return Current; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IEnumerator.Reset() { throw new NotSupportedException(); } } }
Remove Down() from Migrator (it is not used by the engine)
using Microsoft.SharePoint.Client; namespace IonFar.SharePoint.Migration { /// <summary> /// Base class for code-based migrations. /// </summary> public abstract class Migration : IMigration { public abstract void Up(ClientContext clientContext, IUpgradeLog logger); public virtual void Down(ClientContext clientContext, IUpgradeLog logger) { } protected string BaseFolder { get { return System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); } } } }
using Microsoft.SharePoint.Client; namespace IonFar.SharePoint.Migration { /// <summary> /// Base class for code-based migrations. /// </summary> public abstract class Migration : IMigration { public abstract void Up(ClientContext clientContext, IUpgradeLog logger); protected string BaseFolder { get { return System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); } } } }
Add comments about relative Service address.
using System; using System.ServiceModel; using HelloIndigo; namespace Host { class Program { static void Main() { using ( var host = new ServiceHost(typeof (HelloIndigoService), new Uri("http://localhost:8000/HelloIndigo"))) { host.AddServiceEndpoint(typeof (IHelloIndigoService), new BasicHttpBinding(), "HelloIndigoService"); host.Open(); Console.WriteLine( "Press <ENTER> to terminate the service host."); Console.ReadLine(); } } } }
using System; using System.ServiceModel; using HelloIndigo; namespace Host { class Program { static void Main() { // A side effect (although perhaps documented) of supplying // a Uri to the ServiceHost contstructor is that this Uri // becomes the base address for the service. using ( var host = new ServiceHost(typeof (HelloIndigoService), new Uri("http://localhost:8000/HelloIndigo"))) { // By specifying the base address for the service when // constructing the ServiceHost, we can then specify // endpoints using a relative address. That is, the // complete address of the service is // `http://localhost:8080/HelloIndigo/HelloIndigoService`. host.AddServiceEndpoint(typeof (HelloIndigoService), new BasicHttpBinding(), "HelloIndigoService"); host.Open(); Console.WriteLine( "Press <ENTER> to terminate the service host."); Console.ReadLine(); } } } }
Fix nullRef when processing empty entities (imported from main endpoind to extended one)
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace PX.Api.ContractBased.Maintenance.Cli.Utils { static class Sorter { public static void Sort(this XDocument original) { XElement root = original.Elements().Single(); XNamespace Namespace = root.Name.Namespace; IEnumerable<XElement> Entities = root.Elements().Except(new[] { root.Element(Namespace + "ExtendsEndpoint") }).OrderBy(GetName).ToArray(); foreach (XElement elt in Entities) { elt.Element(Namespace + "Fields").SortFields(); elt.Element(Namespace + "Mappings")?.SortMapings(); elt.Remove(); } root.Add(Entities); } private static void SortFields(this XElement FieldsElement) { IEnumerable<XElement> Fields = FieldsElement.Elements().OrderBy(GetName).ToArray(); foreach (XElement e in Fields) e.Remove(); FieldsElement.Add(Fields); } internal static string GetName(XElement elt) { return elt.Attribute("name").Value; } private static void SortMapings(this XElement MappingsElement) { IEnumerable<XElement> Mappings = MappingsElement.Elements().OrderBy(GetField).ToArray(); foreach (XElement e in Mappings) { SortMapings(e); e.Remove(); } MappingsElement.Add(Mappings); } internal static string GetField(XElement elt) { return elt.Attribute("field").Value; } } }
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace PX.Api.ContractBased.Maintenance.Cli.Utils { static class Sorter { public static void Sort(this XDocument original) { XElement root = original.Elements().Single(); XNamespace Namespace = root.Name.Namespace; IEnumerable<XElement> Entities = root.Elements().Except(new[] { root.Element(Namespace + "ExtendsEndpoint") }).OrderBy(GetName).ToArray(); foreach (XElement elt in Entities) { elt.Element(Namespace + "Fields")?.SortFields(); elt.Element(Namespace + "Mappings")?.SortMapings(); elt.Remove(); } root.Add(Entities); } private static void SortFields(this XElement FieldsElement) { IEnumerable<XElement> Fields = FieldsElement.Elements().OrderBy(GetName).ToArray(); foreach (XElement e in Fields) e.Remove(); FieldsElement.Add(Fields); } internal static string GetName(XElement elt) { return elt.Attribute("name").Value; } private static void SortMapings(this XElement MappingsElement) { IEnumerable<XElement> Mappings = MappingsElement.Elements().OrderBy(GetField).ToArray(); foreach (XElement e in Mappings) { SortMapings(e); e.Remove(); } MappingsElement.Add(Mappings); } internal static string GetField(XElement elt) { return elt.Attribute("field").Value; } } }
Add subtasks to main screen on tasks
@model IEnumerable<BatteryCommander.Common.Models.Qualification> @using BatteryCommander.Common.Models; @{ ViewBag.Title = "Qualifications"; } <h2>@ViewBag.Title</h2> <p> @Html.ActionLink("Add New", "New") </p> <table class="table table-striped"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th>GO</th> <th>NOGO</th> <th>UNKNOWN</th> <th></th> </tr> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.Name)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Pass)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Fail)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Unknown)</td> <td> @Html.ActionLink("View", "View", new { qualificationId = item.Id }) | <a href="~/Qualification/@item.Id/Update">Bulk Update Soldiers</a> </td> </tr> } </table>
@model IEnumerable<BatteryCommander.Common.Models.Qualification> @using BatteryCommander.Common.Models; @{ ViewBag.Title = "Qualifications"; } <h2>@ViewBag.Title</h2> <p> @Html.ActionLink("Add New", "New") </p> <table class="table table-striped"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th>GO</th> <th>NOGO</th> <th>UNKNOWN</th> <th>Tasks</th> <th></th> </tr> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.Name)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Pass)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Fail)</td> <td>@item.SoldierQualifications.Count(q => q.Status == QualificationStatus.Unknown)</td> <td> @foreach (var task in item.Tasks) { <li>@Html.DisplayFor(t => task)</li> } </td> <td> @Html.ActionLink("View", "View", new { qualificationId = item.Id }) | <a href="~/Qualification/@item.Id/Update">Bulk Update Soldiers</a> </td> </tr> } </table>
Add raw key blob formats
namespace NSec.Cryptography { public enum KeyBlobFormat { None, } }
namespace NSec.Cryptography { public enum KeyBlobFormat { None = 0, // --- Secret Key Formats --- RawSymmetricKey = -1, RawPrivateKey = -2, // --- Public Key Formats --- RawPublicKey = 1, } }
Add controller random sleep in Management sample
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Threading; using System; namespace CloudFoundry.Controllers { public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { Thread.Sleep(1000); _logger.LogCritical("Test Critical message"); _logger.LogError("Test Error message"); _logger.LogWarning("Test Warning message"); _logger.LogInformation("Test Informational message"); _logger.LogDebug("Test Debug message"); _logger.LogTrace("Test Trace message"); return View(); } public IActionResult Error() { throw new ArgumentException(); //return View(); } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Threading; using System; namespace CloudFoundry.Controllers { public class HomeController : Controller { private readonly ILogger _logger; private readonly Random _random; public HomeController(ILogger<HomeController> logger) { _logger = logger; _random = new Random(); } public IActionResult Index() { Thread.Sleep(_random.Next(500, 2000)); _logger.LogCritical("Test Critical message"); _logger.LogError("Test Error message"); _logger.LogWarning("Test Warning message"); _logger.LogInformation("Test Informational message"); _logger.LogDebug("Test Debug message"); _logger.LogTrace("Test Trace message"); return View(); } public IActionResult Error() { throw new ArgumentException(); //return View(); } } }
Refactor the redisconnection factory slightly
using System; using System.Configuration; using System.Linq; using Autofac; using Autofac.Integration.Mvc; using BookSleeve; namespace Compilify.Web.Infrastructure.DependencyInjection { public class RedisModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(CreateConnection) .InstancePerHttpRequest() .AsSelf(); } private static RedisConnection CreateConnection(IComponentContext context) { var connectionString = ConfigurationManager.AppSettings["REDISTOGO_URL"]; RedisConnection connection; #if !DEBUG var uri = new Uri(connectionString); var password = uri.UserInfo.Split(':').Last(); connection = new RedisConnection(uri.Host, uri.Port, password: password); #else connection = new RedisConnection(connectionString); #endif connection.Wait(connection.Open()); return connection; } } }
using System; using System.Configuration; using System.Linq; using Autofac; using Autofac.Integration.Mvc; using BookSleeve; namespace Compilify.Web.Infrastructure.DependencyInjection { public class RedisModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(CreateConnection) .InstancePerHttpRequest() .AsSelf(); } private static RedisConnection CreateConnection(IComponentContext context) { var connectionString = ConfigurationManager.AppSettings["REDISTOGO_URL"]; var uri = new Uri(connectionString); var password = uri.UserInfo.Split(':').Last(); #if !DEBUG var connection = new RedisConnection(uri.Host, uri.Port, password: password); #else var connection = new RedisConnection(connectionString); #endif connection.Wait(connection.Open()); return connection; } } }
Fix asset usages for field, when script component is assigned to field in Inspector
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.References; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements { public interface IScriptComponentHierarchy : IHierarchyElement { ExternalReference ScriptReference { get; } } }
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.References; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements { public interface IScriptComponentHierarchy : IComponentHierarchy { ExternalReference ScriptReference { get; } } }
Update assembly version to Silverlight 3 Beta version
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Microsoft Public License. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Microsoft Public License, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Microsoft Public License. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if SILVERLIGHT using System.Reflection; using System.Resources; [assembly: AssemblyVersion("2.0.5.0")] [assembly: AssemblyFileVersion("2.0.31005.0")] [assembly: AssemblyInformationalVersion("2.0.31005.0")] #endif
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Microsoft Public License. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Microsoft Public License, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Microsoft Public License. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if SILVERLIGHT using System.Reflection; using System.Resources; [assembly: AssemblyVersion("2.0.5.0")] [assembly: AssemblyFileVersion("3.0.40307.0")] [assembly: AssemblyInformationalVersion("3.0.40307.0")] #endif
Make base class abstract and add documentation
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { public class TestCaseRateAdjustedBeatmap : ScreenTestCase { protected override void Update() { base.Update(); // note that this will override any mod rate application Beatmap.Value.Track.Rate = Clock.Rate; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Tests.Visual { /// <summary> /// Test case which adjusts the beatmap's rate to match any speed adjustments in visual tests. /// </summary> public abstract class TestCaseRateAdjustedBeatmap : ScreenTestCase { protected override void Update() { base.Update(); // note that this will override any mod rate application Beatmap.Value.Track.Rate = Clock.Rate; } } }
Check if managed exception (Android)
using System; using Android.Runtime; namespace AI.XamarinSDK.Android { public class Utils { public Utils () { } public static bool IsManagedException(Exception exception){ // TODO: Check exception type (java.lang., android.) or exception source (entry assembly name) to determine whether the exception is thrown by managed or unmanaged code. return exception.Source.Equals("XamarinTest.Droid") } } }
using System; using Android.Runtime; namespace AI.XamarinSDK.Android { public class Utils { public static readonly string[] JAVA_EXCEPTION_PREFIXES = {"java.lang.", "android."}; public static bool IsManagedException(Exception exception){ string exceptionType = exception.GetBaseException ().GetType ().ToString (); foreach (string prefix in JAVA_EXCEPTION_PREFIXES) { if (exceptionType.ToLower ().StartsWith (prefix)) { return false; } } return true; } } }
Replace client.GetStringAsync(url) with better HttpClient code that also allows for compression
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace WienerLinien.Api { public class DefaultHttpClient : IHttpClient { public async Task<string> GetStringAsync(string url) { try { var c = new HttpClient(); c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return await c.GetStringAsync(url).ConfigureAwait(false); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace WienerLinien.Api { public class DefaultHttpClient : IHttpClient { public async Task<string> GetStringAsync(string url) { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } var client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { using (var response = await client.GetAsync(url).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return body; } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } return null; } } }