// Copyright
// ----------------------------------------------------------------------------------------------------------
//  <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable">
//      MIT
//  </copyright>
//  <license>
//      This source code is subject to terms and conditions of The MIT License (MIT).
//      A copy of the license can be found in the License.txt file at the root of this distribution.
//  </license>
//  <summary>
//      Contains the attributes that provide information about the assembly.
//  </summary>
// ----------------------------------------------------------------------------------------------------------

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

[assembly: AssemblyTitle("Dawn.SocketAwaitable")]
[assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")]
[assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")]
[assembly: AssemblyProduct("Dawn Framework")]
[assembly: AssemblyCopyright("MIT")]

[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif

// Copyright
// ----------------------------------------------------------------------------------------------------------
//  <copyright file="AssemblyInfo.cs" company="https://github.com/safakgur/Dawn.SocketAwaitable">
//      MIT
//  </copyright>
//  <license>
//      This source code is subject to terms and conditions of The MIT License (MIT).
//      A copy of the license can be found in the License.txt file at the root of this distribution.
//  </license>
//  <summary>
//      Contains the attributes that provide information about the assembly.
//  </summary>
// ----------------------------------------------------------------------------------------------------------

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

[assembly: AssemblyTitle("Dawn.SocketAwaitable")]
[assembly: AssemblyCompany("https://github.com/safakgur/Dawn.SocketAwaitable")]
[assembly: AssemblyDescription("Provides utilities for asynchronous socket operations.")]
[assembly: AssemblyProduct("Dawn Framework")]
[assembly: AssemblyCopyright("MIT")]

[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]

#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif

Increase assembly version to 1.1.

Increase assembly version to 1.1.


using System;

namespace AsmResolver.DotNet.Memory
{
    [Flags]
    public enum MemoryLayoutAttributes
    {
        Is32Bit = 0b0,
        Is64Bit = 0b1,
        BitnessMask = 0b1,

        IsPlatformDependent = 0b10,
    }
}

using System;

namespace AsmResolver.DotNet.Memory
{
    /// <summary>
    /// Defines members for all possible attributes that can be assigned to a <see cref="TypeMemoryLayout"/> instance.
    /// </summary>
    [Flags]
    public enum MemoryLayoutAttributes
    {
        /// <summary>
        /// Indicates the layout was determined assuming a 32-bit environment.
        /// </summary>
        Is32Bit = 0b0,

        /// <summary>
        /// Indicates the layout was determined assuming a 32-bit environment.
        /// </summary>
        Is64Bit = 0b1,

        /// <summary>
        /// Used to mask out the bitness of the type layout.
        /// </summary>
        BitnessMask = 0b1,

        /// <summary>
        /// Indicates the type layout depends on the bitness of the environment.
        /// </summary>
        IsPlatformDependent = 0b10,
    }
}

Add xmldoc to mem layout attributes.

Add xmldoc to mem layout attributes.


using System;
using NUnit.Framework;

namespace Business.Core.Test
{
	[TestFixture]
	public class TestDBFunctions
	{
		[Test]
		public void Book() {
			var profile = new Profile.Profile();
			var database = new Fake.Database(profile);
			database.Connect();

			var bookName = "Sales";
			float bookAmount = 111.11F;
			int? entryId = 1;

			database.SetValue(entryId);

			var entry = database.Book(bookName, bookAmount);

			Assert.IsNotNull(entry);
			Assert.Greater(entry, 0);
			Assert.AreEqual(entryId, entry);
		}
	}
}

using System;
using NUnit.Framework;

namespace Business.Core.Test
{
	[TestFixture]
	public class TestDBFunctions
	{
		[Test]
		public void Book() {
			var profile = new Profile.Profile();
			var database = new Fake.Database(profile);
			database.Connect();

			var bookName = "Sales";
			float bookAmount = 111.11F;
			int? entryId = 1;

			database.SetValue(entryId);

			Assert.IsFalse(database.Connection.TransactionStarted);
			var entry = database.Book(bookName, bookAmount);
			Assert.IsTrue(database.Connection.TransactionStarted);
			Assert.IsFalse(database.Connection.TransactionRollback);
			Assert.IsTrue(database.Connection.TransactionCommited);

			Assert.IsNotNull(entry);
			Assert.Greater(entry, 0);
			Assert.AreEqual(entryId, entry);
		}
	}
}

Test Server-side function called in transaction fails


using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      char key = Console.ReadKey(true).KeyChar;

      var game = new Game("HANG THE MAN");
      bool wasCorrect = game.GuessLetter(key);
      Console.WriteLine(wasCorrect.ToString());

      var output = game.ShownWord();
      Console.WriteLine(output);

      // Table table = new Table(2, 3);
      // string output = table.Draw();

      // Console.WriteLine(output);
    }
  }
}

using System;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      // char key = Console.ReadKey(true).KeyChar;

      // var game = new Game("HANG THE MAN");
      // bool wasCorrect = game.GuessLetter(key);
      // Console.WriteLine(wasCorrect.ToString());

      // var output = game.ShownWord();
      // Console.WriteLine(output);

      Table table = new Table(2, 3);
      string output = table.Draw();

      Console.WriteLine(output);
    }
  }
}

Comment out game logic and replace table code

Time to set up the game layout.


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

namespace FileReplacer
{
    public static class FileHelper
    {
        public static readonly Encoding UTF8N = new UTF8Encoding();

        public static void ReplaceContent(FileInfo file, string oldValue, string newValue)
        {
            string oldContent;
            Encoding encoding;

            using (var reader = new StreamReader(file.FullName, UTF8N, true))
            {
                oldContent = reader.ReadToEnd();
                encoding = reader.CurrentEncoding;
            }

            if (!oldContent.Contains(oldValue)) return;

            var newContent = oldContent.Replace(oldValue, newValue);
            File.WriteAllText(file.FullName, newContent, encoding);
            Console.WriteLine($"Replaced content: {file.FullName}");
        }
    }
}

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

namespace FileReplacer
{
    public static class FileHelper
    {
        public static readonly Encoding UTF8N = new UTF8Encoding();

        public static void ReplaceContent(FileInfo file, string oldValue, string newValue)
        {
            if (file.Attributes.HasFlag(FileAttributes.ReadOnly) || file.Attributes.HasFlag(FileAttributes.Hidden)) return;

            string oldContent;
            Encoding encoding;

            using (var reader = new StreamReader(file.FullName, UTF8N, true))
            {
                oldContent = reader.ReadToEnd();
                encoding = reader.CurrentEncoding;
            }

            if (!oldContent.Contains(oldValue)) return;

            var newContent = oldContent.Replace(oldValue, newValue);
            File.WriteAllText(file.FullName, newContent, encoding);
            Console.WriteLine($"Replaced content: {file.FullName}");
        }
    }
}

Exclude files that can not be accessed

Exclude files that can not be accessed


namespace NuPack {
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Cache;

    // REVIEW: This class isn't super clean. Maybe this object should be passed around instead
    // of being static
    public static class HttpWebRequestor {
        [System.Diagnostics.CodeAnalysis.SuppressMessage(
            "Microsoft.Reliability",
            "CA2000:Dispose objects before losing scope",
            Justification="We can't dispose an object if we want to return it.")]
        public static ZipPackage DownloadPackage(Uri uri) {
            return new ZipPackage(() => {
                using (Stream responseStream = GetResponseStream(uri)) {
                    // ZipPackages require a seekable stream
                    var memoryStream = new MemoryStream();
                    // Copy the stream
                    responseStream.CopyTo(memoryStream);
                    // Move it back to the beginning
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    return memoryStream;
                }
            });
        }

        public static Stream GetResponseStream(Uri uri) {
            WebRequest request = WebRequest.Create(uri);
            InitializeRequest(request);

            WebResponse response = request.GetResponse();

            return response.GetResponseStream();
        }

        internal static void InitializeRequest(WebRequest request) {
            request.CachePolicy = new HttpRequestCachePolicy();
            request.UseDefaultCredentials = true;
            if (request.Proxy != null) {
                // If we are going through a proxy then just set the default credentials
                request.Proxy.Credentials = CredentialCache.DefaultCredentials;
            }
        }
    }
}

namespace NuPack {
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Net;
    using System.Net.Cache;

    // REVIEW: This class isn't super clean. Maybe this object should be passed around instead
    // of being static
    public static class HttpWebRequestor {
        public static ZipPackage DownloadPackage(Uri uri) {
            return DownloadPackage(uri, useCache: true);
        }

        [SuppressMessage(
            "Microsoft.Reliability",
            "CA2000:Dispose objects before losing scope",
            Justification = "We can't dispose an object if we want to return it.")]
        public static ZipPackage DownloadPackage(Uri uri, bool useCache) {
            byte[] cachedBytes = null;
            return new ZipPackage(() => {
                if (useCache && cachedBytes != null) {
                    return new MemoryStream(cachedBytes);
                }

                using (Stream responseStream = GetResponseStream(uri)) {
                    // ZipPackages require a seekable stream
                    var memoryStream = new MemoryStream();
                    // Copy the stream
                    responseStream.CopyTo(memoryStream);
                    // Move it back to the beginning
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    if (useCache) {
                        // Cache the bytes for this package
                        cachedBytes = memoryStream.ToArray();
                    }
                    return memoryStream;
                }
            });
        }

        public static Stream GetResponseStream(Uri uri) {
            WebRequest request = WebRequest.Create(uri);
            InitializeRequest(request);

            WebResponse response = request.GetResponse();

            return response.GetResponseStream();
        }

        internal static void InitializeRequest(WebRequest request) {
            request.CachePolicy = new HttpRequestCachePolicy();
            request.UseDefaultCredentials = true;
            if (request.Proxy != null) {
                // If we are going through a proxy then just set the default credentials
                request.Proxy.Credentials = CredentialCache.DefaultCredentials;
            }
        }
    }
}

Add caching option when downloading package.

--HG--
extra : rebase_source : 0701678b4b47fd6ce968f0cb29629d227f60c3df


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;

namespace MaxMind.MaxMindDb.Test
{
    [TestFixture]
    public class ThreadingTest
    {
        [Test]
        public void TestParallelFor()
        {
            var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
            var count = 0;
            var ipsAndResults = new Dictionary<IPAddress, string>();
            var rand = new Random();
            while(count < 10000)
            {
                var ip = new IPAddress(rand.Next(int.MaxValue));
                var resp = reader.Find(ip);
                if (resp != null)
                {
                    ipsAndResults.Add(ip, resp.ToString());
                    count++;
                }
            }

            var ips = ipsAndResults.Keys.ToArray();
            Parallel.For(0, ips.Length, (i) =>
            {
                var ipAddress = ips[i];
                var result = reader.Find(ipAddress);
                var resultString = result.ToString();
                var expectedString = ipsAndResults[ipAddress];
                if(resultString != expectedString)
                    throw new Exception(string.Format("Non-matching zip. Expected {0}, found {1}", expectedString, resultString));
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;

namespace MaxMind.MaxMindDb.Test
{
    [TestFixture]
    public class ThreadingTest
    {
        [Test]
        public void TestParallelFor()
        {
            var reader = new MaxMindDbReader("..\\..\\TestData\\GeoLite2-City.mmdb", FileAccessMode.MemoryMapped);
            var count = 0;
            var ipsAndResults = new Dictionary<IPAddress, string>();
            var rand = new Random();
            while(count < 10000)
            {
                var ip = new IPAddress(rand.Next(int.MaxValue));
                var resp = reader.Find(ip);
                if (resp != null)
                {
                    ipsAndResults.Add(ip, resp.ToString());
                    count++;
                }
            }

            var ips = ipsAndResults.Keys.ToArray();
            Parallel.For(0, ips.Length, (i) =>
            {
                var ipAddress = ips[i];
                var result = reader.Find(ipAddress);
                var resultString = result.ToString();
                var expectedString = ipsAndResults[ipAddress];
                if(resultString != expectedString)
                    throw new Exception(string.Format("Non-matching result. Expected {0}, found {1}", expectedString, resultString));
            });
        }
    }
}

Correct error message in thread test

Correct error message in thread test


namespace CountryFood.Web.Infrastructure.Mappings
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using AutoMapper;

    public class AutoMapperConfig
    {
        private Assembly assembly;

        public AutoMapperConfig(Assembly assembly)
        {
            this.assembly = assembly;
        }

        public void Execute()
        {
            var types = this.assembly.GetExportedTypes();

            LoadStandardMappings(types);

            LoadCustomMappings(types);
        }

        private static void LoadStandardMappings(IEnumerable<Type> types)
        {
            var maps = (from t in types
                        from i in t.GetInterfaces()
                        where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
                              !t.IsAbstract &&
                              !t.IsInterface
                        select new
                        {
                            Source = i.GetGenericArguments()[0],
                            Destination = t
                        }).ToArray();

            foreach (var map in maps)
            {
                Mapper.CreateMap(map.Source, map.Destination);
            }
        }

        private static void LoadCustomMappings(IEnumerable<Type> types)
        {
            var maps = (from t in types
                        from i in t.GetInterfaces()
                        where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
                              !t.IsAbstract &&
                              !t.IsInterface
                        select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();

            foreach (var map in maps)
            {
                map.CreateMappings(Mapper.Configuration);
            }
        }
    }
}

namespace CountryFood.Web.Infrastructure.Mappings
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using AutoMapper;

    public class AutoMapperConfig
    {
        private Assembly assembly;

        public AutoMapperConfig(Assembly assembly)
        {
            this.assembly = assembly;
        }

        public void Execute()
        {
            var types = this.assembly.GetExportedTypes();

            LoadStandardMappings(types);

            LoadCustomMappings(types);
        }

        private static void LoadStandardMappings(IEnumerable<Type> types)
        {
            var maps = (from t in types
                        from i in t.GetInterfaces()
                        where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
                              !t.IsAbstract &&
                              !t.IsInterface
                        select new
                        {
                            Source = i.GetGenericArguments()[0],
                            Destination = t
                        }).ToArray();

            foreach (var map in maps)
            {
                Mapper.CreateMap(map.Source, map.Destination);
                Mapper.CreateMap(map.Destination, map.Source);
            }
        }

        private static void LoadCustomMappings(IEnumerable<Type> types)
        {
            var maps = (from t in types
                        from i in t.GetInterfaces()
                        where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
                              !t.IsAbstract &&
                              !t.IsInterface
                        select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();

            foreach (var map in maps)
            {
                map.CreateMappings(Mapper.Configuration);
            }
        }
    }
}

Add map from view model to db model.

Add map from view model to db model.


using System.IO;
using System.Text;
using System.Threading.Tasks;
using Shouldly;
using Xunit;

namespace MediatR.Tests
{
    public class NotificationHandlerTests
    {
        public class Ping : INotification
        {
            public string Message { get; set; }
        }

        public class PongChildHandler : NotificationHandler<Ping>
        {
            private readonly TextWriter _writer;

            public PongChildHandler(TextWriter writer)
            {
                _writer = writer;
            }

            protected override void Handle(Ping notification)
            {
                _writer.WriteLine(notification.Message + " Pong");
            }
        }

        [Fact]
        public async Task Should_call_abstract_handler()
        {
            var builder = new StringBuilder();
            var writer = new StringWriter(builder);

            INotificationHandler<Ping> handler = new PongChildHandler(writer);

            await handler.Handle(
                new Ping() { Message = "Ping" },
                default
            );

            var result = builder.ToString();
            result.ShouldContain("Ping Pong");
        }
    }
}

using System.IO;
using System.Text;
using System.Threading.Tasks;
using Shouldly;
using Xunit;

namespace MediatR.Tests
{
    public class NotificationHandlerTests
    {
        public class Ping : INotification
        {
            public string Message { get; set; }
        }

        public class PongChildHandler : NotificationHandler<Ping>
        {
            private readonly TextWriter _writer;

            public PongChildHandler(TextWriter writer)
            {
                _writer = writer;
            }

            protected override void Handle(Ping notification)
            {
                _writer.WriteLine(notification.Message + " Pong");
            }
        }

        [Fact]
        public async Task Should_call_abstract_handle_method()
        {
            var builder = new StringBuilder();
            var writer = new StringWriter(builder);

            INotificationHandler<Ping> handler = new PongChildHandler(writer);

            await handler.Handle(
                new Ping() { Message = "Ping" },
                default
            );

            var result = builder.ToString();
            result.ShouldContain("Ping Pong");
        }
    }
}

Rename unit test function to be more explicit on its purpose.

Co-Authored-By: FuncLun <711c73f64afdce07b7e38039a96d2224209e9a6c@functionallunacy.com>


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Text.RegularExpressions;

using Common.Logging;

namespace GesturesViewer {
  class ModelSelector : INotifyPropertyChanged {
    static readonly ILog Log = LogManager.GetCurrentClassLogger();
    static readonly String ModelFilePattern = "*.mat";
    // File names that ends with time stamp.
    static readonly String TimeRegex = @"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}";

    public event PropertyChangedEventHandler PropertyChanged;

    public List<String> ModelFiles { get; private set; }
    public String SelectedModel {
      get {
        return selectedModel;
      }
      set {
        selectedModel = value;
        OnPropteryChanged("SelectedModel");
      }
    }

    String selectedModel, dir;

    public ModelSelector(String dir) {
      this.dir = dir;
      ModelFiles = new List<String>();
      Refresh();
    }

    public void Refresh() {
      Log.Debug("Refresh models.");
      var files = Directory.GetFiles(dir, ModelFilePattern);
      ModelFiles.Clear();
      foreach (var f in files) {
        ModelFiles.Add(f);
        var fileName = Path.GetFileName(f);
        if (SelectedModel == null || Regex.IsMatch(fileName, TimeRegex))
          SelectedModel = f;
      }
    }

    void OnPropteryChanged(String prop) {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
  }
}

using System;
using System.IO;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;

using Common.Logging;

namespace GesturesViewer {
  class ModelSelector : INotifyPropertyChanged {
    static readonly ILog Log = LogManager.GetCurrentClassLogger();
    static readonly String ModelFilePattern = "*.mat";
    // File names that ends with time stamp.
    static readonly String TimeRegex = @"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}";

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<String> ModelFiles { get; private set; }
    public String SelectedModel {
      get {
        return selectedModel;
      }
      set {
        selectedModel = value;
        OnPropteryChanged("SelectedModel");
      }
    }

    String selectedModel, dir;

    public ModelSelector(String dir) {
      this.dir = dir;
      ModelFiles = new ObservableCollection<String>();
      Refresh();
    }

    public void Refresh() {
      Log.Debug("Refresh models.");
      var files = Directory.GetFiles(dir, ModelFilePattern);
      ModelFiles.Clear();
      foreach (var f in files) {
        ModelFiles.Add(f);
        var fileName = Path.GetFileName(f);
        if (SelectedModel == null || Regex.IsMatch(fileName, TimeRegex))
          SelectedModel = f;
      }
    }

    void OnPropteryChanged(String prop) {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
  }
}

Use ObservableCollection for ComboBox item source so that the ComboBox updates when the list changes.


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            long sum = 0;

            for (int n = 2; n < max - 2; n++)
            {
                if (Maths.IsPrime(n))
                {
                    sum += n;
                }
            }

            Answer = sum;

            return 0;
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            long sum = 0;

            for (int n = 2; n < max; n++)
            {
                if (Maths.IsPrime(n))
                {
                    sum += n;
                }
            }

            Answer = sum;

            return 0;
        }
    }
}

Fix regression in puzzle 10

Fix regression in puzzle 10

Fix regression in puzzle 10 caused by bounds being calculated
incorrectly after change from using Enumerable.Range().


using PS.Mothership.Core.Common.Template.Gen;
using Quartz;
using System;
using System.Collections.Generic;

namespace PS.Mothership.Core.Common.Dto.SchedulerManagement
{
    public class TriggerProfileDto
    {
        public string Name { get; set; }
        public TriggerState State { get; set; }
        public DateTimeOffset? NextFireTime { get; set; }
        public string Schedule { get; set; }
        public DateTimeOffset StartTime { get; set; }
        public IntervalUnit Occurrence { get; set; }
        public int TriggerInterval { get; set; }
        public IEnumerable<DayOfWeek> SelectedDaysOfWeek { get; set; }
        public GenSchedulerJobGroupEnum JobGroup { get; set; }
    }
}

using PS.Mothership.Core.Common.Template.Gen;
using Quartz;
using System;
using System.Collections.Generic;

namespace PS.Mothership.Core.Common.Dto.SchedulerManagement
{
    public class TriggerProfileDto
    {
        public string Name { get; set; }
        public TriggerState State { get; set; }
        public DateTimeOffset? NextFireTime { get; set; }
        public DateTimeOffset? PreviousFireTime { get; set; }
        public string Schedule { get; set; }
        public DateTimeOffset StartTime { get; set; }
        public IntervalUnit Occurrence { get; set; }
        public int TriggerInterval { get; set; }
        public IEnumerable<DayOfWeek> SelectedDaysOfWeek { get; set; }
        public GenSchedulerJobGroupEnum JobGroup { get; set; }
    }
}

Add PreviousFireTime to trigger profile dto


<?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
 <channel><?cs
  if:project.name_encoded ?>
   <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
  else ?>
   <title>Revisions of <?cs var:log.path ?></title><?cs
  /if ?>
  <link><?cs var:base_host ?><?cs var:log.log_href ?></link>
  <description>Trac Log - Revisions of <?cs var:log.path ?></description>
  <language>en-us</language>
  <generator>Trac v<?cs var:trac.version ?></generator><?cs
  each:item = log.items ?><?cs
   with:change = log.changes[item.rev] ?>
    <item>
     <author><?cs var:change.author ?></author>
     <pubDate><?cs var:change.date ?></pubDate>
     <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
     <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
     <description><?cs var:change.message ?></description>
     <category>Report</category>
    </item><?cs
   /with ?><?cs
  /each ?>
 </channel>
</rss>

<?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
 <channel><?cs
  if:project.name_encoded ?>
   <title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
  else ?>
   <title>Revisions of <?cs var:log.path ?></title><?cs
  /if ?>
  <link><?cs var:base_host ?><?cs var:log.log_href ?></link>
  <description>Trac Log - Revisions of <?cs var:log.path ?></description>
  <language>en-us</language>
  <generator>Trac v<?cs var:trac.version ?></generator><?cs
  each:item = log.items ?><?cs
   with:change = log.changes[item.rev] ?>
    <item>
     <author><?cs var:change.author ?></author>
     <pubDate><?cs var:change.date ?></pubDate>
     <title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
     <link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
     <description><?cs var:change.message ?></description>
     <category>Log</category>
    </item><?cs
   /with ?><?cs
  /each ?>
 </channel>
</rss>

Fix category of revision log RSS feeds.

Fix category of revision log RSS feeds.

git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@2261 af82e41b-90c4-0310-8c96-b1721e28e2e2


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

using Pingu.Chunks;

namespace Pingu
{

    public class PngFile : IEnumerable<Chunk>
    {
        List<Chunk> chunksToWrite = new List<Chunk>();
        static readonly byte[] magic = new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };

        public void Add(Chunk chunk) => chunksToWrite.Add(chunk);

        IEnumerator<Chunk> IEnumerable<Chunk>.GetEnumerator() => chunksToWrite.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => chunksToWrite.GetEnumerator();

        public int ChunkCount => chunksToWrite.Count;

        public async Task WriteFileAsync(Stream target)
        {
            await target.WriteAsync(magic, 0, magic.Length);
            foreach (var chunk in chunksToWrite)
                await chunk.WriteSelfToStreamAsync(target);
        }
    }
}

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

using Pingu.Chunks;

namespace Pingu
{

    public class PngFile : IEnumerable<Chunk>
    {
        List<Chunk> chunksToWrite = new List<Chunk>();
        static readonly byte[] magic = new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };

        public void Add(Chunk chunk) => chunksToWrite.Add(chunk);

        IEnumerator<Chunk> IEnumerable<Chunk>.GetEnumerator() => chunksToWrite.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => chunksToWrite.GetEnumerator();

        public int ChunkCount => chunksToWrite.Count;

        public async Task WriteFileAsync(Stream target)
        {
            await target.WriteAsync(magic, 0, magic.Length);
            foreach (var chunk in this)
                await chunk.WriteSelfToStreamAsync(target);
        }
    }
}

Enumerate via self instead of directly

Pingu: Enumerate via self instead of directly

Makes changing underlying storage easier. :)


#define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;

namespace Bit.Owin.Implementations
{
    public class DebugLogStore : ILogStore
    {
        private readonly IContentFormatter _formatter;

        public DebugLogStore(IContentFormatter formatter)
        {
            _formatter = formatter;
        }

        protected DebugLogStore()
        {
        }

        public virtual void SaveLog(LogEntry logEntry)
        {
            Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
        }

        public virtual async Task SaveLogAsync(LogEntry logEntry)
        {
            Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
        }
    }
}

#define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;

namespace Bit.Owin.Implementations
{
    public class DebugLogStore : ILogStore
    {
        private readonly IContentFormatter _formatter;

        public DebugLogStore(IContentFormatter formatter)
        {
            _formatter = formatter;
        }

        protected DebugLogStore()
        {
        }

        public virtual void SaveLog(LogEntry logEntry)
        {
            if (Debugger.IsAttached)
                Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
        }

        public virtual async Task SaveLogAsync(LogEntry logEntry)
        {
            if (Debugger.IsAttached)
                Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
        }
    }
}

Debug log store saves logs only when debugger is attached


// 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;

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

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

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

// 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.Diagnostics.CodeAnalysis;

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

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

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

Use null-forgiving operator rather than assertion


using System;
using System.Runtime.InteropServices;
namespace Sodium
{
  /// <summary>
  /// libsodium core information.
  /// </summary>
  public static class SodiumCore
  {
    static SodiumCore()
    {
      SodiumLibrary.init();
    }

    /// <summary>Gets random bytes</summary>
    /// <param name="count">The count of bytes to return.</param>
    /// <returns>An array of random bytes.</returns>
    public static byte[] GetRandomBytes(int count)
    {
      var buffer = new byte[count];
      SodiumLibrary.randombytes_buff(buffer, count);

      return buffer;
    }

    /// <summary>
    /// Returns the version of libsodium in use.
    /// </summary>
    /// <returns>
    /// The sodium version string.
    /// </returns>
    public static string SodiumVersionString()
    {
      var ptr = SodiumLibrary.sodium_version_string();

      return Marshal.PtrToStringAnsi(ptr);
    }
  }
}

using System;
using System.Runtime.InteropServices;
namespace Sodium
{
  /// <summary>
  /// libsodium core information.
  /// </summary>
  public static class SodiumCore
  {
    static SodiumCore()
    {
      SodiumLibrary.init();
    }

    /// <summary>Gets random bytes</summary>
    /// <param name="count">The count of bytes to return.</param>
    /// <returns>An array of random bytes.</returns>
    public static byte[] GetRandomBytes(int count)
    {
      var buffer = new byte[count];
      SodiumLibrary.randombytes_buff(buffer, count);

      return buffer;
    }

    /// <summary>
    /// Returns the version of libsodium in use.
    /// </summary>
    /// <returns>
    /// The sodium version string.
    /// </returns>
    public static string SodiumVersionString()
    {
      var ptr = SodiumLibrary.sodium_version_string();

      return Marshal.PtrToStringAnsi(ptr);
    }

    [Obsolete("Use SodiumLibrary.is64")]
    internal static bool Is64
    {
      get
      {
        return SodiumLibrary.is64;
      }
    }

    [Obsolete("Use SodiumLibrary.isRunningOnMono")]
    internal static bool IsRunningOnMono()
    {
      return SodiumLibrary.isRunningOnMono;
    }

    [Obsolete("Use SodiumLibrary.name")]
    internal static string LibraryName()
    {
      return SodiumLibrary.name;
    }
  }
}

Add obsolete wrappers for compatability

Add obsolete wrappers for compatability


using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;

namespace YesAndEditor {

	// Static class packed to the brim with helpful Unity editor utilities.
	public static class YesAndEditorUtil {

		// Forcefully mark open loaded scenes dirty and save them.
		[MenuItem ("File/Force Save")]
		public static void ForceSaveOpenScenes () {
			EditorSceneManager.MarkAllScenesDirty ();
			EditorSceneManager.SaveOpenScenes ();
		}

		// Mark an object editor-only.
		public static void SetEditorOnly(this MonoBehaviour obj, bool editorOnly = true) {
			if (editorOnly) {
				obj.gameObject.hideFlags ^= HideFlags.NotEditable;
				obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
			}
			else {
				obj.gameObject.hideFlags &= HideFlags.NotEditable;
				obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
			}
		}
	}
}

using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;

namespace YesAndEditor {

	// Static class packed to the brim with helpful Unity editor utilities.
	public static class YesAndEditorUtil {

		// Forcefully mark open loaded scenes dirty and save them.
		[MenuItem ("File/Force Save")]
		public static void ForceSaveOpenScenes () {
			EditorSceneManager.MarkAllScenesDirty ();
			EditorSceneManager.SaveOpenScenes ();
		}

		// Mark an object editor-only.
		public static void SetEditorOnly(this GameObject obj, bool editorOnly = true) {
			if (editorOnly) {
				obj.gameObject.hideFlags ^= HideFlags.NotEditable;
				obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
			}
			else {
				obj.gameObject.hideFlags &= HideFlags.NotEditable;
				obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
			}
		}
	}
}

Attach SetEditorOnly function to GameObjects rather than MonoBehaviors


// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TemplateWizard;

namespace Microsoft.NodejsTools.ProjectWizard
{
    /// <summary>
    /// Provides a project wizard extension which will optionally do an
    /// npm install after the project is created.
    /// </summary>
    public sealed class NpmWizardExtension : IWizard
    {
        #region IWizard Members

        public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
        {
        }

        public void ProjectFinishedGenerating(EnvDTE.Project project)
        {
            Debug.Assert(project != null && project.Object != null);
            Debug.Assert(project.Object is INodePackageModulesCommands);

            ((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
        }

        public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
        {
        }

        public void RunFinished()
        {
        }

        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
        }

        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }

        #endregion
    }
}

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TemplateWizard;

namespace Microsoft.NodejsTools.ProjectWizard
{
    /// <summary>
    /// Provides a project wizard extension which will optionally do an
    /// npm install after the project is created.
    /// </summary>
    public sealed class NpmWizardExtension : IWizard
    {
        #region IWizard Members

        public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
        {
        }

        public void ProjectFinishedGenerating(EnvDTE.Project project)
        {
            Debug.Assert(project != null && project.Object != null);
            Debug.Assert(project.Object is INodePackageModulesCommands);

            // Create the "node_modules/@types" folder before opening any files (which creates the
            // context for the project). This allows tsserver to start watching for type definitions
            // before any are installed (which is needed as "npm install" runs async, so the modules
            // usually aren't installed before the project context is loaded).
            var fullname = project.FullName;
            var projectFolder = Path.GetDirectoryName(fullname);
            Directory.CreateDirectory(Path.Combine(projectFolder, @"node_modules\@types"));

            ((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
        }

        public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
        {
        }

        public void RunFinished()
        {
        }

        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
        }

        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }

        #endregion
    }
}

Create node_modules/@types after project creation

(cherry picked from commit 0be5a02f59e1aa93293352eefe9178160167855f)


using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Salesforce.VisualStudio.Services.ConnectedService
{
    [Export(typeof(ConnectedServiceProvider))]
    [ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
    internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
    {
        private BitmapImage icon;

        public SalesforceConnectedServiceProvider()
        {
            this.Category = Resources.ConnectedServiceProvider_Category;
            this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
            this.Description = Resources.ConnectedServiceProvider_Description;
            this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
            this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
            this.Name = Resources.ConnectedServiceProvider_Name;
            this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
        }

        public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
        {
            ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);

            return Task.FromResult(wizard);
        }
    }
}

using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace Salesforce.VisualStudio.Services.ConnectedService
{
    [Export(typeof(ConnectedServiceProvider))]
    [ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
    internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
    {
        public SalesforceConnectedServiceProvider()
        {
            this.Category = Resources.ConnectedServiceProvider_Category;
            this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
            this.Description = Resources.ConnectedServiceProvider_Description;
            this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
            this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
            this.Name = Resources.ConnectedServiceProvider_Name;
            this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
        }

        public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
        {
            ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);

            return Task.FromResult(wizard);
        }
    }
}

Remove unused field from previous commit


using Newtonsoft.Json;
using System.Collections.Generic;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
        public List<string> OptionSet { get; set; }
        public int StartingPosition { get; set; }
        public int StepSize { get; set; }
        public string Color { get; set; }
    }
}

using Newtonsoft.Json;
using System.Collections.Generic;

namespace SurveyMonkey.Containers
{
    [JsonConverter(typeof(TolerantJsonConverter))]
    public class QuestionDisplayOptionsCustomOptions
    {
        public List<string> OptionSet { get; set; }
        public int StartingPosition { get; set; } //slider questions
        public int StepSize { get; set; } //slider questions
        public string Color { get; set; } //star rating questions
    }
}

Comment on custom display option properties


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;

namespace CSharpViaTest.Collections._30_MapReducePractices
{
    [SuperEasy]
    public class CountNumberOfWordsInMultipleTextFiles
    {
        #region Please modifies the code to pass the test

        static int CountNumberOfWords(IEnumerable<Stream> streams)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Fact]
        public void should_count_number_of_words()
        {
            const int fileCount = 5;
            const int wordsInEachFile = 10;

            Stream[] streams = Enumerable
                .Repeat(0, fileCount)
                .Select(_ => TextStreamFactory.Create(wordsInEachFile))
                .ToArray();

            int count = CountNumberOfWords(streams);

            Assert.Equal(fileCount * wordsInEachFile, count);

            foreach (Stream stream in streams) { stream.Dispose(); }
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;

namespace CSharpViaTest.Collections._30_MapReducePractices
{
    [SuperEasy]
    public class CountNumberOfWordsInMultipleTextFiles
    {
        #region Please modifies the code to pass the test

        // You can add additional functions for readability and performance considerations.

        static int CountNumberOfWords(IEnumerable<Stream> streams)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Fact]
        public void should_count_number_of_words()
        {
            const int fileCount = 5;
            const int wordsInEachFile = 10;

            Stream[] streams = Enumerable
                .Repeat(0, fileCount)
                .Select(_ => TextStreamFactory.Create(wordsInEachFile))
                .ToArray();

            int count = CountNumberOfWords(streams);

            Assert.Equal(fileCount * wordsInEachFile, count);

            foreach (Stream stream in streams) { stream.Dispose(); }
        }
    }
}

Add comment to count word number.

[liuxia] Add comment to count word number.


using Newtonsoft.Json;

namespace Nest
{
	[JsonObject]
	public class CatIndicesRecord : ICatRecord
	{
		[JsonProperty("docs.count")]
		public string DocsCount { get; set; }

		[JsonProperty("docs.deleted")]
		public string DocsDeleted { get; set; }

		[JsonProperty("health")]
		public string Health { get; set; }

		[JsonProperty("index")]
		public string Index { get; set; }

		[JsonProperty("pri")]
		public string Primary { get; set; }

		[JsonProperty("pri.store.size")]
		public string PrimaryStoreSize { get; set; }

		[JsonProperty("rep")]
		public string Replica { get; set; }

		[JsonProperty("store.size")]
		public string StoreSize { get; set; }

		[JsonProperty("status")]
		public string Status { get; set; }
	}
}

using Newtonsoft.Json;

namespace Nest
{
	[JsonObject]
	public class CatIndicesRecord : ICatRecord
	{
		[JsonProperty("docs.count")]
		public string DocsCount { get; set; }

		[JsonProperty("docs.deleted")]
		public string DocsDeleted { get; set; }

		[JsonProperty("health")]
		public string Health { get; set; }

		[JsonProperty("index")]
		public string Index { get; set; }

		[JsonProperty("pri")]
		public string Primary { get; set; }

		[JsonProperty("pri.store.size")]
		public string PrimaryStoreSize { get; set; }

		[JsonProperty("rep")]
		public string Replica { get; set; }

		[JsonProperty("store.size")]
		public string StoreSize { get; set; }

		[JsonProperty("status")]
		public string Status { get; set; }

		[JsonProperty("tm")]
		public string TotalMemory { get; set; }
	}
}

Add total memory to cat indices response

Closes #1349


using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Rs317.Sharp
{
	public static class RsUnityPlatform
	{
		public static bool isWebGLBuild => true;

		public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;

		public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;

		public static bool isInEditor => Application.isEditor;
	}
}

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Rs317.Sharp
{
	public static class RsUnityPlatform
	{
		public static bool isWebGLBuild => Application.platform == RuntimePlatform.WebGLPlayer;

		public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;

		public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;

		public static bool isInEditor => Application.isEditor;
	}
}

Remove forced WebGL test code

Remove forced WebGL test code


namespace DW.ELA.Interfaces.Events
{
    using Newtonsoft.Json;

    public class ModuleEngineering
    {
        [JsonProperty("Engineer")]
        public string Engineer { get; set; }

        [JsonProperty("EngineerID")]
        public ulong EngineerId { get; set; }

        [JsonProperty("BlueprintID")]
        public long BlueprintId { get; set; }

        [JsonProperty("BlueprintName")]
        public string BlueprintName { get; set; }

        [JsonProperty("Level")]
        public short Level { get; set; }

        [JsonProperty("Quality")]
        public double Quality { get; set; }

        [JsonProperty("Modifiers")]
        public Modifier[] Modifiers { get; set; }

        [JsonProperty("ExperimentalEffect")]
        public string ExperimentalEffect { get; set; }

        [JsonProperty("ExperimentalEffect_Localised")]
        public string ExperimentalEffectLocalised { get; set; }
    }
}

namespace DW.ELA.Interfaces.Events
{
    using Newtonsoft.Json;

    public class ModuleEngineering
    {
        [JsonProperty("Engineer")]
        public string Engineer { get; set; }

        [JsonProperty("EngineerID")]
        public ulong EngineerId { get; set; }

        [JsonProperty("BlueprintID")]
        public ulong BlueprintId { get; set; }

        [JsonProperty("BlueprintName")]
        public string BlueprintName { get; set; }

        [JsonProperty("Level")]
        public short Level { get; set; }

        [JsonProperty("Quality")]
        public double Quality { get; set; }

        [JsonProperty("Modifiers")]
        public Modifier[] Modifiers { get; set; }

        [JsonProperty("ExperimentalEffect")]
        public string ExperimentalEffect { get; set; }

        [JsonProperty("ExperimentalEffect_Localised")]
        public string ExperimentalEffectLocalised { get; set; }
    }
}

Fix for serialization errors with Loadout events caused by game bug


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;

namespace ProjectMarkdown.Model
{
    public class DocumentModel : INotifyPropertyChanged
    {
        private string _header;
        private string _markdownText;
        private Uri _source;

        public string Header
        {
            get { return _header; }
            set
            {
                if (value == _header) return;
                _header = value;
                OnPropertyChanged(nameof(Header));
            }
        }

        public string MarkdownText
        {
            get { return _markdownText; }
            set
            {
                if (value == _markdownText) return;
                _markdownText = value;
                OnPropertyChanged(nameof(MarkdownText));
            }
        }

        public Uri Source
        {
            get { return _source; }
            set
            {
                if (Equals(value, _source)) return;
                _source = value;
                OnPropertyChanged(nameof(Source));
            }
        }

        public string MarkdownPath { get; set; }
        public string HtmlPath { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public DocumentModel(string documentName)
        {
            Header = documentName;
            MarkdownText = "";
            Source = "".ToUri();
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;

namespace ProjectMarkdown.Model
{
    public class DocumentModel : INotifyPropertyChanged
    {
        public DocumentMetadata Metadata
        {
            get { return _metadata; }
            set
            {
                if (Equals(value, _metadata)) return;
                _metadata = value;
                OnPropertyChanged(nameof(Metadata));
            }
        }

        public DocumentMarkdown Markdown
        {
            get { return _markdown; }
            set
            {
                if (Equals(value, _markdown)) return;
                _markdown = value;
                OnPropertyChanged(nameof(Markdown));
            }
        }

        public DocumentHtml Html
        {
            get { return _html; }
            set
            {
                if (Equals(value, _html)) return;
                _html = value;
                OnPropertyChanged(nameof(Html));
            }
        }

        private DocumentMetadata _metadata;
        private DocumentMarkdown _markdown;
        private DocumentHtml _html;

        public event PropertyChangedEventHandler PropertyChanged;

        public DocumentModel(string documentName)
        {
            Metadata = new DocumentMetadata(documentName);
            Markdown = new DocumentMarkdown("");
            Html = new DocumentHtml("".ToUri());
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Document model updated as per save document changes.


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

using System.Collections.Generic;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Online.API.Requests
{
    public class GetUserRecentActivitiesRequest : PaginatedAPIRequest<List<APIRecentActivity>>
    {
        private readonly long userId;

        public GetUserRecentActivitiesRequest(long userId, int page = 0, int itemsPerPage = 5)
            : base(page, itemsPerPage)
        {
            this.userId = userId;
        }

        protected override string Target => $"users/{userId}/recent_activity";
    }

    public enum RecentActivityType
    {
        Achievement,
        BeatmapPlaycount,
        BeatmapsetApprove,
        BeatmapsetDelete,
        BeatmapsetRevive,
        BeatmapsetUpdate,
        BeatmapsetUpload,
        Medal,
        Rank,
        RankLost,
        UserSupportAgain,
        UserSupportFirst,
        UserSupportGift,
        UsernameChange,
    }

    public enum BeatmapApproval
    {
        Ranked,
        Approved,
        Qualified,
    }
}

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

using System.Collections.Generic;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Online.API.Requests
{
    public class GetUserRecentActivitiesRequest : PaginatedAPIRequest<List<APIRecentActivity>>
    {
        private readonly long userId;

        public GetUserRecentActivitiesRequest(long userId, int page = 0, int itemsPerPage = 5)
            : base(page, itemsPerPage)
        {
            this.userId = userId;
        }

        protected override string Target => $"users/{userId}/recent_activity";
    }

    public enum RecentActivityType
    {
        Achievement,
        BeatmapPlaycount,
        BeatmapsetApprove,
        BeatmapsetDelete,
        BeatmapsetRevive,
        BeatmapsetUpdate,
        BeatmapsetUpload,
        Medal,
        Rank,
        RankLost,
        UserSupportAgain,
        UserSupportFirst,
        UserSupportGift,
        UsernameChange,
    }

    public enum BeatmapApproval
    {
        Ranked,
        Approved,
        Qualified,
        Loved
    }
}

Add loved enum on BeatmapApproval

Add loved enum on BeatmapApproval


//-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
//    Copyright 2013 Microsoft Corporation
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Storage.File
{
    using System;

    /// <summary>
    /// Specifies which details to include when listing the shares in this storage account.
    /// </summary>
    [Flags]
    public enum ShareListingDetails
    {
        /// <summary>
        /// No additional details.
        /// </summary>
        None = 0x0,

        /// <summary>
        /// Retrieve share metadata.
        /// </summary>
        Metadata = 0x1,

        /// <summary>
        /// Retrieve all available details.
        /// </summary>
        All = Metadata
    }
}

//-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
//    Copyright 2013 Microsoft Corporation
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Storage.File
{
    using System;

    /// <summary>
    /// Specifies which details to include when listing the shares in this storage account.
    /// </summary>
    [Flags]
    public enum ShareListingDetails
    {
        /// <summary>
        /// No additional details.
        /// </summary>
        None = 0x0,

        /// <summary>
        /// Retrieve share metadata.
        /// </summary>
        Metadata = 0x1,

        /// <summary>
        /// Retrieve share snapshots.
        /// </summary>
        Snapshots = 0x2,

        /// <summary>
        /// Retrieve all available details.
        /// </summary>
        All = Metadata | Snapshots
    }
}

Add Snapshots option to listing shares

Add Snapshots option to listing shares


// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright ©  2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0-beta.1+0.Branch.release/1.1.0.Sha.c42b1e80ff319dc8fecfcd9396662a96fcafbfaf")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const string Version = "1.1.0.0";
    }
}

// <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright ©  2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0+1.Branch.master.Sha.25442a58c8498465a9335b9bb288b5450d3d2cba")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const string Version = "1.1.0.0";
    }
}

Replace log4net dependency with LibLog

Replace log4net dependency with LibLog


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Tgstation.Server.Host.Core.Tests
{
	[TestClass]
	public sealed class TestAsyncDelayer
	{
		[TestMethod]
		public async Task TestDelay()
		{
			var delayer = new AsyncDelayer();
			var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
			var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(10), default);
			await startDelay.ConfigureAwait(false);
			Assert.IsTrue(checkDelay.IsCompleted);
		}

		[TestMethod]
		public async Task TestCancel()
		{
			var delayer = new AsyncDelayer();
			using (var cts = new CancellationTokenSource())
			{
				cts.Cancel();
				await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
			}
		}
	}
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Tgstation.Server.Host.Core.Tests
{
	[TestClass]
	public sealed class TestAsyncDelayer
	{
		[TestMethod]
		public async Task TestDelay()
		{
			var delayer = new AsyncDelayer();
			var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
			var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(100), default);
			await startDelay.ConfigureAwait(false);
			Assert.IsTrue(checkDelay.IsCompleted);
		}

		[TestMethod]
		public async Task TestCancel()
		{
			var delayer = new AsyncDelayer();
			using var cts = new CancellationTokenSource();
			cts.Cancel();
			await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
		}
	}
}

Fix a minor async delayer issue

Fix a minor async delayer issue


using Models;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services
{
    public class AdminService : IAdmin
    {
        private readonly IDataService dataService;

        public AdminService(IDataService service)
        {
            if (service == null)
                throw new ArgumentNullException("service", "Service Interface must not be null");
            this.dataService = service;
        }

        public IEnumerable<Person> GetVolunteers(Disaster disaster)
        {
            if (disaster == null)
                throw new ArgumentNullException("disaster", "disaster cannot be null");
            var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
            if (storedDisaster == null)
                throw new ArgumentException("Disaster was not found", "disaster");
            var commitments = from c in dataService.Commitments
                              where c.DisasterId == disaster.Id
                              select c;
            var people = from c in commitments
                         join p in dataService.Persons on c.PersonId equals p.Id
                         select p;
            return people;
        }
    }
}

using Models;
using Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services
{
    public class AdminService : IAdmin
    {
        private readonly IDataService dataService;

        public AdminService(IDataService service)
        {
            if (service == null)
                throw new ArgumentNullException("service", "Service Interface must not be null");
            this.dataService = service;
        }

        public IEnumerable<Person> GetVolunteers(Disaster disaster)
        {
            if (disaster == null)
                throw new ArgumentNullException("disaster", "disaster cannot be null");
            var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
            if (storedDisaster == null)
                throw new ArgumentException("Disaster was not found", "disaster");
            var commitments = from c in dataService.Commitments
                              where c.DisasterId == disaster.Id
                              select c;
            var people = from c in commitments
                         join p in dataService.Persons on c.PersonId equals p.Id
                         select p;
            return people;
        }

        public IEnumerable<Person> GetVolunteersForDate(Disaster disaster, DateTime date)
        {
            if (disaster == null)
                throw new ArgumentNullException("disaster", "disaster cannot be null");
            var storedDisaster = dataService.Disasters.SingleOrDefault(d => d.Id == disaster.Id);
            if (storedDisaster == null)
                throw new ArgumentException("Disaster was not found", "disaster");
            var commitments = from c in dataService.Commitments
                              where c.DisasterId == disaster.Id
                              select c;
            var people = from c in commitments
                         join p in dataService.Persons on c.PersonId equals p.Id
                         select p;
            return people;
        }
    }
}

Add stub method for Getting volunteers by date

Returns the main method for now.


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;

namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
    internal static class TodoCommentOptions
    {
        public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
    }

    [ExportOptionProvider, Shared]
    internal class TodoCommentOptionsProvider : IOptionProvider
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public TodoCommentOptionsProvider()
        {
        }

        public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
            TodoCommentOptions.TokenList);
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;

namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
    internal static class TodoCommentOptions
    {
        public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
    }

    [ExportOptionProvider, Shared]
    internal class TodoCommentOptionsProvider : IOptionProvider
    {
        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public TodoCommentOptionsProvider()
        {
        }

        public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
            TodoCommentOptions.TokenList);
    }
}

Update nullable annotations in TodoComments folder


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

using osu.Game.Beatmaps.Formats;
using System;
using System.Globalization;

namespace osu.Game.Skinning
{
    public class LegacySkinDecoder : LegacyDecoder<SkinConfiguration>
    {
        public LegacySkinDecoder()
            : base(1)
        {
        }

        protected override void ParseLine(SkinConfiguration skin, Section section, string line)
        {
            line = StripComments(line);

            var pair = SplitKeyVal(line);

            switch (section)
            {
                case Section.General:
                    switch (pair.Key)
                    {
                        case @"Name":
                            skin.SkinInfo.Name = pair.Value;
                            break;

                        case @"Author":
                            skin.SkinInfo.Creator = pair.Value;
                            break;

                        case @"CursorExpand":
                            skin.CursorExpand = pair.Value != "0";
                            break;
                        case @"SliderBorderSize":
                            if (Single.TryParse(pair.Value, NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out float size))
                                skin.SliderBorderSize = size;
                            break;
                    }

                    break;

                case Section.Fonts:
                    switch (pair.Key)
                    {
                        case "HitCirclePrefix":
                            skin.HitCircleFont = pair.Value;
                            break;

                        case "HitCircleOverlap":
                            skin.HitCircleOverlap = int.Parse(pair.Value);
                            break;
                    }

                    break;
            }

            base.ParseLine(skin, section, line);
        }
    }
}

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

using osu.Game.Beatmaps.Formats;
using System;
using System.Globalization;

namespace osu.Game.Skinning
{
    public class LegacySkinDecoder : LegacyDecoder<SkinConfiguration>
    {
        public LegacySkinDecoder()
            : base(1)
        {
        }

        protected override void ParseLine(SkinConfiguration skin, Section section, string line)
        {
            line = StripComments(line);

            var pair = SplitKeyVal(line);

            switch (section)
            {
                case Section.General:
                    switch (pair.Key)
                    {
                        case @"Name":
                            skin.SkinInfo.Name = pair.Value;
                            break;

                        case @"Author":
                            skin.SkinInfo.Creator = pair.Value;
                            break;

                        case @"CursorExpand":
                            skin.CursorExpand = pair.Value != "0";
                            break;
                        case @"SliderBorderSize":
                            skin.SliderBorderSize = Parsing.ParseFloat(pair.Value);
                            break;
                    }

                    break;

                case Section.Fonts:
                    switch (pair.Key)
                    {
                        case "HitCirclePrefix":
                            skin.HitCircleFont = pair.Value;
                            break;

                        case "HitCircleOverlap":
                            skin.HitCircleOverlap = int.Parse(pair.Value);
                            break;
                    }

                    break;
            }

            base.ParseLine(skin, section, line);
        }
    }
}

Use more standard parsing method

Use more standard parsing method


using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace core.Extensions.Data
{
    public class AppDbContext : DbContext
    {
        static AppDbContext()
        {

        }
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var tKeys = new KeyValuePair<Type, string>[] {
                new KeyValuePair<Type,string>(typeof(IEntity<int>),"int"),
                new KeyValuePair<Type,string>(typeof(IEntity<long>),"bigint"),
                new KeyValuePair<Type, string>(typeof(IEntity<Guid>),"uniqueidentifier"),
                new KeyValuePair<Type, string>(typeof(IEntity<string>),"varchar")
            };

            foreach (KeyValuePair<Type, string> tKey in tKeys)
            {
                foreach (Type type in Base.Util.GetAllTypesOf(tKey.Key)/*.Where(_ => _ != typeof(Entity<Guid>))*/)
                {
                    try
                    {
                        modelBuilder.Entity(type)
                                    .ToTable(type.Name)
                                    .Property("Id").HasColumnName("Id")
                                    .HasColumnType(tKey.Value)
                                    .HasDefaultValue()
                                    ;
                    }
                    catch { }
                }
            }
        }
    }
}

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace core.Extensions.Data
{
    public class AppDbContext : DbContext
    {
        static AppDbContext()
        {

        }
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var tKeys = new KeyValuePair<Type, int>[] {
                new KeyValuePair<Type,int>(typeof(IEntity<int>),11),
                new KeyValuePair<Type,int>(typeof(IEntity<long>),20),
                new KeyValuePair<Type, int>(typeof(IEntity<Guid>),36),
                new KeyValuePair<Type, int>(typeof(IEntity<string>),255)
            };

            foreach (KeyValuePair<Type, int> tKey in tKeys)
            {
                foreach (Type type in Base.Util.GetAllTypesOf(tKey.Key)/*.Where(_ => _ != typeof(Entity<Guid>))*/)
                {
                    try
                    {
                        modelBuilder.Entity(type)
                                    .ToTable(type.Name)
                                    .Property("Id").HasColumnName("Id")
                                    .IsUnicode(false)
                                    .HasMaxLength(tKey.Value)
                                    //.HasColumnType(tKey.Value)
                                    .HasDefaultValue()
                                    ;
                    }
                    catch { }
                }
            }
        }
    }
}

Fix EF sql column type unit

Fix EF sql column type unit


using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
using ReSharperExtensionsShared.Tests;

[assembly: RequiresSTA]

namespace ReSharperExtensionsShared.Tests
{
    [ZoneDefinition]
    public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
    {
    }

    [ZoneMarker]
    public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
    {
    }
}

// ReSharper disable once CheckNamespace
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
{
}

using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;

[assembly: RequiresSTA]

namespace ReSharperExtensionsShared.Tests
{
    [ZoneDefinition]
    public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
    {
    }

    [ZoneMarker]
    public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
    {
    }

    [SetUpFixture]
    public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
    {
    }
}

Move TestEnvironmentSetUpFixture into project root namespace


// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;

public partial class User32Facts
{
    [Fact]
    public void MessageBeep_Asterisk()
    {
        Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
    }
}

// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;

public partial class User32Facts
{
    [Fact]
    public void MessageBeep_Asterisk()
    {
        Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
    }

    [Fact]
    public void INPUT_Union()
    {
        INPUT i = default(INPUT);
        i.type = InputType.INPUT_HARDWARE;

        // Assert that the first field (type) has its own memory space.
        Assert.Equal(0u, i.hi.uMsg);
        Assert.Equal(0, (int)i.ki.wScan);
        Assert.Equal(0, i.mi.dx);

        // Assert that these three fields (hi, ki, mi) share memory space.
        i.hi.uMsg = 1;
        Assert.Equal(1, (int)i.ki.wVk);
        Assert.Equal(1, i.mi.dx);
    }
}

Add test for INPUT union

Add test for INPUT union


using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Grades.Tests
{
    [TestClass]
    public class GradeBookTests
    {
        private GradeStatistics _stats;

        public GradeBookTests()
        {
            var book = new GradeBook();

            book.AddGrade(90f);
            book.AddGrade(100f);
            book.AddGrade(50f);

            _stats = book.ComputeStatistics();
        }

        [TestMethod]
        public void CalculatesHighestGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }

        [TestMethod]
        public void CalculatesLowestGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }

        [TestMethod]
        public void CalculatesAveragaGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Grades.Tests
{
    [TestClass]
    public class GradeBookTests
    {
        private GradeStatistics _stats;

        public GradeBookTests()
        {
            var book = new GradeBook();

            book.AddGrade(90f);
            book.AddGrade(100f);
            book.AddGrade(50f);

            _stats = book.ComputeStatistics();
        }

        [TestMethod]
        public void CalculatesHighestGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }

        [TestMethod]
        public void CalculatesLowestGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }

        [TestMethod]
        public void CalculatesAverageGrade()
        {
            Assert.AreEqual(100f, _stats.HighestGrade);
        }
    }
}

Fix typo in CalculatesAverageGrade() test


using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;

namespace ruibarbo.core.Wpf.Base
{
    public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
        where TNativeElement : System.Windows.Window
    {
        public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
            : base(searchParent, frameworkElement)
        {
        }

        public void MakeSureWindowIsTopmost()
        {
            OnUiThread.Invoke(this, fe => fe.Activate());
        }
    }
}

using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;

namespace ruibarbo.core.Wpf.Base
{
    public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
        where TNativeElement : System.Windows.Window
    {
        public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
            : base(searchParent, frameworkElement)
        {
        }

        public void MakeSureWindowIsTopmost()
        {
            OnUiThread.Invoke(this, frameworkElement => frameworkElement.Activate());
        }

        public string Title
        {
            get { return OnUiThread.Get(this, frameworkElement => frameworkElement.Title); }
        }
    }
}

Support for Title on Windows.

Support for Title on Windows.


@using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;

@functions
{
    dynamic GetMainPartFromContentItem(ContentItem item)
    {
        // get the ContentPart that has the same name as the item's ContentType
        // so that we can access the item fields.
        var contentType = item.TypeDefinition.Name;
        var parts = item.Parts as List<ContentPart>;
        return parts.First(p => p.PartDefinition.Name.Equals(contentType));
    }
}

@{
    var contentItems = (Model.ContentItems as IEnumerable<ContentItem>);
    var cssClass = contentItems.First().TypeDefinition.Name.HtmlClassify();

        @foreach (ContentItem item in contentItems)
        {
            var itemDisplayUrl = Url.ItemDisplayUrl(item);
            // get the mainPart, so we can access the item's fields
            dynamic mainPart = GetMainPartFromContentItem(item);
            var firstName = mainPart.FirstName.Value;
            var lastName = mainPart.LastName.Value;
            var position = mainPart.Position.Value;
            var email = mainPart.Email.Value;
            //var associatedLcc = mainPart.

@firstName @lastName @position

        }

}

@using System.Dynamic;
@using System.Linq;
@using Orchard.ContentManagement;
@using Orchard.Utility.Extensions;

@functions
{
    dynamic GetMainPartFromContentItem(ContentItem item)
    {
        // get the ContentPart that has the same name as the item's ContentType
        // so that we can access the item fields.
        var contentType = item.TypeDefinition.Name;
        var parts = item.Parts as List<ContentPart>;
        return parts.First(p => p.PartDefinition.Name.Equals(contentType));
    }

    dynamic GetTermPartFromTaxonomyField(dynamic field, int index = 0)
    {
        // get the termPart at index in the taxonomy field
        return field !=null &&
            field.Terms != null &&
            field.Terms.Count > index ?
            field.Terms[index] : null;
    }
}

@{
    var contentItems = (Model.ContentItems as IEnumerable<ContentItem>);
    var cssClass = contentItems.First().TypeDefinition.Name.HtmlClassify();

        @foreach (ContentItem item in contentItems)
        {
            var itemDisplayUrl = Url.ItemDisplayUrl(item);
            // get the mainPart, so we can access the item's fields
            dynamic mainPart = GetMainPartFromContentItem(item);
            var firstName = mainPart.FirstName.Value;
            var lastName = mainPart.LastName.Value;
            var position = mainPart.Position.Value;
            var email = mainPart.Email.Value;
            var lccTermPart = GetTermPartFromTaxonomyField(mainPart.Lcc);
            var associatedLcc = lccTermPart != null ? lccTermPart.Name : string.Empty;

@firstName @lastName @position @email @associatedLcc

        }

}

Tweak the latest news view.

Tweak the latest news view.


using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;

namespace TodotxtTouch.WindowsPhone.Tasks
{
	public class TaskFilterFactory
	{
		private const char Delimiter = ',';

		public static TaskFilter CreateTaskFilterFromString(string filter)
		{
			if (filter.StartsWith("context:"))
			{
				string target = filter.Replace("context:", String.Empty);
				return new ContextTaskFilter(
					task => task.Contexts.Contains(target),
					target);
			}

			if (filter.StartsWith("project:"))
			{
				string target = filter.Replace("project: ", "+");
				return new ContextTaskFilter(
					task => task.Projects.Contains(target),
					target);
			}

			return null;
		}

		public static List<TaskFilter> ParseFilterString(string filter)
		{
			string[] filters = filter.Split(Delimiter);

			return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
		}

		public static string CreateFilterString(List<TaskFilter> filters)
		{
			return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
		}
	}
}

using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;

namespace TodotxtTouch.WindowsPhone.Tasks
{
	public class TaskFilterFactory
	{
		private const char Delimiter = ',';

		public static TaskFilter CreateTaskFilterFromString(string filter)
		{
			if (filter.StartsWith("context:"))
			{
				string target = filter.Replace("context:", String.Empty);
				return new ContextTaskFilter(
					task => task.Contexts.Contains(target),
					target);
			}

			if (filter.StartsWith("project:"))
			{
				string target = filter.Replace("project: ", "+");
				return new ProjectTaskFilter(
					task => task.Projects.Contains(target),
					target);
			}

			return null;
		}

		public static List<TaskFilter> ParseFilterString(string filter)
		{
			string[] filters = filter.Split(Delimiter);

			return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
		}

		public static string CreateFilterString(List<TaskFilter> filters)
		{
			return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
		}
	}
}

Fix attempting to filter by project filtered by context instead


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

using NUnit.Framework;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class DevicelessAudioTest : AudioThreadTest
    {
        public override void SetUp()
        {
            base.SetUp();

            // lose all devices
            Manager.SimulateDeviceLoss();
        }

        [Test]
        public void TestPlayTrackWithoutDevices()
        {
            var track = Manager.Tracks.Get("Tracks.sample-track.mp3");

            // start track
            track.Restart();
            Assert.IsTrue(track.IsRunning);

            CheckTrackIsProgressing(track);

            // stop track
            track.Stop();

            WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);

            Assert.IsFalse(track.IsRunning);

            // seek track
            track.Seek(0);

            Assert.IsFalse(track.IsRunning);
            WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
        }
    }
}

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

using NUnit.Framework;

namespace osu.Framework.Tests.Audio
{
    [TestFixture]
    public class DevicelessAudioTest : AudioThreadTest
    {
        public override void SetUp()
        {
            base.SetUp();

            // lose all devices
            Manager.SimulateDeviceLoss();
        }

        [Test]
        public void TestPlayTrackWithoutDevices()
        {
            var track = Manager.Tracks.Get("Tracks.sample-track.mp3");

            // start track
            track.Restart();

            WaitForOrAssert(() => track.IsRunning, "Track started", 1000);

            CheckTrackIsProgressing(track);

            // stop track
            track.Stop();

            WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);

            Assert.IsFalse(track.IsRunning);

            // seek track
            track.Seek(0);

            Assert.IsFalse(track.IsRunning);
            WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
        }
    }
}

Fix potential test failure due to not waiting long enough on track start