using RealEstateAgencyFranchise.Database;
using Starcounter;
using System.Linq;

namespace RealEstateAgencyFranchise.Controllers
{
    internal class OfficeController
    {
        public Json Get(ulong officeObjectNo)
        {
            return Db.Scope(() =>
            {
                var offices = Db.SQL<Office>(
                    "select o from Office o where o.ObjectNo = ?",
                    officeObjectNo);
                if (offices == null || !offices.Any())
                {
                    return new Response()
                    {
                        StatusCode = 404,
                        StatusDescription = "Office not found"
                    };
                }

                var office = offices.First;

                var json = new OfficeListJson
                {
                    Data = office
                };

                if (Session.Current == null)
                {
                    Session.Current = new Session(SessionOptions.PatchVersioning);
                }

                json.Session = Session.Current;
                return json;
            });
        }
    }
}

using RealEstateAgencyFranchise.Database;
using RealEstateAgencyFranchise.ViewModels;
using Starcounter;
using System.Linq;

namespace RealEstateAgencyFranchise.Controllers
{
    internal class OfficeController
    {
        public Json Get(ulong officeObjectNo)
        {
            return Db.Scope(() =>
            {
                var offices = Db.SQL<Office>(
                    "select o from Office o where o.ObjectNo = ?",
                    officeObjectNo);
                if (offices == null || !offices.Any())
                {
                    return new Response()
                    {
                        StatusCode = 404,
                        StatusDescription = "Office not found"
                    };
                }

                var office = offices.First;

                var json = new OfficeDetailsJson
                {
                    Data = office
                };

                if (Session.Current == null)
                {
                    Session.Current = new Session(SessionOptions.PatchVersioning);
                }

                json.Session = Session.Current;
                return json;
            });
        }
    }
}

Fix missed view model reference

Fix missed view model reference


using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;

namespace LiteNetLibManager
{
    public struct ServerTimeMessage : INetSerializable
    {
        public int serverUnixTime;

        public void Deserialize(NetDataReader reader)
        {
            serverUnixTime = reader.GetPackedInt();
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.PutPackedInt(serverUnixTime);
        }
    }
}

using System.Collections;
using System.Collections.Generic;
using LiteNetLib.Utils;

namespace LiteNetLibManager
{
    public struct ServerTimeMessage : INetSerializable
    {
        public long serverUnixTime;

        public void Deserialize(NetDataReader reader)
        {
            serverUnixTime = reader.GetPackedLong();
        }

        public void Serialize(NetDataWriter writer)
        {
            writer.PutPackedLong(serverUnixTime);
        }
    }
}

Change time type to long

Change time type to long


// 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 UIKit;

namespace TemplateGame.iOS
{
    public static class Application
    {
        public static void Main(string[] args)
        {
            UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
        }
    }
}

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

using osu.Framework.iOS;
using UIKit;

namespace TemplateGame.iOS
{
    public static class Application
    {
        public static void Main(string[] args)
        {
            UIApplication.Main(args, typeof(GameUIApplication), typeof(AppDelegate));
        }
    }
}

Fix `TemplateGame.iOS` failing to build

Fix `TemplateGame.iOS` failing to build


using System;
using System.Globalization;

namespace Avalonia.Utilities
{
#if !BUILDTASK
    public
#endif
    static class StyleClassParser
    {
        public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
        {
            if (IsValidIdentifierStart(r.Peek))
            {
                return r.TakeWhile(c => IsValidIdentifierChar(c));
            }
            else
            {
                return ReadOnlySpan<char>.Empty;
            }
        }

        private static bool IsValidIdentifierStart(char c)
        {
            return char.IsLetter(c) || c == '_';
        }

        private static bool IsValidIdentifierChar(char c)
        {
            if (IsValidIdentifierStart(c) || c == '-')
            {
                return true;
            }
            else
            {
                var cat = CharUnicodeInfo.GetUnicodeCategory(c);
                return cat == UnicodeCategory.NonSpacingMark ||
                       cat == UnicodeCategory.SpacingCombiningMark ||
                       cat == UnicodeCategory.ConnectorPunctuation ||
                       cat == UnicodeCategory.Format ||
                       cat == UnicodeCategory.DecimalDigitNumber;
            }
        }
    }
}

using System;
using System.Globalization;

namespace Avalonia.Utilities
{
#if !BUILDTASK
    public
#endif
    static class StyleClassParser
    {
        public static ReadOnlySpan<char> ParseStyleClass(this ref CharacterReader r)
        {
            if (IsValidIdentifierStart(r.PeekOneOrThrow))
            {
                return r.TakeWhile(c => IsValidIdentifierChar(c));
            }
            else
            {
                return ReadOnlySpan<char>.Empty;
            }
        }

        private static bool IsValidIdentifierStart(char c)
        {
            return char.IsLetter(c) || c == '_';
        }

        private static bool IsValidIdentifierChar(char c)
        {
            if (IsValidIdentifierStart(c) || c == '-')
            {
                return true;
            }
            else
            {
                var cat = CharUnicodeInfo.GetUnicodeCategory(c);
                return cat == UnicodeCategory.NonSpacingMark ||
                       cat == UnicodeCategory.SpacingCombiningMark ||
                       cat == UnicodeCategory.ConnectorPunctuation ||
                       cat == UnicodeCategory.Format ||
                       cat == UnicodeCategory.DecimalDigitNumber;
            }
        }
    }
}

Fix build failure from the merge to master.


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

using System;
using System.Runtime.InteropServices;

namespace osu.Framework.Desktop.Platform
{
    internal static class Architecture
    {
        public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
        private static string arch => Is64Bit ? @"x64" : @"x86";

        internal static bool Is64Bit => IntPtr.Size == 8;

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetDllDirectory(string lpPathName);

        internal static void SetIncludePath()
        {
            //todo: make this not a thing for linux or whatever
            try
            {
                SetDllDirectory(NativeIncludePath);
            }
            catch { }
        }
    }
}

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

using System;
using System.Runtime.InteropServices;

namespace osu.Framework.Desktop.Platform
{
    internal static class Architecture
    {
        public static string NativeIncludePath => $@"{Environment.CurrentDirectory}/{arch}/";
        private static string arch => Is64Bit ? @"x64" : @"x86";

        internal static bool Is64Bit => IntPtr.Size == 8;

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetDllDirectory(string lpPathName);

        internal static void SetIncludePath()
        {
            if (RuntimeInfo.IsWindows)
                SetDllDirectory(NativeIncludePath);
        }
    }
}

Use RuntimeInfo.IsLinux to check for Linux

It's quite easy to do this, FYI


using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;

namespace ReactiveUIMicro
{
    public static class WhenAnyShim
    {
        public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
            where TSender : IReactiveNotifyPropertyChanged
        {
            var propName = Reflection.SimpleExpressionToPropertyName(property);
            var getter = Reflection.GetValueFetcherForProperty<TSender>(propName);

            return This.Changed
                .Where(x => x.PropertyName == propName)
                .Select(_ => new ObservedChange<TSender, TTarget>() {
                    Sender = This,
                    PropertyName = propName,
                    Value = (TTarget)getter(This),
                })
                .StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
                .Select(selector);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Windows;

namespace ReactiveUIMicro
{
    public static class WhenAnyShim
    {
        public static IObservable<TVal> WhenAny<TSender, TTarget, TVal>(this TSender This, Expression<Func<TSender, TTarget>> property, Func<IObservedChange<TSender, TTarget>, TVal> selector)
            where TSender : IReactiveNotifyPropertyChanged
        {
            var propName = Reflection.SimpleExpressionToPropertyName(property);
            var getter = Reflection.GetValueFetcherForProperty(This.GetType(), propName);

            return This.Changed
                .Where(x => x.PropertyName == propName)
                .Select(_ => new ObservedChange<TSender, TTarget>() {
                    Sender = This,
                    PropertyName = propName,
                    Value = (TTarget)getter(This),
                })
                .StartWith(new ObservedChange<TSender, TTarget>() { Sender = This, PropertyName = propName, Value = (TTarget)getter(This) })
                .Select(selector);
        }
    }
}

Fix casting error in WhenAny shim

Fix casting error in WhenAny shim


namespace WindowsUniversalAppDriver.InnerServer.Commands
{
    using System.Reflection;

    using WindowsUniversalAppDriver.Common;

    internal class GetElementAttributeCommand : CommandBase
    {
        #region Public Properties

        public string ElementId { get; set; }

        #endregion

        #region Public Methods and Operators

        public override string DoImpl()
        {
            var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);

            object value;
            var attributeName = (string)null;
            if (this.Parameters.TryGetValue("NAME", out value))
            {
                attributeName = value.ToString();
            }

            if (attributeName == null)
            {
                return this.JsonResponse(ResponseStatus.Success, null);
            }

            var property = element.GetType().GetRuntimeProperty(attributeName);
            if (property == null)
            {
                return this.JsonResponse(ResponseStatus.Success, null);
            }

            var attributeValue = property.GetValue(element, null).ToString();

            return this.JsonResponse(ResponseStatus.Success, attributeValue);
        }

        #endregion
    }
}

namespace WindowsUniversalAppDriver.InnerServer.Commands
{
    using System;
    using System.Reflection;

    using WindowsUniversalAppDriver.Common;

    internal class GetElementAttributeCommand : CommandBase
    {
        #region Public Properties

        public string ElementId { get; set; }

        #endregion

        #region Public Methods and Operators

        public override string DoImpl()
        {
            var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId);

            object value;
            string attributeName = null;
            if (this.Parameters.TryGetValue("NAME", out value))
            {
                attributeName = value.ToString();
            }

            if (attributeName == null)
            {
                return this.JsonResponse(ResponseStatus.Success, null);
            }

            var properties = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            object propertyValueObject = element;
            foreach (var property in properties)
            {
                propertyValueObject = GetProperty(propertyValueObject, property);
                if (propertyValueObject == null)
                {
                    break;
                }
            }

            var propertyValue = propertyValueObject == null ? null : propertyValueObject.ToString();

            return this.JsonResponse(ResponseStatus.Success, propertyValue);
        }

        private static object GetProperty(object obj, string propertyName)
        {
            var property = obj.GetType().GetRuntimeProperty(propertyName);

            return property == null ? null : property.GetValue(obj, null);
        }

        #endregion
    }
}

Add support for nested properties access in GetElementAttribute command using dot separated syntax

Now you can access nested property of element using dot separated syntax in /session/:sessionId/element/:id/attribute/:name command
e.g., "SelectedItem.DisplayName", etc.


@using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}

Page Not Found

Sorry we could not find the page requested. However, we did find a picture of Edgar F. Codd , the inventor of the relational data model.

If you feel something is missing that should be here, contact us.

@using StackExchange.DataExplorer
@{this.SetPageTitle("Page not found - Stack Exchange Data Explorer");}

Page Not Found

Sorry we could not find the page requested. However, we did find a picture of Edgar F. Codd, the inventor of the relational data model.

If you feel something is missing that should be here, contact us.

Remove stray space in 404 page

Remove stray space in 404 page


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

namespace JabbR.Models
{
    public class ChatRoom
    {
        [Key]
        public int Key { get; set; }

        public DateTime LastActivity { get; set; }
        public DateTime? LastNudged { get; set; }
        public string Name { get; set; }

        public virtual ChatUser Owner { get; set; }

        public virtual ICollection<ChatMessage> Messages { get; set; }
        public virtual ICollection<ChatUser> Users { get; set; }

        public ChatRoom()
        {
            Messages = new HashSet<ChatMessage>();
            Users = new HashSet<ChatUser>();
        }
    }
}

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

namespace JabbR.Models
{
    public class ChatRoom
    {
        [Key]
        public int Key { get; set; }

        public DateTime LastActivity { get; set; }
        public DateTime? LastNudged { get; set; }
        public string Name { get; set; }

        public virtual ChatUser Owner { get; set; }

        public virtual ICollection<ChatMessage> Messages { get; set; }
        public virtual ICollection<ChatUser> Users { get; set; }

        public ChatRoom()
        {
            LastActivity = DateTime.UtcNow;
            Messages = new HashSet<ChatMessage>();
            Users = new HashSet<ChatUser>();
        }
    }
}

Set the last activity on creation so sql doesn't blow up.


using System;

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages. Based on Bruce Schneier's RandBytes1-way
    /// function method for committing bits
    /// </summary>
    public class BitCommitmentProvider
    {
        public byte[] AliceRandBytes1 { get; set; }
        public byte[] AliceRandBytes2 { get; set; }
        public byte[] AliceBytesToCommitBytesToCommit { get; set; }

        public BitCommitmentProvider(byte[] randBytes1,
            byte[] randBytes2,
            byte[] bytesToCommit)
        {
            AliceRandBytes1 = randBytes1;
            AliceRandBytes2 = randBytes2;
            AliceBytesToCommitBytesToCommit = bytesToCommit;
        }

        public byte[] BitCommitMessage()
        {
            throw new NotImplementedException();
        }
    }
}

using System;

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
    /// function method for committing bits. See p.87 of `Applied Cryptography`.
    /// </summary>
    public class BitCommitmentProvider
    {
        public byte[] AliceRandBytes1 { get; set; }
        public byte[] AliceRandBytes2 { get; set; }
        public byte[] AliceBytesToCommitBytesToCommit { get; set; }

        public BitCommitmentProvider(byte[] randBytes1,
            byte[] randBytes2,
            byte[] bytesToCommit)
        {
            AliceRandBytes1 = randBytes1;
            AliceRandBytes2 = randBytes2;
            AliceBytesToCommitBytesToCommit = bytesToCommit;
        }

        public byte[] BitCommitMessage()
        {
            throw new NotImplementedException();
        }
    }
}

Fix refactor fail and add book reference


using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;

namespace TeaCommerce.Umbraco.Configuration.Compatibility {
  public static class Domain {

    private const string CacheKey = "Domains";

    public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
      List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );

      if ( domains == null ) {
        domains = new List<umbraco.cms.businesslogic.web.Domain>();

        List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );

        foreach ( dynamic domain in result ) {
          if ( domains.All( d => d.Name != domain.domainName ) ) {
            domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.domainId ) );
          }
        }

        CacheService.Instance.SetCacheValue( CacheKey, domains );
      }

      return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
    }

    public static void InvalidateCache() {
      CacheService.Instance.Invalidate( CacheKey );
    }
  }
}

using System.Collections.Generic;
using System.Linq;
using TeaCommerce.Api.Infrastructure.Caching;
using Umbraco.Core;

namespace TeaCommerce.Umbraco.Configuration.Compatibility {
  public static class Domain {

    private const string CacheKey = "Domains";

    public static umbraco.cms.businesslogic.web.Domain[] GetDomainsById( int nodeId ) {
      List<umbraco.cms.businesslogic.web.Domain> domains = CacheService.Instance.GetCacheValue<List<umbraco.cms.businesslogic.web.Domain>>( CacheKey );

      if ( domains == null ) {
        domains = new List<umbraco.cms.businesslogic.web.Domain>();

        List<dynamic> result = ApplicationContext.Current.DatabaseContext.Database.Fetch<dynamic>( "select id, domainName from umbracoDomains" );

        foreach ( dynamic domain in result ) {
          if ( domains.All( d => d.Name != domain.domainName ) ) {
            domains.Add( new umbraco.cms.businesslogic.web.Domain( domain.id ) );
          }
        }

        CacheService.Instance.SetCacheValue( CacheKey, domains );
      }

      return domains.Where( d => d.RootNodeId == nodeId ).ToArray();
    }

    public static void InvalidateCache() {
      CacheService.Instance.Invalidate( CacheKey );
    }
  }
}

Change domain id to new naming format

Change domain id to new naming format


using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crosscutter")]
[assembly: AssemblyDescription(".NET extensions, safety & convenience methods for known types.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daryl Benzel")]
[assembly: AssemblyProduct("Crosscutter")]
[assembly: AssemblyCopyright("Copyright © Daryl Benzel 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bd03676e-4bbc-4e8e-9f00-a3e2ae2d2b9d")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0")]

Edit assembly description to make xml compliant for nuspec output.


using System.Runtime.Serialization;

namespace PS.Mothership.Core.Common.Rellaid.Dto
{
    [DataContract]
    public class InboundQueueDistributorDto
    {
        [DataMember]
        public string FilterNumber { get; set; }

        [DataMember]
        public int RungCount { get; set; }
    }
}

using System.Runtime.Serialization;

namespace PS.Mothership.Core.Common.Rellaid.Dto
{
    [DataContract]
    public class InboundQueueDistributorDto
    {
        [DataMember]
        public string PhoneNumber { get; set; }

        [DataMember]
        public int RungCount { get; set; }
    }
}

Change FilterNumber to PhoneNumber so that it has the same name as the database field

git-svn-id: 2ba1368c4e437a7d9ecf55f7e32b22ba866dc236@460 0f896bb5-3ab0-2d4e-82a7-85ef10020915


using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;

namespace RocketRegions.Model.Flag.Impl
{
    public class NoVehiclesUsageFlag : BoolFlag
    {
        public override string Description => "Allow/Disallow usage of vehicles in region";

        private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();

        public override void UpdateState(List<UnturnedPlayer> players)
        {
            foreach (var player in players)
            {
                var id = PlayerUtil.GetId(player);
                var veh = player.Player.movement.getVehicle();
                var isInVeh = veh != null;

                if (!_lastVehicleStates.ContainsKey(id))
                    _lastVehicleStates.Add(id, veh);

                var wasDriving = _lastVehicleStates[id];

                if (!isInVeh || wasDriving ||
                    !GetValueSafe(Region.GetGroup(player))) continue;

                byte seat;
                Vector3 point;
                byte angle;
                veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
            }
        }

        public override void OnRegionEnter(UnturnedPlayer p)
        {
            //do nothing
        }

        public override void OnRegionLeave(UnturnedPlayer p)
        {
            //do nothing
        }
    }
}

using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;

namespace RocketRegions.Model.Flag.Impl
{
    public class NoVehiclesUsageFlag : BoolFlag
    {
        public override string Description => "Allow/Disallow usage of vehicles in region";

        private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();

        public override void UpdateState(List<UnturnedPlayer> players)
        {
            foreach (var player in players)
            {
                var id = PlayerUtil.GetId(player);
                var veh = player.Player.movement.getVehicle();
                var isInVeh = veh != null;

                if (!_lastVehicleStates.ContainsKey(id))
                    _lastVehicleStates.Add(id, veh);

                var wasDriving = _lastVehicleStates[id];

                if (!isInVeh || wasDriving ||
                    !GetValueSafe(Region.GetGroup(player))) continue;

                byte seat;
                Vector3 point;
                byte angle;
                veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
                veh.removePlayer(seat, point, angle, true);
            }
        }

        public override void OnRegionEnter(UnturnedPlayer p)
        {
            //do nothing
        }

        public override void OnRegionLeave(UnturnedPlayer p)
        {
            //do nothing
        }
    }
}

Fix for NoVehicleUsage flag doing nothing


using System.Collections.Generic;
using UnityEngine;

namespace LiteNetLibManager
{
    public class DefaultInterestManager : BaseInterestManager
    {
        [Tooltip("Update every ? seconds")]
        public float updateInterval = 1f;

        private float updateCountDown = 0f;

        private void Update()
        {
            if (!IsServer)
            {
                // Update at server only
                return;
            }
            updateCountDown -= Time.unscaledDeltaTime;
            if (updateCountDown <= 0f)
            {
                updateCountDown = updateInterval;
                HashSet<uint> subscribings = new HashSet<uint>();
                foreach (LiteNetLibPlayer player in Manager.GetPlayers())
                {
                    if (!player.IsReady)
                    {
                        // Don't subscribe if player not ready
                        continue;
                    }
                    foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
                    {
                        // Skip destroyed player object
                        if (playerObject == null)
                            continue;
                        // Update subscribing list, it will unsubscribe objects which is not in this list
                        subscribings.Clear();
                        foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
                        {
                            if (ShouldSubscribe(playerObject, spawnedObject))
                                subscribings.Add(spawnedObject.ObjectId);
                        }
                        playerObject.UpdateSubscribings(subscribings);
                    }
                }
            }
        }
    }
}

using System.Collections.Generic;
using UnityEngine;

namespace LiteNetLibManager
{
    public class DefaultInterestManager : BaseInterestManager
    {
        [Tooltip("Update every ? seconds")]
        public float updateInterval = 1f;

        private float updateCountDown = 0f;

        private void Update()
        {
            if (!IsServer)
            {
                // Update at server only
                return;
            }
            updateCountDown -= Time.unscaledDeltaTime;
            if (updateCountDown <= 0f)
            {
                updateCountDown = updateInterval;
                HashSet<uint> subscribings = new HashSet<uint>();
                foreach (LiteNetLibPlayer player in Manager.GetPlayers())
                {
                    if (!player.IsReady)
                    {
                        // Don't subscribe if player not ready
                        continue;
                    }
                    foreach (LiteNetLibIdentity playerObject in player.GetSpawnedObjects())
                    {
                        // Update subscribing list, it will unsubscribe objects which is not in this list
                        subscribings.Clear();
                        foreach (LiteNetLibIdentity spawnedObject in Manager.Assets.GetSpawnedObjects())
                        {
                            if (ShouldSubscribe(playerObject, spawnedObject))
                                subscribings.Add(spawnedObject.ObjectId);
                        }
                        playerObject.UpdateSubscribings(subscribings);
                    }
                }
            }
        }
    }
}

Delete null check codes, it is not necessary because set owner object function bugs was solved.


using Machine.Specifications;

namespace TestingFxTests
{
    [Subject("Booleans")]
    public class When_comparing_booleans
    {
        private static bool Subject;
        private Establish context = () =>  Subject = false;
        private Because of = () => Subject = true;
        private It should_be_true = () => Subject.ShouldEqual(true);
    }
}

using Machine.Specifications;

namespace TestingFxTests
{
    [Subject("Mspec")]
    public class MspecExample
    {
        private static bool Subject;
        private Establish context = () =>  Subject = false;
        private Because of = () => Subject = true;
        private It should_be_true = () => Subject.ShouldEqual(true);
    }
}

Rename recommended mSpec convention to MspecExample for consistency


using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Tiesmaster.Dcc
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(RunDccProxyAsync);
        }

        private static async Task RunDccProxyAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello from DCC ;)");
        }
    }
}

using System;
using System.Net.Http;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Tiesmaster.Dcc
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if(env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(RunDccProxyAsync);
        }

        private static async Task RunDccProxyAsync(HttpContext context)
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod = context.Request.Method;
            if(!HttpMethods.IsGet(requestMethod) &&
                !HttpMethods.IsHead(requestMethod) &&
                !HttpMethods.IsDelete(requestMethod) &&
                !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(context.Request.Body);
                requestMessage.Content = streamContent;
            }

            // Copy the request headers
            foreach(var header in context.Request.Headers)
            {
                if(!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
            var uriString = $"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
            requestMessage.RequestUri = new Uri(uriString);
            requestMessage.Method = new HttpMethod(context.Request.Method);
            using(var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
            {
                context.Response.StatusCode = (int)responseMessage.StatusCode;
                foreach(var header in responseMessage.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                foreach(var header in responseMessage.Content.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
                context.Response.Headers.Remove("transfer-encoding");
                await responseMessage.Content.CopyToAsync(context.Response.Body);
            }
    }
}

Copy in Proxy code from ProxyMiddleware.cs,

from ASP.NET Core Proxy package [1].

[1] https://raw.githubusercontent.com/aspnet/Proxy/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs


// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace IdentityServer.IntegrationTests.Clients
{
    public class DiscoveryClientTests
    {
        const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";

        private readonly HttpClient _client;
        private readonly HttpMessageHandler _handler;

        public DiscoveryClientTests()
        {
            var builder = new WebHostBuilder()
                .UseStartup<Startup>();
            var server = new TestServer(builder);

            _handler = server.CreateHandler();
            _client = server.CreateClient();
        }

        [Fact]
        public async Task Retrieving_discovery_document_should_succeed()
        {
            var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
            var doc = await client.GetAsync();
        }
    }
}

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using FluentAssertions;
using IdentityModel.Client;
using IdentityServer4.IntegrationTests.Clients;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace IdentityServer.IntegrationTests.Clients
{
    public class DiscoveryClientTests
    {
        const string DiscoveryEndpoint = "https://server/.well-known/openid-configuration";

        private readonly HttpClient _client;
        private readonly HttpMessageHandler _handler;

        public DiscoveryClientTests()
        {
            var builder = new WebHostBuilder()
                .UseStartup<Startup>();
            var server = new TestServer(builder);

            _handler = server.CreateHandler();
            _client = server.CreateClient();
        }

        [Fact]
        public async Task Retrieving_discovery_document_should_succeed()
        {
            var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
            var doc = await client.GetAsync();
        }

        [Fact]
        public async Task Discovery_document_should_have_expected_values()
        {
            var client = new DiscoveryClient(DiscoveryEndpoint, _handler);
            var doc = await client.GetAsync();

            // endpoints
            doc.TokenEndpoint.Should().Be("https://server/connect/token");
            doc.AuthorizationEndpoint.Should().Be("https://server/connect/authorize");
            doc.IntrospectionEndpoint.Should().Be("https://server/connect/introspect");
            doc.EndSessionEndpoint.Should().Be("https://server/connect/endsession");

            // jwk
            doc.Keys.Keys.Count.Should().Be(1);
            doc.Keys.Keys.First().E.Should().NotBeNull();
            doc.Keys.Keys.First().N.Should().NotBeNull();
        }
    }
}

Add one more discovery test

Add one more discovery test


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

namespace Sync.IRC.MessageFilter.Filters
{
    class DefaultFormat : FilterBase, IDanmaku, IOsu
    {
        public override void onMsg(ref MessageBase msg)
        {
            msg.user.setPerfix("<");
            msg.user.setSuffix(">");
        }
    }
}

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

namespace Sync.IRC.MessageFilter.Filters
{
    class DefaultFormat : FilterBase, IDanmaku, IOsu
    {
        public override void onMsg(ref MessageBase msg)
        {
            msg.user.setPerfix("<");
            msg.user.setSuffix(">: ");
        }
    }
}

Add ":" to default suffix

Add ":" to default suffix


using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;

namespace CompetitionPlatform.Data.AzureRepositories.Project
{
    public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
    {
        public static string GeneratePartitionKey()
        {
            return "ProjectFileInfo";
        }

        public static string GenerateRowKey(string projectId)
        {
            return projectId;
        }

        public string ProjectId => RowKey;
        public string FileName { get; set; }
        public string ContentType { get; set; }

        public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
        {
            var result = new ProjectFileInfoEntity
            {
                PartitionKey = GeneratePartitionKey(),
                RowKey = GenerateRowKey(src.ProjectId),
                FileName = src.FileName,
                ContentType = src.ContentType
            };

            return result;
        }
    }

    public class ProjectFileInfoRepository : IProjectFileInfoRepository
    {
        private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;

        public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
        {
            _projectFileInfoTableStorage = projectFileInfoTableStorage;
        }

        public async Task<IProjectFileInfoData> GetAsync(string projectId)
        {
            var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
            var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);

            return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
        }

        public async Task SaveAsync(IProjectFileInfoData fileInfoData)
        {
            var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
            await _projectFileInfoTableStorage.InsertAsync(newEntity);
        }
    }
}

using System.Threading.Tasks;
using AzureStorage.Tables;
using Microsoft.WindowsAzure.Storage.Table;

namespace CompetitionPlatform.Data.AzureRepositories.Project
{
    public class ProjectFileInfoEntity : TableEntity, IProjectFileInfoData
    {
        public static string GeneratePartitionKey()
        {
            return "ProjectFileInfo";
        }

        public static string GenerateRowKey(string projectId)
        {
            return projectId;
        }

        public string ProjectId => RowKey;
        public string FileName { get; set; }
        public string ContentType { get; set; }

        public static ProjectFileInfoEntity Create(IProjectFileInfoData src)
        {
            var result = new ProjectFileInfoEntity
            {
                PartitionKey = GeneratePartitionKey(),
                RowKey = GenerateRowKey(src.ProjectId),
                FileName = src.FileName,
                ContentType = src.ContentType
            };

            return result;
        }
    }

    public class ProjectFileInfoRepository : IProjectFileInfoRepository
    {
        private readonly IAzureTableStorage<ProjectFileInfoEntity> _projectFileInfoTableStorage;

        public ProjectFileInfoRepository(IAzureTableStorage<ProjectFileInfoEntity> projectFileInfoTableStorage)
        {
            _projectFileInfoTableStorage = projectFileInfoTableStorage;
        }

        public async Task<IProjectFileInfoData> GetAsync(string projectId)
        {
            var partitionKey = ProjectFileInfoEntity.GeneratePartitionKey();
            var rowKey = ProjectFileInfoEntity.GenerateRowKey(projectId);

            return await _projectFileInfoTableStorage.GetDataAsync(partitionKey, rowKey);
        }

        public async Task SaveAsync(IProjectFileInfoData fileInfoData)
        {
            var newEntity = ProjectFileInfoEntity.Create(fileInfoData);
            await _projectFileInfoTableStorage.InsertOrReplaceAsync(newEntity);
        }
    }
}

Change File Info repository save method, file info can now be updated.


using NUnit.Framework;

namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
    public class MyDatabaseSettings : IMyDatabaseSettings
    {
        public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\Tests.db;Version=3;New=True;BinaryGUID=False;";
    }
}

using NUnit.Framework;

namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
    public class MyDatabaseSettings : IMyDatabaseSettings
    {
        public string ConnectionString { get; } = $@"Data Source={TestContext.CurrentContext.TestDirectory}\IoCTests.db;Version=3;New=True;BinaryGUID=False;";
    }
}

Change name of daabase for IoC

Change name of daabase for IoC


using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;

namespace Injector
{
    public class InstructionRemover
    {
        public InstructionRemover(ModuleDefinition targetModule)
        {
            _targetModule = targetModule;
        }

        ModuleDefinition _targetModule;

        public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
        {
            var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
            var methodBody = method.Body;

            ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
        }

        public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
        {
            methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
        }

        public void ClearAllButLast(string typeName, string methodName)
        {
            var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
            var methodBody = method.Body;

            var methodILProcessor = methodBody.GetILProcessor();

            for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
            {
                methodILProcessor.Remove(methodBody.Instructions.First());
            }
        }
    }
}

using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Linq;

namespace Injector
{
    public class InstructionRemover
    {
        public InstructionRemover(ModuleDefinition targetModule)
        {
            _targetModule = targetModule;
        }

        ModuleDefinition _targetModule;

        public void ReplaceByNopAt(string typeName, string methodName, int instructionIndex)
        {
            var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
            var methodBody = method.Body;

            ReplaceByNop(methodBody, methodBody.Instructions[instructionIndex]);
        }

        public void ReplaceByNop(MethodBody methodBody, Instruction instruction)
        {
            methodBody.GetILProcessor().Replace(instruction, Instruction.Create(OpCodes.Nop));
        }

        public void ClearAllButLast(string typeName, string methodName)
        {
            var method = CecilHelper.GetMethodDefinition(_targetModule, typeName, methodName);
            var methodBody = method.Body;

            ClearAllButLast(methodBody);
        }

        public void ClearAllButLast(MethodBody methodBody)
        {
            var methodILProcessor = methodBody.GetILProcessor();

            for (int i = methodBody.Instructions.Count - 1; i > 0; i--)
            {
                methodILProcessor.Remove(methodBody.Instructions.First());
            }
        }
    }
}

Add useful overload for instruction remover


using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;

namespace Daves.DeepDataDuplicator.IntegrationTests
{
    [TestClass]
    public class SqlDatabaseSetup
    {
        public static readonly string ConnectionString;

        static SqlDatabaseSetup()
        {
            using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
            {
                ConnectionString = executionContext.Connection.ConnectionString;
            }
        }

        [AssemblyInitialize]
        public static void InitializeAssembly(TestContext testContext)
        {
            SqlDatabaseTestClass.TestService.DeployDatabaseProject();

            using (var transaction = new TransactionScope())
            {
                using (var connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    using (IDbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = DeepCopyGenerator.GenerateProcedure(
                            connection: connection,
                            rootTableName: "Nations");
                        command.ExecuteNonQuery();
                    }
                }

                transaction.Complete();
            }
        }
    }
}

using Microsoft.Data.Tools.Schema.Sql.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;

namespace Daves.DeepDataDuplicator.IntegrationTests
{
    [TestClass]
    public class SqlDatabaseSetup
    {
        [AssemblyInitialize]
        public static void InitializeAssembly(TestContext testContext)
        {
            SqlDatabaseTestClass.TestService.DeployDatabaseProject();

            string connectionString;
            using (var executionContext = SqlDatabaseTestClass.TestService.OpenExecutionContext())
            {
                connectionString = executionContext.Connection.ConnectionString;
            }

            using (var transaction = new TransactionScope())
            {
                using (var connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    using (IDbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = DeepCopyGenerator.GenerateProcedure(
                            connection: connection,
                            rootTableName: "Nations");
                        command.ExecuteNonQuery();
                    }
                }

                transaction.Complete();
            }
        }
    }
}

Fix connection bug for fresh environments


using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
    class InsertIncludeFieldWithoutDocumentBuilder
    {
        public static void Run()
        {
            // ExStart:InsertIncludeFieldWithoutDocumentBuilder
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithFields();
            Document doc = new Document(dataDir + "in.doc");
            // Get paragraph you want to append this INCLUDETEXT field to
            Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];

            // We want to insert an INCLUDETEXT field like this:
            // { INCLUDETEXT  "file path" }

            // Create instance of FieldAsk class and lets build the above field code
            FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
            fieldinclude.BookmarkName = "bookmark";
            fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";

            doc.FirstSection.Body.AppendChild(para);

            // Finally update this TOA field
            fieldinclude.Update();

            dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
            doc.Save(dataDir);

            // ExEnd:InsertIncludeFieldWithoutDocumentBuilder
            Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
        }
    }
}

using Aspose.Words.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aspose.Words.Examples.CSharp.Programming_Documents.Working_with_Fields
{
    class InsertIncludeFieldWithoutDocumentBuilder
    {
        public static void Run()
        {
            // ExStart:InsertIncludeFieldWithoutDocumentBuilder
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_WorkingWithFields();
            Document doc = new Document(dataDir + "in.doc");
            // Get paragraph you want to append this INCLUDETEXT field to
            Paragraph para = (Paragraph)doc.GetChildNodes(NodeType.Paragraph, true)[1];

            // We want to insert an INCLUDETEXT field like this:
            // { INCLUDETEXT  "file path" }

            // Create instance of FieldAsk class and lets build the above field code
            FieldInclude fieldinclude = (FieldInclude)para.AppendField(FieldType.FieldInclude, false);
            fieldinclude.BookmarkName = "bookmark";
            fieldinclude.SourceFullName = dataDir + @"IncludeText.docx";

            doc.FirstSection.Body.AppendChild(para);

            // Finally update this Include field
            fieldinclude.Update();

            dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc";
            doc.Save(dataDir);

            // ExEnd:InsertIncludeFieldWithoutDocumentBuilder
            Console.WriteLine("\nInclude field without using document builder inserted successfully.\nFile saved at " + dataDir);
        }
    }
}

Update "Insert Include Field" example

Update "Insert Include Field" example


using System;

namespace Espera.Network
{
    public class NetworkSong
    {
        public string Album { get; set; }

        public string Artist { get; set; }

        public TimeSpan Duration { get; set; }

        public string Genre { get; set; }

        public Guid Guid { get; set; }

        public NetworkSongSource Source { get; set; }

        public string Title { get; set; }
    }
}

using System;

namespace Espera.Network
{
    public class NetworkSong
    {
        public string Album { get; set; }

        public string Artist { get; set; }

        public TimeSpan Duration { get; set; }

        public string Genre { get; set; }

        public Guid Guid { get; set; }

        public NetworkSongSource Source { get; set; }

        public string Title { get; set; }

        public int TrackNumber { get; set; }
    }
}

Add the track number to the song

Add the track number to the song


namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
    using Base.Get;
    using Enums;
    using Objects.Basic;
    using Objects.Get.Shows.Common;
    using System.Collections.Generic;

    internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
    {
        internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }

        internal TraktPeriod? Period { get; set; }

        protected override IDictionary<string, object> GetUriPathParameters()
        {
            var uriParams = base.GetUriPathParameters();

            if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
                uriParams.Add("period", Period.Value.AsString());

            return uriParams;
        }

        protected override string UriTemplate => "shows/played{/period}{?extended,page,limit}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
    using Base;
    using Base.Get;
    using Enums;
    using Objects.Basic;
    using Objects.Get.Shows.Common;
    using System.Collections.Generic;

    internal class TraktShowsMostPlayedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostPlayedShow>, TraktMostPlayedShow>
    {
        internal TraktShowsMostPlayedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; }

        internal TraktPeriod? Period { get; set; }

        protected override IDictionary<string, object> GetUriPathParameters()
        {
            var uriParams = base.GetUriPathParameters();

            if (Period.HasValue && Period.Value != TraktPeriod.Unspecified)
                uriParams.Add("period", Period.Value.AsString());

            return uriParams;
        }

        protected override string UriTemplate => "shows/played{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";

        protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;

        internal TraktShowFilter Filter { get; set; }

        protected override bool SupportsPagination => true;

        protected override bool IsListResult => true;
    }
}

Add filter property to most played shows request.


using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;

namespace Orchard.DynamicForms.Elements {
    public class Fieldset : Container {
        public override string Category {
            get { return "Forms"; }
        }

        public string Legend {
            get { return this.Retrieve(f => f.Legend); }
            set { this.Store(f => f.Legend, value); }
        }

        public Form Form {
            get {
                var parent = Container;

                while (parent != null) {
                    var form = parent as Form;

                    if (form != null)
                        return form;

                    parent = parent.Container;
                }

                return null;
            }
        }
    }
}

using Orchard.Layouts.Helpers;
using Orchard.Layouts.Elements;

namespace Orchard.DynamicForms.Elements {
    public class Fieldset : Container {
        public override string Category {
            get { return "Forms"; }
        }

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

        public string Legend {
            get { return this.Retrieve(f => f.Legend); }
            set { this.Store(f => f.Legend, value); }
        }

        public Form Form {
            get {
                var parent = Container;

                while (parent != null) {
                    var form = parent as Form;

                    if (form != null)
                        return form;

                    parent = parent.Container;
                }

                return null;
            }
        }
    }
}

Remove editor completely when adding a fieldset to the layout editor.


using System;
using System.IO;
using System.Management.Automation;

namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
    internal static class CommandUtilities
    {
        private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";

        public const string MODULE_PREFIX = "PSCompatibility";

        public static void WriteExceptionAsError(
            this Cmdlet cmdlet,
            Exception exception,
            string errorId = COMPATIBILITY_ERROR_ID,
            ErrorCategory errorCategory = ErrorCategory.ReadError,
            object targetObject = null)
        {
            cmdlet.WriteError(CreateCompatibilityErrorRecord(exception, errorId, errorCategory, targetObject));
        }

        public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
        {
            if (Path.IsPathRooted(path))
            {
                return path;
            }

            return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
        }

        private static ErrorRecord CreateCompatibilityErrorRecord(
            Exception e,
            string errorId = COMPATIBILITY_ERROR_ID,
            ErrorCategory errorCategory = ErrorCategory.ReadError,
            object targetObject = null)
        {
            return new ErrorRecord(
                e,
                errorId,
                errorCategory,
                targetObject);
        }
    }
}

using System;
using System.IO;
using System.Management.Automation;

namespace Microsoft.PowerShell.CrossCompatibility.Commands
{
    internal static class CommandUtilities
    {
        private const string COMPATIBILITY_ERROR_ID = "CompatibilityAnalysisError";

        public const string MODULE_PREFIX = "PSCompatibility";

        public static void WriteExceptionAsWarning(
            this Cmdlet cmdlet,
            Exception exception,
            string errorId = COMPATIBILITY_ERROR_ID,
            ErrorCategory errorCategory = ErrorCategory.ReadError,
            object targetObject = null)
        {
            cmdlet.WriteWarning(exception.ToString());
        }

        public static string GetNormalizedAbsolutePath(this PSCmdlet cmdlet, string path)
        {
            if (Path.IsPathRooted(path))
            {
                return path;
            }

            return cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
        }

        private static ErrorRecord CreateCompatibilityErrorRecord(
            Exception e,
            string errorId = COMPATIBILITY_ERROR_ID,
            ErrorCategory errorCategory = ErrorCategory.ReadError,
            object targetObject = null)
        {
            return new ErrorRecord(
                e,
                errorId,
                errorCategory,
                targetObject);
        }
    }
}

Convert scrap errors to warnings

Convert scrap errors to warnings


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Windows.UI.Xaml;

namespace Microsoft.Xaml.Interactivity
{
    /// <summary>
    /// A base class for behaviors, implementing the basic plumbing of IBehavior
    /// </summary>
    public abstract class Behavior : DependencyObject, IBehavior
    {
        public DependencyObject AssociatedObject { get; private set; }

        public void Attach(DependencyObject associatedObject)
        {
            AssociatedObject = associatedObject;
            OnAttached();
        }

        public void Detach()
        {
            OnDetaching();
        }

        protected virtual void OnAttached()
        {
        }

        protected virtual void OnDetaching()
        {
        }
    }
}

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using Windows.UI.Xaml;

namespace Microsoft.Xaml.Interactivity
{
    /// <summary>
    /// A base class for behaviors, implementing the basic plumbing of IBehavior
    /// </summary>
    public abstract class Behavior : DependencyObject, IBehavior
    {
        public DependencyObject AssociatedObject { get; private set; }

        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject == null) throw new ArgumentNullException(nameof(associatedObject));

            AssociatedObject = associatedObject;
            OnAttached();
        }

        public void Detach()
        {
            OnDetaching();
        }

        protected virtual void OnAttached()
        {
        }

        protected virtual void OnDetaching()
        {
        }
    }
}

Check associated object parameter for null. Throw ArgumentNullException if it is null


using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace VCSJones.FiddlerCert
{
    public class SettingsModel : INotifyPropertyChanged
    {
        private bool _checkForUpdates;
        private RelayCommand _saveCommand, _cancelCommand;

        public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;

        public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;

        public bool CheckForUpdates
        {
            get
            {
                return _checkForUpdates;
            }
            set
            {
                _checkForUpdates = value;
                OnPropertyChanged();
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                return _saveCommand;
            }
            set
            {
                _saveCommand = value;
                OnPropertyChanged();
            }
        }

        public RelayCommand CancelCommand
        {
            get
            {
                return _cancelCommand;
            }
            set
            {
                _cancelCommand = value;
                OnPropertyChanged();
            }
        }

        public SettingsModel()
        {
            SaveCommand = new RelayCommand(_ =>
            {
                FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
                CloseRequest?.Invoke();
            });
            CancelCommand = new RelayCommand(_ =>
            {
                CloseRequest?.Invoke();
            });
            CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public event Action CloseRequest;

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

using Fiddler;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace VCSJones.FiddlerCert
{
    public class SettingsModel : INotifyPropertyChanged
    {
        private bool _checkForUpdates;
        private RelayCommand _saveCommand, _cancelCommand;

        public Version LatestVersion => CertificateInspector.LatestVersion?.Item1;

        public Version CurrentVersion => typeof(CertInspector).Assembly.GetName().Version;

        public bool CheckForUpdates
        {
            get
            {
                return _checkForUpdates;
            }
            set
            {
                _checkForUpdates = value;
                OnPropertyChanged();
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                return _saveCommand;
            }
            set
            {
                _saveCommand = value;
                OnPropertyChanged();
            }
        }

        public RelayCommand CancelCommand
        {
            get
            {
                return _cancelCommand;
            }
            set
            {
                _cancelCommand = value;
                OnPropertyChanged();
            }
        }

        public SettingsModel()
        {
            SaveCommand = new RelayCommand(_ =>
            {
                FiddlerApplication.Prefs.SetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, CheckForUpdates);
                CloseRequest?.Invoke();
            });
            CancelCommand = new RelayCommand(_ =>
            {
                CloseRequest?.Invoke();
            });
            CheckForUpdates = FiddlerApplication.Prefs.GetBoolPref(UpdateServices.CHECK_FOR_UPDATED_PREF, false);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public event Action CloseRequest;

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

Fix default value in settings window.

Fix default value in settings window.


using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;

class SubscriptionWriter
{
    public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
    {
        var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
        File.Delete(createPath);
        using (var writer = File.CreateText(createPath))
        {
            SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
        }
        var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
        File.Delete(dropPath);
        using (var writer = File.CreateText(dropPath))
        {
            SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
        }
    }
}

using System.IO;
using NServiceBus.Persistence.Sql.ScriptBuilder;

class SubscriptionWriter
{
    public static void WriteSubscriptionScript(string scriptPath, BuildSqlDialect sqlDialect)
    {
        var createPath = Path.Combine(scriptPath, "Subscription_Create.sql");
        File.Delete(createPath);
        using (var writer = File.CreateText(createPath))
        {
            SubscriptionScriptBuilder.BuildCreateScript(writer, sqlDialect);
        }
        var dropPath = Path.Combine(scriptPath, "Subscription_Drop.sql");
        File.Delete(dropPath);
        using (var writer = File.CreateText(dropPath))
        {
            SubscriptionScriptBuilder.BuildDropScript(writer, sqlDialect);
        }
    }
}

Fix the subscription drop script

Fix the subscription drop script


using Mono.Addins;
using Mono.Addins.Description;

[assembly: Addin(
    Id = "jzeferino.XSAddin",
    Namespace = "jzeferino.XSAddin",
    Version = "0.0.1"
)]

[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
                            "When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
                            "It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
                            "It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]

using Mono.Addins;
using Mono.Addins.Description;

[assembly: Addin(
    Id = "jzeferino.XSAddin",
    Namespace = "jzeferino.XSAddin",
    Version = "0.1"
)]

[assembly: AddinName("jzeferino.XSAddin")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("This add-in let you create a Xamarin Cross Platform solution (Xamarin.Native) or (Xamarin.Forms)." +
                            "When creating the project the addin will show you a custom wizard wich the user can select the application name, the application identifier and if he wants, .gitignore, readme and cake." +
                            "It already creates some PCL projects to allow the shared code to be separated in different layers using MVVM pattern." +
                            "It also allows you to create some file templates.")]
[assembly: AddinAuthor("jzeferino")]
[assembly: AddinUrl("https://github.com/jzeferino/jzeferino.XSAddin")]

Make addin version assembly to 0.1.

Make addin version assembly to 0.1.


using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;

namespace JSIL.Proxies {
    [JSProxy(
        new[] {
            "System.Collections.ArrayList",
            "System.Collections.Hashtable",
            "System.Collections.Generic.List`1",
            "System.Collections.Generic.Dictionary`2",
            "System.Collections.Generic.Stack`1",
            "System.Collections.Generic.Queue`1",
            "System.Collections.Generic.HashSet`1",
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: false
    )]
    public abstract class CollectionProxy<T> : IEnumerable {
        [JSIsPure]
        [JSResultIsNew]
        System.Collections.IEnumerator IEnumerable.GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSIsPure]
        [JSResultIsNew]
        public AnyType GetEnumerator () {
            throw new InvalidOperationException();
        }
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using JSIL.Meta;
using JSIL.Proxy;

namespace JSIL.Proxies {
    [JSProxy(
        new[] {
            "System.Collections.ArrayList",
            "System.Collections.Hashtable",
            "System.Collections.Generic.List`1",
            "System.Collections.Generic.Dictionary`2",
            "System.Collections.Generic.Stack`1",
            "System.Collections.Generic.Queue`1",
            "System.Collections.Generic.HashSet`1",
            "System.Collections.Hashtable/KeyCollection",
            "System.Collections.Hashtable/ValueCollection",
            "System.Collections.Generic.Dictionary`2/KeyCollection",
            "System.Collections.Generic.Dictionary`2/ValueCollection"
        },
        memberPolicy: JSProxyMemberPolicy.ReplaceNone,
        inheritable: false
    )]
    public abstract class CollectionProxy<T> : IEnumerable {
        [JSIsPure]
        [JSResultIsNew]
        System.Collections.IEnumerator IEnumerable.GetEnumerator () {
            throw new InvalidOperationException();
        }

        [JSIsPure]
        [JSResultIsNew]
        public AnyType GetEnumerator () {
            throw new InvalidOperationException();
        }
    }
}

Fix MemberwiseClone calls being generated for .GetEnumerator() on dictionary keys/values collections.


using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;

namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
	[TestFixture]
	public class ArtistTagsTests
	{
		[Test]
		public void Can_hit_endpoint()
		{
			ArtistTags tags = Api<ArtistTags>.Create
									.WithParameter("artistId", "1")
									.Please();

			Assert.That(tags, Is.Not.Null);
			Assert.That(tags.TagList.Count, Is.GreaterThan(0));
			Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
			Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
		}

		[Test]
		public void Can_hit_endpoint_with_paging()
		{
			ArtistTags artistBrowse = Api<ArtistTags>.Create
				.WithParameter("artistId", "1")
				.WithParameter("page", "2")
				.WithParameter("pageSize", "1")
				.Please();

			Assert.That(artistBrowse, Is.Not.Null);
			Assert.That(artistBrowse.Page, Is.EqualTo(2));
			Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
		}
	}
}

using System.Linq;
using NUnit.Framework;
using SevenDigital.Api.Schema.Tags;

namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.TagsEndpoint
{
	[TestFixture]
	public class ArtistTagsTests
	{
		[Test]
		public void Can_hit_endpoint()
		{
			ArtistTags tags = Api<ArtistTags>.Create
									.WithParameter("artistId", "1")
									.Please();

			Assert.That(tags, Is.Not.Null);
			Assert.That(tags.TagList.Count, Is.GreaterThan(0));
			Assert.That(tags.TagList.FirstOrDefault().Id, Is.Not.Empty);
			Assert.That(tags.TagList.Where(x => x.Id == "rock").FirstOrDefault().Text, Is.EqualTo("rock"));
		}

		[Test]
		public void Can_hit_endpoint_with_paging()
		{
			ArtistTags artistBrowse = Api<ArtistTags>.Create
				.WithParameter("artistId", "2")
				.WithParameter("page", "2")
				.WithParameter("pageSize", "1")
				.Please();

			Assert.That(artistBrowse, Is.Not.Null);
			Assert.That(artistBrowse.Page, Is.EqualTo(2));
			Assert.That(artistBrowse.PageSize, Is.EqualTo(1));
		}
	}
}

Change artist in tags test

Change artist in tags test

- After migrating to solr kkeane no longer has multiple tags.:wqa


using Photosphere.Mapping.Static;

namespace Photosphere.Mapping.Extensions
{
    public static class MappingObjectExtensions
    {
        ///  Map from source to existent object target
        public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
            where TTarget : class, new()
        {
            StaticMapper<TSource, TTarget>.Map(source, target);
        }

        ///  Map from source to new object of TTarget
        public static TTarget Map<TSource, TTarget>(this TSource source)
            where TTarget : class, new()
        {
            return StaticMapper<TSource, TTarget>.Map(source);
        }

        ///  Map from object source to existent object target
        public static void MapToObject(this object source, object target)
        {
            StaticMapper.Map(source, target);
        }

        ///  Map from object source to new object of TTarget
        public static TTarget MapObject<TTarget>(this object source)
            where TTarget : new()
        {
            return StaticMapper.Map<TTarget>(source);
        }
    }
}

using Photosphere.Mapping.Static;

namespace Photosphere.Mapping.Extensions
{
    public static class MappingObjectExtensions
    {
        ///  Map from source to existent object target
        public static void MapTo<TSource, TTarget>(this TSource source, TTarget target)
            where TTarget : class, new()
        {
            StaticMapper<TSource, TTarget>.Map(source, target);
        }

        ///  Map from object source to existent object target
        public static void MapToObject(this object source, object target)
        {
            StaticMapper.Map(source, target);
        }

        ///  Map from source to new object of TTarget
        public static TTarget Map<TSource, TTarget>(this TSource source)
            where TTarget : class, new()
        {
            return StaticMapper<TSource, TTarget>.Map(source);
        }

        ///  Map from object source to new object of TTarget
        public static TTarget MapObject<TTarget>(this object source)
            where TTarget : new()
        {
            return StaticMapper.Map<TTarget>(source);
        }
    }
}

Make beauty to extensions API

Make beauty to extensions API


using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;

namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
    public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
    {
        public ApprenticeshipViewModelValidator()
        {
            RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("'ULN' is not in the correct format.");
            RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Cost is not in the correct format");
        }
    }
}

using FluentValidation;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;

namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
    public sealed class ApprenticeshipViewModelValidator : AbstractValidator<ApprenticeshipViewModel>
    {
        public ApprenticeshipViewModelValidator()
        {
            RuleFor(x => x.ULN).Matches("^$|^[1-9]{1}[0-9]{9}$").WithMessage("Please enter the unique learner number - this should be 10 digits long.");
            RuleFor(x => x.Cost).Matches("^$|^[1-9]{1}[0-9]*$").WithMessage("Please enter the cost in whole pounds. For example, for £1500 you should enter 1500.");
        }
    }
}

Update the validation messages for uln and cost


using System;

namespace Toggl.Phoebe
{
    public static class Build
    {
#warning Please fill in build settings and make git assume this file is unchanged.
        #region Phoebe build config

        public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
        public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
        public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
        public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
        public static readonly string GoogleAnalyticsId = "";
        public static readonly int GoogleAnalyticsPlanIndex = 1;
        public static readonly int GoogleAnalyticsExperimentIndex = 2;

        #endregion

        #region Joey build configuration

        #if __ANDROID__
        public static readonly string AppIdentifier = "TogglJoey";
        public static readonly string GcmSenderId = "";
        public static readonly string BugsnagApiKey = "";
        public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
        #endif
        #endregion

        #region Ross build configuration

        #if __IOS__
        public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
        public static readonly string AppIdentifier = "TogglRoss";
        public static readonly string BugsnagApiKey = "";
        public static readonly string GoogleOAuthClientId = "";
        #endif
        #endregion
    }
}

using System;

namespace Toggl.Phoebe
{
    public static class Build
    {
#warning Please fill in build settings and make git assume this file is unchanged.
        #region Phoebe build config

        public static readonly Uri ApiUrl = new Uri ("https://toggl.com/api/");
        public static readonly Uri ReportsApiUrl = new Uri ("https://toggl.com/reports/api/");
        public static readonly Uri PrivacyPolicyUrl = new Uri ("https://toggl.com/privacy");
        public static readonly Uri TermsOfServiceUrl = new Uri ("https://toggl.com/terms");
        public static readonly string GoogleAnalyticsId = "";
        public static readonly int GoogleAnalyticsPlanIndex = 1;
        public static readonly int GoogleAnalyticsExperimentIndex = 2;

        #endregion

        #region Joey build configuration

        #if __ANDROID__
        public static readonly string AppIdentifier = "TogglJoey";
        public static readonly string GcmSenderId = "";
        public static readonly string BugsnagApiKey = "";
        public static readonly string XamInsightsApiKey = "";
        public static readonly string GooglePlayUrl = "https://play.google.com/store/apps/details?id=com.toggl.timer";
        #endif
        #endregion

        #region Ross build configuration

        #if __IOS__
        public static readonly string AppStoreUrl = "itms-apps://itunes.com/apps/toggl/toggltimer";
        public static readonly string AppIdentifier = "TogglRoss";
        public static readonly string BugsnagApiKey = "";
        public static readonly string GoogleOAuthClientId = "";
        #endif
        #endregion
    }
}

Add InsightsApiKey to conf file.

Add InsightsApiKey to conf file.


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

namespace GRA.Data.Model
{
    public class AvatarLayer : Abstract.BaseDbEntity
    {
        [Required]
        public int SiteId { get; set; }

        [Required]
        [MaxLength(255)]
        public string Name { get; set; }
        [Required]
        public int Position { get; set; }
        public bool CanBeEmpty { get; set; }
        public int GroupId { get; set; }
        public int SortOrder { get; set; }
        public bool DefaultLayer { get; set; }
        public bool ShowItemSelector { get; set; }
        public bool ShowColorSelector { get; set; }

        [MaxLength(255)]
        public string Icon { get; set; }

        public decimal ZoomScale { get; set; }
        public int ZoomYOffset { get; set; }

        public ICollection<AvatarColor> AvatarColors { get; set; }
        public ICollection<AvatarItem> AvatarItems { get; set; }
    }
}

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

namespace GRA.Data.Model
{
    public class AvatarLayer : Abstract.BaseDbEntity
    {
        [Required]
        public int SiteId { get; set; }

        [Required]
        [MaxLength(255)]
        public string Name { get; set; }
        [Required]
        public int Position { get; set; }
        public bool CanBeEmpty { get; set; }
        public int GroupId { get; set; }
        public int SortOrder { get; set; }
        public bool DefaultLayer { get; set; }
        public bool ShowItemSelector { get; set; }
        public bool ShowColorSelector { get; set; }

        [MaxLength(255)]
        public string Icon { get; set; }
        [Column(TypeName = "decimal(4,2)")]
        public decimal ZoomScale { get; set; }
        public int ZoomYOffset { get; set; }

        public ICollection<AvatarColor> AvatarColors { get; set; }
        public ICollection<AvatarItem> AvatarItems { get; set; }
    }
}

Add precision and scale to avatar zoom scale


using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;

namespace AwsTools.UnitTests.SqsNotificationListener
{
    public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
    {
        private int _sqsCallCounter;

        protected override void Given()
        {
            TestWaitTime = 50;
            base.Given();
            Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
                .Returns(x => { throw new Exception(); })
                .AndDoes(x => { _sqsCallCounter++; });
        }

        [Then]
        public void QueueIsPolledMoreThanOnce()
        {
            Assert.Greater(_sqsCallCounter, 1);
        }
    }
}

using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;

namespace AwsTools.UnitTests.SqsNotificationListener
{
    public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
    {
        private int _sqsCallCounter;

        protected override void Given()
        {
            TestWaitTime = 1000;
            base.Given();
            Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
                .Returns(x => { throw new Exception(); })
                .AndDoes(x => { _sqsCallCounter++; });
        }

        [Then]
        public void QueueIsPolledMoreThanOnce()
        {
            Assert.Greater(_sqsCallCounter, 1);
        }
    }
}

Test requires longer to run on slower aws build agents


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

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;

namespace osu.Game.Overlays.Profile.Sections.Historical
{
    public class UserHistoryGraph : UserGraph<DateTime, long>
    {
        private readonly LocalisableString tooltipCounterName;

        [CanBeNull]
        public UserHistoryCount[] Values
        {
            set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
        }

        public UserHistoryGraph(LocalisableString tooltipCounterName)
        {
            this.tooltipCounterName = tooltipCounterName;
        }

        protected override float GetDataPointHeight(long playCount) => playCount;

        protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount)
        {
            return new UserGraphTooltipContent(
                tooltipCounterName,
                playCount.ToLocalisableString("N0"),
                date.ToLocalisableString("MMMM yyyy"));
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;

namespace osu.Game.Overlays.Profile.Sections.Historical
{
    public class UserHistoryGraph : UserGraph<DateTime, long>
    {
        private readonly LocalisableString tooltipCounterName;

        [CanBeNull]
        public UserHistoryCount[] Values
        {
            set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
        }

        public UserHistoryGraph(LocalisableString tooltipCounterName)
        {
            this.tooltipCounterName = tooltipCounterName;
        }

        protected override float GetDataPointHeight(long playCount) => playCount;

        protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount) =>
            new UserGraphTooltipContent(
                tooltipCounterName,
                playCount.ToLocalisableString("N0"),
                date.ToLocalisableString("MMMM yyyy"));
    }
}

Use lambda spec for method

Use lambda spec for method


using Microsoft.AspNetCore.Mvc;

namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
    public class GetApprenticeshipRequest
    {
        [FromQuery]
        public long? AccountId { get; set; }
        [FromQuery]
        public long? ProviderId { get; set; }
        [FromQuery]
        public int PageNumber { get; set; }
        [FromQuery]
        public int PageItemCount { get; set; }
        [FromQuery]
        public string SortField { get; set; }
        [FromQuery]
        public bool ReverseSort { get; set; }

    }
}

namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
    public class GetApprenticeshipRequest
    {
        public long? AccountId { get; set; }
        public long? ProviderId { get; set; }
        public int PageNumber { get; set; }
        public int PageItemCount { get; set; }
        public string SortField { get; set; }

        public bool ReverseSort { get; set; }

    }
}

Remove dot net core dependency

Remove dot net core dependency


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
    private RectTransform rectTransform;
    private Vector2 prevRectSize = default;

    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    private void Update()
    {
        var size = rectTransform.rect.size;

        if (prevRectSize != size)
        {
            prevRectSize = size;

            this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
        }
    }
}

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Utilities
{
    /// <summary>
    /// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
    /// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
    /// The Z component is scaled to the min of the X and Y components.
    /// </summary>
    [ExecuteInEditMode]
    [RequireComponent(typeof(RectTransform))]
    public class RectTransformCubeScaler : MonoBehaviour
    {
        private RectTransform rectTransform;
        private Vector2 prevRectSize = default;

        private void Start()
        {
            rectTransform = GetComponent<RectTransform>();
        }

        private void Update()
        {
            var size = rectTransform.rect.size;

            if (prevRectSize != size)
            {
                prevRectSize = size;

                this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
            }
        }
    }
}

Move REcttransform scaler into mrtk namespace


using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;

namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
  public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
  {
    public Guid CorrelationId { get; }

    internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
      CorrelationId = correlationId;
    }
  }

  public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
  {
    private IArangoDatabase Db { get; }

    public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
      Db = db;
    }

    public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
      UserDocument user = Db.Query<UserDocument>()
        .SingleOrDefault(x => AQL.In(query.CorrelationId, x.ContactChallenges.Select(y => y.CorrelationId)));
      return Task.FromResult(user);
    }
  }
}

using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;

namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
  public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
  {
    public Guid CorrelationId { get; }

    internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
      CorrelationId = correlationId;
    }
  }

  public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
  {
    private IArangoDatabase Db { get; }

    public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
      Db = db;
    }

    public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
      UserDocument user = Db.Query<UserDocument>()
        .SingleOrDefault(x =>
          AQL.In(query.CorrelationId, x.ContactEmailChallenges.Select(y => y.CorrelationId)) ||
          AQL.In(query.CorrelationId, x.ContactSmsChallenges.Select(y => y.CorrelationId)));
      return Task.FromResult(user);
    }
  }
}

Fix bug with query after json ignoring user doc contact challenges.


using Newtonsoft.Json;

namespace SyncTrayzor.Syncthing.ApiClient
{
    [JsonConverter(typeof(DefaultingStringEnumConverter))]
    public enum EventType
    {
        Unknown,

        Starting,
        StartupComplete,
        Ping,
        DeviceDiscovered,
        DeviceConnected,
        DeviceDisconnected,
        RemoteIndexUpdated,
        LocalIndexUpdated,
        ItemStarted,
        ItemFinished,

        // Not quite sure which it's going to be, so play it safe...
        MetadataChanged,
        ItemMetadataChanged,

        StateChanged,
        FolderRejected,
        DeviceRejected,
        ConfigSaved,
        DownloadProgress,
        FolderSummary,
        FolderCompletion,
        FolderErrors,
        FolderScanProgress,
        DevicePaused,
        DeviceResumed,
        LoginAttempt,
        ListenAddressChanged,
        RelayStateChanged,
        ExternalPortMappingChanged,
    }
}

using Newtonsoft.Json;

namespace SyncTrayzor.Syncthing.ApiClient
{
    [JsonConverter(typeof(DefaultingStringEnumConverter))]
    public enum EventType
    {
        Unknown,

        Starting,
        StartupComplete,
        Ping,
        DeviceDiscovered,
        DeviceConnected,
        DeviceDisconnected,
        RemoteIndexUpdated,
        LocalIndexUpdated,
        ItemStarted,
        ItemFinished,

        // Not quite sure which it's going to be, so play it safe...
        MetadataChanged,
        ItemMetadataChanged,

        StateChanged,
        FolderRejected,
        DeviceRejected,
        ConfigSaved,
        DownloadProgress,
        FolderSummary,
        FolderCompletion,
        FolderErrors,
        FolderScanProgress,
        DevicePaused,
        DeviceResumed,
        LoginAttempt,
        ListenAddressChanged,
        RelayStateChanged,
        ExternalPortMappingChanged,
        ListenAddressesChanged,
    }
}

Add a missing event type

Add a missing event type


namespace Gigobyte.Mockaroo.Fields
{
    public partial class JSONArrayField
    {
        public int Min { get; set; } = 1;

        public int Max { get; set; } = 5;

        public override string ToJson()
        {
            return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
        }
    }
}

namespace Gigobyte.Mockaroo.Fields
{
    public partial class JSONArrayField
    {
        public int Min
        {
            get { return _min; }
            set { _min = value.Between(0, 100); }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value.Between(0, 100); }
        }

        public override string ToJson()
        {
            return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
        }

        #region Private Members

        private int _min = 1, _max = 5;

        #endregion Private Members
    }
}

Add limiter to JsonArrayField min and max properties


@model Badges.Models.Shared.ExperienceViewModel

        @foreach (var work in @Model.SupportingWorks)
        {
        	@*
 *@

	                @Html.Partial("_ViewWork", work)

@work.Description

            @*
 *@
        }

Add edit / remove buttons to each file on experience page


//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//

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

namespace AIWolf.Lib
{
#if JHELP
    /// <summary>
    /// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
    /// </summary>
#else
    /// <summary>
    /// Defines extension method to shuffle what implements IEnumerable interface.
    /// </summary>
#endif
    public static class ShuffleExtensions
    {
#if JHELP
        /// <summary>
        /// IEnumerableをシャッフルしたものを返す
        /// </summary>
        /// <typeparam name="T">IEnumerableの要素の型</typeparam>
        /// <param name="s">TのIEnumerable</param>
        /// <returns>シャッフルされたIEnumerable</returns>
#else
        /// <summary>
        /// Returns shuffled IEnumerable of T.
        /// </summary>
        /// <typeparam name="T">Type of element of IEnumerable.</typeparam>
        /// <param name="s">IEnumerable of T.</param>
        /// <returns>Shuffled IEnumerable of T.</returns>
#endif
        public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid());
    }
}

//
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//

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

namespace AIWolf.Lib
{
#if JHELP
    /// <summary>
    /// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
    /// </summary>
#else
    /// <summary>
    /// Defines extension method to shuffle what implements IEnumerable interface.
    /// </summary>
#endif
    public static class ShuffleExtensions
    {
#if JHELP
        /// <summary>
        /// IEnumerableをシャッフルしたIListを返す
        /// </summary>
        /// <typeparam name="T">IEnumerableの要素の型</typeparam>
        /// <param name="s">TのIEnumerable</param>
        /// <returns>シャッフルされたTのIList</returns>
#else
        /// <summary>
        /// Returns shuffled IList of T.
        /// </summary>
        /// <typeparam name="T">Type of element of IEnumerable.</typeparam>
        /// <param name="s">IEnumerable of T.</param>
        /// <returns>Shuffled IList of T.</returns>
#endif
        public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList();
    }
}

Make Shuffle() returns IList to avoid delayed execution.