Lucene.Net.Core.Codecs.Lucene45.Lucene45Codec refactor: renamed private/internal fields camelCase

--- src/Lucene.Net.Core/Codecs/Lucene45/Lucene45Codec.cs
+++ src/Lucene.Net.Core/Codecs/Lucene45/Lucene45Codec.cs
@@ -44,26 +44,26 @@
     [Obsolete("Only for reading old 4.3-4.5 segments")]
     public class Lucene45Codec : Codec
     {
-        private readonly StoredFieldsFormat FieldsFormat = new Lucene41StoredFieldsFormat();
-        private readonly TermVectorsFormat VectorsFormat = new Lucene42TermVectorsFormat();
-        private readonly FieldInfosFormat FieldInfosFormat_Renamed = new Lucene42FieldInfosFormat();
-        private readonly SegmentInfoFormat InfosFormat = new Lucene40SegmentInfoFormat();
-        private readonly LiveDocsFormat LiveDocsFormat_Renamed = new Lucene40LiveDocsFormat();
+        private readonly StoredFieldsFormat fieldsFormat = new Lucene41StoredFieldsFormat();
+        private readonly TermVectorsFormat vectorsFormat = new Lucene42TermVectorsFormat();
+        private readonly FieldInfosFormat fieldInfosFormat = new Lucene42FieldInfosFormat();
+        private readonly SegmentInfoFormat infosFormat = new Lucene40SegmentInfoFormat();
+        private readonly LiveDocsFormat liveDocsFormat = new Lucene40LiveDocsFormat();

         private readonly PostingsFormat postingsFormat;

         private class PerFieldPostingsFormatAnonymousInnerClassHelper : PerFieldPostingsFormat
         {
-            private readonly Lucene45Codec OuterInstance;
+            private readonly Lucene45Codec outerInstance;

             public PerFieldPostingsFormatAnonymousInnerClassHelper(Lucene45Codec outerInstance)
             {
-                this.OuterInstance = outerInstance;
+                this.outerInstance = outerInstance;
             }

             public override PostingsFormat GetPostingsFormatForField(string field)
             {
-                return OuterInstance.GetPostingsFormatForField(field);
+                return outerInstance.GetPostingsFormatForField(field);
             }
         }

@@ -71,16 +71,16 @@

         private class PerFieldDocValuesFormatAnonymousInnerClassHelper : PerFieldDocValuesFormat
         {
-            private readonly Lucene45Codec OuterInstance;
+            private readonly Lucene45Codec outerInstance;

             public PerFieldDocValuesFormatAnonymousInnerClassHelper(Lucene45Codec outerInstance)
             {
-                this.OuterInstance = outerInstance;
+                this.outerInstance = outerInstance;
             }

             public override DocValuesFormat GetDocValuesFormatForField(string field)
             {
-                return OuterInstance.GetDocValuesFormatForField(field);
+                return outerInstance.GetDocValuesFormatForField(field);
             }
         }

@@ -95,12 +95,12 @@

         public override sealed StoredFieldsFormat StoredFieldsFormat
         {
-            get { return FieldsFormat; }
+            get { return fieldsFormat; }
         }

         public override sealed TermVectorsFormat TermVectorsFormat
         {
-            get { return VectorsFormat; }
+            get { return vectorsFormat; }
         }

         public override sealed PostingsFormat PostingsFormat
@@ -110,17 +110,17 @@

         public override FieldInfosFormat FieldInfosFormat
         {
-            get { return FieldInfosFormat_Renamed; }
+            get { return fieldInfosFormat; }
         }

         public override SegmentInfoFormat SegmentInfoFormat
         {
-            get { return InfosFormat; }
+            get { return infosFormat; }
         }

         public override sealed LiveDocsFormat LiveDocsFormat
         {
-            get { return LiveDocsFormat_Renamed; }
+            get { return liveDocsFormat; }
         }

         /// <summary>
@@ -131,7 +131,7 @@
         /// </summary>
         public virtual PostingsFormat GetPostingsFormatForField(string field)
         {
-            return DefaultFormat;
+            return defaultFormat;
         }

         /// <summary>
@@ -142,7 +142,7 @@
         /// </summary>
         public virtual DocValuesFormat GetDocValuesFormatForField(string field)
         {
-            return DefaultDVFormat;
+            return defaultDVFormat;
         }

         public override sealed DocValuesFormat DocValuesFormat
@@ -150,14 +150,14 @@
             get { return docValuesFormat; }
         }

-        private readonly PostingsFormat DefaultFormat = Codecs.PostingsFormat.ForName("Lucene41");
-        private readonly DocValuesFormat DefaultDVFormat = Codecs.DocValuesFormat.ForName("Lucene45");
+        private readonly PostingsFormat defaultFormat = Codecs.PostingsFormat.ForName("Lucene41");
+        private readonly DocValuesFormat defaultDVFormat = Codecs.DocValuesFormat.ForName("Lucene45");

-        private readonly NormsFormat NormsFormat_Renamed = new Lucene42NormsFormat();
+        private readonly NormsFormat normsFormat = new Lucene42NormsFormat();

         public override sealed NormsFormat NormsFormat
         {
-            get { return NormsFormat_Renamed; }
+            get { return normsFormat; }
         }
     }
 }


Ensure deps file contains correct extension

Previously the GenerateDepsJson task was assuming all assemblies were
dlls, however that is not the case; xunit.console.netcore.exe is an exe.

This didn't seem to cause an issue if the file existed in the
application folder.  If xunit.console.netcore.exe existed in the app folder, the host would
ignore the incorrect entry in the framework deps file.

If, however, the file was missing from the app folder and had incorrect
extension, the host would fail at startup.

This change fixes the deps file to have the correct extension.

--- src/Microsoft.DotNet.Build.Tasks/GenerateDepsJson.cs
+++ src/Microsoft.DotNet.Build.Tasks/GenerateDepsJson.cs
@@ -50,7 +50,7 @@
                 AssemblyName result;
                 if (TryGetManagedAssemblyName(file, out result))
                 {
-                    assemblyNames.Add(new FileNameAssemblyPair(result, Path.GetFileNameWithoutExtension(file)));
+                    assemblyNames.Add(new FileNameAssemblyPair(result, Path.GetFileName(file)));
                 }
                 else
                 {
@@ -116,8 +116,8 @@
             {
                 JObject runtimes = new JObject();
                 JObject runtimeLocation = new JObject();
-                string key = $"{assembly.FileName}/{assembly.AssemblyName.Version.Major}.{assembly.AssemblyName.Version.Minor}.{assembly.AssemblyName.Version.Build}";
-                runtimeLocation.Add(assembly.FileName + ".dll", new JObject());
+                string key = $"{assembly.AssemblyName.Name}/{assembly.AssemblyName.Version.Major}.{assembly.AssemblyName.Version.Minor}.{assembly.AssemblyName.Version.Build}";
+                runtimeLocation.Add(assembly.FileName, new JObject());
                 runtimes.Add("runtime", runtimeLocation);
                 try
                 {


Updated handling for cancel messages

Updated handling for cancel messages

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

--- src/MonoTorrent.Client/PeerMessages/CancelMessage.cs
+++ src/MonoTorrent.Client/PeerMessages/CancelMessage.cs
@@ -155,11 +155,13 @@
                 }

                 PieceMessage piece = msg as PieceMessage;
-                if (!(piece.PieceIndex == this.pieceIndex
-                    && piece.StartOffset == this.startOffset
-                    && piece.BlockLength == this.requestLength))
+                if (!(piece.PieceIndex == this.pieceIndex && piece.StartOffset == this.startOffset && piece.BlockLength == this.requestLength))
                 {
                     id.Peer.Connection.EnQueue(msg);
+                }
+                else
+                {
+                    id.Peer.Connection.IsRequestingPiecesCount--;
                 }
             }
         }


Changed the test to make more sense and pass the build.

--- src/NUnitFramework/tests/Constraints/NumericsTest.cs
+++ src/NUnitFramework/tests/Constraints/NumericsTest.cs
@@ -168,7 +168,7 @@
         [Test]
         public void FailsOnDecimalIsPartOfIsFixedPointNumericMethod()
         {
-            Assert.Throws<AssertionException>(() => Assert.IsFalse(Numerics.IsFixedPointNumeric(1000m)));
+            Assert.IsFalse(Numerics.IsFixedPointNumeric(1000m));
         }
     }
 }


remove SetWaitHandle_Enqueue_AsynchronousTest

--- src/NUnitFramework/tests/Internal/EventQueueTests.cs
+++ src/NUnitFramework/tests/Internal/EventQueueTests.cs
@@ -133,42 +133,6 @@
             }
         }

-        [TestFixture]
-        public class SetWaitHandle_Enqueue_AsynchronousTest : ProducerConsumerTest
-        {
-            private EventQueue q;
-            private volatile bool afterEnqueue;
-
-            [Test]
-#if THREAD_ABORT
-            [Timeout(1000)]
-#endif
-            public void SetWaitHandle_Enqueue_Asynchronous()
-            {
-                using (new AutoResetEvent(false))
-                {
-                    this.q = new EventQueue();
-                    this.afterEnqueue = false;
-                    this.RunProducerConsumer();
-                }
-            }
-
-            protected override void Producer()
-            {
-                Event asynchronousEvent = new TestStartedEvent(new TestSuite("Dummy"));
-                this.q.Enqueue(asynchronousEvent);
-                this.afterEnqueue = true;
-                Thread.MemoryBarrier();
-            }
-
-            protected override void Consumer()
-            {
-                this.q.Dequeue(true);
-                Thread.Sleep(30);
-                Assert.IsTrue(this.afterEnqueue);
-            }
-        }
-
         #endregion

         #region QueuingEventListener Tests


Allow for random zero values in the randomness tests

--- src/NUnitFramework/tests/Internal/RandomizerTests.cs
+++ src/NUnitFramework/tests/Internal/RandomizerTests.cs
@@ -61,7 +61,7 @@
         public void RandomUInt()
         {
             uint u = _randomizer.NextUInt();
-            Assert.That(u, Is.GreaterThan(0u));
+            Assert.That(u, Is.InRange(0u, uint.MaxValue));
         }

         [Test]
@@ -110,7 +110,7 @@
         public void RandomShort()
         {
             short s = _randomizer.NextShort();
-            Assert.That(s, Is.GreaterThan((short)0));
+            Assert.That(s, Is.InRange((short)0, short.MaxValue));
         }

         [Test]
@@ -166,7 +166,7 @@
         public void RandomUShort()
         {
             ushort us = _randomizer.NextUShort();
-            Assert.That(us, Is.GreaterThan((ushort)0));
+            Assert.That(us, Is.InRange((ushort)0, ushort.MaxValue));
         }

         [Test]
@@ -222,8 +222,7 @@
         public void RandomLong()
         {
             long val = _randomizer.NextLong();
-            Assert.That(val, Is.GreaterThan(0L));
-            Assert.That(val, Is.Not.EqualTo(long.MaxValue)); // Not much of a test!
+            Assert.That(val, Is.InRange(0L, long.MaxValue));
         }

         [Test]
@@ -273,7 +272,7 @@
         public void RandomULong()
         {
             ulong val = _randomizer.NextULong();
-            Assert.That(val, Is.Not.EqualTo(ulong.MaxValue)); // Not much of a test!
+            Assert.That(val, Is.InRange(0UL, ulong.MaxValue));
         }

         [Test]
@@ -323,7 +322,7 @@
         public void RandomByte()
         {
             byte b = _randomizer.NextByte();
-            Assert.That(b >= byte.MinValue && b < byte.MaxValue);
+            Assert.That(b, Is.InRange(byte.MinValue, byte.MaxValue));
         }

         [Test]
@@ -378,7 +377,8 @@
         public void RandomSByte()
         {
             sbyte b = _randomizer.NextSByte();
-            Assert.That(b >= sbyte.MinValue && b < sbyte.MaxValue);
+            Assert.That(b, Is.GreaterThanOrEqualTo(sbyte.MinValue));
+            Assert.That(b, Is.Not.EqualTo(sbyte.MaxValue));
         }

         [Test]
@@ -468,7 +468,8 @@
         public void RandomDouble()
         {
             double d = _randomizer.NextDouble();
-            Assert.That(d, Is.GreaterThan(0.0));
+            Assert.That(d, Is.GreaterThanOrEqualTo(0.0));
+            Assert.That(d, Is.LessThan(1.0));
         }

         [Test]
@@ -518,7 +519,8 @@
         public void RandomFloat()
         {
             float f = _randomizer.NextFloat();
-            Assert.That(f, Is.GreaterThan(0.0f));
+            Assert.That(f, Is.GreaterThanOrEqualTo(0.0f));
+            Assert.That(f, Is.LessThan(1.0f));
         }

         [Test]


Fixed an error which prevented RELEASE builds from building.

--- src/Neptunium/Core/Stations/NepAppStationsManager.cs
+++ src/Neptunium/Core/Stations/NepAppStationsManager.cs
@@ -266,7 +266,7 @@

                                     listings.Add(listing);
                                 }
-                                catch (Exception)
+                                catch (Exception ex)
                                 {
 #if !DEBUG
                                             Microsoft.HockeyApp.HockeyClient.Current.TrackException(ex);


revert change

revert change

--- src/NuGetGallery/Views/Packages/VerifyPackage.cshtml
+++ src/NuGetGallery/Views/Packages/VerifyPackage.cshtml
@@ -138,7 +138,7 @@

     @Html.AntiForgeryToken()
-    <input id="verifyPackageSubmit" type="submit" value="Submit" title="Verify Details & Submit" />
+    <input type="submit" value="Submit" title="Verify Details & Submit" />
     Cancel
 </fieldset>
 }


added DefinedConstants to ProjectFileInfo

--- src/OmniSharp/MSBuild/ProjectFile/ProjectFileInfo.cs
+++ src/OmniSharp/MSBuild/ProjectFile/ProjectFileInfo.cs
@@ -31,13 +31,7 @@

         public LanguageVersion? SpecifiedLanguageVersion { get; private set; }

-        public string ProjectDirectory
-        {
-            get
-            {
-                return Path.GetDirectoryName(ProjectFilePath);
-            }
-        }
+        public string ProjectDirectory => Path.GetDirectoryName(ProjectFilePath);

         public string AssemblyName { get; private set; }

@@ -50,6 +44,8 @@
         public IList<string> ProjectReferences { get; private set; }

         public IList<string> Analyzers { get; private set; }
+
+        public IList<string> DefinedConstants { get; private set; }

         public static ProjectFileInfo Create(MSBuildOptions options, ILogger logger, string solutionDirectory, string projectFilePath, ICollection<MSBuildDiagnosticsMessage> diagnostics)
         {
@@ -115,6 +111,12 @@
                     projectInstance.GetItems("Analyzer")
                                    .Select(p => p.GetMetadataValue("FullPath"))
                                    .ToList();
+
+                var definedConstants = projectInstance.GetPropertyValue("DefineConstants");
+                if (!string.IsNullOrWhiteSpace(definedConstants))
+                {
+                    projectFileInfo.DefinedConstants = definedConstants.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+                }
             }
             else
             {
@@ -181,6 +183,12 @@
                 projectFileInfo.Analyzers = itemsLookup["Analyzer"]
                     .Select(p => Path.GetFullPath(Path.Combine(projectFileInfo.ProjectDirectory, p.FinalItemSpec)))
                     .ToList();
+
+                var definedConstants = properties["DefineConstants"].FinalValue;
+                if (!string.IsNullOrWhiteSpace(definedConstants))
+                {
+                    projectFileInfo.DefinedConstants = definedConstants.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+                }
             }
 #else
             // TODO: Shell out to msbuild/xbuild here?


Fixed mispelling in error message

Fixed mispelling in error message

git-svn-id: 223c0ba935819ffdcafdc68147dc609b4e469b1e@312051 13f79535-47bb-0310-9956-ffa450edef68

--- src/Repository/Hierarchy/XmlHierarchyConfigurator.cs
+++ src/Repository/Hierarchy/XmlHierarchyConfigurator.cs
@@ -676,7 +676,7 @@

 				if (levelValue == null)
 				{
-					LogLog.Error("XmlConfigurator: Unknown Level Specifed ["+ value +"]");
+					LogLog.Error("XmlConfigurator: Unknown Level Specified ["+ value +"]");
 				}

 				return levelValue;


Refactoring commitments api

Refactoring commitments api

--- src/SFA.DAS.Commitments.Api.Client/CommitmentsApi.cs
+++ src/SFA.DAS.Commitments.Api.Client/CommitmentsApi.cs
@@ -36,9 +36,14 @@
         {
             var url = $"{_baseUrl}api/provider/{providerId}/commitments/{commitmentId}";

-            var content = await Execute(url);
+            return await GetCommitment(url);
+        }

-            return JsonConvert.DeserializeObject<Commitment>(content);
+        public async Task<Commitment> GetEmployerCommitment(long employerAccountId, long commitmentId)
+        {
+            var url = $"{_baseUrl}api/employer/{employerAccountId}/commitments/{commitmentId}";
+
+            return await GetCommitment(url);
         }

         private async Task<List<CommitmentListItem>> GetCommitments(string url)
@@ -46,6 +51,13 @@
             var content = await Execute(url);

             return JsonConvert.DeserializeObject<List<CommitmentListItem>>(content);
+        }
+
+        private async Task<Commitment> GetCommitment(string url)
+        {
+            var content = await Execute(url);
+
+            return JsonConvert.DeserializeObject<Commitment>(content);
         }

         private async Task<string> Execute(string url)


Updated docs on CheckpointType

Updated docs on CheckpointType

--- src/SampSharp.GameMode/Definitions/CheckpointType.cs
+++ src/SampSharp.GameMode/Definitions/CheckpointType.cs
@@ -19,12 +19,12 @@
     public enum CheckpointType
     {
         /// <summary>
-        ///     Normal racecheckpoint. (Normal red circle)
+        ///     Normal racecheckpoint. (Normal red cilinder)
         /// </summary>
         Normal = 0,

         /// <summary>
-        ///     Finish racecheckpoint. (Finish flag in red circle)
+        ///     Finish racecheckpoint. (Finish flag in red cilinder)
         /// </summary>
         Finish = 1,


Remove dead comment.

Remove dead comment.

--- src/StructuredLogger/Construction/ItemGroupParser.cs
+++ src/StructuredLogger/Construction/ItemGroupParser.cs
@@ -13,7 +13,6 @@
         /// </summary>
         /// <param name="message">The message output from the logger.</param>
         /// <param name="prefix">The prefix parsed out (e.g. 'Output Item(s): '.).</param>
-        /// <param name="name">Out: The name of the list.</param>
         /// <returns>List of items within the list and all metadata.</returns>
         public static object ParsePropertyOrItemList(string message, string prefix, StringCache stringTable)
         {


Detect if Process performance counter is enabled

To query information on remote machines, the Process class uses the
Performance Counters API to access the processes performance counter on
the remote machine.

This performance counter can be disabled, in which case we fail to get
remote process information (leading to InvalidOperationExceptions like
this):

```
 System.InvalidOperationException : Couldn't connect to remote machine.
 ---- System.InvalidOperationException : Process performance counter is disabled, so the requested operation cannot be performed.
 Stack Trace:
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(531,0): at System.Diagnostics.NtProcessManager.GetProcessInfos(String machineName, Boolean isRemoteMachine)
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(262,0): at System.Diagnostics.NtProcessManager.GetProcessIds(String machineName, Boolean isRemoteMachine)
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(71,0): at System.Diagnostics.ProcessManager.GetProcessIds(String machineName)
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(32,0): at System.Diagnostics.ProcessManager.IsProcessRunning(Int32 processId, String machineName)
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\Process.cs(879,0): at System.Diagnostics.Process.GetProcessById(Int32 processId, String machineName)
    D:\git\corefx\src\System.Diagnostics.Process\tests\ProcessTests.cs(574,0): at System.Diagnostics.Tests.ProcessTests.<GetTestProcess>d__39.MoveNext()
       at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
    ----- Inner Stack Trace -----
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(563,0): at System.Diagnostics.NtProcessManager.GetProcessInfos(PerformanceCounterLib library)
    D:\git\corefx\src\System.Diagnostics.Process\src\System\Diagnostics\ProcessManager.Windows.cs(522,0): at System.Diagnostics.NtProcessManager.GetProcessInfos(String machineName, Boolean isRemoteMachine)
```

While this counter could be disabled on any version of Windows, it
appears that is being disabled by default in newer Windows 10 builds, as
the build I upgraded to today had this disabled by default.

Use `ConditionalTheory` to only run this test in cases where we know the
service is enabled (defaulting to run the test if our sniffing fails to
work for some reason).

--- src/System.Diagnostics.Process/tests/ProcessTests.cs
+++ src/System.Diagnostics.Process/tests/ProcessTests.cs
@@ -576,7 +576,23 @@
             yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
         }

-        [Theory, PlatformSpecific(PlatformID.Windows)]
+        private static bool ProcessPeformanceCounterEnabled()
+        {
+            try
+            {
+                int? value = (int?)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance", "Disable Performance Counters", null);
+                return !value.HasValue || value.Value == 0;
+            }
+            catch (Exception)
+            {
+                // Ignore exceptions, and just assume the counter is enabled.
+            }
+
+            return true;
+        }
+
+        [PlatformSpecific(PlatformID.Windows)]
+        [ConditionalTheory(nameof(ProcessPeformanceCounterEnabled))]
         [MemberData(nameof(GetTestProcess))]
         public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
         {


Several fixes in wallabagItemSource.cs

Several fixes in wallabagItemSource.cs

--- wallabag/wallabag.Shared/DataModel/wallabagItemSource.cs
+++ wallabag/wallabag.Shared/DataModel/wallabagItemSource.cs
@@ -20,7 +20,7 @@

         public Item()
         {
-            UniqueId = new Guid("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz").ToString();
+            UniqueId = Guid.NewGuid().ToString();
         }
         public Item(String uniqueId, String title, String content, Uri url, bool isRead, bool isFavourite)
         {
@@ -94,7 +94,7 @@
         private static wallabagDataSource _wallabagDataSource = new wallabagDataSource();
         public ApplicationSettings AppSettings { get { return ApplicationSettings.Instance; } }

-        private ObservableCollection<Item> _items;
+        private ObservableCollection<Item> _items = new ObservableCollection<Item>();
         public ObservableCollection<Item> Items { get { return this._items; } }

         public static async Task<IEnumerable<Item>> GetItemsAsync()
@@ -137,7 +137,7 @@
         }
         private async Task GetDataAsync()
         {
-            if (this._items.Count != 0 || !everythingFine)
+            if (!everythingFine)
                 return;

             Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();


Only scan assemblies that refer to Alpaca

--- src/Alpaca.Weld/Core/WeldEngine.cs
+++ src/Alpaca.Weld/Core/WeldEngine.cs
@@ -25,8 +25,10 @@

         public WeldCatalog AutoScan()
         {
+            var assemblyName = Assembly.GetExecutingAssembly().GetName();
+
             var types = (from assembly in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
-                      where !assembly.FullName.StartsWith("System.")
+                      where assembly.GetReferencedAssemblies().Any(x=> AssemblyName.ReferenceMatchesDefinition(x, assemblyName))
                       from type in assembly.GetLoadableTypes()
                       where type.IsPublic && type.IsClass && !type.IsPrimitive
                       select type).ToArray();


BL-9085 Simpler Device XMatter handling

BL-9085 Simpler Device XMatter handling

Don't change to Device xmatter if current xmatter's css handles Device16x9

--- src/BloomExe/Book/XMatterHelper.cs
+++ src/BloomExe/Book/XMatterHelper.cs
@@ -85,11 +85,30 @@
 			if (xmatterName.EndsWith("Device"))
 				return xmatterName;

+			// Look to see if there is a special Device version of this xmatter
 			var deviceXmatterName = $"{xmatterName}-Device";
 			var directoryPath = GetXMatterDirectory(deviceXmatterName, fileLocator, null, false, true);
-
-			// if "{xmatterName}-Device" is unavailable, use the default Device xmatter which is just named "Device"
-			return directoryPath != null ? deviceXmatterName : "Device";
+			if (directoryPath != null)
+				return deviceXmatterName;
+
+			// Look in the stylesheet and see if it already handles device layout
+			try
+			{
+				var plainXmatterDirectory = GetXMatterDirectory(xmatterName, fileLocator, null, false, true);
+				if (plainXmatterDirectory != null)
+				{
+					var cssPath = Path.Combine(plainXmatterDirectory, GetStyleSheetFileName(xmatterName));
+					if (RobustFile.ReadAllText(cssPath).Contains(".Device16x9"))
+						return xmatterName;
+				}
+			}
+			catch (Exception)
+			{
+				// swallow and fall back to dedicated device xmatter
+			}
+
+			// use the default Device xmatter which is just named "Device"
+			return  "Device";
 		}

 		public static string GetXMatterDirectory(string nameOfXMatterPack, IFileLocator fileLocator, string errorMsg, bool throwIfError, bool silent = false)
@@ -113,11 +132,12 @@

 		public string GetStyleSheetFileName()
 		{
-//			var layout = SizeAndOrientation.FromDom(_dom);
-//			return layout.PageSizeName + "-" + layout.OrientationName + "-" + _nameOfXMatterPack + "-XMatter.css";
-			return _nameOfXMatterPack + "-XMatter.css";
-		}
-
+			return GetStyleSheetFileName(_nameOfXMatterPack);
+		}
+		public static string GetStyleSheetFileName(string xmatterName)
+		{
+			return xmatterName + "-XMatter.css";
+		}
 		/// <summary>
 		/// Set this if you want the xmatter stuff copied into a document folder. This makes sense when setting up or
 		/// modifying one of the users books, but not when just displaying a book from a shell collection.


Update ProjectEditor.cs

Update ProjectEditor.cs

--- src/Core2D/Editor/ProjectEditor.cs
+++ src/Core2D/Editor/ProjectEditor.cs
@@ -2574,69 +2574,72 @@
         {
             try
             {
-                if (files?.Length >= 1)
-                {
-                    bool result = false;
-                    foreach (var path in files)
-                    {
-                        if (string.IsNullOrEmpty(path))
+                if (files?.Length < 1)
+                {
+                    return false;
+                }
+
+                bool result = false;
+
+                foreach (var path in files)
+                {
+                    if (string.IsNullOrEmpty(path))
+                    {
+                        continue;
+                    }
+
+                    string ext = System.IO.Path.GetExtension(path);
+
+                    if (string.Compare(ext, ProjectEditorConfiguration.ProjectExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        OnOpenProject(path);
+                        result = true;
+                    }
+                    else if (string.Compare(ext, ProjectEditorConfiguration.CsvExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        var reader = TextFieldReaders.FirstOrDefault(x => x.Extension == "csv");
+                        if (reader != null)
                         {
-                            continue;
-                        }
-
-                        string ext = System.IO.Path.GetExtension(path);
-
-                        if (string.Compare(ext, ProjectEditorConfiguration.ProjectExtension, StringComparison.OrdinalIgnoreCase) == 0)
-                        {
-                            OnOpenProject(path);
+                            OnImportData(Project, path, reader);
                             result = true;
                         }
-                        else if (string.Compare(ext, ProjectEditorConfiguration.CsvExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    }
+                    else if (string.Compare(ext, ProjectEditorConfiguration.XlsxExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        var reader = TextFieldReaders.FirstOrDefault(x => x.Extension == "xlsx");
+                        if (reader != null)
                         {
-                            var reader = TextFieldReaders.FirstOrDefault(x => x.Extension == "csv");
-                            if (reader != null)
-                            {
-                                OnImportData(Project, path, reader);
-                                result = true;
-                            }
-                        }
-                        else if (string.Compare(ext, ProjectEditorConfiguration.XlsxExtension, StringComparison.OrdinalIgnoreCase) == 0)
-                        {
-                            var reader = TextFieldReaders.FirstOrDefault(x => x.Extension == "xlsx");
-                            if (reader != null)
-                            {
-                                OnImportData(Project, path, reader);
-                                result = true;
-                            }
-                        }
-                        else if (string.Compare(ext, ProjectEditorConfiguration.JsonExtension, StringComparison.OrdinalIgnoreCase) == 0)
-                        {
-                            OnImportJson(path);
+                            OnImportData(Project, path, reader);
                             result = true;
                         }
-                        else if (string.Compare(ext, ProjectEditorConfiguration.XamlExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    }
+                    else if (string.Compare(ext, ProjectEditorConfiguration.JsonExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        OnImportJson(path);
+                        result = true;
+                    }
+                    else if (string.Compare(ext, ProjectEditorConfiguration.XamlExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        OnImportXaml(path);
+                        result = true;
+                    }
+                    else if (string.Compare(ext, ProjectEditorConfiguration.ScriptExtension, StringComparison.OrdinalIgnoreCase) == 0)
+                    {
+                        OnExecuteScriptFile(path);
+                        result = true;
+                    }
+                    else if (ProjectEditorConfiguration.ImageExtensions.Any(x => string.Compare(ext, x, StringComparison.OrdinalIgnoreCase) == 0))
+                    {
+                        var key = OnGetImageKey(path);
+                        if (key != null && !string.IsNullOrEmpty(key))
                         {
-                            OnImportXaml(path);
-                            result = true;
+                            OnDropImageKey(key, x, y);
                         }
-                        else if (string.Compare(ext, ProjectEditorConfiguration.ScriptExtension, StringComparison.OrdinalIgnoreCase) == 0)
-                        {
-                            OnExecuteScriptFile(path);
-                            result = true;
-                        }
-                        else if (ProjectEditorConfiguration.ImageExtensions.Any(x => string.Compare(ext, x, StringComparison.OrdinalIgnoreCase) == 0))
-                        {
-                            var key = OnGetImageKey(path);
-                            if (key != null && !string.IsNullOrEmpty(key))
-                            {
-                                OnDropImageKey(key, x, y);
-                            }
-                            result = true;
-                        }
-                    }
-
-                    return result;
-                }
+                        result = true;
+                    }
+                }
+
+                return result;
             }
             catch (Exception ex)
             {


fix missing checkin

fix missing checkin

--- src/DnsClient/DnsDatagramReader.cs
+++ src/DnsClient/DnsDatagramReader.cs
@@ -171,6 +171,7 @@
             return new IPAddress(ReadByteArray(IPv6Length));
         }

+
         private static readonly byte[] ACEPrefixBytes = ACEPrefix.Select(p => (byte)p).ToArray();

         private const string ACEPrefix = "xn--";
@@ -179,60 +180,47 @@
         {
             var builder = new StringBuilder();
             var original = new StringBuilder();
-
             foreach (var labelArray in ReadLabels())
             {
-                var bytesIndex = 0;
-
-                foreach (var current in labelArray)
-                {
-                    char chr = (char)current;
-
-                    byte a = labelArray.Array[labelArray.Offset + 1], b = labelArray.Array[labelArray.Offset + 2], c = labelArray.Array[labelArray.Offset + 3];
-                    if (current == ACEPrefixBytes[0] && a == ACEPrefixBytes[1] && b == ACEPrefixBytes[2] && c == ACEPrefixBytes[3])
-                    {
-                        var label = Encoding.UTF8.GetString(labelArray.Array, labelArray.Offset, labelArray.Count);
-                        var unicode = label;
-                        try
-                        {
-                            unicode = DnsString.IDN.GetUnicode(label);
-                        }
-                        catch { /* just do nothing in case the IDN is invalid, better to return something at least */ }
-
-                        builder.Append(label);
-                        original.Append(unicode);
-                        break;
-                    }
-
-                    if (current < 32 || current > 126)
-                    {
-                        builder.Append("\\" + current.ToString("000"));
-                    }
-                    else if (chr == ';')
+                foreach (var b in labelArray)
+                {
+                    char c = (char)b;
+
+                    if (b < 32 || b > 126)
+                    {
+                        builder.Append("\\" + b.ToString("000"));
+                    }
+                    else if (c == ';')
                     {
                         builder.Append("\\;");
                     }
-                    else if (chr == '\\')
+                    else if (c == '\\')
                     {
                         builder.Append("\\\\");
                     }
-                    else if (chr == '"')
+                    else if (c == '"')
                     {
                         builder.Append("\\\"");
                     }
                     else
                     {
-                        builder.Append(chr);
-                    }
-
-                    bytesIndex++;
+                        builder.Append(c);
+                    }
                 }

                 builder.Append(".");

-                var lbl = Encoding.UTF8.GetString(labelArray.Array, labelArray.Offset, labelArray.Count);
-
-                original.Append(lbl);
+                var label = Encoding.UTF8.GetString(labelArray.Array, labelArray.Offset, labelArray.Count);
+                if (label.Contains(ACEPrefix))
+                {
+                    try
+                    {
+                        label = DnsString.IDN.GetUnicode(label);
+                    }
+                    catch { /* just do nothing in case the IDN is invalid, better to return something at least */ }
+                }
+
+                original.Append(label);
                 original.Append(".");
             }

@@ -248,7 +236,7 @@
                 orig += '.';
             }

-            return new DnsString(value, orig);
+            return new DnsString(orig, value);
         }

         // only used by the DnsQuestion as we don't expect any escaped chars in the actual query posted to and send back from the DNS Server (not supported).


simplified and fixed PositionInTime calculation.

It does not internally increment time counter anymore. It instead only
calculates ticks, and then calculate TimeSpan only when it is requested.

(For frequent requests it results in more calculation, but it is kind of
trade offs for consistent processing.)

--- lib/base/MidiPlayer.cs
+++ lib/base/MidiPlayer.cs
@@ -26,6 +26,7 @@
 	}

 	// Player implementation. Plays a MIDI song synchronously.
+	[Obsolete ("This class is an internal, will be removed in the next API-breaking updates.")]
 	public class MidiSyncPlayer : IDisposable, IMidiPlayerStatus
 	{
 		public MidiSyncPlayer (MidiMusic music)
@@ -58,9 +59,7 @@
 		}
 		public int PlayDeltaTime { get; set; }
 		public TimeSpan PositionInTime {
-			// FIXME: this is not exact after seek operation.
-			get { return GetTimerOffsetWithTempoRatio () + playtime_delta; }
-			// get { return TimeSpan.FromMilliseconds (music.GetTimePositionInMillisecondsForTick (PlayDeltaTime)); }
+			get { return TimeSpan.FromMilliseconds (music.GetTimePositionInMillisecondsForTick (PlayDeltaTime)); }
 		}
 		public int Tempo {
 			get { return current_tempo; }
@@ -70,27 +69,11 @@
 			get { return current_time_signature; }
 		}

-		public double TempoChangeRatio {
-			get { return tempo_ratio; }
-			set {
-				playtime_delta += GetTimerOffsetWithTempoRatio ();
-				timer_resumed = DateTime.Now;
-				tempo_ratio = value;
-			}
-		}
+		public double TempoChangeRatio { get; set; } = 1.0;
+
 		public int GetTotalPlayTimeMilliseconds ()
 		{
 			return MidiMusic.GetTotalPlayTimeMilliseconds (messages, music.DeltaTimeSpec);
-		}
-
-		TimeSpan GetTimerOffsetWithTempoRatio ()
-		{
-			switch (state) {
-			case PlayerState.Playing:
-			case PlayerState.FastForward:
-				return TimeSpan.FromMilliseconds ((DateTime.Now - timer_resumed).TotalMilliseconds * tempo_ratio);
-			}
-			return TimeSpan.Zero;
 		}

 		public virtual void Dispose ()
@@ -104,7 +87,6 @@
 		{
 			time_manager.Counting = true;
 			pause_handle.Set ();
-			timer_resumed = DateTime.Now;
 			state = PlayerState.Playing;
 		}

@@ -124,8 +106,6 @@
 		{
 			time_manager.Counting = false;
 			do_pause = true;
-			playtime_delta += DateTime.Now - timer_resumed;
-			timer_resumed = DateTime.Now;
 			Mute ();
 		}

@@ -134,7 +114,6 @@
 		public void PlayerLoop ()
 		{
 			AllControlReset ();
-			playtime_delta = TimeSpan.Zero;
 			{
 				while (true) {
 					pause_handle.WaitOne ();
@@ -163,15 +142,12 @@

 		int current_tempo = MidiMetaType.DefaultTempo;
 		byte [] current_time_signature = new byte [4];
-		double tempo_ratio = 1.0;
-		DateTime timer_resumed;
-		TimeSpan playtime_delta;

 		int GetDeltaTimeInMilliseconds (int deltaTime)
 		{
 			if (music.DeltaTimeSpec < 0)
 				throw new NotSupportedException ("SMPTe-basd delta time is not implemented yet");
-			return (int) (current_tempo / 1000 * deltaTime / music.DeltaTimeSpec / tempo_ratio);
+			return (int) (current_tempo / 1000 * deltaTime / music.DeltaTimeSpec / TempoChangeRatio);
 		}

 		string ToBinHexString (byte [] bytes)
@@ -240,7 +216,7 @@
 			var state = State;
 			seek_processor = seekProcessor ?? new SimpleSeekProcessor (ticks);
 			event_idx = 0;
-			PlayDeltaTime = 0;
+			PlayDeltaTime = ticks;
 		}
 	}

@@ -284,7 +260,8 @@
 				throw new ArgumentNullException ("output");
 			if (timeManager == null)
 				throw new ArgumentNullException ("timeManager");
-
+
+			this.music = music;
 			this.output = output;

 			player = new MidiSyncPlayer (music, timeManager);
@@ -318,6 +295,7 @@
 		}

 		IMidiOutput output;
+		MidiMusic music;
 		bool should_dispose_output;
 		byte [] buffer = new byte [0x100];
 		bool [] channel_mask;
@@ -352,8 +330,12 @@
 			get { return player.PlayDeltaTime; }
 		}

+		public int PositionInMilliseconds {
+			get { return music.GetTimePositionInMillisecondsForTick (PlayDeltaTime); }
+		}
+
 		public TimeSpan PositionInTime {
-			get { return player.PositionInTime; }
+			get { return TimeSpan.FromMilliseconds (PositionInMilliseconds); }
 		}

 		public int GetTotalPlayTimeMilliseconds ()


Microsoft.CSharp is not mark spurious (but should be !)"

--- src/FullBuild/Commands/Projects.cs
+++ src/FullBuild/Commands/Projects.cs
@@ -109,7 +109,7 @@
                 itemGroupPackage.AddAfterSelf(itemGroupFile);

                 // generate binary references
-                var spuriousReferences = projectDef.BinaryReferences.Where(x => !x.InvariantStartsWith("System"));
+                var spuriousReferences = projectDef.BinaryReferences.Where(x => !x.InvariantStartsWith("System") && ! x.InvariantEquals("Microsoft.CSharp"));
                 if (spuriousReferences.Any())
                 {
                     Console.WriteLine("WARNING: Project {0} has spurious binary references", projectDef.ProjectFile);


Use properties instead of fields

Use properties instead of fields

--- src/IniFileParser/Model/IniData.cs
+++ src/IniFileParser/Model/IniData.cs
@@ -1,6 +1,5 @@
 using System;
 using IniParser.Model.Configuration;
-using IniParser.Model.Formatting;

 namespace IniParser.Model
 {
@@ -13,7 +12,6 @@
         /// <summary>
         ///     Represents all sections from an INI file
         /// </summary>
-        SectionCollection _sections;
         protected IniScheme _schemeInternal;
         #endregion

@@ -25,9 +23,8 @@
         public IniData()
         {
             Global = new PropertyCollection();
-            _sections = new SectionCollection();
+            Sections = new SectionCollection();
             _schemeInternal = new IniScheme();
-            SectionKeySeparator = '.';
         }

         /// <summary>
@@ -51,13 +48,13 @@
         public IniData(SectionCollection sdc)
             :this()
         {
-            _sections = (SectionCollection)sdc.DeepClone();
+            Sections = sdc.DeepClone();
         }

         public IniData(IniData ori)
         {
-            _sections = ori._sections.DeepClone();
-            Global = (PropertyCollection)ori.Global.DeepClone();
+            Sections = ori.Sections.DeepClone();
+            Global = ori.Global.DeepClone();
             Configuration = ori.Configuration.DeepClone();
         }
         #endregion
@@ -74,7 +71,6 @@
         ///     Defaults to false.
         /// </remarks>
         public bool CreateSectionsIfTheyDontExist { get; set; } = false;
-

         /// <summary>
         ///     Configuration used to write an ini file with the proper
@@ -120,13 +116,13 @@
         {
             get
             {
-                if (!_sections.ContainsSection(sectionName))
+                if (!Sections.ContainsSection(sectionName))
                     if (CreateSectionsIfTheyDontExist)
-                        _sections.AddSection(sectionName);
+                        Sections.AddSection(sectionName);
                     else
                         return null;

-                return _sections[sectionName];
+                return Sections[sectionName];
             }
         }

@@ -134,11 +130,7 @@
         /// Gets or sets all the <see cref="Section"/>
         /// for this IniData instance.
         /// </summary>
-        public SectionCollection Sections
-        {
-            get { return _sections; }
-            set { _sections = value; }
-        }
+        public SectionCollection Sections { get; set; }

         /// <summary>
         ///     Used to mark the separation between the section name and the key name


refactor comments

refactor comments

--- src/KafkaNetClient/BrokerRouter.cs
+++ src/KafkaNetClient/BrokerRouter.cs
@@ -80,14 +80,9 @@
         /// Select a broker for a given topic using the IPartitionSelector function.
         /// </summary>
         /// <param name="topic">The topic to retreive a broker route for.</param>
-        /// <param name="key">
-        /// The key used by the IPartitionSelector to collate to a consistent partition. Null value
-        /// means key will be ignored in selection process.
-        /// </param>
+        /// <param name="key">The key used by the IPartitionSelector to collate to a consistent partition. Null value means key will be ignored in selection process.</param>
         /// <returns>A broker route for the given topic.</returns>
-        /// <exception cref="InvalidTopicNotExistsInCache">
-        /// Thrown if the topic metadata does not exist in the cache.
-        /// </exception>
+        /// <exception cref="InvalidTopicNotExistsInCache">Thrown if the topic metadata does not exist in the cache.</exception>
         public BrokerRoute SelectBrokerRouteFromLocalCache(string topic, byte[] key = null)
         {
             //get topic either from cache or server.
@@ -109,13 +104,10 @@
         /// <param name="topics">Collection of topics to request metadata for.</param>
         /// <returns>List of Topics as provided by Kafka.</returns>
         /// <remarks>
-        /// The topic metadata will by default check the cache first and then if it does not exist
-        /// it will then request metadata from the server. To force querying the metadata from the
-        /// server use <see cref="RefreshTopicMetadata"/>
+        /// The topic metadata will by default check the cache first and then if it does not exist it will then
+        /// request metadata from the server.  To force querying the metadata from the server use <see cref="RefreshTopicMetadata"/>
         /// </remarks>
-        /// <exception cref="InvalidTopicNotExistsInCache">
-        /// Thrown if the topic metadata does not exist in the cache.
-        /// </exception>
+        /// <exception cref="InvalidTopicNotExistsInCache">Thrown if the topic metadata does not exist in the cache.</exception>
         public List<Topic> GetTopicMetadataFromLocalCache(params string[] topics)
         {
             var topicSearchResult = SearchCacheForTopics(topics, null);
@@ -133,10 +125,8 @@
         /// </summary>
         /// <param name="topics">List of topics to update metadata for.</param>
         /// <remarks>
-        /// This method will ignore the cache and initiate a call to the kafka servers for all given
-        /// topics, updating the cache with the resulting metadata. Only call this method to force a
-        /// metadata update. For all other queries use <see cref="GetTopicMetadataFromLocalCache"/>
-        /// which uses cached values.
+        /// This method will ignore the cache and initiate a call to the kafka servers for all given topics, updating the cache with the resulting metadata.
+        /// Only call this method to force a metadata update.  For all other queries use <see cref="GetTopicMetadataFromLocalCache"/> which uses cached values.
         /// </remarks>

         public Task<bool> RefreshTopicMetadata(params string[] topics)


Added debug looging to detect problems related to misconfigured experiments

--- src/Kerbalism/Science/ScienceDB.cs
+++ src/Kerbalism/Science/ScienceDB.cs
@@ -625,6 +625,16 @@

 		public static BodiesSituationsBiomesSubject GetSubjectsForExperiment(ExperimentInfo expInfo)
 		{
+			if (!expBodiesSituationsBiomesSubject.ContainsKey(expInfo))
+			{
+				Lib.Log("ERROR: " + expInfo.ExperimentId + " isn't in the ScienceDB!!!");
+			}
+
+			if (ResearchAndDevelopment.Instance == null)
+			{
+				Lib.Log("ERROR: GetSubjectsForExperiment: RnD instance is null!!!");
+			}
+
 			return expBodiesSituationsBiomesSubject[expInfo];
 		}
 	}


Added case-sensitivity option to markov generator

--- src/MarkovTweet/MarkovGenerator.cs
+++ src/MarkovTweet/MarkovGenerator.cs
@@ -7,20 +7,39 @@
 {
     class MarkovGenerator
     {
-        // TODO make prefixes case insensitive, or at least add an option for it
-
         // the size of the prefix
         private int order;
         // A prefix is a set of n words, where n = the order of the generator.
         // A suffix is a single word, but a prefix can have an arbitrary number of suffixes.
         private Dictionary<List<string>, List<string>> prefixes;
         private Random rng;
-
-        public MarkovGenerator(int order)
+        private bool caseSensitive;
+
+        public MarkovGenerator(int order, bool caseSensitive)
         {
             this.order = order;
             this.prefixes = new Dictionary<List<string>, List<string>>(comparer: new PrefixComparer());
             this.rng = new Random();
+            this.caseSensitive = caseSensitive;
+        }
+
+        // returns the prefix with each member set to all lower case if the generator is in case-insensitive mode
+        // (prefix case-sensitivity should be a monad.)
+        private List<string> FixPrefixCase(List<string> prefix)
+        {
+            if (caseSensitive)
+            {
+                return prefix;
+            }
+            else
+            {
+                var lowerPrefix = new List<string>();
+                foreach (string s in prefix)
+                {
+                    lowerPrefix.Add(s.ToLower());
+                }
+                return lowerPrefix;
+            }
         }

         private class PrefixComparer : IEqualityComparer<List<string>>
@@ -73,14 +92,17 @@
             }
         }

+        /*
         private void AddPrefixSuffixPair(List<string> prefix, string suffix)
         {
             if (prefix.Count != order)
             {
                 throw new ArgumentException("Prefix is of wrong size: Markov chain is order " + order + ", prefix length is " + prefix.Count);
             }
-            prefixes[prefix].Add(suffix);
-        }
+            var fixedPrefix = FixPrefixCase(prefix);
+            prefixes[fixedPrefix].Add(suffix);
+        }
+        */

         private String GetSuffix(List<string> prefix)
         {
@@ -89,11 +111,16 @@
                 throw new ArgumentException("Prefix is of wrong size: Markov chain is order " + order + ", prefix length is " + prefix.Count);
             }
             // TODO fix null pointer exception occasionally thrown here
-            var curPrefix = prefixes[prefix];
+            // Why would there ever exist a prefix without a suffix?
+            // something could have gone wrong when initially adding the prefix,
+            // or when initially adding the suffix,
+            // or the prefix given to this method is wrong, somehow.
+            var fixedPrefix = FixPrefixCase(prefix);
+            var curPrefix = prefixes[fixedPrefix];

             int index = rng.Next(curPrefix.Count);

-            return prefixes[prefix][index];
+            return prefixes[fixedPrefix][index];
         }

         public void ReadInput(string input)
@@ -108,7 +135,7 @@
             words.Add("");

             // fill the current prefix so we have something to start with
-            List<string> curPrefix = words.Take(order).ToList();
+            List<string> curPrefix = FixPrefixCase((words.Take(order).ToList()));

             // now we step through each word, adding it to the suffix-list of the current prefix,
             // then updating the prefix, "shifting" it along the input text
@@ -136,7 +163,7 @@
                 newPrefix.AddRange(curPrefix);
                 newPrefix.Add(word);
                 newPrefix.RemoveAt(0);
-                curPrefix = newPrefix;
+                curPrefix = FixPrefixCase(newPrefix);
             }
         }


Bugfix. Should've been <=

Bugfix. Should've been <=

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

--- src/MonoTorrent.Client/BitField.cs
+++ src/MonoTorrent.Client/BitField.cs
@@ -270,7 +270,7 @@
             int start;
             int end;

-            for (int i = (startIndex/32); i < (endIndex/32); i++)
+            for (int i = (startIndex/32); i <= (endIndex/32); i++)
             {
                 if (this.array[i] == 0)        // This one has no true values
                     continue;


Log creating a child session

Log creating a child session

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@4849

--- src/NHibernate/Impl/SessionImpl.cs
+++ src/NHibernate/Impl/SessionImpl.cs
@@ -2436,6 +2436,7 @@

 				if (rtn == null)
 				{
+					log.DebugFormat("Creating child session with {0}", entityMode);
 					rtn = new SessionImpl(this, entityMode);
 					childSessionsByEntityMode.Add(entityMode, rtn);
 				}


implemented IDisposable according to .net standards - finalizer, Dispose,
and Dispose(bool).  Still need to modify some other classes for IDisposable
and to throw ObjectDisposedException on certain operations.

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@1241

--- src/NHibernate/Impl/SessionImpl.cs
+++ src/NHibernate/Impl/SessionImpl.cs
@@ -36,13 +36,41 @@
 		private bool autoClose;
 		private long timestamp;

-		private bool closed = false;
+		///
+		/// Indicates if the Session has been closed.
+		///
+		/// <value>
+		/// <c>false</c> (by default) if the Session is Open and can be used,
+		/// <c>true</c> if the Session has had the methods <c>Close()</c> or
+		/// <c>Dispose()</c> invoked.</value>
+		private bool closed;
 		private FlushMode flushMode = FlushMode.Auto;

+		///
+		/// A boolean indicating if the method AfterTransactionCompletion() should
+		/// be called from the method Disconnect().
+		///
+		/// <value>
+		/// <c>true</c> (by default) if the method should be called.
+		/// </value>
+		/// <remarks>
+		/// This is set to false when the method BeginTransaction() is invoked
+		/// because the Transaction will call the method AfterTransactionCompletion()
+		/// when the Transaction is Committed.
+		/// </remarks>
 		private bool callAfterTransactionCompletionFromDisconnect = true;

-		private IDictionary entitiesByKey; //key=Key, value=Object
-		private IDictionary proxiesByKey; //key=Key, value=HibernateProxy
+		///
+		/// An <see cref="IDictionary"/> with the <see cref="Key"/> as the key
+		/// and an <see cref="Object"/> as the value.
+		///
+		private IDictionary entitiesByKey;
+
+		///
+		/// An <see cref="IDictionary"/> with the <see cref="Key"/> as the key
+		/// and an <see cref="INHibernateProxy"/> as the value.
+		///
+		private IDictionary proxiesByKey;

 		// these are used to serialize the proxiesByKey Dictionary - I was not able to
 		// have a Hashtable serialize fully by the time that SessionImpl OnDeserialization
@@ -54,22 +82,56 @@

 		//IdentityMaps are serializable in NH
-		private IdentityMap entries; //key=Object, value=EntityEntry
-		private IdentityMap arrayHolders; //key=array, value=ArrayHolder
-		private IdentityMap collections; //key=PersistentCollection, value=CollectionEntry
-
-		private ISet nullifiables = new HashedSet(); //set of Keys of deleted objects
+		///
+		/// An <see cref="IdentityMap"/> with the <see cref="Object"/> as the key
+		/// and an <see cref="EntityEntry"/> as the value.
+		///
+		private IdentityMap entries;
+		///
+		/// An <see cref="IdentityMap"/> with the <see cref="Array"/> as the key
+		/// and an <see cref="ArrayHolder"/> as the value.
+		///
+		private IdentityMap arrayHolders;
+		///
+		/// An <see cref="IdentityMap"/> with the <see cref="PersistentCollection"/> as the key
+		/// and an <see cref="CollectionEntry"/> as the value.
+		///
+		private IdentityMap collections;
+
+		///
+		/// An <see cref="ISet"/> of <see cref="Key"/> objects of the deleted entities.
+		///
+		private ISet nullifiables = new HashedSet();

 		private IInterceptor interceptor;

 		[NonSerialized]
 		private IDbConnection connection;

+		///
+		/// A boolean indicating if the Session should automattically connect to the
+		/// database - ie, open a new <see cref="IDbConnection"/> for the operation if
+		/// <c>this.Connection==null</c>.
+		///
+		/// <remarks>
+		///

+		/// This will be initialzed to <c>true</c> by the ctor if NHibernate is managing
+		/// the Connections, <c>false</c> if the user passes in their own connection -
+		/// indicating they will be responsible for managing connections.
+		///

+		///

+		/// This can also be set to <c>false</c> when NHibernate has opened the connection
+		/// on its own and the Session has had the methods <c>Close()</c> or
+		/// <c>Disconnect()</c> invoked.
+		///

+		///

+		/// This can also be set to <c>true</c> when the Session has had the method
+		/// <c>Reconnect()</c> invoked.
+		///

+		/// </remarks>
 		[NonSerialized]
 		private bool connect;

-		// TODO: find out if we want the reference to IDbTransaction or ITransaction - leaning
-		// towards an ITransaction because we can get the IDbTransaction from that.
 		[NonSerialized]
 		private ITransaction transaction;

@@ -354,7 +416,17 @@

 			try
 			{
-				return ( connection == null ) ? null : Disconnect();
+				// when the connection is null nothing needs to be done - if there
+				// is a value for connection then Disconnect() was not called - so we
+				// need to ensure it gets called.
+				if( connection==null )
+				{
+					return null;
+				}
+				else
+				{
+					return Disconnect();
+				}
 			}
 			finally
 			{
@@ -362,7 +434,11 @@
 			}
 		}

-		///
+		///
+		/// Ensure that the locks are downgraded to <see cref="LockMode.None"/>
+		/// and that all of the softlocks in the <see cref="Cache"/> have
+		/// been released.
+		///
 		public void AfterTransactionCompletion()
 		{
 			log.Debug( "transaction completion" );
@@ -392,7 +468,9 @@
 			}
 			executions.Clear();

-			callAfterTransactionCompletionFromDisconnect = true; //not really necessary
+			// the transaction was completed so reset the field callAfter... to its default
+			// value.
+			callAfterTransactionCompletionFromDisconnect = true; //h2.0.3-not really necessary
 		}

 		private void InitTransientCollections()
@@ -406,6 +484,11 @@
 			executions = new ArrayList( 50 );
 		}

+		///
+		/// Mark the Session as being closed and Clear out the HashTables of
+		/// entities and proxies along with the Identity Maps for entries, array
+		/// holders, collections, and nullifiables.
+		///
 		private void Cleanup()
 		{
 			closed = true;
@@ -3847,7 +3930,17 @@
 			}
 		}

-		///
+		///
+		/// Gets if the ISession is connected.
+		///
+		/// <value>
+		/// <c>true</c> if the ISession is connected.
+		/// </value>
+		/// <remarks>
+		/// An ISession is considered connected if there is an <see cref="IDbConnection"/> (regardless
+		/// of its state) or if it the field <c>connect</c> is true.  Meaning that it will connect
+		/// at the next operation that requires a connection.
+		/// </remarks>
 		public bool IsConnected
 		{
 			get { return connection != null || connect; }
@@ -3860,14 +3953,17 @@

 			try
 			{
+				// the Session is flagged as needing to create a Connection for the
+				// next operation
 				if( connect )
 				{
+					// a Disconnected Session should not automattically "connect"
 					connect = false;
 					return null;
 				}
 				else
 				{
-					if( connection == null )
+					if( connection==null )
 					{
 						throw new HibernateException( "session already disconnected" );
 					}
@@ -3876,21 +3972,34 @@
 					{
 						batcher.CloseCommands();
 					}
+
+					// get a new reference to the the Session's connection before
+					// closing it - and set the existing to Session's connection to
+					// null but don't close it yet
 					IDbConnection c = connection;
 					connection = null;
+
+					// if Session is supposed to auto-close the connection then
+					// the Sesssion is managing the IDbConnection.
 					if( autoClose )
 					{
+						// let the SessionFactory close it and return null
+						// because the connection is internal to the Session
 						factory.CloseConnection( c );
 						return null;
 					}
 					else
 					{
+						// return the connection the user provided - at this point
+						// it has been disassociated with the NHibernate session.
 						return c;
 					}
 				}
 			}
 			finally
 			{
+				// ensure that AfterTransactionCompletion gets called since
+				// it takes care of the Locks and Cache.
 				if( callAfterTransactionCompletionFromDisconnect )
 				{
 					AfterTransactionCompletion();
@@ -3927,30 +4036,100 @@
 		#region System.IDisposable Members

 		///
+		/// A flag to indicate if <c>Disose()</c> has been called.
+		///
+		private bool _isAlreadyDisposed;
+
+		///
+		/// Finalizer that ensures the object is correctly disposed of.
+		///
+		~SessionImpl()
+		{
+			Dispose( false );
+		}
+
+		///
 		/// Just in case the user forgot to Commit() or Close()
 		///
-		void IDisposable.Dispose()
+		public void Dispose()
 		{
 			log.Debug( "running ISession.Dispose()" );
-
-			// it was never disconnected
-			if( connection != null )
-			{
-				AfterTransactionCompletion();
-
-				if( connection.State == ConnectionState.Closed )
-				{
-					log.Warn( "finalizing unclosed session with closed connection" );
-				}
-				else
-				{
-					log.Warn( "unclosed connection" );
-					if( autoClose )
-					{
-						connection.Close();
-					}
-				}
-			}
+			Dispose( true );
+
+//			// it was never disconnected
+//			if( connection != null )
+//			{
+//				AfterTransactionCompletion();
+//
+//				if( connection.State == ConnectionState.Closed )
+//				{
+//					log.Warn( "finalizing unclosed session with closed connection" );
+//				}
+//				else
+//				{
+//					log.Warn( "unclosed connection" );
+//					if( autoClose )
+//					{
+//						connection.Close();
+//					}
+//				}
+//			}
+		}
+
+		///
+		/// Takes care of freeing the managed and unmanaged resources that
+		/// this class is responsible for.
+		///
+		/// <param name="isDisposing">Indicates if this Session is being Disposed of or Finalized.</param>
+		/// <remarks>
+		/// If this Session is being Finalized (<c>isDisposing==false</c>) then make sure not
+		/// to call any methods that could potentially bring this Session back to life.
+		/// </remarks>
+		protected virtual void Dispose(bool isDisposing)
+		{
+			if( _isAlreadyDisposed )
+			{
+				// don't dispose of multiple times.
+				return;
+			}
+
+			// free managed resources that are being managed by the session if we
+			// know this call came through Dispose()
+			if( isDisposing )
+			{
+				// we are not reusing the Close() method because that sets the connection==null
+				// during the Close() - if the connection is null we can't get to it to Dispose
+				// of it.
+				if( connection!=null )
+				{
+					// ensure the Locks are downgraded and the Cache releases its softlocks.
+					AfterTransactionCompletion();
+				}
+				//TODO: add a Dispose to IBatcher (NDataReader), & ITransaction
+
+				// if the Session is responsible for managing the connection then make sure
+				// the connection is disposed of.
+				if( autoClose )
+				{
+					if( connection!=null )
+					{
+						connection.Dispose();
+					}
+				}
+
+				// it is important to call Cleanup because that marks the Session as being
+				// closed - the Session could still be associated with a Proxy that is attempting
+				// to be reassociated with another Session.  If the Proxy sees ISession.IsOpen==true
+				// then an exception will be thrown for trying to associate it with 2 open sessions.
+				Cleanup();
+
+			}
+
+			// free unmanaged resources here
+
+			_isAlreadyDisposed = true;
+			// nothing for Finalizer to do - so tell the GC to ignore it
+			GC.SuppressFinalize( this );
 		}

 		#endregion


-h now properly shows and works with aliases

--- src/NadekoBot/Modules/Help/Help.cs
+++ src/NadekoBot/Modules/Help/Help.cs
@@ -76,11 +76,19 @@
                 await (await (umsg.Author as IGuildUser).CreateDMChannelAsync()).SendMessageAsync(HelpString).ConfigureAwait(false);
                 return;
             }
-            var com = _commands.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind);
+            var com = _commands.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind));

+            if (com == null)
+            {
+                await channel.SendMessageAsync("`No command found.`");
+                return;
+            }
+            var str = $"**__Help for:__ `{com.Text}`**";
+            var alias = com.Aliases.Skip(1).FirstOrDefault();
+            if (alias != null)
+                str += $" / `{ alias }`";
             if (com != null)
-                await channel.SendMessageAsync($@"**__Help for:__ `{com.Text}`**
-**Desc:** {com.Description}
+                await channel.SendMessageAsync(str + $@"{Environment.NewLine}**Desc:** {com.Description}
 **Usage:** {com.Summary}").ConfigureAwait(false);
         }


Updated program to fire off package restore

--- src/OmniSharp.Bootstrap/Program.cs
+++ src/OmniSharp.Bootstrap/Program.cs
@@ -1,8 +1,10 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.IO;
 using System.Linq;
 using System.Security.Cryptography;
+using System.Text;
 using System.Threading.Tasks;
 using Microsoft.Framework.Runtime;
 using Newtonsoft.Json;
@@ -13,22 +15,24 @@
     public class Program
     {
         private readonly IApplicationEnvironment _appEnv;
-        private readonly string[] _nonPlugins = { "OmniSharp.Plugins", "OmniSharp.Stdio", "OmniSharp", "OmniSharp.Stdio" };
+        private readonly string[] _nonPlugins = { "OmniSharp.Plugins", "OmniSharp.Abstractions", "OmniSharp.Stdio", "OmniSharp", "OmniSharp.Stdio" };

         public Program(IApplicationEnvironment appEnv)
         {
             _appEnv = appEnv;
         }

-        public void Main(string[] args)
+        public int Main(string[] args)
         {
             var enumerator = args.GetEnumerator();
             var pluginPaths = new List<string>();
             var bootstrapPath = Path.GetDirectoryName(_appEnv.ApplicationBasePath);
             var omnisharpProjectPath = Path.Combine(bootstrapPath, "OmniSharp", "project.json");
-            if (!File.Exists(omnisharpProjectPath)) {
+            if (!File.Exists(omnisharpProjectPath))
+            {
                 omnisharpProjectPath = Path.Combine(bootstrapPath, "OmniSharp", "1.0.0", "root", "project.json");
             }
+
             var defaultFrameworks = JObject.Parse(File.ReadAllText(omnisharpProjectPath))["frameworks"]
                 .Select(x => x.Path.Replace("frameworks.", ""))
                 .OrderBy(x => x).ToArray();
@@ -39,7 +43,7 @@
             {
                 var arg = (string)enumerator.Current;

-                if (arg == "--plugin")
+                if (arg == "--plugins")
                 {
                     enumerator.MoveNext();
                     pluginPaths.Add((string)enumerator.Current);
@@ -57,41 +61,33 @@
             var md5 = MD5.Create();

             var pluginAges = new Dictionary<string, string>();
-            var offset = 0;
+            var sb = new StringBuilder();

             // OrderBy ensures consistent hashing
             foreach (var path in pluginPaths.OrderBy(x => x))
             {
-                var bytes = System.Text.Encoding.UTF8.GetBytes(path);
-                md5.TransformBlock(bytes, offset, bytes.Length, null, 0);
-
-                var projectJsonFiles = Directory.EnumerateFiles(path, "project.json", SearchOption.AllDirectories).OrderBy(x => x);
-                foreach (var projectJson in projectJsonFiles)
-                {
-                    var writeTime = File.GetLastWriteTime(projectJson);
-                    bytes = System.Text.Encoding.UTF8.GetBytes(writeTime.Ticks.ToString());
-                    md5.TransformBlock(bytes, offset, bytes.Length, null, 0);
-                }
-
-                var omnisharpPlugins = Directory.EnumerateFiles(path, "omnisharp.plugin", SearchOption.AllDirectories).OrderBy(x => x);
-                foreach (var omnisharpPlugin in omnisharpPlugins)
-                {
-                    var writeTime = File.GetLastWriteTime(omnisharpPlugin);
-                    bytes = System.Text.Encoding.UTF8.GetBytes(writeTime.Ticks.ToString());
-                    md5.TransformBlock(bytes, offset, bytes.Length, null, 0);
-                }
-            }
-
-            md5.TransformFinalBlock(new byte[0], 0, 0);
-
-            var hash = string.Join("", Convert.ToBase64String(md5.Hash).Except(Path.GetInvalidFileNameChars()));
-            Console.WriteLine(hash);
+                sb.AppendLine(path);
+
+                var projectOrPlugins = Directory.EnumerateFiles(path, "project.json", SearchOption.AllDirectories)
+                    .Concat(Directory.EnumerateFiles(path, "omnisharp.plugin", SearchOption.AllDirectories))
+                    .OrderBy(x => x)
+                    .Where(project => !_nonPlugins.Any(z => project.EndsWith($"{Path.DirectorySeparatorChar}{z}{Path.DirectorySeparatorChar}")));
+
+                foreach (var projectOrPlugin in projectOrPlugins)
+                {
+                    var writeTime = File.GetLastWriteTime(projectOrPlugin);
+                    sb.Append(projectOrPlugin);
+                    sb.AppendLine(writeTime.Ticks.ToString());
+                }
+            }
+
+            var hash = string.Join("", Convert.ToBase64String(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(sb.ToString()))).Except(Path.GetInvalidFileNameChars()));
             var omnisharpPath = Path.Combine(omnisharpHome, hash);
-            // if (Directory.Exists(omnisharpPath))
-            // {
-            //     Console.Write(Path.Combine(omnisharpPath, "bootstrap/OmniSharp.WithPlugins"));
-            //     return;
-            // }
+            if (Directory.Exists(omnisharpPath))
+            {
+                Console.WriteLine(Path.Combine(omnisharpPath, "bootstrap", "Bootstrapper"));
+                return 0;
+            }

             Directory.CreateDirectory(omnisharpPath);
             var globalJobject = new JObject();
@@ -105,11 +101,12 @@
             File.WriteAllText(Path.Combine(omnisharpPath, "global.json"), globalJobject.ToString());

             Directory.CreateDirectory(Path.Combine(omnisharpPath, "bootstrap"));
-            Directory.CreateDirectory(Path.Combine(omnisharpPath, "bootstrap", "OmniSharp.WithPlugins"));
+            Directory.CreateDirectory(Path.Combine(omnisharpPath, "bootstrap", "Bootstrapper"));

             var pluginDirectories = pluginPaths
                 .SelectMany(pluginPath => Directory.EnumerateDirectories(pluginPath)
                     .Where(directory => File.Exists(Path.Combine(directory, "project.json")) || File.Exists(Path.Combine(directory, "1.0.0", "root", "project.json"))))
+                    .Where(directory => !_nonPlugins.Any(z => directory.EndsWith($"{Path.DirectorySeparatorChar}{z}")))
                     .ToArray();

             var allDeps = new Dictionary<string, string>();
@@ -120,6 +117,8 @@
                 frameworkDeps.Add(framework, new Dictionary<string, string>());
             }

+            Console.WriteLine(string.Join(",", pluginDirectories));
+
             foreach (var dir in pluginDirectories)
             {
                 JObject json = null;
@@ -138,17 +137,11 @@
                 if (json != null)
                 {
                     var name = Path.GetFileName(dir);
-                    Console.WriteLine(name);
-
                     var frameworks = json["frameworks"].Select(x => x.Path.Replace("frameworks.", "")).OrderBy(x => x).ToArray();

                     if (defaultFrameworks.SequenceEqual(frameworks))
                     {
-                        if (allDeps.ContainsKey(name))
-                        {
-                            Console.WriteLine($"name found {name}");
-                        }
-                        else
+                        if (!allDeps.ContainsKey(name))
                         {
                             allDeps.Add(name, "1.0.0-*");
                         }
@@ -162,12 +155,7 @@
                                 Dictionary<string, string> deps = null;
                                 if (frameworkDeps.TryGetValue(framework, out deps))
                                 {
-                                    if (deps.ContainsKey(name))
-                                    {
-                                        Console.WriteLine($"name found {name}");
-                                    }
-                                    else
-                                    {
+                                    if (!deps.ContainsKey(name)) {
                                         deps.Add(name, "1.0.0-*");
                                     }
                                 }
@@ -193,13 +181,144 @@
             projectJobject["frameworks"] = frameworksJobject;
             projectJobject["entryPoint"] = new JValue("OmniSharp");

-            File.WriteAllText(Path.Combine(omnisharpPath, "bootstrap", "OmniSharp.WithPlugins", "project.json"), projectJobject.ToString());
-            File.Copy(Path.Combine(Path.GetDirectoryName(omnisharpProjectPath), "config.json"), Path.Combine(omnisharpPath, "bootstrap", "OmniSharp.WithPlugins", "config.json"));
+            var bootstrapProjectPath = Path.Combine(omnisharpPath, "bootstrap", "Bootstrapper", "project.json");
+            File.WriteAllText(bootstrapProjectPath, projectJobject.ToString());
+            File.Copy(Path.Combine(Path.GetDirectoryName(omnisharpProjectPath), "config.json"), Path.Combine(omnisharpPath, "bootstrap", "Bootstrapper", "config.json"));

             // Scaffold out an app that uses OmniSharp, has a global.json that references all the Plugins that we want to load.
             // Put that in a temporary directory
             // return the full Path to the folder that will Run omnisharp

+            Console.WriteLine(Path.Combine(omnisharpPath, "bootstrap", "Bootstrapper"));
+
+            PackageRestore(bootstrapProjectPath, "1.0.0-beta4");
+
+            return 0;
+        }
+
+        private int PackageRestore(string project, string version)
+        {
+            var psi = new ProcessStartInfo()
+            {
+                FileName = FirstPath(GetRuntimePath(version), "dnu", "dnu.cmd"),
+                WorkingDirectory = Path.GetDirectoryName(project),
+                CreateNoWindow = true,
+                UseShellExecute = false,
+                RedirectStandardOutput = true,
+                RedirectStandardError = true,
+                Arguments = "restore"
+            };
+
+            var restoreProcess = Process.Start(psi);
+            if (restoreProcess.HasExited)
+            {
+                return restoreProcess.ExitCode;
+            }
+
+            restoreProcess.BeginOutputReadLine();
+            restoreProcess.BeginErrorReadLine();
+            restoreProcess.WaitForExit();
+
+            return 0;
+        }
+
+        private string GetRuntimePath(string version)
+        {
+            var seachedLocations = new List<string>();
+
+            foreach (var location in GetRuntimeLocations())
+            {
+                //  Need to expand variables, because DNX_HOME variable might include %USERPROFILE%.
+                var paths = GetRuntimePathsFromVersionOrAlias(version, Environment.ExpandEnvironmentVariables(location));
+
+                foreach (var path in paths)
+                {
+                    if (string.IsNullOrEmpty(path))
+                    {
+                        continue;
+                    }
+
+                    if (Directory.Exists(path))
+                    {
+                        return path;
+                    }
+
+                    seachedLocations.Add(path);
+                }
+            }
+
+            throw new Exception(string.Format("The specified runtime path '{0}' does not exist. Searched locations {1}.\nVisit https://github.com/aspnet/Home for an installation guide.", version, string.Join("\n", seachedLocations)));
+        }
+
+        private IEnumerable<string> GetRuntimeLocations()
+        {
+            yield return Environment.GetEnvironmentVariable("DNX_HOME") ?? string.Empty;
+
+            //  %HOME% and %USERPROFILE% might point to different places.
+            foreach (var home in new string[] { Environment.GetEnvironmentVariable("HOME"), Environment.GetEnvironmentVariable("USERPROFILE") }.Where(s => !string.IsNullOrEmpty(s)))
+            {
+                // Newer path
+                yield return Path.Combine(home, ".dnx");
+            }
+        }
+
+        private IEnumerable<string> GetRuntimePathsFromVersionOrAlias(string versionOrAlias, string runtimePath)
+        {
+            // Newer format
+            yield return GetRuntimePathFromVersionOrAlias(versionOrAlias, runtimePath, ".dnx", "dnx-mono.{0}", "dnx-clr-win-x86.{0}", "runtimes");
+        }
+
+        private string GetRuntimePathFromVersionOrAlias(string versionOrAlias,
+                                                        string runtimeHome,
+                                                        string sdkFolder,
+                                                        string monoFormat,
+                                                        string windowsFormat,
+                                                        string runtimeFolder)
+        {
+            if (string.IsNullOrEmpty(runtimeHome))
+            {
+                return null;
+            }
+
+            var aliasDirectory = Path.Combine(runtimeHome, "alias");
+
+            var aliasFiles = new[] { "{0}.alias", "{0}.txt" };
+
+            // Check alias first
+            foreach (var shortAliasFile in aliasFiles)
+            {
+                var aliasFile = Path.Combine(aliasDirectory, string.Format(shortAliasFile, versionOrAlias));
+
+                if (File.Exists(aliasFile))
+                {
+                    var fullName = File.ReadAllText(aliasFile).Trim();
+
+                    return Path.Combine(runtimeHome, runtimeFolder, fullName);
+                }
+            }
+
+            // There was no alias, look for the input as a version
+            var version = versionOrAlias;
+
+            if (PlatformHelper.IsMono)
+            {
+                return Path.Combine(runtimeHome, runtimeFolder, string.Format(monoFormat, versionOrAlias));
+            }
+            else
+            {
+                return Path.Combine(runtimeHome, runtimeFolder, string.Format(windowsFormat, versionOrAlias));
+            }
+        }
+
+        internal static string FirstPath(string runtimePath, params string[] candidates)
+        {
+            if (runtimePath == null)
+            {
+                return null;
+            }
+            return candidates
+                .Select(candidate => Path.Combine(runtimePath, "bin", candidate))
+                .FirstOrDefault(File.Exists);
         }
     }
 }


Properly initialize projections database.

--- src/PushNotifications.WS/Cronus.cs
+++ src/PushNotifications.WS/Cronus.cs
@@ -95,6 +95,7 @@
                     .WithConnectionString(ApplicationConfiguration.Get("pushnot_conn_str_projections"))
                     .Build();
                 var session = cluster.ConnectAndCreateDefaultKeyspaceIfNotExists();
+                session.InitializeProjectionDatabase(Assembly.GetAssembly(typeof(APNSSubscriptionsProjection)));
                 return session;
             }
         }


Minor changes (renamings)

Minor changes (renamings)

--- src/RabbitDB/Storage/DbProvider.cs
+++ src/RabbitDB/Storage/DbProvider.cs
@@ -73,13 +73,13 @@
             return _dbCommand.ExecuteReader();
         }

-        public virtual ObjectReader<T> ExecuteReader<T>(IQuery query)
+        public virtual EntityReader<T> ExecuteReader<T>(IQuery query)
         {
             CreateConnection();
             _dbCommand = query.Compile(this);
             _dbCommand.Transaction = _dbTransaction;

-            return new ObjectReader<T>(_dbCommand.ExecuteReader(), this);
+            return new EntityReader<T>(_dbCommand.ExecuteReader(), this);
         }

         public virtual T ExecuteScalar<T>(IQuery query)


refactor: upgrade C#

refactor: upgrade C#

--- src/Reni/SyntaxTree/ValueSyntax.cs
+++ src/Reni/SyntaxTree/ValueSyntax.cs
@@ -3,6 +3,7 @@
 using hw.DebugFormatter;
 using hw.Helper;
 using hw.Scanner;
+using JetBrains.Annotations;
 using Reni.Basics;
 using Reni.Context;
 using Reni.Helper;
@@ -11,109 +12,109 @@
 using Reni.Type;
 using Reni.Validation;

-namespace Reni.SyntaxTree
+namespace Reni.SyntaxTree;
+
+/// <summary>
+///     Static syntax items that represent a value
+/// </summary>
+abstract class ValueSyntax : Syntax, IStatementSyntax
 {
-    /// <summary>
-    ///     Static syntax items that represent a value
-    /// </summary>
-    abstract class ValueSyntax : Syntax, IStatementSyntax
+    internal new abstract class NoChildren : ValueSyntax
     {
-        internal new abstract class NoChildren : ValueSyntax
-        {
-            protected NoChildren(Anchor anchor, Issue issue = null)
-                : base(anchor, issue)
-                => anchor.AssertIsNotNull();
-
-            [DisableDump]
-            protected sealed override int DirectChildCount => 0;
-
-            protected sealed override Syntax GetDirectChild(int index)
-                => throw new($"Unexpected call: {nameof(GetDirectChild)}({index})");
-        }
-
-        // Used for debug only
-        [DisableDump]
-        [Node]
-        internal readonly FunctionCache<ContextBase, ResultCache> ResultCache = new();
-
-        protected ValueSyntax(Anchor anchor, Issue issue = null)
+        protected NoChildren(Anchor anchor, Issue issue = null)
             : base(anchor, issue)
             => anchor.AssertIsNotNull();

-        protected ValueSyntax(int objectId, Anchor anchor, Issue issue = null)
-            : base(anchor, issue, objectId) { }
+        [DisableDump]
+        protected sealed override int DirectChildCount => 0;

-        DeclarerSyntax IStatementSyntax.Declarer => null;
+        protected sealed override Syntax GetDirectChild(int index)
+            => throw new($"Unexpected call: {nameof(GetDirectChild)}({index})");
+    }

-        SourcePart IStatementSyntax.SourcePart => Anchor.SourceParts.Combine();
+    // Used for debug only
+    [DisableDump]
+    [Node]
+    [UsedImplicitly]
+    internal readonly FunctionCache<ContextBase, ResultCache> ResultCache = new();

-        ValueSyntax IStatementSyntax.ToValueSyntax(Anchor anchor) => this;
+    protected ValueSyntax(Anchor anchor, Issue issue = null)
+        : base(anchor, issue)
+        => anchor.AssertIsNotNull();

-        ValueSyntax IStatementSyntax.Value => this;
+    protected ValueSyntax(int objectId, Anchor anchor, Issue issue = null)
+        : base(anchor, issue, objectId) { }

-        IStatementSyntax IStatementSyntax.With(Anchor frameItems)
-        {
-            if(frameItems == null || !frameItems.Items.Any())
-                return this;
-            NotImplementedMethod(frameItems);
-            return default;
-        }
+    DeclarerSyntax IStatementSyntax.Declarer => null;

-        [DisableDump]
-        internal virtual bool IsLambda => false;
+    SourcePart IStatementSyntax.SourcePart => Anchor.SourceParts.Combine();

-        [DisableDump]
-        internal virtual bool? IsHollow => IsLambda? true : null;
+    ValueSyntax IStatementSyntax.ToValueSyntax(Anchor anchor) => this;

-        [DisableDump]
-        internal virtual IRecursionHandler RecursionHandler => null;
+    ValueSyntax IStatementSyntax.Value => this;

-        //[DebuggerHidden]
-        internal virtual Result ResultForCache(ContextBase context, Category category)
-        {
-            NotImplementedMethod(context, category);
-            return null;
-        }
+    IStatementSyntax IStatementSyntax.With(Anchor frameItems)
+    {
+        if(frameItems == null || !frameItems.Items.Any())
+            return this;
+        NotImplementedMethod(frameItems);
+        return default;
+    }

-        internal virtual ValueSyntax Visit(ISyntaxVisitor visitor)
-        {
-            NotImplementedMethod(visitor);
-            return null;
-        }
+    [DisableDump]
+    internal virtual bool IsLambda => false;

-        [DisableDump]
-        internal Issue[] AllIssues => this.CachedValue(GetAllIssues);
+    [DisableDump]
+    internal virtual bool? IsHollow => IsLambda? true : null;

-        Issue[] GetAllIssues() => this
-            .GetNodesFromLeftToRight()
-            .SelectMany(node => node?.Issues)
-            .ToArray();
+    [DisableDump]
+    internal virtual IRecursionHandler RecursionHandler => null;

-        internal void AddToCacheForDebug(ContextBase context, ResultCache cacheItem)
-            => ResultCache.Add(context, cacheItem);
+    //[DebuggerHidden]
+    internal virtual Result ResultForCache(ContextBase context, Category category)
+    {
+        NotImplementedMethod(context, category);
+        return null;
+    }

-        internal Result Result(ContextBase context) => context.Result(Category.All, this);
+    internal virtual ValueSyntax Visit(ISyntaxVisitor visitor)
+    {
+        NotImplementedMethod(visitor);
+        return null;
+    }

-        internal BitsConst Evaluate(ContextBase context)
-            => Result(context).Evaluate(context.RootContext.ExecutionContext);
+    [DisableDump]
+    internal Issue[] AllIssues => this.CachedValue(GetAllIssues);

-        //[DebuggerHidden]
-        internal TypeBase Type(ContextBase context) => context.Result(Category.Type, this)?.Type;
+    Issue[] GetAllIssues() => this
+        .GetNodesFromLeftToRight()
+        .SelectMany(node => node?.Issues)
+        .ToArray();

-        internal bool IsHollowStructureElement(ContextBase context)
-        {
-            var result = IsHollow;
-            if(result != null)
-                return result.Value;
+    internal void AddToCacheForDebug(ContextBase context, ResultCache cacheItem)
+        => ResultCache.Add(context, cacheItem);

-            var type = context.TypeIfKnown(this);
-            return (type ?? Type(context)).SmartUn<FunctionType>().IsHollow;
-        }
+    internal Result Result(ContextBase context) => context.Result(Category.All, this);

-        internal ValueSyntax ReplaceArg(ValueSyntax syntax)
-            => Visit(new ReplaceArgVisitor(syntax)) ?? this;
+    internal BitsConst Evaluate(ContextBase context)
+        => Result(context).Evaluate(context.RootContext.ExecutionContext);

-        internal IEnumerable<string> GetDeclarationOptions(ContextBase context)
-            => Type(context).DeclarationOptions;
+    //[DebuggerHidden]
+    internal TypeBase Type(ContextBase context) => context.Result(Category.Type, this)?.Type;
+
+    internal bool IsHollowStructureElement(ContextBase context)
+    {
+        var result = IsHollow;
+        if(result != null)
+            return result.Value;
+
+        var type = context.TypeIfKnown(this);
+        return (type ?? Type(context)).SmartUn<FunctionType>().IsHollow;
     }
+
+    internal ValueSyntax ReplaceArg(ValueSyntax syntax)
+        => Visit(new ReplaceArgVisitor(syntax)) ?? this;
+
+    internal IEnumerable<string> GetDeclarationOptions(ContextBase context)
+        => Type(context).DeclarationOptions;
 }


Added 2 new CreateIndex() methods which take a string[] columnNames argument.

This is just a much much much cleaner way of providing an API that is meant
to index an array of columns in a table.

Also fixed the gross hack that CreateTable() was using in order to index
multiple columns by using the new API.

Merged-by: Øystein Krog <oystein.krog@gmail.com>

Conflicts:
	src/SQLite.Net/SQLiteConnection.cs

--- src/SQLite.Net/SQLiteConnection.cs
+++ src/SQLite.Net/SQLiteConnection.cs
@@ -352,11 +352,10 @@
                 }
             }

-            foreach (string indexName in indexes.Keys)
-            {
-                IndexInfo index = indexes[indexName];
-                string columns = String.Join("\",\"",
-                                     index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray());
+            foreach (var indexName in indexes.Keys)
+            {
+                var index = indexes[indexName];
+                var columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray();
                 count += CreateIndex(indexName, index.TableName, columns, index.Unique);
             }

@@ -364,7 +363,21 @@
         }

         /// <summary>
-        ///     Creates an index for the specified table and column.
+        /// Creates an index for the specified table and columns.
+        /// </summary>
+        /// <param name="indexName">Name of the index to create</param>
+        /// <param name="tableName">Name of the database table</param>
+        /// <param name="columnNames">An array of column names to index</param>
+        /// <param name="unique">Whether the index should be unique</param>
+        public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false)
+        {
+            const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
+            var sql = String.Format(sqlFormat, tableName, string.Join("\", \"", columnNames), unique ? "unique" : "", indexName);
+            return Execute(sql);
+        }
+
+        /// <summary>
+        /// Creates an index for the specified table and column.
         /// </summary>
         /// <param name="indexName">Name of the index to create</param>
         /// <param name="tableName">Name of the database table</param>
@@ -372,21 +385,29 @@
         /// <param name="unique">Whether the index should be unique</param>
         public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false)
         {
-            const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")";
-            string sql = String.Format(sqlFormat, tableName, columnName, unique ? "unique" : "", indexName);
-            return Execute(sql);
-        }
-
-        /// <summary>
-        ///     Creates an index for the specified table and column.
+            return CreateIndex(indexName, tableName, new string[] { columnName }, unique);
+        }
+
+        /// <summary>
+        /// Creates an index for the specified table and column.
         /// </summary>
         /// <param name="tableName">Name of the database table</param>
         /// <param name="columnName">Name of the column to index</param>
         /// <param name="unique">Whether the index should be unique</param>
         public int CreateIndex(string tableName, string columnName, bool unique = false)
         {
-            return CreateIndex(string.Concat(tableName, "_", columnName.Replace("\",\"", "_")), tableName, columnName,
-                unique);
+            return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique);
+        }
+
+        /// <summary>
+        /// Creates an index for the specified table and columns.
+        /// </summary>
+        /// <param name="tableName">Name of the database table</param>
+        /// <param name="columnNames">An array of column names to index</param>
+        /// <param name="unique">Whether the index should be unique</param>
+        public int CreateIndex(string tableName, string[] columnNames, bool unique = false)
+        {
+            return CreateIndex(tableName + "_" + string.Join("_", columnNames), tableName, columnNames, unique);
         }

         /// <summary>


Add locks around Funq's disposables and childContainers which gets mutated at runtime.

--- src/ServiceStack/Funq/Container.cs
+++ src/ServiceStack/Funq/Container.cs
@@ -37,24 +37,31 @@
 		public Container CreateChildContainer()
 		{
 			var child = new Container { parent = this };
-			childContainers.Push(child);
+            lock (childContainers) childContainers.Push(child);
 			return child;
 		}

 		/// <include file='Container.xdoc' path='docs/doc[@for="Container.Dispose"]/*'/>
 		public void Dispose()
 		{
-			while (disposables.Count > 0)
-			{
-				var wr = disposables.Pop();
-				var disposable = (IDisposable)wr.Target;
-				if (wr.IsAlive)
-					disposable.Dispose();
-			}
-			while (childContainers.Count > 0)
-			{
-				childContainers.Pop().Dispose();
-			}
+		    lock (disposables)
+		    {
+                while (disposables.Count > 0)
+                {
+                    var wr = disposables.Pop();
+                    var disposable = (IDisposable)wr.Target;
+                    if (wr.IsAlive)
+                        disposable.Dispose();
+                }
+            }
+
+            lock (childContainers)
+            {
+                while (childContainers.Count > 0)
+                {
+                    childContainers.Pop().Dispose();
+                }
+            }
 		}

 		/// <include file='Container.xdoc' path='docs/doc[@for="Container.Register(instance)"]/*'/>
@@ -229,7 +236,7 @@

 		internal void TrackDisposable(object instance)
 		{
-			disposables.Push(new WeakReference(instance));
+            lock (disposables) disposables.Push(new WeakReference(instance));
 		}

 		private ServiceEntry<TService, TFunc> GetEntry<TService, TFunc>(string serviceName, bool throwIfMissing)


Add user_id parameter (present with Stripe Connect) to StripeEvent

--- src/Stripe/Entities/StripeEvent.cs
+++ src/Stripe/Entities/StripeEvent.cs
@@ -24,5 +24,8 @@

 		[JsonProperty("livemode")]
 		public bool? LiveMode { get; set; }
+
+        [JsonProperty("user_id")]
+        public string UserId { get; set; }
 	}
 }


Additional syntaxes on Pizza sample

Additional syntaxes on Pizza sample

--- src/Takenet.Textc.Samples/Pizza.cs
+++ src/Takenet.Textc.Samples/Pizza.cs
@@ -22,9 +22,7 @@
                 Flavor = flavor,
                 Address = address
             };
-
-            var orderId = ++_globalOrderId;
-            _orderDictionary.Add(orderId, order);
+            var orderId = SaveOrder(order);

             var builder = new StringBuilder();
             builder.AppendLine("Seu pedido:");
@@ -40,19 +38,19 @@

         public Task<string> ProcessOrderAsync(long orderId, IRequestContext context)
         {
-            Order order;
-            if (!_orderDictionary.TryGetValue(orderId, out order))
+            var order = GetOrder(orderId);
+            if (order == null)
             {
-                return Task.FromResult("Ops, não encontrei seu pedido :(");
+                return Task.FromResult("Ops, não encontrei o pedido solicitado :(");
             }
-            _orderDictionary.Remove(orderId);
+            DeleteOrder(orderId);

             context.SetVariable("size", order.Size);
             context.SetVariable("flavor", order.Flavor);
             context.SetVariable("address", order.Address);

             context.RemoveVariable(nameof(orderId));
-
+
             var builder = new StringBuilder();
             builder.AppendLine("Seu pedido foi realizado com sucesso!");
             builder.Append("Ah, salvamos suas preferências para os próximos pedidos :)");
@@ -61,16 +59,39 @@

         public Task<string> CancelOrderAsync(long orderId, IRequestContext context)
         {
-            _orderDictionary.Remove(orderId);
+            DeleteOrder(orderId);
             context.Clear();
             return Task.FromResult("O pedido foi cancelado e suas preferências removidas");
+        }
+
+        private long SaveOrder(Order order)
+        {
+            var orderId = ++_globalOrderId;
+            _orderDictionary.Add(orderId, order);
+            return orderId;
+        }
+
+        private Order GetOrder(long orderId)
+        {
+            Order order;
+            _orderDictionary.TryGetValue(orderId, out order);
+            return order;
+        }
+
+        private void DeleteOrder(long orderId)
+        {
+            _orderDictionary.Remove(orderId);
         }

         public static ITextProcessor CreateTextProcessor()
         {
             // The parsed syntaxes
-            var confirmOrderSyntax = CsdlParser.Parse(
-                ":Word?(quero,mande,solicito) :Word?(uma) :Word?(pizza) size:Word(pequena,media,grande,gigante) :Word?(sabor,de) flavor:Word(marguerita,pepperoni,calabreza) :Word?(para) :Word?(à,a,o) address:Text");
+            var confirmOrderSyntax1 = CsdlParser.Parse(
+                ":LDWord?(quero,mande,solicito) :Word?(uma) :Word?(pizza) :Word?(do,no) :LDWord?(tamanho) size:LDWord(pequena,media,média,grande,gigante) :Word?(sabor,de) flavor:LDWord(marguerita,pepperoni,calabreza) :Word?(para) :Word?(à,a,o) address:Text");
+
+            var confirmOrderSyntax2 = CsdlParser.Parse(
+                ":LDWord?(quero,mande,solicito) :Word?(uma) :Word?(pizza) :Word?(sabor,de) flavor:LDWord(marguerita,pepperoni,calabreza) :Word?(do,no) :LDWord?(tamanho) size:LDWord(pequena,media,média,grande,gigante) :Word?(para) :Word?(à,a,o) address:Text");
+
             var processOrderSyntax = CsdlParser.Parse(
                 ":Word(sim) orderId:Long");
             var cancelOrderSyntax = CsdlParser.Parse(
@@ -86,7 +107,8 @@
                 nameof(ConfirmOrderAsync),
                 true,
                 addReminderOutputProcessor,
-                confirmOrderSyntax);
+                confirmOrderSyntax1,
+                confirmOrderSyntax2);
             var processOrderCommandProcessor2 = new ReflectionCommandProcessor(
                 pizza,
                 nameof(ProcessOrderAsync),