Fixed infinite recursion sound registering bug

--- src/Desktop/Core/Components/SettingsManager.cs
+++ src/Desktop/Core/Components/SettingsManager.cs
@@ -1,7 +1,7 @@
 // ****************************** Module Header ****************************** //
 //
 //
-// Last Modified: 04:07:2017 / 21:26
+// Last Modified: 16:07:2017 / 18:54
 // Creation: 24:06:2017
 // Project: AstroSoundBoard
 //
@@ -117,7 +117,7 @@
         /// Registers a Sound into the Manager.
         /// </summary>
         /// <param name="soundModel">Sound to be registered</param>
-        private static void Create(SoundModel soundModel)
+        private static void Add(SoundModel soundModel)
         {
             Log.Debug("Registering Definition!");
             Cache.Add(soundModel);
@@ -157,13 +157,13 @@
         {
             foreach (SoundModel item in Cache)
             {
-                if (item.Name == name.ToFileName())
+                if (item.Name == name.ToDisplayName())
                 {
                     return item;
                 }
             }

-            Create(new SoundModel { Name = name, IsFavorite = JsonConvert.False });
+            Add(new SoundModel { Name = name, IsFavorite = JsonConvert.False });
             return GetSound(name);
         }


declare friendship to web

declare friendship to web

--- src/Eshopworld.Core/Properties/AssemblyInfo.cs
+++ src/Eshopworld.Core/Properties/AssemblyInfo.cs
@@ -8,3 +8,6 @@

 [assembly: InternalsVisibleTo("Eshopworld.Messaging")]
 [assembly: InternalsVisibleTo("Eshopworld.Messaging.Tests")]
+
+[assembly: InternalsVisibleTo("Eshopworld.Web")]
+[assembly: InternalsVisibleTo("Eshopworld.Web.Tests")]


Switched to 1.1.8

Switched to 1.1.8

--- src/SharedVersionInfo.cs
+++ src/SharedVersionInfo.cs
@@ -1,5 +1,5 @@
 using System.Reflection;

-[assembly: AssemblyVersion("1.1.7")]
-[assembly: AssemblyFileVersion("1.1.7")]
-[assembly: AssemblyInformationalVersion("1.1.7")]+[assembly: AssemblyVersion("1.1.8")]
+[assembly: AssemblyFileVersion("1.1.8")]
+[assembly: AssemblyInformationalVersion("1.1.8")]


Switch to version 1.2.4

Switch to version 1.2.4

--- src/SharedVersionInfo.cs
+++ src/SharedVersionInfo.cs
@@ -1,5 +1,5 @@
 using System.Reflection;

-[assembly: AssemblyVersion("1.2.3")]
-[assembly: AssemblyFileVersion("1.2.3")]
-[assembly: AssemblyInformationalVersion("1.2.3")]
+[assembly: AssemblyVersion("1.2.4")]
+[assembly: AssemblyFileVersion("1.2.4")]
+[assembly: AssemblyInformationalVersion("1.2.4")]


Switch version to 1.3.1

Switch version to 1.3.1

--- src/SharedVersionInfo.cs
+++ src/SharedVersionInfo.cs
@@ -1,5 +1,5 @@
 using System.Reflection;

-[assembly: AssemblyVersion("1.3.0")]
-[assembly: AssemblyFileVersion("1.3.0")]
-[assembly: AssemblyInformationalVersion("1.3.0")]
+[assembly: AssemblyVersion("1.3.1")]
+[assembly: AssemblyFileVersion("1.3.1")]
+[assembly: AssemblyInformationalVersion("1.3.1")]


Small optimization in configuration

Small optimization in configuration

--- src/Kephas.Core/Configuration/Configuration.cs
+++ src/Kephas.Core/Configuration/Configuration.cs
@@ -104,7 +104,7 @@
             var factory = orderedFactories.FirstOrDefault(f => f.Metadata.SettingsType == typeof(TSettings));
             if (factory == null)
             {
-                factory = orderedFactories.FirstOrDefault(f => f.Metadata.SettingsType?.GetTypeInfo().IsAssignableFrom(typeof(TSettings).GetTypeInfo()) ?? false);
+                factory = orderedFactories.FirstOrDefault(f => f.Metadata.SettingsType?.IsAssignableFrom(typeof(TSettings)) ?? false);
                 if (factory == null)
                 {
                     factory = orderedFactories.FirstOrDefault(f => f.Metadata.SettingsType == null);


Lucene.Net.Core.Index.TieredMergePolicy refactor: renamed fields camelCase

--- src/Lucene.Net.Core/Index/TieredMergePolicy.cs
+++ src/Lucene.Net.Core/Index/TieredMergePolicy.cs
@@ -336,19 +336,19 @@

         private class SegmentByteSizeDescending : IComparer<SegmentCommitInfo>
         {
-            private readonly TieredMergePolicy OuterInstance;
+            private readonly TieredMergePolicy outerInstance;

             public SegmentByteSizeDescending(TieredMergePolicy outerInstance)
             {
-                this.OuterInstance = outerInstance;
+                this.outerInstance = outerInstance;
             }

             public virtual int Compare(SegmentCommitInfo o1, SegmentCommitInfo o2)
             {
                 try
                 {
-                    long sz1 = OuterInstance.Size(o1);
-                    long sz2 = OuterInstance.Size(o2);
+                    long sz1 = outerInstance.Size(o1);
+                    long sz2 = outerInstance.Size(o2);
                     if (sz1 > sz2)
                     {
                         return -1;
@@ -641,25 +641,25 @@

         private class MergeScoreAnonymousInnerClassHelper : MergeScore
         {
-            private readonly TieredMergePolicy OuterInstance;
-
-            private double Skew;
-            private double NonDelRatio;
-            private double FinalMergeScore;
+            private readonly TieredMergePolicy outerInstance;
+
+            private double skew;
+            private double nonDelRatio;
+            private double finalMergeScore;

             public MergeScoreAnonymousInnerClassHelper(TieredMergePolicy outerInstance, double skew, double nonDelRatio, double finalMergeScore)
             {
-                this.OuterInstance = outerInstance;
-                this.Skew = skew;
-                this.NonDelRatio = nonDelRatio;
-                this.FinalMergeScore = finalMergeScore;
+                this.outerInstance = outerInstance;
+                this.skew = skew;
+                this.nonDelRatio = nonDelRatio;
+                this.finalMergeScore = finalMergeScore;
             }

             internal override double Score
             {
                 get
                 {
-                    return FinalMergeScore;
+                    return finalMergeScore;
                 }
             }

@@ -667,7 +667,7 @@
             {
                 get
                 {
-                    return "skew=" + string.Format(CultureInfo.InvariantCulture, "%.3f", Skew) + " nonDelRatio=" + string.Format(CultureInfo.InvariantCulture, "%.3f", NonDelRatio);
+                    return "skew=" + string.Format(CultureInfo.InvariantCulture, "%.3f", skew) + " nonDelRatio=" + string.Format(CultureInfo.InvariantCulture, "%.3f", nonDelRatio);
                 }
             }
         }


TestFSTs: Added LongRunningTest and Ignore attributes for applicable tests.

--- src/Lucene.Net.Tests/core/Util/Fst/TestFSTs.cs
+++ src/Lucene.Net.Tests/core/Util/Fst/TestFSTs.cs
@@ -1,10 +1,14 @@
+using Lucene.Net.Attributes;
+using Lucene.Net.Randomized.Generators;
+using Lucene.Net.Support;
+using NUnit.Framework;
 using System;
+using System.Collections.Generic;
 using System.Diagnostics;
-using System.Collections.Generic;
+using System.Globalization;
 using System.IO;
 using System.Linq;
 using System.Text;
-using Lucene.Net.Randomized.Generators;

 namespace Lucene.Net.Util.Fst
 {
@@ -25,46 +29,38 @@
      * limitations under the License.
      */

-    using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
-    using Document = Lucene.Net.Documents.Document;
-    using Field = Lucene.Net.Documents.Field;
-    using DirectoryReader = Lucene.Net.Index.DirectoryReader;
-    using IndexReader = Lucene.Net.Index.IndexReader;
-    using IndexWriter = Lucene.Net.Index.IndexWriter;
-    using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
-    using MultiFields = Lucene.Net.Index.MultiFields;
-    using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
-    using Term = Lucene.Net.Index.Term;
-    using Terms = Lucene.Net.Index.Terms;
-    using TermsEnum = Lucene.Net.Index.TermsEnum;
-    using IndexSearcher = Lucene.Net.Search.IndexSearcher;
-    using TermQuery = Lucene.Net.Search.TermQuery;
-    using Directory = Lucene.Net.Store.Directory;
-    using FSDirectory = Lucene.Net.Store.FSDirectory;
-    using IOContext = Lucene.Net.Store.IOContext;
-    using IndexInput = Lucene.Net.Store.IndexInput;
-    using IndexOutput = Lucene.Net.Store.IndexOutput;
-    using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
     //using Slow = Lucene.Net.Util.LuceneTestCase.Slow;
-    using SuppressCodecs = Lucene.Net.Util.LuceneTestCase.SuppressCodecs;
     using Automaton = Lucene.Net.Util.Automaton.Automaton;
-    using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;
-    using RegExp = Lucene.Net.Util.Automaton.RegExp;
     //using InputOutput = Lucene.Net.Util.Fst.BytesRefFSTEnum.InputOutput;
     //using Arc = Lucene.Net.Util.Fst.FST.Arc;
     using BytesReader = Lucene.Net.Util.Fst.FST.BytesReader;
-    using Pair = Lucene.Net.Util.Fst.PairOutputs<long?, long?>.Pair;
+    using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;
+    using Directory = Lucene.Net.Store.Directory;
+    using DirectoryReader = Lucene.Net.Index.DirectoryReader;
+    using Document = Lucene.Net.Documents.Document;
+    using Field = Lucene.Net.Documents.Field;
+    using FSDirectory = Lucene.Net.Store.FSDirectory;
+    using IndexInput = Lucene.Net.Store.IndexInput;
+    using IndexOutput = Lucene.Net.Store.IndexOutput;
+    using IndexReader = Lucene.Net.Index.IndexReader;
+    using IndexSearcher = Lucene.Net.Search.IndexSearcher;
+    using IndexWriter = Lucene.Net.Index.IndexWriter;
+    using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
+    using IOContext = Lucene.Net.Store.IOContext;
+    using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
+    using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
+    using MultiFields = Lucene.Net.Index.MultiFields;
     //using ResultLong = Lucene.Net.Util.Fst.Util.Result<long?>;
     //using ResultPair = Lucene.Net.Util.Fst.Util.Result<long?>;
     using PackedInts = Lucene.Net.Util.Packed.PackedInts;
-    using Lucene.Net.Support;
-    using NUnit.Framework;
-    using System.Globalization;
-
-    /*
-    import static Lucene.Net.Util.Fst.FSTTester.GetRandomString;
-    import static Lucene.Net.Util.Fst.FSTTester.SimpleRandomString;
-    import static Lucene.Net.Util.Fst.FSTTester.ToIntsRef;*/
+    using Pair = Lucene.Net.Util.Fst.PairOutputs<long?, long?>.Pair;
+    using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
+    using RegExp = Lucene.Net.Util.Automaton.RegExp;
+    using Term = Lucene.Net.Index.Term;
+    using TermQuery = Lucene.Net.Search.TermQuery;
+    using Terms = Lucene.Net.Index.Terms;
+    using TermsEnum = Lucene.Net.Index.TermsEnum;
+

     [TestFixture]
     public class TestFSTs : LuceneTestCase
@@ -269,7 +265,7 @@
         }

-        [Test]
+        [Test, LongRunningTest, Timeout(27000000)] // 45 minutes to be on the safe side
         public virtual void TestRandomWords()
         {
             TestRandomWords(1000, AtLeast(2));
@@ -313,6 +309,7 @@
         }

         [Test]
+        [Ignore("LUCENENET TODO: This test will take around 10-14 hours to finish. It was marked with a Nightly attribute in the original Java source, but we don't currently have a corresponding attribute")]
         public virtual void TestBigSet()
         {
             TestRandomWords(TestUtil.NextInt(Random(), 50000, 60000), 1);


namespace rename

namespace rename

Former-commit-id: 88a54d7c12426d13b636fa7678ce65fb27252c98

--- src/MassTransit.Reactive.Tests/BasicExample.cs
+++ src/MassTransit.Reactive.Tests/BasicExample.cs
@@ -10,15 +10,14 @@
 // 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.
-namespace MassTransit.Tests.Reactive.Samples
+namespace MassTransit.Reactive.Tests
 {
 	using System;
 	using System.Reactive.Linq;
 	using Magnum.Extensions;
 	using Magnum.TestFramework;
-	using MassTransit.Reactive;
 	using NUnit.Framework;
-	using TestFramework;
+	using MassTransit.TestFramework;

 	[Scenario, Explicit("Fails from command-line build, don't know why, so I'm removing it from the build")]
 	public class BasicExample :


Update AsyncLazy.cs

Update AsyncLazy.cs

--- src/Meziantou.Framework/Utilities/AsyncLazy.cs
+++ src/Meziantou.Framework/Utilities/AsyncLazy.cs
@@ -46,7 +46,7 @@
             }
         }

-        public void Dipose()
+        public void Dispose()
         {
             _semaphoreSlim.Dispose();
         }


Removed a #warning

Removed a #warning

svn path=/trunk/bitsharp/; revision=92185

--- src/MonoTorrent/Client/Managers/FileManager.cs
+++ src/MonoTorrent/Client/Managers/FileManager.cs
@@ -244,7 +244,7 @@
         {
             try
             {
-#warning Store all the fast resume in a 'data' file in a known location instead?
+                // FIXME: #warning Store all the fast resume in a 'data' file in a known location instead?
                 // If we don't know where the .torrent is on disk, then don't save
                 // fast resume data.
                 if (string.IsNullOrEmpty(manager.Torrent.TorrentPath))


Adjusted text. See issue #17.

Adjusted text. See issue #17.

--- src/MyTryHard/Controllers/TrackerController.cs
+++ src/MyTryHard/Controllers/TrackerController.cs
@@ -34,7 +34,7 @@
             tvm.SportsList = _ctx.Tracker.GetSportsList();
             ViewBag.PieData = new ChartData();
             GeneratePieItemsFromTracker(tvm, ViewBag.PieData);
-            ViewBag.PieData.Title = "Proportions d'entrées des sports";
+            ViewBag.PieData.Title = "Proportions de suivi des sports";
             return View(tvm);
         }


Fixing compiler error.

Fixing compiler error.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@3053

--- src/NHibernate.Search/LuceneQueryExpression.cs
+++ src/NHibernate.Search/LuceneQueryExpression.cs
@@ -19,7 +19,7 @@
 			this.luceneQuery = luceneQuery;
 		}

-		public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, System.Collections.IDictionary enabledFilters)
+		public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters)
 		{
 			System.Type type = GetCriteriaClass(criteria);
 			SearchFactory searchFactory = SearchFactory.GetSearchFactory(GetSession(criteria));


Attempt to fix the Mono build by not using an extension method. We may need to revisit this if we ever want to expose any extension methods, but by then we may understand the situation better.

--- src/NodaTime/TimeZones/ZoneEqualityComparer.cs
+++ src/NodaTime/TimeZones/ZoneEqualityComparer.cs
@@ -9,17 +9,6 @@

 namespace NodaTime.TimeZones
 {
-    /// <summary>
-    /// Extension method to make it easier to handle options.
-    /// </summary>
-    internal static class ZoneEqualityComparerOptionsExtensions
-    {
-        internal static bool Includes(this ZoneEqualityComparer.Options options, ZoneEqualityComparer.Options candidate)
-        {
-            return (options & candidate) != 0;
-        }
-    }
-
     /// <summary>
     /// Equality comparer for time zones, comparing specific aspects of the zone intervals within
     /// a time zone for a specific interval of the time line.
@@ -77,6 +66,15 @@
             PreciseMatch = MatchNames | MatchOffsetComponents | MatchAllTransitions | MatchStartAndEndTransitions
         }

+        /// <summary>
+        /// Checks whether the given set of options includes the candidate one. This would be an extension method, but
+        /// that causes problems on Mono at the moment.
+        /// </summary>
+        private static bool CheckOption(Options options, Options candidate)
+        {
+            return (options & candidate) != 0;
+        }
+
         private readonly Interval interval;
         private readonly Options options;
         private readonly ZoneIntervalEqualityComparer zoneIntervalComparer;
@@ -159,7 +157,7 @@
         private IEnumerable<ZoneInterval> GetIntervals(DateTimeZone zone)
         {
             var unelided = zone.GetAllZoneIntervals(interval.Start, interval.End);
-            return options.Includes(Options.MatchAllTransitions) ? unelided : ElideIntervals(unelided);
+            return CheckOption(options, Options.MatchAllTransitions) ? unelided : ElideIntervals(unelided);
         }

         private IEnumerable<ZoneInterval> ElideIntervals(IEnumerable<ZoneInterval> zoneIntervals)
@@ -213,7 +211,7 @@
             public int GetHashCode(ZoneInterval obj)
             {
                 int hash = HashCodeHelper.Initialize();
-                if (options.Includes(Options.MatchOffsetComponents))
+                if (CheckOption(options, Options.MatchOffsetComponents))
                 {
                     hash = HashCodeHelper.Hash(hash, obj.StandardOffset);
                     hash = HashCodeHelper.Hash(hash, obj.Savings);
@@ -222,7 +220,7 @@
                 {
                     hash = HashCodeHelper.Hash(hash, obj.WallOffset);
                 }
-                if (options.Includes(Options.MatchNames))
+                if (CheckOption(options, Options.MatchNames))
                 {
                     hash = HashCodeHelper.Hash(hash, obj.Name);
                 }
@@ -233,13 +231,13 @@

             private Instant GetEffectiveStart(ZoneInterval zoneInterval)
             {
-                return options.Includes(Options.MatchStartAndEndTransitions)
+                return CheckOption(options, Options.MatchStartAndEndTransitions)
                     ? zoneInterval.Start : Instant.Max(zoneInterval.Start, interval.Start);
             }

             private Instant GetEffectiveEnd(ZoneInterval zoneInterval)
             {
-                return options.Includes(Options.MatchStartAndEndTransitions)
+                return CheckOption(options, Options.MatchStartAndEndTransitions)
                     ? zoneInterval.End : Instant.Min(zoneInterval.End, interval.End);
             }

@@ -256,11 +254,11 @@
                 }
                 // As we've already compared wall offsets, we only need to compare savings...
                 // If the savings are equal, the standard offset will be too.
-                if (options.Includes(Options.MatchOffsetComponents) && x.Savings != y.Savings)
-                {
-                    return false;
-                }
-                if (options.Includes(Options.MatchNames) && x.Name != y.Name)
+                if (CheckOption(options, Options.MatchOffsetComponents) && x.Savings != y.Savings)
+                {
+                    return false;
+                }
+                if (CheckOption(options, Options.MatchNames) && x.Name != y.Name)
                 {
                     return false;
                 }


Use ISO 8601 format for date times

Use ISO 8601 format for date times

Fixes #6973

--- src/Orchard/ContentManagement/IHqlCriterion.cs
+++ src/Orchard/ContentManagement/IHqlCriterion.cs
@@ -133,8 +133,8 @@

                     return EncodeQuotes(Convert.ToString(value, CultureInfo.InvariantCulture));
                 case TypeCode.DateTime:
-                    // convert the date time to a valid string representation for Hql
-                    var sortableDateTime = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
+                    // convert the date time to a valid string representation for Hql (ISO 8601 format, which is language neutral)
+                    var sortableDateTime = ((DateTime)value).ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
                     return quoteStrings ? String.Concat("'", EncodeQuotes(sortableDateTime), "'") : sortableDateTime;
             }


Allow for null short and long strings

Allow for null short and long strings

--- src/RabbitMQClient/WritableBufferExtensions.cs
+++ src/RabbitMQClient/WritableBufferExtensions.cs
@@ -24,6 +24,12 @@

         public static void WriteShortString(this WritableBuffer buffer, string value)
         {
+            if (value == null)
+            {
+                buffer.WriteBigEndian<byte>(0);
+                return;
+            }
+
             var valueBytes = Encoding.UTF8.GetBytes(value);

             if (valueBytes.Length > byte.MaxValue)
@@ -37,6 +43,12 @@

         public static void WriteLongString(this WritableBuffer buffer, string value)
         {
+            if (value == null)
+            {
+                buffer.WriteBigEndian<byte>(0);
+                return;
+            }
+
             var valueBytes = Encoding.UTF8.GetBytes(value);

             buffer.WriteBigEndian((uint)valueBytes.Length);


Guard against nullpoiner in default strategy

--- src/RawRabbit/ErrorHandling/DefaultStrategy.cs
+++ src/RawRabbit/ErrorHandling/DefaultStrategy.cs
@@ -30,10 +30,10 @@

 			rawConsumer.Model.BasicPublish(
 				exchange: string.Empty,
-				routingKey: args.BasicProperties?.ReplyTo,
+				routingKey: args.BasicProperties?.ReplyTo ?? String.Empty,
 				basicProperties: new BasicProperties
 				{
-					CorrelationId = args.BasicProperties?.CorrelationId,
+					CorrelationId = args.BasicProperties?.CorrelationId ?? string.Empty,
 					Headers = new Dictionary<string, object>
 					{
 						{ExceptionHeader, _messageExceptionName }


Replace Funq registration with Autofac registration.

--- src/ServiceStack/ServiceHost/ServiceManager.cs
+++ src/ServiceStack/ServiceHost/ServiceManager.cs
@@ -144,16 +144,9 @@
         {
             var serviceType = serviceImplementation.GetType();

-            this.ServiceController.RegisterNService(typeFactory, serviceType);
-
-            //Container.Register<TService>(TService instance)
-            var containerType = typeof(Container);
-            var registrationMethodGeneric = containerType.GetMethods()
-                .Where(x => x.Name == "Register")
-                .Select(y => new { Method = y, Parameters = y.GetParameters() })
-                .Single(z => z.Parameters.Length == 1 && !z.Parameters[0].ParameterType.IsGenericType);
-            var registrationMethod = registrationMethodGeneric.Method.MakeGenericMethod(serviceType);
-            registrationMethod.Invoke(this.Container, new object[] { serviceImplementation });
+            DependencyService.RegisterSingletonInstance(serviceImplementation, serviceType);
+
+            this.ServiceController.RegisterNService(serviceType, DependencyService);
         }

 		public object Execute(object dto)


minor fixes to async orders processing

minor fixes to async orders processing

--- src/ShipStationAccess/V2/ShipStationService.cs
+++ src/ShipStationAccess/V2/ShipStationService.cs
@@ -134,7 +134,7 @@
 						currentPage++;
 						ordersCount += ordersWithinPage.Orders.Count;

-						processOrders( ordersWithinPage );
+						await processOrders( ordersWithinPage );
 					} );
 				} while( currentPage <= pagesCount );


Using the IsEmpty property

Using the IsEmpty property

--- src/SimpleSoft.IniParser/Impl/IniNormalizer.cs
+++ src/SimpleSoft.IniParser/Impl/IniNormalizer.cs
@@ -291,7 +291,7 @@
                 throw new ArgumentNullException(nameof(destination));

             if (!Options.IncludeEmptyProperties)
-                source = source.Where(e => !string.IsNullOrWhiteSpace(e.Value));
+                source = source.Where(e => !e.IsEmpty);

             //  creates a normalized copy of all properties
             var itemsToCopy = source.Select(Normalize);
@@ -334,7 +334,7 @@
                 throw new ArgumentNullException(nameof(destination));

             if (!Options.IncludeEmptyProperties)
-                source = source.Where(e => !string.IsNullOrWhiteSpace(e.Value));
+                source = source.Where(e => !e.IsEmpty);

             var itemsToCopy = new List<IniProperty>();
             foreach (var property in source)


Comments

Comments

--- src/SourceCode.Clay.Threading/ParallelAsync.cs
+++ src/SourceCode.Clay.Threading/ParallelAsync.cs
@@ -2,31 +2,39 @@
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
+using System.Runtime.CompilerServices;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Threading.Tasks.Dataflow;

 namespace SourceCode.Clay.Threading
 {
+    /// <summary>
+    /// Provides support for asynchronous looping.
+    /// </summary>
     public static class ParallelAsync
     {
         #region For

-        public static async Task ForAsync(int from, int to, ParallelOptions options, Func<int, Task> action)
+        /// <summary>
+        /// Executes a For loop in which executions may run asynchronously.
+        /// </summary>
+        /// <param name="fromInclusive">The start index, inclusive.</param>
+        /// <param name="toExclusive">The end index, exclusive.</param>
+        /// <param name="options">Options that control the loop execution.</param>
+        /// <param name="action">The delegate that is invoked once per iteration.</param>
+        /// <returns></returns>
+        public static async Task ForAsync(int fromInclusive, int toExclusive, ParallelOptions options, Func<int, Task> action)
         {
-            if (to < from) throw new ArgumentOutOfRangeException(nameof(to));
+            if (toExclusive < fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
             if (action == null) throw new ArgumentNullException(nameof(action));

-            var opt = new ExecutionDataflowBlockOptions
-            {
-                CancellationToken = options == null ? CancellationToken.None : options.CancellationToken,
-                MaxDegreeOfParallelism = options == null ? -1 : options.MaxDegreeOfParallelism
-            };
+            var opt = Build(options);

             var block = new ActionBlock<int>(action, opt);

             // Send
-            for (var i = from; i < to; i++)
+            for (var i = fromInclusive; i < toExclusive; i++)
             {
                 await block.SendAsync(i, opt.CancellationToken).ConfigureAwait(false);
             }
@@ -35,29 +43,34 @@
             await block.Completion;
         }

-        public static async Task<IReadOnlyDictionary<int, TValue>> ForAsync<TValue>(int from, int to, ParallelOptions options, Func<int, Task<TValue>> func)
+        /// <summary>
+        /// Executes a For loop in which executions may run in parallel. Returns a set of correlated values.
+        /// </summary>
+        /// <typeparam name="TValue">The type of items to return.</typeparam>
+        /// <param name="fromInclusive">The start index, inclusive.</param>
+        /// <param name="toExclusive">The end index, exclusive.</param>
+        /// <param name="options">Options that control the loop execution.</param>
+        /// <param name="func">The delegate that is invoked once per iteration.</param>
+        /// <returns></returns>
+        public static async Task<IReadOnlyDictionary<int, TValue>> ForAsync<TValue>(int fromInclusive, int toExclusive, ParallelOptions options, Func<int, Task<TValue>> func)
         {
-            if (to < from) throw new ArgumentOutOfRangeException(nameof(to));
+            if (toExclusive < fromInclusive) throw new ArgumentOutOfRangeException(nameof(toExclusive));
             if (func == null) throw new ArgumentNullException(nameof(func));

             var dict = new ConcurrentDictionary<int, TValue>();

-            var opt = new ExecutionDataflowBlockOptions
-            {
-                CancellationToken = options == null ? CancellationToken.None : options.CancellationToken,
-                MaxDegreeOfParallelism = options == null ? -1 : options.MaxDegreeOfParallelism
-            };
+            var opt = Build(options);

             var block = new TransformBlock<int, TValue>(func, opt);

             // Send
-            for (var i = from; i < to; i++)
+            for (var i = fromInclusive; i < toExclusive; i++)
             {
                 await block.SendAsync(i, opt.CancellationToken).ConfigureAwait(false);
             }

             // Receive
-            for (var i = from; i < to; i++)
+            for (var i = fromInclusive; i < toExclusive; i++)
             {
                 var value = await block.ReceiveAsync(opt.CancellationToken).ConfigureAwait(false);
                 dict[i] = value;
@@ -73,16 +86,20 @@

         #region ForEach

+        /// <summary>
+        /// Executes a ForEach loop in which executions may run in parallel.
+        /// </summary>
+        /// <typeparam name="TSource">The type of items in the source data.</typeparam>
+        /// <param name="source">An enumerable data source.</param>
+        /// <param name="options">Options that control the loop execution.</param>
+        /// <param name="action">The delegate that is invoked once per iteration.</param>
+        /// <returns></returns>
         public static async Task ForEachAsync<TSource>(IEnumerable<TSource> source, ParallelOptions options, Func<TSource, Task> action)
         {
             if (source == null) return;
             if (action == null) throw new ArgumentNullException(nameof(action));

-            var opt = new ExecutionDataflowBlockOptions
-            {
-                CancellationToken = options == null ? CancellationToken.None : options.CancellationToken,
-                MaxDegreeOfParallelism = options == null ? -1 : options.MaxDegreeOfParallelism
-            };
+            var opt = Build(options);

             var block = new ActionBlock<TSource>(action, opt);

@@ -96,6 +113,15 @@
             await block.Completion;
         }

+        /// <summary>
+        /// Executes a ForEach loop in which executions may run in parallel. Returns a set of correlated values.
+        /// </summary>
+        /// <typeparam name="TSource">The type of items in the source data.</typeparam>
+        /// <typeparam name="TValue">The type of items to return.</typeparam>
+        /// <param name="source">An enumerable data source.</param>
+        /// <param name="options">Options that control the loop execution.</param>
+        /// <param name="func">The delegate that is invoked once per iteration.</param>
+        /// <returns></returns>
         public static async ValueTask<IReadOnlyDictionary<TSource, TValue>> ForEachAsync<TSource, TValue>(IEnumerable<TSource> source, ParallelOptions options, Func<TSource, Task<KeyValuePair<TSource, TValue>>> func)
         {
             if (source == null) return EmptyDictionaryImpl<TSource, TValue>.ReadOnlyValue;
@@ -103,11 +129,7 @@

             var dict = new ConcurrentDictionary<TSource, TValue>();

-            var opt = new ExecutionDataflowBlockOptions
-            {
-                CancellationToken = options == null ? CancellationToken.None : options.CancellationToken,
-                MaxDegreeOfParallelism = options == null ? -1 : options.MaxDegreeOfParallelism
-            };
+            var opt = Build(options);

             var block = new TransformBlock<TSource, KeyValuePair<TSource, TValue>>(func, opt);

@@ -133,5 +155,17 @@
         }

         #endregion
+
+        #region Helpers
+
+        [MethodImpl(MethodImplOptions.AggressiveInlining)]
+        private static ExecutionDataflowBlockOptions Build(ParallelOptions options)
+        => new ExecutionDataflowBlockOptions
+        {
+            CancellationToken = options == null ? CancellationToken.None : options.CancellationToken,
+            MaxDegreeOfParallelism = options == null ? -1 : options.MaxDegreeOfParallelism
+        };
+
+        #endregion
     }
 }


Add tests to exercise sbyte string constructors with invalid UTF8 characters on Unix (#27789)

--- src/System.Runtime/tests/System/StringTests.cs
+++ src/System.Runtime/tests/System/StringTests.cs
@@ -2857,6 +2857,19 @@
         }

         [Fact]
+        [PlatformSpecific(TestPlatforms.AnyUnix)] // These tests assume that UTF8 is the default encoding
+        public static unsafe void ConstructorsTest_InvalidUTF8()
+        {
+            byte[] invalidUTF8Bytes = new byte[] { (byte)'A', (byte)'B', 0xEE, (byte)'C', (byte)'D', 0 };
+
+            fixed (byte* pBytes = invalidUTF8Bytes)
+            {
+                Assert.Equal("AB\ufffdCD", new String((sbyte*)pBytes));
+                Assert.Equal("B\ufffdC", new String((sbyte*)pBytes, 1, 3));
+            }
+        }
+
+        [Fact]
         public static unsafe void CloneTest()
         {
             string s = "some string to clone";


OPTIMIZATION SetRefFieldValue: don't copy on write if settings to the same value.

--- src/Sooda/SoodaObject.cs
+++ src/Sooda/SoodaObject.cs
@@ -1137,6 +1137,14 @@
             }
         }

+        void SetFieldValue(int fieldOrdinal, object value)
+        {
+            CopyOnWrite();
+            _fieldValues.SetFieldValue(fieldOrdinal, value);
+            SetFieldDirty(fieldOrdinal, true);
+            SetObjectDirty();
+        }
+
         internal void SetPlainFieldValue(int tableNumber, string fieldName, int fieldOrdinal, object newValue, SoodaFieldUpdateDelegate before, SoodaFieldUpdateDelegate after)
         {
             EnsureFieldsInited();
@@ -1152,12 +1160,7 @@

                     if (before != null)
                         before(oldValue, newValue);
-
-                    CopyOnWrite();
-                    _fieldValues.SetFieldValue(fieldOrdinal, newValue);
-                    SetFieldDirty(fieldOrdinal, true);
-                    SetObjectDirty();
-
+                    SetFieldValue(fieldOrdinal, newValue);
                     if (after != null)
                         after(oldValue, newValue);

@@ -1170,10 +1173,7 @@
             else
             {
                 // optimization here - we don't even need to load old values from database
-                CopyOnWrite();
-                _fieldValues.SetFieldValue(fieldOrdinal, newValue);
-                SetFieldDirty(fieldOrdinal, true);
-                SetObjectDirty();
+                SetFieldValue(fieldOrdinal, newValue);
             }
         }

@@ -1188,7 +1188,6 @@

             EnsureFieldsInited();
             EnsureDataLoaded(tableNumber);
-            CopyOnWrite();

             SoodaObject oldValue = null;

@@ -1216,10 +1215,8 @@
                     listInternal.InternalRemove(this);
                 }
             }
-            _fieldValues.SetFieldValue(fieldOrdinal, newValue != null ? newValue.GetPrimaryKeyValue() : null);
-            SetFieldDirty(fieldOrdinal, true);
+            SetFieldValue(fieldOrdinal, newValue != null ? newValue.GetPrimaryKeyValue() : null);
             refcache[refCacheOrdinal] = null;
-            SetObjectDirty();
             if (newValue != null && backRefCollections != null)
             {
                 foreach (string collectionName in backRefCollections)
@@ -1508,8 +1505,7 @@
         {
             if (FromCache)
             {
-                SoodaObjectFieldValues newFieldValues = _fieldValues.Clone();
-                _fieldValues = newFieldValues;
+                _fieldValues = _fieldValues.Clone();
                 FromCache = false;
             }
         }


removed aggressive empty checks, employed some format standards

--- src/AspNet.Identity.RavenDB/Stores/RavenUserStore.cs
+++ src/AspNet.Identity.RavenDB/Stores/RavenUserStore.cs
@@ -57,9 +57,9 @@

         public Task<TUser> FindByIdAsync(string userId)
         {
-            if (string.IsNullOrWhiteSpace(userId))
-            {
-                throw new ArgumentException("Input cannot be null, empty or white space", "userId");
+            if (userId == null)
+            {
+                throw new ArgumentNullException("userId");
             }

             return GetUser(userId);
@@ -67,9 +67,9 @@

         public Task<TUser> FindByNameAsync(string userName)
         {
-            if (string.IsNullOrWhiteSpace(userName))
-            {
-                throw new ArgumentException("Input cannot be null, empty or white space", "userName");
+            if (userName == null)
+            {
+                throw new ArgumentNullException("userName");
             }

             return GetUserByUserName(userName);
@@ -131,14 +131,8 @@

         public Task AddLoginAsync(TUser user, UserLoginInfo login)
         {
-            if (user == null)
-            {
-                throw new ArgumentNullException("user");
-            }
-            if (login == null)
-            {
-                throw new ArgumentNullException("login");
-            }
+            if (user == null) throw new ArgumentNullException("user");
+            if (login == null) throw new ArgumentNullException("login");

             user.Logins.Add(new RavenUserLogin(login));
             return Task.FromResult(0);
@@ -146,14 +140,8 @@

         public Task RemoveLoginAsync(TUser user, UserLoginInfo login)
         {
-            if (user == null)
-            {
-                throw new ArgumentNullException("user");
-            }
-            if (login == null)
-            {
-                throw new ArgumentNullException("login");
-            }
+            if (user == null) throw new ArgumentNullException("user");
+            if (login == null) throw new ArgumentNullException("login");

             RavenUserLogin userLogin = user.Logins
                 .FirstOrDefault(lgn => lgn.LoginProvider == login.LoginProvider && lgn.ProviderKey == login.ProviderKey);
@@ -180,14 +168,8 @@

         public Task AddClaimAsync(TUser user, Claim claim)
         {
-            if (user == null)
-            {
-                throw new ArgumentNullException("user");
-            }
-            if (claim == null)
-            {
-                throw new ArgumentNullException("claim");
-            }
+            if (user == null) throw new ArgumentNullException("user");
+            if (claim == null) throw new ArgumentNullException("claim");

             user.Claims.Add(new RavenUserClaim(claim));
             return Task.FromResult(0);
@@ -195,14 +177,8 @@

         public Task RemoveClaimAsync(TUser user, Claim claim)
         {
-            if (user == null)
-            {
-                throw new ArgumentNullException("user");
-            }
-            if (claim == null)
-            {
-                throw new ArgumentNullException("claim");
-            }
+            if (user == null) throw new ArgumentNullException("user");
+            if (claim == null) throw new ArgumentNullException("claim");

             RavenUserClaim userClaim = user.Claims
                 .FirstOrDefault(clm => clm.ClaimType == claim.Type && clm.ClaimValue == claim.Value);
@@ -243,6 +219,7 @@
             {
                 throw new ArgumentNullException("user");
             }
+
             user.PasswordHash = passwordHash;
             return Task.FromResult(0);
         }
@@ -290,7 +267,7 @@
             }

             user.IsTwoFactorEnabled = enabled;
-            return Task.FromResult<int>(0);
+            return Task.FromResult(0);
         }

         // IUserEmailStore


Tweak minigun projectile missed enemy effect.

--- game/server/weapons/minigun.projectile.gfx.red.cs
+++ game/server/weapons/minigun.projectile.gfx.red.cs
@@ -350,7 +350,7 @@

 	textureName = "share/textures/rotc/corona";

-	colors[0]	  = "1.0 0.0 1.0 1.0";
+	colors[0]	  = "1.0 0.0 1.0 0.25";
 	colors[1]	  = "1.0 0.0 1.0 0.0";
 	sizes[0]		= 1.0;
 	sizes[1]		= 0.0;


Some none cross platform safe tests

Some none cross platform safe tests

--- src/AutoTest.Test/Core/FileSystem/PathParserTests.cs
+++ src/AutoTest.Test/Core/FileSystem/PathParserTests.cs
@@ -1,6 +1,7 @@
 using System;
 using NUnit.Framework;
 using AutoTest.Core.FileSystem;
+using System.IO;
 namespace AutoTest.Test.Core.FileSystem
 {
 	[TestFixture]
@@ -9,13 +10,23 @@
 		[Test]
 		public void When_no_relative_path_it_should_return_passed_path()
 		{
-			Assert.That(new PathParser(".ignorefile").ToAbsolute("/some/reference/path"), Is.EqualTo("/some/reference/path/.ignorefile"));
+            var path = "/some/reference/path";
+            if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX)
+                path = @"C:\some\reference\path";
+			Assert.That(new PathParser(".ignorefile").ToAbsolute(path), Is.EqualTo(Path.Combine(path, ".ignorefile")));
 		}

 		[Test]
 		public void When_relative_path_it_should_return_path_relative_to_passed_path()
 		{
-			Assert.That(new PathParser("../.ignorefile").ToAbsolute("/some/reference/path"), Is.EqualTo("/some/reference/.ignorefile"));
+            var path = "/some/reference/path";
+            var relative = "/some/reference";
+            if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX)
+            {
+                path = @"C:\some\reference\path";
+                relative = @"C:\some\reference";
+            }
+			Assert.That(new PathParser("../.ignorefile").ToAbsolute(path), Is.EqualTo(Path.Combine(relative, ".ignorefile")));
 		}
 	}
 }


Add Equals implementation to the TransformedBounds

--- src/Avalonia.Visuals/VisualTree/TransformedBounds.cs
+++ src/Avalonia.Visuals/VisualTree/TransformedBounds.cs
@@ -50,5 +50,41 @@
                 return Bounds.Contains(point);
             }
         }
+
+        public bool Equals(TransformedBounds other)
+        {
+            return Bounds == other.Bounds && Clip == other.Clip && Transform == other.Transform;
+        }
+
+        public override bool Equals(object obj)
+        {
+            if (obj is null)
+            {
+                return false;
+            }
+
+            return obj is TransformedBounds other && Equals(other);
+        }
+
+        public override int GetHashCode()
+        {
+            unchecked
+            {
+                var hashCode = Bounds.GetHashCode();
+                hashCode = (hashCode * 397) ^ Clip.GetHashCode();
+                hashCode = (hashCode * 397) ^ Transform.GetHashCode();
+                return hashCode;
+            }
+        }
+
+        public static bool operator ==(TransformedBounds left, TransformedBounds right)
+        {
+            return left.Equals(right);
+        }
+
+        public static bool operator !=(TransformedBounds left, TransformedBounds right)
+        {
+            return !left.Equals(right);
+        }
     }
 }


asdfwqsefg

asdfwqsefg

--- teethris.NET/Snake.cs
+++ teethris.NET/Snake.cs
@@ -33,7 +33,7 @@

         public void ChangeHead(KeyboardNames key)
         {
-            SetLighting(this.Head, this.color, 30);
+            SetLighting(this.Head, this.color, 50);
             this.Head = key;
             SetLighting(this.Head, this.color, 100);
             this.Size += 1;


Fix warning.

Fix warning.

--- src/Workspaces/CSharpTest/Json/CSharpJsonTests.cs
+++ src/Workspaces/CSharpTest/Json/CSharpJsonTests.cs
@@ -118,10 +118,9 @@
                 {
                     JToken.Parse(token.ValueText);
                 }
-                catch (Exception ex)
+                catch (Exception)
                 {
                     Assert.NotEmpty(tree.Diagnostics);
-                    // Assert.True(tree.Diagnostics.Any(d => e.Message.Contains(d.Message)));
                     return tree;
                 }


Ensure a media type correctly inherits it's selected parent

(cherry picked from commit ab63d2664c14b72e8d19b31d0963964dbc92dd50)

--- src/Umbraco.Web/Editors/MediaTypeController.cs
+++ src/Umbraco.Web/Editors/MediaTypeController.cs
@@ -19,6 +19,7 @@
 using Umbraco.Core.Logging;
 using Umbraco.Core.Persistence;
 using Umbraco.Web.Composing;
+using IMediaType = Umbraco.Core.Models.IMediaType;

 namespace Umbraco.Web.Editors
 {
@@ -135,12 +136,18 @@
         }
         public MediaTypeDisplay GetEmpty(int parentId)
         {
-            var ct = new MediaType(parentId)
-            {
-                Icon = Constants.Icons.MediaImage
-            };
-
-            var dto = Mapper.Map<IMediaType, MediaTypeDisplay>(ct);
+            IMediaType mt;
+            if (parentId != Constants.System.Root)
+            {
+                var parent = Services.MediaTypeService.Get(parentId);
+                mt = parent != null ? new MediaType(parent, string.Empty) : new MediaType(parentId);
+            }
+            else
+                mt = new MediaType(parentId);
+
+            mt.Icon = Constants.Icons.MediaImage;
+
+            var dto = Mapper.Map<IMediaType, MediaTypeDisplay>(mt);
             return dto;
         }


Give some initial time for 0+N time controls

--- src/ChessVariantsTraining/Models/Variant960/Clock.cs
+++ src/ChessVariantsTraining/Models/Variant960/Clock.cs
@@ -1,4 +1,5 @@
 using MongoDB.Bson.Serialization.Attributes;
+using System;
 using System.Diagnostics;

 namespace ChessVariantsTraining.Models.Variant960
@@ -29,7 +30,7 @@
         public Clock(TimeControl tc) : this()
         {
             Increment = tc.Increment;
-            SecondsLeftAfterLatestMove = tc.InitialSeconds;
+            SecondsLeftAfterLatestMove = tc.InitialSeconds != 0 ? tc.InitialSeconds : Math.Max(tc.Increment, 3);
         }

         public void Start()


Refactor EqualsStateTrigger.

Refactor EqualsStateTrigger.

--- src/WindowsStateTriggers/EqualsStateTrigger.cs
+++ src/WindowsStateTriggers/EqualsStateTrigger.cs
@@ -70,33 +70,33 @@
 			{
 				return true;
 			}
-			if (value1 != null && value2 != null)
+			if (value1 != null && value2 != null && value1.GetType() != value2.GetType() && convertType)
 			{
-				//Let's see if we can convert - for perf reasons though, try and use the right type in and out
-				if (value1.GetType() != value2.GetType() && convertType)
+				if (ConvertTypeEquals(value1, value2))
 				{
-					if (value2 is Enum)
-					{
-						value1 = Enum.ToObject(value2.GetType(), value1);
-					}
-					var t2 = Convert.ChangeType(value1, value2.GetType(), CultureInfo.InvariantCulture);
-					if (value2.Equals(t2))
-					{
-						return true;
-					}
-					//try the other way around
-					if (value1 is Enum)
-					{
-						value2 = Enum.ToObject(value1.GetType(), value2);
-					}
-					t2 = Convert.ChangeType(value2, value1.GetType(), CultureInfo.InvariantCulture);
-					if (value1.Equals(t2))
-					{
-						return true;
-					}
+					return true;
+				}
+				// Try the other way around:
+				if (ConvertTypeEquals(value2, value1))
+				{
+					return true;
 				}
 			}
 			return false;
+		}
+
+		private static bool ConvertTypeEquals(object value1, object value2)
+		{
+			// Let's see if we can convert:
+			if (value2 is Enum)
+			{
+				value1 = Enum.ToObject(value2.GetType(), value1);
+			}
+			else
+			{
+				value1 = Convert.ChangeType(value1, value2.GetType(), CultureInfo.InvariantCulture);
+			}
+			return value2.Equals(value1);
 		}

 		#region ITriggerValue


Don't block during tests.

Don't block during tests.

--- src/Workspaces/CoreTest/FindReferencesTests.cs
+++ src/Workspaces/CoreTest/FindReferencesTests.cs
@@ -2,6 +2,7 @@

 using System.Collections.Generic;
 using System.Linq;
+using System.Threading.Tasks;
 using Microsoft.CodeAnalysis;
 using Microsoft.CodeAnalysis.CSharp;
 using Microsoft.CodeAnalysis.CSharp.Symbols;
@@ -31,7 +32,7 @@
         }

         [Fact]
-        public void FindFieldReferencesInSingleDocumentProject()
+        public async Task FindFieldReferencesInSingleDocumentProject()
         {
             var text = @"
 public class C {
@@ -45,15 +46,15 @@
 ";
             var solution = GetSingleDocumentSolution(text);
             var project = solution.Projects.First();
-            var symbol = project.GetCompilationAsync().Result.GetTypeByMetadataName("C").GetMembers("X").First();
-
-            var result = SymbolFinder.FindReferencesAsync(symbol, solution).Result.ToList();
+            var symbol = (await project.GetCompilationAsync()).GetTypeByMetadataName("C").GetMembers("X").First();
+
+            var result = (await SymbolFinder.FindReferencesAsync(symbol, solution)).ToList();
             Assert.Equal(1, result.Count); // 1 symbol found
             Assert.Equal(3, result[0].Locations.Count()); // 3 locations found
         }

         [Fact]
-        public void FindTypeReference_DuplicateMetadataReferences()
+        public async Task FindTypeReference_DuplicateMetadataReferences()
         {
             var text = @"
 public class C {
@@ -69,9 +70,9 @@
                            .AddDocument(did, "foo.cs", SourceText.From(text));

             var project = solution.Projects.First();
-            var symbol = (IFieldSymbol)project.GetCompilationAsync().Result.GetTypeByMetadataName("C").GetMembers("X").First();
-
-            var result = SymbolFinder.FindReferencesAsync(symbol.Type, solution).Result.ToList();
+            var symbol = (IFieldSymbol)(await project.GetCompilationAsync()).GetTypeByMetadataName("C").GetMembers("X").First();
+
+            var result = (await SymbolFinder.FindReferencesAsync(symbol.Type, solution)).ToList();
             Assert.Equal(9, result.Count);

             var typeSymbol = result.Where(@ref => @ref.Definition.Kind == SymbolKind.NamedType).Single();
@@ -79,7 +80,7 @@
         }

         [Fact]
-        public void PinvokeMethodReferences_VB()
+        public async Task PinvokeMethodReferences_VB()
         {
             var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                 @"
@@ -112,14 +113,14 @@
             ProjectId prj1Id = ProjectId.CreateNewId();
             DocumentId docId = DocumentId.CreateNewId(prj1Id);

-            Microsoft.CodeAnalysis.Solution sln = new AdhocWorkspace().CurrentSolution
+            Solution sln = new AdhocWorkspace().CurrentSolution
                 .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                 .AddMetadataReference(prj1Id, MscorlibRef)
                 .AddDocument(docId, "testFile", tree.GetText());

-            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
-            tree = prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
-            Compilation comp = prj.GetCompilationAsync().Result;
+            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
+            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();
+            Compilation comp = await prj.GetCompilationAsync();

             SemanticModel semanticModel = comp.GetSemanticModel(tree);

@@ -128,17 +129,17 @@

             // declared method calls
             var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
-            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
+            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);
             Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

             // normal method calls
             symbol = semanticModel.GetDeclaredSymbol(normalMethod);
-            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
+            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);
             Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
         }

         [Fact]
-        public void PinvokeMethodReferences_CS()
+        public async Task PinvokeMethodReferences_CS()
         {
             var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                 @"
@@ -188,9 +189,9 @@
                 .AddMetadataReference(prj1Id, MscorlibRef)
                 .AddDocument(docId, "testFile", tree.GetText());

-            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));
-            tree = prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
-            Compilation comp = prj.GetCompilationAsync().Result;
+            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));
+            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();
+            Compilation comp = await prj.GetCompilationAsync();

             SemanticModel semanticModel = comp.GetSemanticModel(tree);

@@ -200,17 +201,17 @@

             // pinvoke method calls
             var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
-            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
+            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);
             Assert.Equal(2, references.ElementAt(0).Locations.Count());

             // normal method calls
             symbol = semanticModel.GetDeclaredSymbol(normalMethod);
-            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
+            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);
             Assert.Equal(2, references.ElementAt(0).Locations.Count());
         }

         [Fact, WorkItem(537936, "DevDiv")]
-        public void FindReferences_InterfaceMapping()
+        public async Task FindReferences_InterfaceMapping()
         {
             var text = @"
 abstract class C
@@ -231,12 +232,12 @@
 ";
             var solution = GetSingleDocumentSolution(text);
             var project = solution.Projects.First();
-            var comp = project.GetCompilationAsync().Result;
+            var comp = await project.GetCompilationAsync();

             // Find references on definition B.Boo()
             var typeB = comp.GetTypeByMetadataName("B");
             var boo = typeB.GetMembers("Boo").First();
-            var result = SymbolFinder.FindReferencesAsync(boo, solution).Result.ToList();
+            var result = (await SymbolFinder.FindReferencesAsync(boo, solution)).ToList();
             Assert.Equal(2, result.Count); // 2 symbols found

             HashSet<int> expectedMatchedLines = new HashSet<int> { 3, 13, 14 };
@@ -247,7 +248,7 @@
             // Find references on definition C.Boo()
             var typeC = comp.GetTypeByMetadataName("C");
             boo = typeC.GetMembers("Boo").First();
-            result = SymbolFinder.FindReferencesAsync(boo, solution).Result.ToList();
+            result = (await SymbolFinder.FindReferencesAsync(boo, solution)).ToList();
             Assert.Equal(2, result.Count); // 2 symbols found

             expectedMatchedLines = new HashSet<int> { 3, 13, 14 };
@@ -258,7 +259,7 @@
             // Find references on definition A.Boo()
             var typeA = comp.GetTypeByMetadataName("A");
             boo = typeA.GetMembers("Boo").First();
-            result = SymbolFinder.FindReferencesAsync(boo, solution).Result.ToList();
+            result = (await SymbolFinder.FindReferencesAsync(boo, solution)).ToList();
             Assert.Equal(2, result.Count); // 2 symbols found

             expectedMatchedLines = new HashSet<int> { 7, 12 };


Update RoslynScriptRunner.cs

Update RoslynScriptRunner.cs

--- src/Core2D/ScriptRunner/Roslyn/RoslynScriptRunner.cs
+++ src/Core2D/ScriptRunner/Roslyn/RoslynScriptRunner.cs
@@ -1,5 +1,6 @@
 #if !_CORERT
 using System;
+using System.Threading.Tasks;
 using Core2D.Editor;
 using Core2D.Interfaces;
 using Microsoft.CodeAnalysis.CSharp.Scripting;
@@ -24,21 +25,15 @@
         }

         /// <inheritdoc/>
-        public void Execute(string code)
+        public async Task<object> Execute(string code)
         {
-            ScriptState<object> state = null;
-
             var options = ScriptOptions.Default
                 .WithImports("System");

-            var globals = new EditorScript
-            {
-                Editor = _serviceProvider.GetService<IProjectEditor>()
-            };
-
             try
             {
-                state = CSharpScript.RunAsync(code, options, globals).Result;
+                var editor = _serviceProvider.GetService<IProjectEditor>();
+                return await CSharpScript.RunAsync(code, options, editor);
             }
             catch (CompilationErrorException ex)
             {
@@ -46,18 +41,17 @@
                 log?.LogException(ex);
                 log?.LogError($"{Environment.NewLine}{ex.Diagnostics}");
             }
+            return null;
         }

         /// <inheritdoc/>
-        public object Execute(string code, object state)
+        public async Task<object> Execute(string code, object state)
         {
-            ScriptState<object> next = null;
-
             if (state is ScriptState<object> previous)
             {
                 try
                 {
-                    next = previous.ContinueWithAsync(code).Result;
+                    return await previous.ContinueWithAsync(code);
                 }
                 catch (CompilationErrorException ex)
                 {
@@ -65,20 +59,15 @@
                     log?.LogException(ex);
                     log?.LogError($"{Environment.NewLine}{ex.Diagnostics}");
                 }
-                return next;
             }

             var options = ScriptOptions.Default
                 .WithImports("System");

-            var globals = new EditorScript
-            {
-                Editor = _serviceProvider.GetService<IProjectEditor>()
-            };
-
             try
             {
-                next = CSharpScript.RunAsync(code, options, globals).Result;
+                var editor = _serviceProvider.GetService<IProjectEditor>();
+                return await CSharpScript.RunAsync(code, options, editor);
             }
             catch (CompilationErrorException ex)
             {
@@ -87,7 +76,7 @@
                 log?.LogError($"{Environment.NewLine}{ex.Diagnostics}");
             }

-            return next;
+            return null;
         }
     }
 }


Limit the number of threads during batch conversion

If not specified, .NET will keep using more threads if the CPU isn't completely active. If the bottleneck is disk I/O, more threads will be spawned, creating a positive feedback loop that results in 400+ threads using 6+ GB of memory. All while only using ~5% CPU on a 4-core machine. I don't know whether I should be amused or horrified.

--- src/VGAudio.Cli/Batch.cs
+++ src/VGAudio.Cli/Batch.cs
@@ -21,7 +21,7 @@
             {
                 progress.SetTotal(files.Length);

-                Parallel.ForEach(files, inPath =>
+                Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 }, inPath =>
                 {
                     string relativePath = inPath.Substring(options.InDir.Length).TrimStart('\\');
                     string outPath = Path.ChangeExtension(Path.Combine(options.OutDir, relativePath), options.OutTypeName);
@@ -32,7 +32,7 @@

                     try
                     {
-                       progress.LogMessage(Path.GetFileName(inPath));
+                        progress.LogMessage(Path.GetFileName(inPath));
                         Convert.ConvertFile(options, jobFiles, false);
                     }
                     catch (Exception ex)


fixed tests

fixed tests

--- src/Maestro.Tests/Factories/type_instance_factory.cs
+++ src/Maestro.Tests/Factories/type_instance_factory.cs
@@ -1,5 +1,4 @@
 using Shouldly;
-using System;
 using System.Collections.Generic;
 using Xunit;

@@ -91,7 +90,6 @@
 													{
 														x.Use<IEnumerable<int>>().Instance(ints);
 														x.Use<IEnumerable<string>>().Instance(strings);
-														x.Use(typeof(IGeneric<,>)).Type(typeof(Generic<,>));
 													});

 			var instanceWithInts = container.GetService<OptionalDependency<IEnumerable<int>>>();
@@ -99,14 +97,7 @@

 			instanceWithInts.Dependency.ShouldBe(ints);
 			instanceWithStrings.Dependency.ShouldBe(strings);
-
-			container.GetService<IGeneric<int, object>>();
-
-			throw new Exception(container.Diagnostics.WhatDoIHave());
 		}
-
-		interface IGeneric<T1, T2> { }
-		class Generic<T1, T2> : IGeneric<T1, T2> { }

 		[Fact]
 		public void should_use_custom_parameter_values()


Avoid disposing of ErrorPixbuf

Avoid disposing of ErrorPixbuf

This leads to a crash on next iteration.

--- src/Widgets/SlideShow.cs
+++ src/Widgets/SlideShow.cs
@@ -90,7 +90,7 @@
 			if (running)
 				flip.Start ();
 			lock (sync_handle) {
-				if (prev != null)
+				if (prev != null && prev != PixbufUtils.ErrorPixbuf)
 					prev.Dispose ();
 				prev = next;


update

update

--- src/AttributeMapping.cs
+++ src/AttributeMapping.cs
@@ -15,7 +15,7 @@
         private bool   _CanWrite     = true;
         private bool   _Compulsory   = false;
         private bool   _Ignore       = false;
-        private bool   _NonPrintable = false;
+        private bool   _NonPrintable = true;
         private bool   _Nullable     = false;
         private bool   _PrimaryKey   = false;
         private bool   _Readonly     = true;
@@ -39,7 +39,6 @@
         private string _Status       = "";
         private string _TableName    = "";
         private string _TypeChar     = "c";
-        private string _Axis         = "";
         private string _enabledMode  = "";
         private string _format       = "";

@@ -52,7 +51,7 @@
         public bool AutoIdentity      { get { return _AutoIdentity; } set { _AutoIdentity = value; }  }
         public bool Compulsory        { get { return _Compulsory;   } set { _Compulsory   = value; }  }
         public bool Ignore            { get { return _Ignore;       } set { _Ignore       = value; }  }
-        public bool NonPrintable      { get { return _NonPrintable; } set { _NonPrintable = value; }  }
+        public bool Hidden            { get { return _NonPrintable; } set { _NonPrintable = value; }  }
         public bool Nullable          { get { return _Nullable;     } set { _Nullable     = value; }  }
         public bool PrimaryKey        { get { return _PrimaryKey;   } set { _PrimaryKey   = value; }  }
         public bool Readonly          { get { return _Readonly;     } set { _Readonly     = value; }  }
@@ -77,33 +76,11 @@
         public string Status          { get { return _Status;       } set { _Status       = value; }  }
         public string TableName       { get { return _TableName;    } set { _TableName    = value; }  }
         public string TypeChar        { get { return _TypeChar;     } set { _TypeChar     = value; }  }
-        public string Axis            { get { return _Axis;         } set { _Axis         = value; }  }
         public string Format          { get { return _format;       } set { _format       = value; }  }
         public JSONObject Props       { get { return _Props;        } set { _Props        = value; }  }
         public List<JSONObject> Group { get { return _Group;        } set { _Group        = value; }  }

         public bool CanWrite     { get { return _CanWrite && !_AutoIdentity; } set { _CanWrite     = value; }  }
-
-        public string ClassName
-        {
-            get {
-                string _ccss = "";
-
-                if (this.Compulsory) {
-                    _ccss = _ccss + "r";
-                } else {
-                    _ccss = _ccss + "n";
-                }
-
-                if (this.Readonly) {
-                    _ccss = _ccss + "v";
-                } else {
-                    _ccss = _ccss + "e";
-                }
-
-                return "c" + this.TypeChar + _ccss;
-            }
-        }

         public string this[string name]
         {


Update WebHost.cs (#986)

Update WebHost.cs (#986)

--- src/Microsoft.AspNetCore.Hosting/Internal/WebHost.cs
+++ src/Microsoft.AspNetCore.Hosting/Internal/WebHost.cs
@@ -131,7 +131,6 @@
                 }
             }

-            // REVIEW: Is this the right place to log these errors?
             if (_hostingStartupErrors != null)
             {
                 foreach (var exception in _hostingStartupErrors.InnerExceptions)


Optimize stack trace string allocations.

--- src/MiniProfiler.Shared/Helpers/StackTraceSnippet.cs
+++ src/MiniProfiler.Shared/Helpers/StackTraceSnippet.cs
@@ -1,7 +1,7 @@
-using System.Collections.Generic;
-using System.Diagnostics;
+using System.Diagnostics;
 using System.Linq;
 using System.Reflection;
+using System.Text;

 namespace StackExchange.Profiling.Helpers
 {
@@ -22,14 +22,14 @@
 #if NET46
             var frames = new StackTrace().GetFrames();
 #else // TODO: Make this work in .NET Standard, true fix isn't until 2.0 via https://github.com/dotnet/corefx/pull/12527
-            var frames = Enumerable.Empty<StackFrame>();
+            StackFrame[] frames = null;
 #endif
             if (frames == null || MiniProfiler.Settings.StackMaxLength <= 0)
             {
                 return "";
             }

-            var methods = new List<string>();
+            var sb = new StringBuilder();
             int stackLength = -1; // Starts on -1 instead of zero to compensate for adding 1 first time

             foreach (StackFrame t in frames)
@@ -48,12 +48,16 @@
                     && !MiniProfiler.Settings.AssembliesToExclude.Contains(assembly)
                     && !MiniProfiler.Settings.MethodsToExclude.Contains(method.Name))
                 {
-                    methods.Add(method.Name);
+                    if (sb.Length > 0)
+                    {
+                        sb.Append(" ");
+                    }
+                    sb.Append(method.Name);
                     stackLength += method.Name.Length + 1; // 1 added for spaces.
                 }
             }

-            return string.Join(" ", methods);
+            return sb.ToString();
         }

         private static bool ShouldExcludeType(MethodBase method)


Only show the 'brownouts'-message for networks that actually contain power suppliers.

--- src/Mirage.Urbanization/Networks/PowerNetworkInfo.cs
+++ src/Mirage.Urbanization/Networks/PowerNetworkInfo.cs
@@ -88,7 +88,7 @@
                 powerConsumer.TogglePowered((availableContributionUnits > 0));
                 powerConsumer.ToggleConnected(suppliers.Any());

-                if (availableContributionUnits <= 0)
+                if (availableContributionUnits <= 0 && suppliers.Any())
                     _onBrownoutsMessageFunc("Brownouts. Build another power plant.");
             }
             return new PowerGridNetworkStatistics(


The other test for the same fixed issue (fixed in the last commit)

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@4092

--- src/NHibernate.Test/NHSpecificTest/NH1677/Fixture.cs
+++ src/NHibernate.Test/NHSpecificTest/NH1677/Fixture.cs
@@ -1,14 +1,12 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
+using System.Collections;
 using System.Data;
-using System.Text;
+using NHibernate.Cfg;
 using NUnit.Framework;

 namespace NHibernate.Test.NHSpecificTest.NH1677
 {
-	[TestFixture,Ignore]
-	public class EntityModeMapCriteria:BugTestCase
+	[TestFixture]
+	public class EntityModeMapCriteria : BugTestCase
 	{
 		private const int NumberOfRecordPerEntity = 10;
 		private const string Entity1Name = "Entity1";
@@ -17,18 +15,17 @@
 		private const string Entity2Property = "Entity2Property";
 		private const string EntityPropertyPrefix = "Record";

-		protected override void Configure(NHibernate.Cfg.Configuration configuration)
+		protected override void Configure(Configuration configuration)
 		{
 			base.Configure(configuration);
-			configuration.SetProperty("default_entity_mode",
-			                          EntityModeHelper.ToString(EntityMode.Map));
+			configuration.SetProperty("default_entity_mode", EntityModeHelper.ToString(EntityMode.Map));
 		}

 		protected override void OnSetUp()
 		{
-			using (var s = OpenSession())
+			using (ISession s = OpenSession())
 			{
-				using (var tx = s.BeginTransaction(IsolationLevel.ReadCommitted))
+				using (ITransaction tx = s.BeginTransaction(IsolationLevel.ReadCommitted))
 				{
 					for (int i = 0; i < NumberOfRecordPerEntity; i++)
 					{
@@ -47,39 +44,39 @@
 				}
 			}
 		}
+
 		protected override void OnTearDown()
 		{
-			using(var s=OpenSession())
+			using (ISession s = OpenSession())
 			{
-				using(var tx=s.BeginTransaction())
+				using (ITransaction tx = s.BeginTransaction())
 				{
 					s.Delete(string.Format("from {0}", Entity1Name));
+					s.Delete(string.Format("from {0}", Entity2Name));
 					tx.Commit();
 				}
-
 			}
 		}
+
 		[Test]
 		public void EntityModeMapFailsWithCriteria()
 		{
-			using (var sf = cfg.BuildSessionFactory())
+			using (ISessionFactory sf = cfg.BuildSessionFactory())
 			{
-
-				using (var s = sf.OpenSession())
+				using (ISession s = sf.OpenSession())
 				{
-					var query = s.CreateQuery(string.Format("from {0}", Entity1Name));
-					var entity1List = query.List();
-					Assert.AreEqual(NumberOfRecordPerEntity, entity1List.Count);  // OK, Count == 10
+					IQuery query = s.CreateQuery(string.Format("from {0}", Entity1Name));
+					IList entity1List = query.List();
+					Assert.AreEqual(NumberOfRecordPerEntity, entity1List.Count); // OK, Count == 10
 				}

-				using (var s = sf.OpenSession())
+				using (ISession s = sf.OpenSession())
 				{
-					var entity1Criteria = s.CreateCriteria(Entity1Name);
-					var entity1List = entity1Criteria.List();
-					Assert.AreEqual(NumberOfRecordPerEntity, entity1List.Count);  // KO !!! Count == 20 !!!
+					ICriteria entity1Criteria = s.CreateCriteria(Entity1Name);
+					IList entity1List = entity1Criteria.List();
+					Assert.AreEqual(NumberOfRecordPerEntity, entity1List.Count); // KO !!! Count == 20 !!!
 				}
 			}
 		}
 	}
-
-}
+}


Fix API Key Authentication attribute which wasn't picking up apiKey value.

--- src/NuGetGallery/Filters/ApiKeyAuthorizeAttribute.cs
+++ src/NuGetGallery/Filters/ApiKeyAuthorizeAttribute.cs
@@ -25,7 +25,7 @@
             }

             var controller = filterContext.Controller;
-            string apiKeyStr = (string)((Controller)controller).RouteData.Values["apiKey"];
+            string apiKeyStr = (string)filterContext.ActionParameters["apiKey"];
             filterContext.Result = CheckForResult(apiKeyStr);
         }


delet5e old co0mment

delet5e old co0mment

--- src/OpenInApp.Common/Helpers/GeneralOptionsHelper.cs
+++ src/OpenInApp.Common/Helpers/GeneralOptionsHelper.cs
@@ -58,7 +58,6 @@
             return searchPaths;
         }

-        // private static string GetPath(string executableFileToBrowseFor, ActualPathToExeDto actualPathToExeDto)
         private static string GetPath(string executableFileToBrowseFor, InitialFolderType initialFolderType, string secondaryFilePathSegment)
         {
             string path = null;


LeftPad StationCellId with zeros

LeftPad StationCellId with zeros

--- src/OpenProtocolInterpreter/Communication/Mid0002.cs
+++ src/OpenProtocolInterpreter/Communication/Mid0002.cs
@@ -390,7 +390,7 @@
                             {
                                 new DataField((int)DataFields.SEQUENCE_NUMBER_SUPPORT, 173, 1),
                                 new DataField((int)DataFields.LINKING_HANDLING_SUPPORT, 176, 1),
-                                new DataField((int)DataFields.STATION_CELL_ID, 179, 10),
+                                new DataField((int)DataFields.STATION_CELL_ID, 179, 10, '0', DataField.PaddingOrientations.LEFT_PADDED),
                                 new DataField((int)DataFields.STATION_CELL_NAME, 191, 25),
                                 new DataField((int)DataFields.CLIENT_ID, 218, 1)
                             }


#116 - Changed stats controller to use ActionResult

--- SoraBot/SoraBot.WebApi/Controllers/StatsController.cs
+++ SoraBot/SoraBot.WebApi/Controllers/StatsController.cs
@@ -34,7 +34,7 @@
             }

             using var proc = Process.GetCurrentProcess();
-            return new SoraStats()
+            var soraStats = new SoraStats()
             {
                 Version = _config.SoraVersion,
                 Ping = _client.Latency,
@@ -45,6 +45,7 @@
                 CommandsExecuted = GlobalConstants.CommandsExecuted,
                 MessagesReceived = GlobalConstants.MessagesReceived.ToString()
             };
+            return Ok(soraStats);
         }
     }
 }


Fixed authentication issue mentioned in this issue https://github.com/managedfusion/fluentcassandra/issues/119

--- src/CassandraSession.cs
+++ src/CassandraSession.cs
@@ -149,7 +149,7 @@

 			try
 			{
-				GetClient(setLogin: false).login(auth);
+				GetClient(setKeyspace: false, setLogin: false).login(auth);
 				IsAuthenticated = true;
 			}
 			catch (Exception exc)


Fix possible NRE in QuartzHostedService.StopAsync (#1124)

Fix `NullReferenceException` in `QuartzHostedService.StopAsync` if
`StartAsync` has not been run.

`StartAsync` won't run if there's another hosted service that is registered
earlier and throws in its `StartAsync`. Exception in `StartAsync` causes
Asp.Net Core to begin shutdown during which all hosted services are stopped
via `StopAsync`.

--- src/Quartz.Extensions.Hosting/QuartzHostedService.cs
+++ src/Quartz.Extensions.Hosting/QuartzHostedService.cs
@@ -26,9 +26,12 @@
             await scheduler.Start(cancellationToken);
         }

-        public Task StopAsync(CancellationToken cancellationToken)
+        public async Task StopAsync(CancellationToken cancellationToken)
         {
-            return scheduler.Shutdown(options.Value.WaitForJobsToComplete, cancellationToken);
+            if (scheduler != null)
+            {
+                await scheduler.Shutdown(options.Value.WaitForJobsToComplete, cancellationToken);
+            }
         }
     }
 }


ReportsManager: improving and simplifying code

--- projects/Epicycle.Commons_cs/Reporting/ReportsManager.cs
+++ projects/Epicycle.Commons_cs/Reporting/ReportsManager.cs
@@ -19,7 +19,6 @@
 using Epicycle.Commons.FileSystem;
 using Epicycle.Commons.FileSystemBasedObjects;
 using System.Collections.Generic;
-using System.Text;

 namespace Epicycle.Commons.Reporting
 {
@@ -45,7 +44,10 @@
             {
                 if (!_reports.ContainsKey(id))
                 {
-                    _reports[id] = new SerializableReport();
+                    var report = new SerializableReport();
+                    report.Prefix = string.Format("######## ID: {0}\n", id);
+
+                    _reports[id] = report;
                 }

                 return _reports[id];
@@ -56,14 +58,9 @@
         {
             lock (_lock)
             {
-                var report = GetOrInitReport(id);
-                var data = new StringBuilder();
-                data.AppendFormat("ID: {0}\n", id);
-                data.Append(report.Serialize());
-
                 var reportFilePath = Path.Join(string.Format("{0}.report", FileSystemPathUtils.SanitizePathString(id)));

-                FileSystem.WriteTextFile(reportFilePath, data.ToString());
+                FileSystem.WriteReport(reportFilePath, GetOrInitReport(id), append: false);
             }
         }
     }


Fix wrong condition check

Fix wrong condition check

--- src/Seq.Client.Log4Net/Client/Log4Net/SeqAppender.cs
+++ src/Seq.Client.Log4Net/Client/Log4Net/SeqAppender.cs
@@ -44,10 +44,8 @@
             }
             set
             {
-                if (value.EndsWith("/"))
-                {
+                if (!value.EndsWith("/"))
                     value += "/";
-                }

                 _httpClient.BaseAddress = new Uri(value);
             }


Added overloads for the GetAuthorizationUrl method

--- src/Skybrud.Social.GitHub/OAuth/GitHubOAuthClient.cs
+++ src/Skybrud.Social.GitHub/OAuth/GitHubOAuthClient.cs
@@ -144,6 +144,28 @@
         /// <param name="state">A unique state for the request.</param>
         /// <param name="scope">The scope of your application.</param>
         /// <returns>A <see cref="String"/> with the authorization URL.</returns>
+        public string GetAuthorizationUrl(string state, GitHubScope scope) {
+            return GetAuthorizationUrl(state, scope == null ? null : new GitHubScopeCollection(scope));
+        }
+
+        /// <summary>
+        /// Gets an authorization URL using the specified <paramref name="state"/> and request the specified
+        /// <paramref name="scope"/>.
+        /// </summary>
+        /// <param name="state">A unique state for the request.</param>
+        /// <param name="scope">The scope of your application.</param>
+        /// <returns>A <see cref="String"/> with the authorization URL.</returns>
+        public string GetAuthorizationUrl(string state, params GitHubScope[] scope) {
+            return GetAuthorizationUrl(state, scope == null ? null : new GitHubScopeCollection(scope));
+        }
+
+        /// <summary>
+        /// Gets an authorization URL using the specified <paramref name="state"/> and request the specified
+        /// <paramref name="scope"/>.
+        /// </summary>
+        /// <param name="state">A unique state for the request.</param>
+        /// <param name="scope">The scope of your application.</param>
+        /// <returns>A <see cref="String"/> with the authorization URL.</returns>
         public string GetAuthorizationUrl(string state, GitHubScopeCollection scope) {
             return GetAuthorizationUrl(state, scope == null ? "" : scope.ToString());
         }
@@ -164,7 +186,7 @@

             // Initialize the query string
             IHttpQueryString query = new SocialHttpQueryString {
-                { "client_id", ClientId },
+                {"client_id", ClientId },
                 {"redirect_uri", RedirectUri},
                 {"state", state}
             };


Wtf?

Wtf?

Seems like I've forgot to commit this file when releasing beta1. The release however is build with the correct version number.

--- src/Skybrud.Social/Properties/AssemblyInfoVersion.cs
+++ src/Skybrud.Social/Properties/AssemblyInfoVersion.cs
@@ -1,5 +1,5 @@
 using System.Reflection;

 [assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyInformationalVersion("1.0.0-alpha5")]
+[assembly: AssemblyInformationalVersion("1.0.0-beta1")]
 [assembly: AssemblyMetadata("StartDate", "2012-07-30")]


Fix hang in HttpListener test

Fix hang in HttpListener test

--- src/System.Net.HttpListener/tests/SimpleHttpTests.cs
+++ src/System.Net.HttpListener/tests/SimpleHttpTests.cs
@@ -117,8 +117,13 @@
             }
         }

-        [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
-        public async Task UnknownHeaders_Success()
+        [ActiveIssue(19754)] // Recombine into UnknownHeaders_Success when fixed
+        [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
+        public Task UnknownHeaders_Success_Large() => UnknownHeaders_Success(1000);
+
+        [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
+        [InlineData(100)]
+        public async Task UnknownHeaders_Success(int numHeaders)
         {
             Task<HttpListenerContext> server = _listener.GetContextAsync();

@@ -128,15 +133,22 @@

                 HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, _factory.ListeningUrl);

-                for (int i = 0; i < 1000; i++)
+                for (int i = 0; i < numHeaders; i++)
                 {
                     requestMessage.Headers.Add($"custom{i}", i.ToString());
                 }

                 Task<HttpResponseMessage> clientTask = client.SendAsync(requestMessage);
+
+                if (clientTask == await Task.WhenAny(server, clientTask))
+                {
+                    (await clientTask).EnsureSuccessStatusCode();
+                    Assert.True(false, "Client should not have completed prior to server sending response");
+                }
+
                 HttpListenerContext context = await server;

-                for (int i = 0; i < 1000; i++)
+                for (int i = 0; i < numHeaders; i++)
                 {
                     Assert.Equal(i.ToString(), context.Request.Headers[$"custom{i}"]);
                 }
@@ -151,4 +163,3 @@
         }
     }
 }
-


Setup

Setup

--- src/Miningcore/Blockchain/Bitcoin/BitcoinJobManagerBase.cs
+++ src/Miningcore/Blockchain/Bitcoin/BitcoinJobManagerBase.cs
@@ -483,7 +483,7 @@
             }

             // extract results
-            var validateAddressResponse = results[0].Response.ToObject<ValidateAddressResponse>();
+            var validateAddressResponse = results[0].Error == null ? results[0].Response.ToObject<ValidateAddressResponse>() : null;
             var submitBlockResponse = results[1];
             var blockchainInfoResponse = !hasLegacyDaemon ? results[2].Response.ToObject<BlockchainInfo>() : null;
             var daemonInfoResponse = hasLegacyDaemon ? results[2].Response.ToObject<DaemonInfo>() : null;
@@ -498,29 +498,27 @@
             PostChainIdentifyConfigure();

             // ensure pool owns wallet
-            if (!validateAddressResponse.IsValid)
+            if (validateAddressResponse == null || !validateAddressResponse.IsValid)
                 logger.ThrowLogPoolStartupException($"Daemon reports pool-address '{poolConfig.Address}' as invalid");
-
-            //if (clusterConfig.PaymentProcessing?.Enabled == true && !validateAddressResponse.IsMine)
-            //    logger.ThrowLogPoolStartupException($"Daemon does not own pool-address '{poolConfig.Address}'", LogCat);

             isPoS = difficultyResponse.Values().Any(x => x.Path == "proof-of-stake");

             // Create pool address script from response
             if (!isPoS)
-            {
-                // bitcoincashd returns a different address than what was passed in
-                if (!validateAddressResponse.Address.StartsWith("bitcoincash:"))
-                    poolAddressDestination = AddressToDestination(validateAddressResponse.Address, extraPoolConfig?.AddressType);
-                else
-                    poolAddressDestination = AddressToDestination(poolConfig.Address, extraPoolConfig?.AddressType);
-            }
-
+                poolAddressDestination = AddressToDestination(poolConfig.Address, extraPoolConfig?.AddressType);
             else
                 poolAddressDestination = new PubKey(validateAddressResponse.PubKey);

-            if (clusterConfig.PaymentProcessing?.Enabled == true && poolConfig.PaymentProcessing?.Enabled == true)
+            // Payment-processing setup
+            if (clusterConfig.PaymentProcessing?.Enabled == true &&
+                poolConfig.PaymentProcessing?.Enabled == true)
+            {
+                // ensure pool owns wallet
+                if (!validateAddressResponse.IsMine)
+                    logger.ThrowLogPoolStartupException($"Daemon does not own pool-address '{poolConfig.Address}'");
+
                 ConfigureRewards();
+            }

             // update stats
             BlockchainStats.NetworkType = network.Name;


fixed two more tests related to cache

fixed two more tests related to cache

--- src/Config.Net/Value.cs
+++ src/Config.Net/Value.cs
@@ -1,8 +1,4 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;

 namespace Config.Net
 {
@@ -14,6 +10,8 @@

       public bool IsExpired(TimeSpan ttl)
       {
+         if (ttl == TimeSpan.Zero) return true;
+
          return (DateTime.UtcNow - Updated) > ttl;
       }


Implement support for kCVZeroTime and kCVIndefiniteTime

--- src/CoreVideo/CVTime.cs
+++ src/CoreVideo/CVTime.cs
@@ -36,13 +36,20 @@
 		public Int64 TimeScale;
 		public Int32 Flags;

-		/* FIXME:
-		 *
-		 * These are global constant structures, so we need to extend Dlfcn to handle this.
-		 *
-		 * const CVTime kCVZeroTime;
-		 * const CVTime kCVIndefiniteTime;
-		 */
+		static IntPtr CoreVideo_libraryHandle = Dlfcn.dlopen (Constants.CoreVideoLibrary, 0);
+
+		public static CVTime ZeroTime {
+			get {
+				return (CVTime) Marshal.PtrToStructure (Dlfcn.GetIndirect (CoreVideo_libraryHandle, "kCVZeroTime"), typeof (CVTime));
+			}
+		}
+
+		public static CVTime IndefiniteTime {
+			get {
+				return (CVTime) Marshal.PtrToStructure (Dlfcn.GetIndirect (CoreVideo_libraryHandle, "kCVIndefiniteTime"), typeof (CVTime));
+			}
+		}
+
                 public override bool Equals (object other)
                 {
                         if (!(other is CVTime))


chore(SemanticValidation): added temporarily styling for the validation message on mobile

--- src/StockportWebapp/Views/stockportgov/Shared/Components/QuestionRenderer/Semantic/_ValidationError.cshtml
+++ src/StockportWebapp/Views/stockportgov/Shared/Components/QuestionRenderer/Semantic/_ValidationError.cshtml
@@ -1,30 +1,24 @@
-@using System.Diagnostics
-@model StockportWebapp.QuestionBuilder.Entities.Question
+@model StockportWebapp.QuestionBuilder.Entities.Question

+@* Temporarily adding inline styling for the error message *@

-@(Model.ValidationResult?.Message ?? "")
-
-
-@*@if (Model.ValidationResult?.Message != null || Model.ValidationResult?.Message != string.Empty)
-{
-    @if (string.IsNullOrEmpty(Model.ValidationResult?.Message) && Model.ValidationResult?.Message != "No message")
-     {
-         @(Model.ValidationResult?.Message ?? "")
-     }
-
-    @if (Model.ValidationResult?.Message != string.Empty)
-    {
-        @(Model.ValidationResult?.Message ?? "")
-    }
-}*@
-
+
+    @(Model.ValidationResult?.Message ?? "")
+


Api/OrganizationRight post and delete restrictions

--- Presentation.Web/Controllers/API/OrganizationRightController.cs
+++ Presentation.Web/Controllers/API/OrganizationRightController.cs
@@ -127,13 +127,30 @@
             }
         }

-        public HttpResponseMessage PostRightByOrganizationRight(bool? rightByOrganizationRight, int organizationId, int userId, OrganizationRightDTO dto)
+        public HttpResponseMessage PostRightByOrganizationRight(bool? rightByOrganizationRight, int organizationId, OrganizationRightDTO dto)
         {
             try
             {
                 var right = AutoMapper.Mapper.Map<OrganizationRightDTO, OrganizationRight>(dto);

-                if(!base.HasWriteAccess(right, KitosUser, organizationId))
+                // Only global admin can set other users as global admins
+                if(right.Role == OrganizationRole.GlobalAdmin)
+                {
+                    if (!KitosUser.IsGlobalAdmin)
+                        return Unauthorized();
+                }
+
+                // Only local and global admins can make users local admins
+                if(right.Role == OrganizationRole.LocalAdmin)
+                {
+                    if(!KitosUser.IsGlobalAdmin && !KitosUser.IsGlobalAdmin)
+                        return Unauthorized();
+                }
+
+                right.OrganizationId = organizationId;
+                right.ObjectOwner = KitosUser;
+
+                if (!base.HasWriteAccess(right, KitosUser, organizationId))
                 {
                     return Unauthorized();
                 }
@@ -143,8 +160,6 @@
                 //    if (!_rightRepository.Get(r => r.UserId == userId && r.OrganizationId == organizationId).Any())
                 //        return Unauthorized();

-                right.OrganizationId = organizationId;
-                right.ObjectOwner = KitosUser;
                 right.LastChangedByUser = KitosUser;
                 right.LastChanged = DateTime.UtcNow;

@@ -189,41 +204,58 @@
             }
         }

-        /// <summary>
-        /// Post a new right to the object
-        /// </summary>
-        /// <param name="id">The id of the object</param>
-        /// <param name="organizationId"></param>
-        /// <param name="dto">DTO of right</param>
-        /// <returns></returns>
-        public HttpResponseMessage PostRight(int id, int organizationId, OrganizationRightDTO dto)
-        {
-            try
-            {
-                if (!HasWriteAccess(id, KitosUser, organizationId))
-                    return Unauthorized();
-
-                var right = AutoMapper.Mapper.Map<OrganizationRightDTO, OrganizationRight>(dto);
-                right.OrganizationId = id;
-                right.ObjectOwner = KitosUser;
-                right.LastChangedByUser = KitosUser;
-                right.LastChanged = DateTime.UtcNow;
-
-                right = _rightRepository.Insert(right);
-                _rightRepository.Save();
-
-                //TODO: FIX navigation properties not loading properly!!!
-                right.User = UserRepository.GetByKey(right.UserId);
-
-                var outputDTO = AutoMapper.Mapper.Map<OrganizationRight, OrganizationRightDTO>(right);
-
-                return Created(outputDTO);
-            }
-            catch (Exception e)
-            {
-                return Error(e);
-            }
-        }
+        ///// <summary>
+        ///// Post a new right to the object
+        ///// </summary>
+        ///// <param name="id">The id of the object</param>
+        ///// <param name="organizationId"></param>
+        ///// <param name="dto">DTO of right</param>
+        ///// <returns></returns>
+        //public HttpResponseMessage PostRight(int id, int organizationId, OrganizationRightDTO dto)
+        //{
+        //    try
+        //    {
+        //        var right = AutoMapper.Mapper.Map<OrganizationRightDTO, OrganizationRight>(dto);
+        //        right.OrganizationId = id;
+        //        right.ObjectOwner = KitosUser;
+
+        //        // Only global admin can set other users as global admins
+        //        if (right.Role == OrganizationRole.GlobalAdmin)
+        //        {
+        //            if (!KitosUser.IsGlobalAdmin)
+        //                return Unauthorized();
+        //        }
+
+        //        // Only local and global admins can make users local admins
+        //        if (right.Role == OrganizationRole.LocalAdmin)
+        //        {
+        //            if (!KitosUser.IsGlobalAdmin && !KitosUser.IsGlobalAdmin)
+        //                return Unauthorized();
+        //        }
+
+        //        if (!base.HasWriteAccess(right, KitosUser, organizationId))
+        //        {
+        //            return Unauthorized();
+        //        }
+
+        //        right.LastChangedByUser = KitosUser;
+        //        right.LastChanged = DateTime.UtcNow;
+
+        //        right = _rightRepository.Insert(right);
+        //        _rightRepository.Save();
+
+        //        //TODO: FIX navigation properties not loading properly!!!
+        //        right.User = UserRepository.GetByKey(right.UserId);
+
+        //        var outputDTO = AutoMapper.Mapper.Map<OrganizationRight, OrganizationRightDTO>(right);
+
+        //        return Created(outputDTO);
+        //    }
+        //    catch (Exception e)
+        //    {
+        //        return Error(e);
+        //    }
+        //}

         /// <summary>
         /// Delete a right from the object
@@ -237,10 +269,26 @@
         {
             try
             {
-                if (!HasWriteAccess(id, KitosUser, organizationId))
+                var right = _rightRepository.Get(r => r.OrganizationId == id && r.Role == (OrganizationRole)rId && r.UserId == uId).FirstOrDefault();
+
+                // Only global admin can set other users as global admins
+                if (right.Role == OrganizationRole.GlobalAdmin)
+                {
+                    if (!KitosUser.IsGlobalAdmin)
+                        return Unauthorized();
+                }
+
+                // Only local and global admins can make users local admins
+                if (right.Role == OrganizationRole.LocalAdmin)
+                {
+                    if (!KitosUser.IsGlobalAdmin && !KitosUser.IsGlobalAdmin)
+                        return Unauthorized();
+                }
+
+                if(!base.HasWriteAccess(right, KitosUser, organizationId))
+                {
                     return Unauthorized();
-
-                var right = _rightRepository.Get(r => r.OrganizationId == id && r.Role == (OrganizationRole)rId && r.UserId == uId).FirstOrDefault();
+                }

                 if (right == null) return NotFound();


Remove log

Remove log

--- UnityProject/Assets/Scripts/Camera/CameraEffectControlScript.cs
+++ UnityProject/Assets/Scripts/Camera/CameraEffectControlScript.cs
@@ -39,8 +39,6 @@

 			if (timer < TIMER_INTERVAL) return;

-			Debug.Log("drunkCameraTime "+ drunkCameraTime);
-
 			if (drunkCameraTime > 0)
 			{
 				drunkCamera.enabled = true;


csharp-mvc: fix null user

csharp-mvc: fix null user

--- web/documentserver-example/csharp-mvc/Helpers/DocManagerHelper.cs
+++ web/documentserver-example/csharp-mvc/Helpers/DocManagerHelper.cs
@@ -175,10 +175,12 @@
         {
             var histDir = HistoryDir(StoragePath(fileName, userAddress));
             Directory.CreateDirectory(histDir);
+            var id = string.IsNullOrEmpty(uid) ? "uid-1" : uid;
+            var name = string.IsNullOrEmpty(uname) ? "John Smith" : uname;
             File.WriteAllText(Path.Combine(histDir, "createdInfo.json"), new JavaScriptSerializer().Serialize(new Dictionary<string, object> {
                 { "created", DateTime.Now.ToString("yyyy'-'MM'-'dd HH':'mm':'ss") },
-                { "id", string.IsNullOrEmpty(uid) ? "uid-1" : uid },
-                { "name", string.IsNullOrEmpty(uname) ? "John Smith" : uname }
+                { "id", id },
+                { "name", id.Equals("uid-0") ? null : name }
             }));
         }


Fix for null ref of _defaultGlobalVariables when initialising a VAR with a list item

--- ink-engine-runtime/VariablesState.cs
+++ ink-engine-runtime/VariablesState.cs
@@ -155,7 +155,7 @@

 		internal bool GlobalVariableExistsWithName(string name)
 		{
-			return _globalVariables.ContainsKey(name) || _defaultGlobalVariables.ContainsKey(name);
+			return _globalVariables.ContainsKey(name) || _defaultGlobalVariables != null && _defaultGlobalVariables.ContainsKey(name);
 		}

         Runtime.Object GetVariableWithName(string name, int contextIndex)
@@ -177,8 +177,18 @@

             // 0 context = global
             if (contextIndex == 0 || contextIndex == -1) {
-                if ( _globalVariables.TryGetValue (name, out varValue) || _defaultGlobalVariables.TryGetValue(name, out varValue) )
+
+                if ( _globalVariables.TryGetValue (name, out varValue) )
                     return varValue;
+
+                // Getting variables can actually happen during globals set up since you can do
+                //  VAR x = A_LIST_ITEM
+                // So _defaultGlobalVariables may be null.
+                // We need to do this check though in case a new global is added, so we need to
+                // revert to the default globals dictionary since an initial value hasn't yet been set.
+                if( _defaultGlobalVariables != null && _defaultGlobalVariables.TryGetValue(name, out varValue) ) {
+                    return varValue;
+                }

                 var listItemValue = _listDefsOrigin.FindSingleItemListWithName (name);
                 if (listItemValue)


refactor: better naming

refactor: better naming

--- src/reni2/Parser/ExpressionSyntax.cs
+++ src/reni2/Parser/ExpressionSyntax.cs
@@ -36,8 +36,8 @@
         }

         internal static Result<ValueSyntax> Create
-            (BinaryTree parent, ValueSyntax left, Definable definable, ValueSyntax right)
-            => new Result<ValueSyntax>(new ExpressionSyntax(parent, left, definable, right));
+            (BinaryTree target, ValueSyntax left, Definable definable, ValueSyntax right)
+            => new Result<ValueSyntax>(new ExpressionSyntax(target, left, definable, right));

         internal static Result<ValueSyntax> Create(Definable definable, BinaryTree binaryTree, ISyntaxScope scope)
         {
@@ -51,8 +51,8 @@

         int CurrentResultDepth;

-        ExpressionSyntax(BinaryTree parent, ValueSyntax left, Definable definable, ValueSyntax right)
-            : base(parent)
+        ExpressionSyntax(BinaryTree target, ValueSyntax left, Definable definable, ValueSyntax right)
+            : base(target)
         {
             Left = left;
             Definable = definable;