using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }
        }
    }
}

using StackExchange.Elastic;

namespace StackExchange.Opserver
{
    public class OpserverCore
    {
        // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so.
        public static void Init()
        {
            try
            {
                ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix;
                // We're going to get errors - that's kinda the point of monitoring
                // No need to log every one here unless for crazy debugging
                //ElasticException.ExceptionOccurred += e => Current.LogException(e);
            }
            catch { }
        }
    }
}

Comment out per-error logging, now only needed for logging


/*
   Copyright 2014 David Bordoley
   Copyright 2014 Zumero, LLC

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace SQLitePCL.pretty
{
    public static class ResultSet
    {
        public static IEnumerable<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs)
        {
            Contract.Requires(rs != null);

            return rs.Select(value => value.ColumnInfo);
        }
    }
}

/*
   Copyright 2014 David Bordoley
   Copyright 2014 Zumero, LLC

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace SQLitePCL.pretty
{
    public static class ResultSet
    {
        public static IReadOnlyList<IColumnInfo> Columns(this IReadOnlyList<IResultSetValue> rs)
        {
            Contract.Requires(rs != null);

            return new ResultSetColumnsListImpl(rs);
        }

        internal sealed class ResultSetColumnsListImpl : IReadOnlyList<IColumnInfo>
        {
            private readonly IReadOnlyList<IResultSetValue> rs;

            internal ResultSetColumnsListImpl(IReadOnlyList<IResultSetValue> rs)
            {
                this.rs = rs;
            }

            public IColumnInfo this[int index]
            {
                get
                {
                    return rs[index].ColumnInfo;
                }
            }

            public int Count
            {
                get
                {
                    return rs.Count;
                }
            }

            public IEnumerator<IColumnInfo> GetEnumerator()
            {
                return rs.Select(val => val.ColumnInfo).GetEnumerator();
            }

            IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }
        }
    }
}

Change Columns static method to return IReadOnlyList.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Contentful.Core.Models
{
    /// <summary>
    /// Represents information about the actual binary file of an <see cref="Asset"/>.
    /// </summary>
    public class File
    {
        /// <summary>
        /// The original name of the file.
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// The content type of the data contained within this file.
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// An absolute URL to this file.
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// Detailed information about the file stored by Contentful.
        /// </summary>
        public FileDetails Details { get; set; }
    }
}

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Contentful.Core.Models
{
    /// <summary>
    /// Represents information about the actual binary file of an <see cref="Asset"/>.
    /// </summary>
    public class File
    {
        /// <summary>
        /// The original name of the file.
        /// </summary>
        public string FileName { get; set; }
        /// <summary>
        /// The content type of the data contained within this file.
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// An absolute URL to this file.
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// The url to upload this file from.
        /// </summary>
        [JsonProperty("upload")]
        public string UploadUrl { get; set; }
        /// <summary>
        /// Detailed information about the file stored by Contentful.
        /// </summary>
        public FileDetails Details { get; set; }
    }
}

Add upload property to file

Add upload property to file


using System;
using System.Collections.Generic;
using ArcGIS.ServiceModel;
using ArcGIS.ServiceModel.Operation;

namespace ArcGIS.Test
{
    public class JsonDotNetSerializer : ISerializer
    {
        static ISerializer _serializer = null;

        public static void Init()
        {
            _serializer = new JsonDotNetSerializer();
            SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer());
        }

        readonly Newtonsoft.Json.JsonSerializerSettings _settings;

        public JsonDotNetSerializer()
        {
            _settings = new Newtonsoft.Json.JsonSerializerSettings
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
        }

        public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters
        {
            var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings);

            var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue);
            var dict = new Dictionary<String, String>();
            foreach (var item in jobject)
            {
                dict.Add(item.Key, item.Value.ToString());
            }
            return dict;
        }

        public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings);
        }
    }

}

using System;
using System.Collections.Generic;
using ArcGIS.ServiceModel;
using ArcGIS.ServiceModel.Operation;

namespace ArcGIS.ServiceModel.Serializers
{
    public class JsonDotNetSerializer : ISerializer
    {
        static ISerializer _serializer = null;

        public static void Init()
        {
            _serializer = new JsonDotNetSerializer();
            SerializerFactory.Get = (() => _serializer ?? new JsonDotNetSerializer());
        }

        readonly Newtonsoft.Json.JsonSerializerSettings _settings;

        public JsonDotNetSerializer()
        {
            _settings = new Newtonsoft.Json.JsonSerializerSettings
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
        }

        public Dictionary<String, String> AsDictionary<T>(T objectToConvert) where T : CommonParameters
        {
            var stringValue = Newtonsoft.Json.JsonConvert.SerializeObject(objectToConvert, _settings);

            var jobject = Newtonsoft.Json.Linq.JObject.Parse(stringValue);
            var dict = new Dictionary<String, String>();
            foreach (var item in jobject)
            {
                dict.Add(item.Key, item.Value.ToString());
            }
            return dict;
        }

        public T AsPortalResponse<T>(String dataToConvert) where T : IPortalResponse
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(dataToConvert, _settings);
        }
    }

}

Use same namespace for serializers

Use same namespace for serializers


namespace XSerializer.Encryption
{
    /// <summary>
    /// Provides a mechanism for an application to specify an instance of
    /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when
    /// encrypting or decrypting data.
    /// </summary>
    public static class EncryptionMechanism
    {
        /// <summary>
        /// The default instance of <see cref="IEncryptionMechanism"/>.
        /// </summary>
        public static readonly IEncryptionMechanism _defaultEncryptionMechanism = new ClearTextEncryptionMechanism();

        private static IEncryptionMechanism _current = _defaultEncryptionMechanism;

        /// <summary>
        /// Gets or sets the instance of <see cref="IEncryptionMechanism"/>
        /// to be used by XSerializer when encrypting or decrypting data.
        /// When setting this property, if <paramref name="value"/> is null,
        /// then <see cref="_defaultEncryptionMechanism"/> will be used instead.
        /// </summary>
        public static IEncryptionMechanism Current
        {
            internal get { return _current; }
            set { _current = value ?? _defaultEncryptionMechanism; }
        }
    }
}

namespace XSerializer.Encryption
{
    /// <summary>
    /// Provides a mechanism for an application to specify an instance of
    /// <see cref="IEncryptionMechanism"/> to be used by XSerializer when
    /// encrypting or decrypting data.
    /// </summary>
    public static class EncryptionMechanism
    {
        /// <summary>
        /// The default instance of <see cref="IEncryptionMechanism"/>.
        /// </summary>
        public static readonly IEncryptionMechanism DefaultEncryptionMechanism = new ClearTextEncryptionMechanism();

        private static IEncryptionMechanism _current = DefaultEncryptionMechanism;

        /// <summary>
        /// Gets or sets the instance of <see cref="IEncryptionMechanism"/>
        /// to be used by XSerializer when encrypting or decrypting data.
        /// When setting this property, if <paramref name="value"/> is null,
        /// then <see cref="DefaultEncryptionMechanism"/> will be used instead.
        /// </summary>
        public static IEncryptionMechanism Current
        {
            internal get { return _current; }
            set { _current = value ?? DefaultEncryptionMechanism; }
        }
    }
}

Use correct casing on public static field.


// 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.IO;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osuTK;

namespace osu.Framework.Graphics.UserInterface
{
    public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay
    {
        protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new ComputerPiece();

        protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new CurrentDisplayPiece(directory, displayName);

        public BasicDirectorySelectorBreadcrumbDisplay()
        {
            RelativeSizeAxes = Axes.X;
            AutoSizeAxes = Axes.Y;
        }

        protected class ComputerPiece : CurrentDisplayPiece
        {
            protected override IconUsage? Icon => null;

            public ComputerPiece()
                : base(null, "Computer")
            {
            }
        }

        protected class CurrentDisplayPiece : BasicDirectorySelectorDirectory
        {
            protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null;

            public CurrentDisplayPiece(DirectoryInfo directory, string displayName = null)
                : base(directory, displayName)
            {
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                Flow.Add(new SpriteIcon
                {
                    Anchor = Anchor.CentreLeft,
                    Origin = Anchor.CentreLeft,
                    Icon = FontAwesome.Solid.ChevronRight,
                    Size = new Vector2(FONT_SIZE / 2)
                });
            }
        }
    }
}

// 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.IO;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osuTK;

namespace osu.Framework.Graphics.UserInterface
{
    public class BasicDirectorySelectorBreadcrumbDisplay : DirectorySelectorBreadcrumbDisplay
    {
        protected override DirectorySelectorDirectory CreateRootDirectoryItem() => new BreadcrumbDisplayComputer();

        protected override DirectorySelectorDirectory CreateDirectoryItem(DirectoryInfo directory, string displayName = null) => new BreadcrumbDisplayDirectory(directory, displayName);

        public BasicDirectorySelectorBreadcrumbDisplay()
        {
            RelativeSizeAxes = Axes.X;
            AutoSizeAxes = Axes.Y;
        }

        protected class BreadcrumbDisplayComputer : BreadcrumbDisplayDirectory
        {
            protected override IconUsage? Icon => null;

            public BreadcrumbDisplayComputer()
                : base(null, "Computer")
            {
            }
        }

        protected class BreadcrumbDisplayDirectory : BasicDirectorySelectorDirectory
        {
            protected override IconUsage? Icon => Directory.Name.Contains(Path.DirectorySeparatorChar) ? base.Icon : null;

            public BreadcrumbDisplayDirectory(DirectoryInfo directory, string displayName = null)
                : base(directory, displayName)
            {
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                Flow.Add(new SpriteIcon
                {
                    Anchor = Anchor.CentreLeft,
                    Origin = Anchor.CentreLeft,
                    Icon = FontAwesome.Solid.ChevronRight,
                    Size = new Vector2(FONT_SIZE / 2)
                });
            }
        }
    }
}

Rename some more nested classes

Rename some more nested classes


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KGP.Curves
{
    public class ThresholdLinearCurve : ICurve
    {
        private float threshold;

        public float Threshold
        {
            get { return this.threshold; }
            set { this.threshold = value; }
        }

        public ThresholdLinearCurve(float threshold)
        {
            this.threshold = threshold;
        }

        public float Apply(float value)
        {
            float absval = Math.Abs(value);
            if (absval <= threshold)
            {
                return 0.0f;
            }
            else
            {
                float diff = (absval - threshold) / (1.0f - threshold);
                return diff * Math.Sign(value);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KGP
{
    /// <summary>
    /// Linear threshold curve, clamp while absolute value is within threshold
    /// </summary>
    public class ThresholdLinearCurve : ICurve
    {
        private float threshold;

        /// <summary>
        /// Current threshold
        /// </summary>
        public float Threshold
        {
            get { return this.threshold; }
            set { this.threshold = value; }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="threshold">Initial threshold value</param>
        public ThresholdLinearCurve(float threshold)
        {
            this.threshold = threshold;
        }

        /// <summary>
        ///Apply threshold curve
        /// </summary>
        /// <param name="value">Intial value</param>
        /// <returns>Value with curve applied</returns>
        public float Apply(float value)
        {
            float absval = Math.Abs(value);
            if (absval <= threshold)
            {
                return 0.0f;
            }
            else
            {
                float diff = (absval - threshold) / (1.0f - threshold);
                return diff * Math.Sign(value);
            }
        }
    }
}

Comment and fix on namespace

Comment and fix on namespace


namespace Server
{
    using System;
    using System.IO;
    using System.Text;

    internal partial class Program
    {
        class Dup : Stream
        {
            string _name;

            private Dup() { }

            public Dup(string name) { _name = name; }

            public override bool CanRead { get { return false; } }

            public override bool CanSeek { get { return false; } }

            public override bool CanWrite { get { return true; } }

            public override long Length => throw new NotImplementedException();

            public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

            public override void Flush()
            {
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                throw new NotImplementedException();
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                throw new NotImplementedException();
            }

            public override void SetLength(long value)
            {
                throw new NotImplementedException();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                DateTime now = DateTime.Now;
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Raw message from " + _name + " " + now.ToString());
                var truncated_array = new byte[count];
                for (int i = offset; i < offset + count; ++i)
                    truncated_array[i - offset] = buffer[i];
                string str = System.Text.Encoding.Default.GetString(truncated_array);
                sb.AppendLine("data = '" + str);
                LoggerNs.Logger.Log.WriteLine(sb.ToString());
            }
        }
    }
}

namespace Server
{
    using System;
    using System.IO;
    using System.Text;

    internal partial class Program
    {
        class Dup : Stream
        {
            string _name;

            private Dup() { }

            public Dup(string name) { _name = name; }

            public override bool CanRead { get { return false; } }

            public override bool CanSeek { get { return false; } }

            public override bool CanWrite { get { return true; } }

            public override long Length => throw new NotImplementedException();

            public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

            public override void Flush()
            {
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                throw new NotImplementedException();
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                throw new NotImplementedException();
            }

            public override void SetLength(long value)
            {
                throw new NotImplementedException();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                DateTime now = DateTime.Now;
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Raw message from " + _name + " " + now.ToString());
                var truncated_array = new byte[count];
                for (int i = offset; i < offset + count; ++i)
                    truncated_array[i - offset] = buffer[i];
                string str = System.Text.Encoding.Default.GetString(truncated_array);
                sb.AppendLine("data (length " + str.Length + ")= '" + str + "'");
                LoggerNs.Logger.Log.WriteLine(sb.ToString());
            }
        }
    }
}

Add quotes and length of JSON packets being sent.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
    interface ICodeModelInstanceFactory
    {
        /// <summary>
        /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system.
        /// </summary>
        /// <remarks>
        /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another,
        /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/>
        /// member should be. The expectation is the implementer of this will do what is necessary and call back into the code model implementation
        /// with a parent object.</remarks>
        EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
    interface ICodeModelInstanceFactory
    {
        /// <summary>
        /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system.
        /// </summary>
        /// <remarks>
        /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another,
        /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/>
        /// member should be. The expectation is the implementer of this will do what is necessary and call back into <see cref="IProjectCodeModel.GetOrCreateFileCodeModel(string, object)"/>
        /// handing it the appropriate parent.</remarks>
        EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath);
    }
}

Update documentation now that we can point to a concrete method


using System;
using Shouldly;
using Spk.Common.Helpers.Service;
using Xunit;

namespace Spk.Common.Tests.Helpers.Service
{
    public class ServiceResultTests
    {
        [Theory]
        [InlineData("test")]
        [InlineData("")]
        [InlineData(null)]
        public void SetData_SuccessShouldBeTrue(string value)
        {
            // Arrange
            var sr = new ServiceResult<string>();

            // Act
            sr.SetData(value);

            // Assert
            sr.Success.ShouldBeTrue();
        }

        [Theory]
        [InlineData("error")]
        public void GetFirstError_ShouldReturnFirstError(string error)
        {
            // Arrange
            var sr = new ServiceResult<string>();

            // Act
            sr.AddError(error);

            // Assert
            sr.GetFirstError().ShouldBe(error);
        }

        [Fact]
        public void AddError_ShouldArgumentNullException_WhenNullError()
        {
            // Act & assert
            Assert.Throws<ArgumentNullException>(() =>
            {
                var sr = new ServiceResult<string>();
                sr.AddError(null);
            });
        }
    }
}

using System;
using Shouldly;
using Spk.Common.Helpers.Service;
using Xunit;

namespace Spk.Common.Tests.Helpers.Service
{
    public class ServiceResultTests
    {
        [Theory]
        [InlineData("test")]
        [InlineData("")]
        [InlineData(null)]
        public void Success_ShouldBeTrue_WhenDataIsSet(string value)
        {
            // Arrange
            var sr = new ServiceResult<string>();

            // Act
            sr.SetData(value);

            // Assert
            sr.Success.ShouldBeTrue();
        }

        [Theory]
        [InlineData("error")]
        public void GetFirstError_ShouldReturnFirstError(string error)
        {
            // Arrange
            var sr = new ServiceResult<string>();

            // Act
            sr.AddError(error);
            sr.AddError("bleh");

            // Assert
            sr.GetFirstError().ShouldBe(error);
        }

        [Fact]
        public void AddError_ShouldArgumentNullException_WhenNullError()
        {
            // Act & assert
            Assert.Throws<ArgumentNullException>(() =>
            {
                var sr = new ServiceResult<string>();
                sr.AddError(null);
            });
        }
    }
}

Test case renamed to be more accurate

Test case renamed to be more accurate


using System.Collections.Concurrent;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;

namespace Microsoft.Azure.Commands.DataLakeStore.Models
{
    /// <summary>
    /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target
    /// which basically queues the debug data to the ConcurrentQueue for debug messages.
    /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
    /// </summary>
    [Target("AdlsLogger")]
    public sealed class AdlsLoggerTarget : TargetWithLayout
    {
        internal ConcurrentQueue<string> DebugMessageQueue;
        public AdlsLoggerTarget()
        {
        }
        protected override void Write(LogEventInfo logEvent)
        {
            string logMessage = Layout.Render(logEvent);
            DebugMessageQueue?.Enqueue(logMessage);
        }
    }
}

using System.Collections.Concurrent;
using NLog;
using NLog.Targets;

namespace Microsoft.Azure.Commands.DataLakeStore.Models
{
    /// <summary>
    /// NLog is used by the ADLS dataplane sdk to log debug messages. We can create a custom target
    /// which basically queues the debug data to the ConcurrentQueue for debug messages.
    /// https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
    /// </summary>
    [Target("AdlsLogger")]
    internal sealed class AdlsLoggerTarget : TargetWithLayout
    {
        internal ConcurrentQueue<string> DebugMessageQueue;
        protected override void Write(LogEventInfo logEvent)
        {
            string logMessage = Layout.Render(logEvent);
            DebugMessageQueue?.Enqueue(logMessage);
        }
    }
}

Remove unused usings and make the target class internal


using Simpler;
using System;
using Schedules.API.Models;
using Schedules.API.Tasks.Reminders;

namespace Schedules.API.Tasks.Sending
{
  public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output>
  {
    public class Input
    {
      public Send Send { get; set; }
    }

    public class Output
    {
      public Send Send { get; set; }
    }

    public FetchDueReminders FetchDueReminders { get; set; }
    public SendEmails SendEmails { get; set; }

    public override void Execute ()
    {
      FetchDueReminders.In.RemindOn = In.Send.RemindOn;
      FetchDueReminders.Execute();

      SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders;
      SendEmails.Execute();

      Out.Send = new Send {
        Sent = SendEmails.Out.Sent,
        Errors = SendEmails.Out.Errors
      };
    }
  }
}

using Simpler;
using System;
using Schedules.API.Models;
using Schedules.API.Tasks.Reminders;

namespace Schedules.API.Tasks.Sending
{
  public class PostRemindersEmailSend : InOutTask<PostRemindersEmailSend.Input, PostRemindersEmailSend.Output>
  {
    public class Input
    {
      public Send Send { get; set; }
    }

    public class Output
    {
      public Send Send { get; set; }
    }

    public FetchDueReminders FetchDueReminders { get; set; }
    public SendEmails SendEmails { get; set; }

    public override void Execute ()
    {
      FetchDueReminders.In.RemindOn = In.Send.RemindOn;
      FetchDueReminders.Execute();

      SendEmails.In.DueReminders = FetchDueReminders.Out.DueReminders;
      SendEmails.Execute();

      Out.Send = new Send {
        RemindOn = In.Send.RemindOn,
        Sent = SendEmails.Out.Sent,
        Errors = SendEmails.Out.Errors
      };
    }
  }
}

Return the given RemindOn date

Return the given RemindOn date


using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Net.Mail;
using System.Net.Mime;
using RazorEngine.Text;

namespace Essential.Templating.Razor.Email.Helpers
{
    public static class ResourceTemplateHelperExtensions
    {
        public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType,
            TransferEncoding transferEncoding, CultureInfo culture = null)
        {
            Contract.Requires<ArgumentNullException>(helper != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType));

            var resource = helper.Get(path, culture);
            if (resource == null)
            {
                var message = string.Format("Resource [{0}] was not found.", contentId);
                throw new TemplateHelperException(message);
            }
            var linkedResource = new LinkedResource(resource, mediaType)
            {
                TransferEncoding = transferEncoding
            };
            helper.AddLinkedResource(linkedResource);
            var renderedResult = new RawString(string.Format("cid:{0}", contentId));
            return renderedResult;
        }
    }
}

using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Net.Mail;
using System.Net.Mime;
using RazorEngine.Text;

namespace Essential.Templating.Razor.Email.Helpers
{
    public static class ResourceTemplateHelperExtensions
    {
        public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType,
            TransferEncoding transferEncoding, CultureInfo culture = null)
        {
            Contract.Requires<ArgumentNullException>(helper != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType));

            var resource = helper.Get(path, culture);
            if (resource == null)
            {
                var message = string.Format("Resource [{0}] was not found.", contentId);
                throw new TemplateHelperException(message);
            }
            var linkedResource = new LinkedResource(resource, mediaType)
            {
                TransferEncoding = transferEncoding,
                ContentId = contentId
            };
            helper.AddLinkedResource(linkedResource);
            var renderedResult = new RawString(string.Format("cid:{0}", contentId));
            return renderedResult;
        }
    }
}

Store ContentId against the LinkedResource

ContentId is not being set for the LinkedResource so once rendered, the cid value in the HTML content can't be found as it isn't named.


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using OpenTK.Graphics;

namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components
{
    public class SliderBodyPiece : CompositeDrawable
    {
        private readonly Slider slider;
        private readonly SliderBody body;

        public SliderBodyPiece(Slider slider)
        {
            this.slider = slider;
            InternalChild = body = new SliderBody(slider)
            {
                AccentColour = Color4.Transparent,
                PathWidth = slider.Scale * 64
            };

            slider.PositionChanged += _ => updatePosition();
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;

            updatePosition();
        }

        private void updatePosition() => Position = slider.StackedPosition;

        protected override void Update()
        {
            base.Update();

            Size = body.Size;
            OriginPosition = body.PathOffset;

            // Need to cause one update
            body.UpdateProgress(0);
        }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using OpenTK.Graphics;

namespace osu.Game.Rulesets.Osu.Edit.Masks.SliderMasks.Components
{
    public class SliderBodyPiece : CompositeDrawable
    {
        private readonly Slider slider;
        private readonly SnakingSliderBody body;

        public SliderBodyPiece(Slider slider)
        {
            this.slider = slider;
            InternalChild = body = new SnakingSliderBody(slider)
            {
                AccentColour = Color4.Transparent,
                PathWidth = slider.Scale * 64
            };

            slider.PositionChanged += _ => updatePosition();
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;

            updatePosition();
        }

        private void updatePosition() => Position = slider.StackedPosition;

        protected override void Update()
        {
            base.Update();

            Size = body.Size;
            OriginPosition = body.PathOffset;

            // Need to cause one update
            body.UpdateProgress(0);
        }
    }
}

Update with slider body changes

Update with slider body changes


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace AlertRoster.Web.Models
{
    public class Group
    {
        [Key]
        public int Id { get; private set; }

        [Required, StringLength(25)]
        public String DisplayName { get; set; }

        [StringLength(25)]
        public String PhoneNumber { get; set; }

        public virtual ICollection<MemberGroup> Members { get; private set; }

        public virtual ICollection<Message> Messages { get; private set; }

        // TODO Who are admins?

        // TODO Reply-mode : Reply-All, Reply-to-Admin, Reject?

        private Group()
        {
            // Parameter-less ctor for EF
        }

        public Group(String displayName)
        {
            this.DisplayName = displayName;
            this.Members = new List<MemberGroup>();
            this.Messages = new List<Message>();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace AlertRoster.Web.Models
{
    public class Group
    {
        [Key]
        public int Id { get; private set; }

        [Required, StringLength(25)]
        public String DisplayName { get; set; }

        [StringLength(25)]
        public String PhoneNumber { get; set; }

        public virtual ICollection<MemberGroup> Members { get; private set; }

        public virtual IEnumerable<Member> Admins => Members.Where(_ => _.Role == MemberGroup.GroupRole.Administrator).Select(_ => _.Member);

        public virtual ICollection<Message> Messages { get; private set; }

        [Required]
        public ReplyMode Replies { get; set; } = ReplyMode.ReplyAll;

        private Group()
        {
            // Parameter-less ctor for EF
        }

        public Group(String displayName)
        {
            this.DisplayName = displayName;
            this.Members = new List<MemberGroup>();
            this.Messages = new List<Message>();
        }

        public enum ReplyMode : byte
        {
            ReplyAll = 0,

            ReplyToAdmins = 1,

            Reject = 2
        }
    }
}

Add reply mode and a shortcut for getting admins


// MvxColorExtensions.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using Cirrious.CrossCore.UI;
using MonoTouch.UIKit;

namespace Cirrious.MvvmCross.Plugins.Color.Touch
{
    public static class MvxColorExtensions
    {
        public static UIColor ToAndroidColor(this MvxColor color)
        {
            return MvxTouchColor.ToUIColor(color);
        }
    }
}

// MvxColorExtensions.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using Cirrious.CrossCore.UI;
using MonoTouch.UIKit;

namespace Cirrious.MvvmCross.Plugins.Color.Touch
{
    public static class MvxColorExtensions
    {
        public static UIColor ToNativeColor(this MvxColor color)
        {
            return MvxTouchColor.ToUIColor(color);
        }
    }
}

Fix for native extension method name (not Android!)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace PS.Mothership.Core.Common.Dto.Merchant
{
    [DataContract]
    public class OpportunityDto
    {
        [DataMember]
        public Guid OpportunityGuid { get; set; }

        [DataMember]
        public string OpportunityLocatorId { get; set; }

        [DataMember]
        public Guid ProspectGuid { get; set; }

        [DataMember]
        public Guid CustomerGuid { get; set; }

        [DataMember]
        public Guid CurrentOfferGuid { get; set; }

        [DataMember]
        public Guid PartnerGuid { get; set; }

        [DataMember]
        public Guid CurrentStatusTrnGuid { get; set; }

        [DataMember]
        public OfferDto CurrentOffer { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace PS.Mothership.Core.Common.Dto.Merchant
{
    [DataContract]
    public class OpportunityDto
    {
        [DataMember]
        public Guid OpportunityGuid { get; set; }

        [DataMember]
        public string OpportunityLocatorId { get; set; }

        [DataMember]
        public Guid ProspectGuid { get; set; }

        [DataMember]
        public Guid CustomerGuid { get; set; }

        [DataMember]
        public Guid CurrentOfferGuid { get; set; }

        [DataMember]
        public Guid PartnerGuid { get; set; }

        [DataMember]
        public Guid CurrentStatusTrnGuid { get; set; }

        [DataMember]
        public OfferDto CurrentOffer { get; set; }

        [DataMember]
        public Guid UpdateUserGuid { get; set; }

        [DataMember]
        public string UpdateUsername { get; set; }

        [DataMember]
        public DateTimeOffset UpdateDate { get; set; }
    }
}

Update user info on opportunity.

Update user info on opportunity.


using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.Models.Classi.Marker;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti;
using SO115App.Models.Servizi.Infrastruttura.Marker;

namespace SO115App.Persistence.MongoDB.Marker
{
    public class DeleteChiamataInCorsoByIdUtente : IDeleteChiamataInCorsoByIdUtente
    {
        private readonly DbContext _dbContext;
        private readonly IGetUtenteById _getUtente;

        public DeleteChiamataInCorsoByIdUtente(DbContext dbContext, IGetUtenteById getUtente)
        {
            _dbContext = dbContext;
            _getUtente = getUtente;
        }

        public void Delete(string idUtente)
        {
            var utente = _getUtente.GetUtenteByCodice(idUtente);
            var nominativo = utente.Nome + " " + utente.Cognome;

            _dbContext.ChiamateInCorsoCollection.DeleteOne(Builders<ChiamateInCorso>.Filter.Eq(x => x.DescrizioneOperatore, nominativo));
        }
    }
}

using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.Models.Classi.Marker;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti;
using SO115App.Models.Servizi.Infrastruttura.Marker;

namespace SO115App.Persistence.MongoDB.Marker
{
    public class DeleteChiamataInCorsoByIdUtente : IDeleteChiamataInCorsoByIdUtente
    {
        private readonly DbContext _dbContext;
        private readonly IGetUtenteById _getUtente;

        public DeleteChiamataInCorsoByIdUtente(DbContext dbContext, IGetUtenteById getUtente)
        {
            _dbContext = dbContext;
            _getUtente = getUtente;
        }

        public void Delete(string idUtente)
        {
            var utente = _getUtente.GetUtenteByCodice(idUtente);
            var nominativo = utente.Nome + " " + utente.Cognome;

            _dbContext.ChiamateInCorsoCollection.DeleteMany(Builders<ChiamateInCorso>.Filter.Eq(x => x.DescrizioneOperatore, nominativo));
        }
    }
}

Fix - Cancellazione Chiamate In Corso al logout


using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// Represents a media picker property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MediaPicker,
        EditorType.PropertyValue | EditorType.MacroParameter,
        "Media Picker",
        "mediapicker",
        ValueType = ValueTypes.Text,
        Group = Constants.PropertyEditors.Groups.Media,
        Icon = Constants.Icons.MediaImage)]
    public class MediaPickerPropertyEditor : DataEditor
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
        /// </summary>
        public MediaPickerPropertyEditor(ILogger logger)
            : base(logger)
        {
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();

        protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);

        internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
        {
            public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
            {
            }

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString)) yield break;

                if (Udi.TryParse(asString, out var udi))
                    yield return new UmbracoEntityReference(udi);
            }
        }
    }

}

using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// Represents a media picker property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MediaPicker,
        EditorType.PropertyValue | EditorType.MacroParameter,
        "Media Picker",
        "mediapicker",
        ValueType = ValueTypes.Text,
        Group = Constants.PropertyEditors.Groups.Media,
        Icon = Constants.Icons.MediaImage)]
    public class MediaPickerPropertyEditor : DataEditor
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class.
        /// </summary>
        public MediaPickerPropertyEditor(ILogger logger)
            : base(logger)
        {
        }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor();

        protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute);

        internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference
        {
            public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute)
            {
            }

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                var asString = value is string str ? str : value?.ToString();

                if (string.IsNullOrEmpty(asString)) yield break;

                foreach (var udiStr in asString.Split(','))
                {
                    if (Udi.TryParse(udiStr, out var udi))
                        yield return new UmbracoEntityReference(udi);
                }
            }
        }
    }

}

7879: Handle for multiple picked media relations

(cherry picked from commit 9f7c44c64ebfb23acd1bb06aa22c5bc39ad5079a)


using System;

namespace ChamberLib
{
    public interface IShaderProgram
    {
        string Name { get; }

        void Apply();
        void UnApply();

        IShaderStage VertexShader { get; }
        IShaderStage FragmentShader { get; }

        void SetUniform(string name, bool value);
        void SetUniform(string name, byte value);
        void SetUniform(string name, sbyte value);
        void SetUniform(string name, short value);
        void SetUniform(string name, ushort value);
        void SetUniform(string name, int value);
        void SetUniform(string name, uint value);
        void SetUniform(string name, float value);
        void SetUniform(string name, double value);
        void SetUniform(string name, Vector2 value);
        void SetUniform(string name, Vector3 value);
        void SetUniform(string name, Vector4 value);
        void SetUniform(string name, Matrix value);
    }
}

using System;
using System.Collections.Generic;

namespace ChamberLib
{
    public interface IShaderProgram
    {
        string Name { get; }

        void Apply();
        void UnApply();

        IShaderStage VertexShader { get; }
        IShaderStage FragmentShader { get; }

        IEnumerable<string> BindAttributes { get; }
        void SetBindAttributes(IEnumerable<string> bindattrs);

        void SetUniform(string name, bool value);
        void SetUniform(string name, byte value);
        void SetUniform(string name, sbyte value);
        void SetUniform(string name, short value);
        void SetUniform(string name, ushort value);
        void SetUniform(string name, int value);
        void SetUniform(string name, uint value);
        void SetUniform(string name, float value);
        void SetUniform(string name, double value);
        void SetUniform(string name, Vector2 value);
        void SetUniform(string name, Vector3 value);
        void SetUniform(string name, Vector4 value);
        void SetUniform(string name, Matrix value);
    }
}

Add the bind attributes property and method to the interface.


@using Piranha.Extend;
@using Piranha.Manager.Manager;
@model Block

@foreach(var name in Model.GetFieldNames())
{

        @name
        @Html.Editor(name)

}

@using Piranha.Extend;
@using Piranha.Manager.Manager;
@using System.Text.RegularExpressions;
@model Block

@foreach(var name in Model.GetFieldNames())
{
    var label = Regex.Replace(name, "(\\B[A-Z])", " $1");

        @label
        @Html.Editor(name)

}

Split Pascal cased property names into words


using System;
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet.Compiler.Lexer;
using System.Linq.Expressions;

namespace HandlebarsDotNet.Compiler
{
    internal class ExpressionScopeConverter : TokenConverter
    {
        public static IEnumerable<object> Convert(IEnumerable<object> sequence)
        {
            return new ExpressionScopeConverter().ConvertTokens(sequence).ToList();
        }

        private ExpressionScopeConverter()
        {
        }

        public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
        {
            var enumerator = sequence.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var item = enumerator.Current;
                if (item is StartExpressionToken)
                {
                    var startExpression = item as StartExpressionToken;
                    item = GetNext(enumerator);
                    if ((item is Expression) == false)
                    {
                        throw new HandlebarsCompilerException(
                            string.Format("Token '{0}' could not be converted to an expression", item));
                    }
                    yield return HandlebarsExpression.Statement(
                        (Expression)item,
                        startExpression.IsEscaped);
                    item = GetNext(enumerator);
                    if ((item is EndExpressionToken) == false)
                    {
                        throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression");
                    }
                    if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped)
                    {
                        throw new HandlebarsCompilerException("Starting and ending handleabars do not match");
                    }
                }
                else
                {
                    yield return item;
                }
            }
        }

        private static object GetNext(IEnumerator<object> enumerator)
        {
            enumerator.MoveNext();
            return enumerator.Current;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet.Compiler.Lexer;
using System.Linq.Expressions;

namespace HandlebarsDotNet.Compiler
{
    internal class ExpressionScopeConverter : TokenConverter
    {
        public static IEnumerable<object> Convert(IEnumerable<object> sequence)
        {
            return new ExpressionScopeConverter().ConvertTokens(sequence).ToList();
        }

        private ExpressionScopeConverter()
        {
        }

        public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
        {
            var enumerator = sequence.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var item = enumerator.Current;
                if (item is StartExpressionToken)
                {
                    var startExpression = item as StartExpressionToken;
                    item = GetNext(enumerator);
                    if ((item is Expression) == false)
                    {
                        throw new HandlebarsCompilerException(
                            string.Format("Token '{0}' could not be converted to an expression", item));
                    }
                    yield return HandlebarsExpression.Statement(
                        (Expression)item,
                        startExpression.IsEscaped);
                    item = GetNext(enumerator);
                    if ((item is EndExpressionToken) == false)
                    {
                        throw new HandlebarsCompilerException("Handlebars statement was not reduced to a single expression");
                    }
                    if (((EndExpressionToken)item).IsEscaped != startExpression.IsEscaped)
                    {
                        throw new HandlebarsCompilerException("Starting and ending handlebars do not match");
                    }
                }
                else
                {
                    yield return item;
                }
            }
        }

        private static object GetNext(IEnumerator<object> enumerator)
        {
            enumerator.MoveNext();
            return enumerator.Current;
        }
    }
}

Fix spelling mistake in error message

Fix spelling mistake in error message


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;

using TestObjectBuilder;

namespace TestObjectBuilderTests.Tests
{
    public class TestObjectBuilderBuilderTests
    {
        [TestFixture]
        public class CreateNewObject
        {
            [Test]
            public void CreatesProductWithoutPropertiesAndAZeroArgConstructor()
            {
                // Arrange
                ITestObjBuilder<ProductWithoutProperties> builder =
                    TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject();

                // Act
                ProductWithoutProperties product = builder.Build();

                // Assert
                Assert.NotNull(product);
            }

        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;

using TestObjectBuilder;

namespace TestObjectBuilderTests.Tests
{
    public class TestObjectBuilderBuilderTests
    {
        [TestFixture]
        public class CreateNewObject
        {
            [Test]
            public void ProductBuilderCreateBuildsObjectsOfTypeProduct()
            {
                // Arrange
                // Act
                ITestObjBuilder<ProductWithoutProperties> builder =
    TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject();
                // Assert
                Assert.AreSame(typeof(ProductWithoutProperties), builder.GetType().GetMethod("Build").ReturnType);
            }

            [Test]
            public void ProductBuilderHasNoPropertiesWhenProductHasNoProperties()
            {
                // Arrange
                // Act
                ITestObjBuilder<ProductWithoutProperties> builder =
                    TestObjectBuilderBuilder<ProductWithoutProperties>.CreateNewObject();

                // Assert
                Assert.AreEqual(0, builder.GetType().GetProperties().Count());
            }
        }
    }
}

Replace first TestObjectBuilderBuilder unit test with two tests to make the tests less brittle.


using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGameUtils.Diagnostics;

namespace PCGame.GameComponents
{
    public class UIFPSCounter : DrawableGameComponent
    {
        private FPSCounter _fpsCounter = new FPSCounter();
        private SpriteBatch _spriteBatch;
        private SpriteFont _font;
        private Vector2 _topLeftPoint;
        private Vector2 _avgFPSLocation;
        private readonly Color _fontColor = Color.Black;

        public UIFPSCounter(Game game,
                            SpriteFont font,
                            Vector2 topLeftPoint,
                            SpriteBatch spriteBatch) : base(game)
        {
            _spriteBatch = spriteBatch;
            _font = font;
            _topLeftPoint = topLeftPoint;
            _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20));
        }

        public override void Update(GameTime gameTime)
        {
            _fpsCounter.Update(gameTime);

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor);
            _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor);

            base.Draw(gameTime);
        }
    }
}

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGameUtils.Diagnostics;

namespace MonoGameUtils.UI.GameComponents
{
    public class UIFPSCounter : DrawableGameComponent
    {
        private FPSCounter _fpsCounter = new FPSCounter();
        private SpriteBatch _spriteBatch;
        private SpriteFont _font;
        private Vector2 _topLeftPoint;
        private Vector2 _avgFPSLocation;
        private readonly Color _fontColor = Color.Black;

        public UIFPSCounter(Game game,
                            SpriteFont font,
                            Vector2 topLeftPoint,
                            SpriteBatch spriteBatch) : base(game)
        {
            _spriteBatch = spriteBatch;
            _font = font;
            _topLeftPoint = topLeftPoint;
            _avgFPSLocation = Vector2.Add(_topLeftPoint, new Vector2(0, 20));
        }

        public override void Update(GameTime gameTime)
        {
            _fpsCounter.Update(gameTime);

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.DrawString(_font, "Current FPS: " + _fpsCounter.CurrentFPS, _topLeftPoint, _fontColor);
            _spriteBatch.DrawString(_font, "Avg FPS: " + _fpsCounter.AverageFPS, _avgFPSLocation, _fontColor);

            base.Draw(gameTime);
        }
    }
}

Fix incorrect namespace for UI component.


using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace RebirthTracker.PacketHandlers
{
    /// <summary>
    /// Request a game host try a hole punch
    /// </summary>
    [Opcode(26)]
    public class HolePunchPacketHandler : IPacketHandler
    {
        /// <summary>
        /// Constructor called through reflection in PacketHandlerFactory
        /// </summary>
        public HolePunchPacketHandler()
        {
        }

        /// <summary>
        /// Handle the packet
        /// </summary>
        public async Task Handle(UdpReceiveResult result)
        {
            var peer = result.RemoteEndPoint;

            await Logger.Log("Hole Punch").ConfigureAwait(false);

            ushort gameID = BitConverter.ToUInt16(result.Buffer, 1);

            await Logger.Log($"Got Game ID {gameID}");

            Game game;

            using (var db = new GameContext())
            {
                game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault();
            }

            Packet packet;

            if (game != null)
            {
                packet = new Packet(26, $"{peer.Address}/{peer.Port}");
                await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false);
                return;
            }

            packet = new Packet(27, gameID);
            await packet.Send(Globals.MainClient, peer).ConfigureAwait(false);
        }
    }
}

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace RebirthTracker.PacketHandlers
{
    /// <summary>
    /// Request a game host try a hole punch
    /// </summary>
    [Opcode(26)]
    public class HolePunchPacketHandler : IPacketHandler
    {
        /// <summary>
        /// Constructor called through reflection in PacketHandlerFactory
        /// </summary>
        public HolePunchPacketHandler()
        {
        }

        /// <summary>
        /// Handle the packet
        /// </summary>
        public async Task Handle(UdpReceiveResult result)
        {
            var peer = result.RemoteEndPoint;

            await Logger.Log("Hole Punch").ConfigureAwait(false);

            ushort gameID = BitConverter.ToUInt16(result.Buffer, 1);

            await Logger.Log($"Got Game ID {gameID}").ConfigureAwait(false);

            Game game;

            using (var db = new GameContext())
            {
                game = (await db.Games.Where(x => x.ID == gameID).ToListAsync().ConfigureAwait(false)).FirstOrDefault();
            }

            Packet packet;

            if (game != null)
            {
                await Logger.Log("Sending hole punch packet").ConfigureAwait(false);
                packet = new Packet(26, $"{peer.Address}/{peer.Port}");
                await packet.Send(Globals.MainClient, game.Endpoint).ConfigureAwait(false);
                return;
            }

            await Logger.Log("Couldn't fetch game").ConfigureAwait(false);
            packet = new Packet(27, gameID);
            await packet.Send(Globals.MainClient, peer).ConfigureAwait(false);
        }
    }
}

Add additional hole punch logging

Add additional hole punch logging


namespace TraktApiSharp.Tests.Experimental.Requests.Calendars
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Calendars;
    using TraktApiSharp.Objects.Get.Calendars;

    [TestClass]
    public class TraktCalendarAllDVDMoviesRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsSealed()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue();
        }
    }
}

namespace TraktApiSharp.Tests.Experimental.Requests.Calendars
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Calendars;
    using TraktApiSharp.Objects.Get.Calendars;
    using TraktApiSharp.Requests;

    [TestClass]
    public class TraktCalendarAllDVDMoviesRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsNotAbstract()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsSealed()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestIsSubclassOfATraktCalendarAllRequest()
        {
            typeof(TraktCalendarAllDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarAllRequest<TraktCalendarMovie>)).Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("Without OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarAllDVDMoviesRequestHasAuthorizationNotRequired()
        {
            var request = new TraktCalendarAllDVDMoviesRequest(null);
            request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.NotRequired);
        }
    }
}

Make sure that authorization of TraktCalendarAllDVDMoviesRequest is not required


@using ForumModels;

@{
    string usersFile = Server.MapPath("~/App_Data/users.json");
    var userList = new UserList(usersFile);
}

            Name
            MSDN Name
            StackOverflow ID

    @{int count = 0; }
    @foreach (var user in userList.Users)
    {
        count++;

            @count
            @user.Name
            @user.MSDNName
            @user.StackOverflowID

    }

Add user photo to users list

Add user photo to users list


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Components;

namespace osu.Game.Screens.OnlinePlay.Playlists
{
    public class PlaylistsReadyButton : ReadyButton
    {
        [Resolved(typeof(Room), nameof(Room.EndDate))]
        private Bindable<DateTimeOffset?> endDate { get; set; }

        [Resolved]
        private IBindable<WorkingBeatmap> gameBeatmap { get; set; }

        public PlaylistsReadyButton()
        {
            Text = "Start";
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            BackgroundColour = colours.Green;
            Triangles.ColourDark = colours.Green;
            Triangles.ColourLight = colours.GreenLight;
        }

        protected override void Update()
        {
            base.Update();

            Enabled.Value = endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value;
        }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Components;

namespace osu.Game.Screens.OnlinePlay.Playlists
{
    public class PlaylistsReadyButton : ReadyButton
    {
        [Resolved(typeof(Room), nameof(Room.EndDate))]
        private Bindable<DateTimeOffset?> endDate { get; set; }

        [Resolved]
        private IBindable<WorkingBeatmap> gameBeatmap { get; set; }

        public PlaylistsReadyButton()
        {
            Text = "Start";
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            BackgroundColour = colours.Green;
            Triangles.ColourDark = colours.Green;
            Triangles.ColourLight = colours.GreenLight;
        }

        private bool hasRemainingAttempts = true;

        protected override void LoadComplete()
        {
            base.LoadComplete();

            userScore.BindValueChanged(aggregate =>
            {
                if (maxAttempts.Value == null)
                    return;

                int remaining = maxAttempts.Value.Value - aggregate.NewValue.PlaylistItemAttempts.Sum(a => a.Attempts);

                hasRemainingAttempts = remaining > 0;
            });
        }

        protected override void Update()
        {
            base.Update();

            Enabled.Value = hasRemainingAttempts && enoughTimeLeft;
        }

        private bool enoughTimeLeft =>
            // This should probably consider the length of the currently selected item, rather than a constant 30 seconds.
            endDate.Value != null && DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(gameBeatmap.Value.Track.Length) < endDate.Value;
    }
}

Disable playlist start button when attempts have been exhausted


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable enable

using System.Diagnostics;

namespace osu.Framework.Extensions.ObjectExtensions
{
    /// <summary>
    /// Extensions that apply to all objects.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
        /// </summary>
        /// <remarks>
        /// This should only be used when an assertion or other handling is not a reasonable alternative.
        /// </remarks>
        /// <param name="obj">The nullable object.</param>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
        public static T AsNonNull<T>(this T? obj)
            where T : class
        {
            Debug.Assert(obj != null);
            return obj;
        }

        /// <summary>
        /// If the given object is null.
        /// </summary>
        public static bool IsNull<T>(this T obj) => ReferenceEquals(obj, null);

        /// <summary>
        /// <c>true</c> if the given object is not null, <c>false</c> otherwise.
        /// </summary>
        public static bool IsNotNull<T>(this T obj) => !ReferenceEquals(obj, null);
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable enable

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace osu.Framework.Extensions.ObjectExtensions
{
    /// <summary>
    /// Extensions that apply to all objects.
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
        /// </summary>
        /// <remarks>
        /// This should only be used when an assertion or other handling is not a reasonable alternative.
        /// </remarks>
        /// <param name="obj">The nullable object.</param>
        /// <typeparam name="T">The type of the object.</typeparam>
        /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
        public static T AsNonNull<T>(this T? obj)
            where T : class
        {
            Debug.Assert(obj != null);
            return obj;
        }

        /// <summary>
        /// If the given object is null.
        /// </summary>
        public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);

        /// <summary>
        /// <c>true</c> if the given object is not null, <c>false</c> otherwise.
        /// </summary>
        public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
    }
}

Annotate return value for consumers

Annotate return value for consumers


using System;
using Baseline;

namespace Marten.Testing
{
    public class ConnectionSource : ConnectionFactory
    {
        public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database");

        static ConnectionSource()
        {
            if (ConnectionString.IsEmpty())
                throw new Exception(
                    "You need to set the connection string for your local Postgresql database in the environment variable 'marten-testing-database'");
        }

        public ConnectionSource() : base(ConnectionString)
        {
        }
    }
}

using System;

namespace Marten.Testing
{
    public class ConnectionSource : ConnectionFactory
    {
        public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database");

        static ConnectionSource()
        {
            if (ConnectionString.IsEmpty())
                throw new Exception(
                    "You need to set the connection string for your local Postgresql database in the environment variable 'marten_testing_database'");
        }

        public ConnectionSource() : base(ConnectionString)
        {
        }
    }
}

Correct error message for missing test connection string


using Harmony;
using LunaClient.Systems.Lock;
using LunaCommon.Enums;
using System.Collections.Generic;
// ReSharper disable All

namespace LunaClient.Harmony
{
    /// <summary>
    /// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site
    /// We just remove the other controlled vessels from that check and set them correctly
    /// </summary>
    [HarmonyPatch(typeof(ShipConstruction))]
    [HarmonyPatch("FindVesselsLandedAt")]
    [HarmonyPatch(new[] { typeof(FlightState), typeof(string) })]
    public class ShipConstruction_FindVesselsLandedAt
    {
        private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>();

        [HarmonyPostfix]
        private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result)
        {
            if (MainSystem.NetworkState < ClientState.Connected) return;

            ProtoVesselsToRemove.Clear();

            foreach (var pv in __result)
            {
                if (!LockSystem.LockQuery.ControlLockExists(pv.vesselID))
                    ProtoVesselsToRemove.Add(pv);
            }

            foreach (var pv in ProtoVesselsToRemove)
            {
                __result.Remove(pv);
            }
        }
    }
}

using Harmony;
using LunaClient.Systems.Lock;
using LunaCommon.Enums;
using System.Collections.Generic;
// ReSharper disable All

namespace LunaClient.Harmony
{
    /// <summary>
    /// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site
    /// We just remove the other controlled vessels from that check and set them correctly
    /// </summary>
    [HarmonyPatch(typeof(ShipConstruction))]
    [HarmonyPatch("FindVesselsLandedAt")]
    [HarmonyPatch(new[] { typeof(FlightState), typeof(string) })]
    public class ShipConstruction_FindVesselsLandedAt
    {
        private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>();

        [HarmonyPostfix]
        private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result)
        {
            if (MainSystem.NetworkState < ClientState.Connected) return;

            ProtoVesselsToRemove.Clear();

            foreach (var pv in __result)
            {
                if (LockSystem.LockQuery.ControlLockExists(pv.vesselID))
                    ProtoVesselsToRemove.Add(pv);
            }

            foreach (var pv in ProtoVesselsToRemove)
            {
                __result.Remove(pv);
            }
        }
    }
}

Fix find vessels landed at

Fix find vessels landed at


// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Draw2D.Core
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public bool IsDirty { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (!Equals(field, value))
            {
                field = value;
                IsDirty = true;
                Notify(propertyName);
                return true;
            }
            return false;
        }
    }
}

// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Draw2D.Core
{
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        internal bool IsDirty { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Notify([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (!Equals(field, value))
            {
                field = value;
                IsDirty = true;
                Notify(propertyName);
                return true;
            }
            return false;
        }
    }
}

Mark IsDirty property as internal

Mark IsDirty property as internal


using System.Data.Entity;

namespace food_tracker {
    public class TrackerContext : DbContext {

        public TrackerContext() : base("name=NutritionTrackerContext") {
            Configuration.LazyLoadingEnabled = false;

            this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
        }

        public DbSet<WholeDay> Days { get; set; }
        public DbSet<NutritionItem> Nutrition { get; set; }
    }
}

using System.Data.Entity;

namespace food_tracker {
    public class TrackerContext : DbContext {

        public TrackerContext() : base() {
            Configuration.LazyLoadingEnabled = false;

            this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
        }

        public DbSet<WholeDay> Days { get; set; }
        public DbSet<NutritionItem> Nutrition { get; set; }
    }
}

Change back to use the default database name.


namespace Bakery.Processes
{
	using Specification.Builder;
	using System;
	using System.Text;
	using System.Threading.Tasks;
	using Xunit;

	public class SystemDiagnosticsProcessTests
	{
		[Fact]
		public async Task EchoWithCombinedOutput()
		{
			var processSpecification =
				ProcessSpecificationBuilder.Create()
					.WithProgram(@"echo")
					.WithArguments("a", "b", "c")
					.WithEnvironment()
					.WithCombinedOutput()
					.Build();

			var processFactory = new ProcessFactory();

			var process = processFactory.Start(processSpecification);
			var stringBuilder = new StringBuilder();

			await process.WaitForExit(TimeSpan.FromSeconds(5));

			while (true)
			{
				var output = await process.TryReadAsync(TimeSpan.FromSeconds(1));

				if (output == null)
					break;

				stringBuilder.Append(output.Text);
			}

			var totalOutput = stringBuilder.ToString();

			Assert.Equal("a b c", totalOutput);
		}
	}
}

namespace Bakery.Processes
{
	using System;
	using System.Text;
	using System.Threading.Tasks;
	using Xunit;

	public class SystemDiagnosticsProcessTests
	{
		[Fact]
		public async Task EchoWithCombinedOutput()
		{
			var process = await new ProcessFactory().RunAsync(builder =>
			{
				return builder
					.WithProgram("echo")
					.WithArguments("a", "b", "c")
					.WithEnvironment()
					.WithCombinedOutput()
					.Build();
			});

			var stringBuilder = new StringBuilder();

			while (true)
			{
				var output = await process.TryReadAsync(TimeSpan.FromSeconds(1));

				if (output == null)
					break;

				stringBuilder.Append(output.Text);
			}

			var totalOutput = stringBuilder.ToString();

			Assert.Equal("a b c", totalOutput);
		}
	}
}

Update tests re: process builder, etc.

Update tests re: process builder, etc.


using System;
using System.Collections.Generic;
using Cake.Core.Diagnostics;

namespace Cake.Arguments
{
    /// <summary>
    /// Responsible for parsing <see cref="Verbosity"/>.
    /// </summary>
    internal sealed class VerbosityParser
    {
        private readonly Dictionary<string, Verbosity> _lookup;

        /// <summary>
        /// Initializes a new instance of the <see cref="VerbosityParser"/> class.
        /// </summary>
        public VerbosityParser()
        {
            _lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase)
            {
                { "q", Verbosity.Quiet },
                { "quiet", Verbosity.Quiet },
                { "m", Verbosity.Minimal },
                { "minimal", Verbosity.Minimal },
                { "n", Verbosity.Normal },
                { "normal", Verbosity.Normal },
                { "v", Verbosity.Verbose },
                { "verbose", Verbosity.Verbose },
                { "d", Verbosity.Diagnostic },
                { "diagnostic", Verbosity.Diagnostic }
            };
        }

        /// <summary>
        /// Parses the provided string to a <see cref="Verbosity"/>.
        /// </summary>
        /// <param name="value">The string to parse.</param>
        /// <returns>The verbosity.</returns>
        public Verbosity Parse(string value)
        {
            Verbosity verbosity;
            if (_lookup.TryGetValue(value, out verbosity))
            {
                return verbosity;
            }
            const string format = "The value '{0}' is not a valid verbosity.";
            var message = string.Format(format, value ?? string.Empty);
            throw new InvalidOperationException(message);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Globalization;
using Cake.Core.Diagnostics;

namespace Cake.Arguments
{
    /// <summary>
    /// Responsible for parsing <see cref="Verbosity"/>.
    /// </summary>
    internal sealed class VerbosityParser
    {
        private readonly Dictionary<string, Verbosity> _lookup;

        /// <summary>
        /// Initializes a new instance of the <see cref="VerbosityParser"/> class.
        /// </summary>
        public VerbosityParser()
        {
            _lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase)
            {
                { "q", Verbosity.Quiet },
                { "quiet", Verbosity.Quiet },
                { "m", Verbosity.Minimal },
                { "minimal", Verbosity.Minimal },
                { "n", Verbosity.Normal },
                { "normal", Verbosity.Normal },
                { "v", Verbosity.Verbose },
                { "verbose", Verbosity.Verbose },
                { "d", Verbosity.Diagnostic },
                { "diagnostic", Verbosity.Diagnostic }
            };
        }

        /// <summary>
        /// Parses the provided string to a <see cref="Verbosity"/>.
        /// </summary>
        /// <param name="value">The string to parse.</param>
        /// <returns>The verbosity.</returns>
        public Verbosity Parse(string value)
        {
            Verbosity verbosity;
            if (_lookup.TryGetValue(value, out verbosity))
            {
                return verbosity;
            }
            const string format = "The value '{0}' is not a valid verbosity.";
            var message = string.Format(CultureInfo.InvariantCulture, format, value);
            throw new InvalidOperationException(message);
        }
    }
}

Add invariant IFormatterProvider to avoid issues based on user local


namespace TraktApiSharp.Services
{
    using Authentication;
    using System;

    /// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary>
    public static class TraktSerializationService
    {
        public static string Serialize(TraktAuthorization authorization)
        {
            if (authorization == null)
                throw new ArgumentNullException(nameof(authorization), "authorization must not be null");

            return string.Empty;
        }

        public static TraktAuthorization Deserialize(string authorization)
        {
            return null;
        }
    }
}

namespace TraktApiSharp.Services
{
    using Authentication;
    using Extensions;
    using System;
    using Utils;

    /// Provides helper methods for serializing and deserializing Trakt objects.
    public static class TraktSerializationService
    {
        /// Serializes an <see cref="TraktAuthorization" /> instance to a Json string.
        /// <param name="authorization">The authorization information, which should be serialized.</param>
        /// <returns>A Json string, containing all properties of the given authorization.</returns>
        /// <exception cref="ArgumentNullException">Thrown, if the given authorization is null.</exception>
        public static string Serialize(TraktAuthorization authorization)
        {
            if (authorization == null)
                throw new ArgumentNullException(nameof(authorization), "authorization must not be null");

            var anonymousAuthorization = new
            {
                AccessToken = authorization.AccessToken,
                RefreshToken = authorization.RefreshToken,
                ExpiresIn = authorization.ExpiresIn,
                Scope = authorization.AccessScope.ObjectName,
                TokenType = authorization.TokenType.ObjectName,
                CreatedAt = authorization.Created.ToTraktLongDateTimeString(),
                IgnoreExpiration = authorization.IgnoreExpiration
            };

            return Json.Serialize(anonymousAuthorization);
        }

        public static TraktAuthorization Deserialize(string authorization)
        {
            return null;
        }
    }
}

Add implementation for serializing TraktAuthorization.


using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;

namespace IIUWr
{
    public static class ConfigureIoC
    {
        public static void All()
        {
#if DEBUG
            IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
            IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif

            ViewModels();
            Fereol.Common();

            Fereol.HTMLParsing();
        }

        public static void ViewModels()
        {
            IoC.AsSingleton<SemestersViewModel>();
            IoC.PerRequest<SemesterViewModel>();
            IoC.PerRequest<CourseViewModel>();
            IoC.PerRequest<TutorialViewModel>();
        }

        public static class Fereol
        {
            public static void Common()
            {
                IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
                IoC.AsSingleton<ISessionManager, CredentialsManager>();
            }

            public static void HTMLParsing()
            {
                IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
                IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();

                IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
            }
        }
    }
}

using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;

namespace IIUWr
{
    public static class ConfigureIoC
    {
        public static void All()
        {
#if DEBUG
            IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
            IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif

            ViewModels();
            Fereol.Common();

            Fereol.HTMLParsing();
        }

        public static void ViewModels()
        {
            IoC.AsSingleton<SemestersViewModel>();
        }

        public static class Fereol
        {
            public static void Common()
            {
                IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
                IoC.AsSingleton<ISessionManager, CredentialsManager>();
            }

            public static void HTMLParsing()
            {
                IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
                IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();

                IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
            }
        }
    }
}

Remove not needed IoC registrations

Remove not needed IoC registrations


using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NBi.Testing.Integration.Core.Structure
{
    public class StructureDiscoveryFactoryProviderTest
    {
        private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
        {
            public new string InquireFurtherAnalysisService(string connectionString)
            {
                return base.InquireFurtherAnalysisService(connectionString);
            }
        }

        [Test]
        [Category("Olap")]
        public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
        {
            var connectionString = ConnectionStringReader.GetAdomd();

            var provider = new FakeStructureDiscoveryFactoryProvider();
            var serverMode = provider.InquireFurtherAnalysisService(connectionString);
            Assert.That(serverMode, Is.EqualTo("olap"));
        }

        [Test]
        [Category("Tabular")]
        public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
        {
            var connectionString = ConnectionStringReader.GetAdomdTabular();

            var provider = new FakeStructureDiscoveryFactoryProvider();
            var serverMode = provider.InquireFurtherAnalysisService(connectionString);
            Assert.That(serverMode, Is.EqualTo("tabular"));
        }
    }
}

using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NBi.Testing.Integration.Core.Structure
{
    public class StructureDiscoveryFactoryProviderTest
    {
        private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
        {
            public new string InquireFurtherAnalysisService(string connectionString)
            {
                return base.InquireFurtherAnalysisService(connectionString);
            }
        }

        [Test]
        [Category("Olap")]
        public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
        {
            var connectionString = ConnectionStringReader.GetAdomd();

            var provider = new FakeStructureDiscoveryFactoryProvider();
            var serverMode = provider.InquireFurtherAnalysisService(connectionString);
            Assert.That(serverMode, Is.EqualTo("olap"));
        }

        [Test]
        [Category("Olap")]
        public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
        {
            var connectionString = ConnectionStringReader.GetAdomdTabular();

            var provider = new FakeStructureDiscoveryFactoryProvider();
            var serverMode = provider.InquireFurtherAnalysisService(connectionString);
            Assert.That(serverMode, Is.EqualTo("tabular"));
        }
    }
}

Fix category for a test about tabular structure

Goal: Exclude them in the nightly build


using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;

namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
    public class UserAccountsViewModel
    {
        public Accounts Accounts;
        public int Invitations;
        public string SuccessMessage;
    }
}

using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;

namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
    public class UserAccountsViewModel
    {
        public Accounts Accounts;
        public int Invitations;
        public SuccessMessageViewModel SuccessMessage;
    }
}

Change user accounts view model to use the new viewmodel for displaying SuccessMessage


/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;

namespace Cube.Xui.Converters
{
    /* --------------------------------------------------------------------- */
    ///
    /// ImageConverter
    ///
    /// <summary>
    /// Provides functionality to convert from an Image object to
    /// a BitmapImage object.
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    public class ImageConverter : SimplexConverter
    {
        /* ----------------------------------------------------------------- */
        ///
        /// ImageValueConverter
        ///
        /// <summary>
        /// Initializes a new instance of the ImageConverter class.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public ImageConverter() : base(e =>
        {
            var src = e is System.Drawing.Image image ? image :
                      e is System.Drawing.Icon  icon  ? icon.ToBitmap() :
                      null;
            return src.ToBitmapImage();
        }) { }
    }
}

/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;

namespace Cube.Xui.Converters
{
    /* --------------------------------------------------------------------- */
    ///
    /// ImageConverter
    ///
    /// <summary>
    /// Provides functionality to convert from an Image object to
    /// a BitmapImage object.
    /// </summary>
    ///
    /* --------------------------------------------------------------------- */
    public class ImageConverter : SimplexConverter
    {
        /* ----------------------------------------------------------------- */
        ///
        /// ImageValueConverter
        ///
        /// <summary>
        /// Initializes a new instance of the ImageConverter class.
        /// </summary>
        ///
        /* ----------------------------------------------------------------- */
        public ImageConverter() : base(e =>
        {
            if (e is System.Drawing.Image i0) return i0.ToBitmapImage(false);
            if (e is System.Drawing.Icon  i1) return i1.ToBitmap().ToBitmapImage(true);
            return null;
        }) { }
    }
}

Fix to dispose when the specified object is Icon.