Convert to new WebAgent

Convert to new WebAgent

--- RedditSharp/AuthProvider.cs
+++ RedditSharp/AuthProvider.cs
@@ -6,7 +6,6 @@

 namespace RedditSharp
 {
-
     public class AuthProvider
     {
         private const string AccessUrl = "https://ssl.reddit.com/api/v1/access_token";
@@ -67,7 +66,7 @@
         /// <returns></returns>
         public string GetAuthUrl(string state, Scope scope, bool permanent = false)
         {
-            return String.Format("https://ssl.reddit.com/api/v1/authorize?client_id={0}&response_type=code&state={1}&redirect_uri={2}&duration={3}&scope={4}", _clientId, state, _redirectUri, permanent ? "permanent" : "temporary", scope);
+            return String.Format("https://ssl.reddit.com/api/v1/authorize?client_id={0}&response_type=code&state={1}&redirect_uri={2}&duration={3}&scope={4}", _clientId, state, _redirectUri, permanent ? "permanent" : "temporary", scope.ToString().Replace(" ",""));
         }

         /// <summary>
@@ -91,34 +90,28 @@
             {
                 _webAgent.WritePostBody(stream, new
                 {
-                    grant_type = "authorization_code",
-                    code,
-                    redirect_uri = _redirectUri
+                    grant_type = "refresh_token",
+                    refresh_token = code
                 });
             }
             else
             {
                 _webAgent.WritePostBody(stream, new
                 {
-                    grant_type = "refresh_token",
-                    refresh_token = code
+                    grant_type = "authorization_code",
+                    code,
+                    redirect_uri = _redirectUri
                 });
             }

             stream.Close();
-            var response = (HttpWebResponse)request.GetResponse();
-            var result = _webAgent.GetResponseString(response.GetResponseStream());
-            var json = JObject.Parse(result);
+            var json = _webAgent.ExecuteRequest(request);
             if (json["access_token"] != null)
             {
                 if (json["refresh_token"] != null)
                     RefreshToken = json["refresh_token"].ToString();
                 OAuthToken = json["access_token"].ToString();
                 return json["access_token"].ToString();
-            }
-            if (json["error"] != null)
-            {
-                throw new AuthenticationException("Could not log in: " + json["error"]);
             }
             throw new AuthenticationException("Could not log in.");
         }


removed unused creApp variable

removed unused creApp variable

--- BuildingCoder/BuildingCoder/CmdDetailCurves.cs
+++ BuildingCoder/BuildingCoder/CmdDetailCurves.cs
@@ -47,8 +47,8 @@
       UIApplication app = commandData.Application;
       Document doc = app.ActiveUIDocument.Document;
       View view = doc.ActiveView;
-
-      Autodesk.Revit.Creation.Application creApp = app.Application.Create;
+
+      //Autodesk.Revit.Creation.Application creApp = app.Application.Create;
       Autodesk.Revit.Creation.Document creDoc = doc.Create;

       // Create a geometry line


Refactoring

Refactoring

--- CMSEngine.Api/Controllers/WebsiteController.cs
+++ CMSEngine.Api/Controllers/WebsiteController.cs
@@ -1,11 +1,9 @@
+using CmsEngine.Data.AccessLayer;
+using CmsEngine.Services;
+using Microsoft.AspNetCore.Mvc;
 using System;
 using System.Collections.Generic;
 using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using CmsEngine.Data.AccessLayer;
-using CmsEngine.Services;

 namespace CmsEngine.Api.Controllers
 {


removeuseless usings

removeuseless usings

--- WhenItsDone/Tests/LibTests/WhenItsDone.MVP.Tests/AdminPageControlsTests/APWorkersControlMVP/APWorkersControlPresenterTests/Constructor_Should.cs
+++ WhenItsDone/Tests/LibTests/WhenItsDone.MVP.Tests/AdminPageControlsTests/APWorkersControlMVP/APWorkersControlPresenterTests/Constructor_Should.cs
@@ -1,6 +1,5 @@
 using Moq;
 using NUnit.Framework;
-using System.Linq;
 using System.Reflection;
 using WhenItsDone.MVP.AdminPageControls.APWorkersControlMVP;
 using WhenItsDone.Services.Contracts;


- Forced loading of AutoDetect and Bootstrap Resource groups before all others.

git-svn-id: ad71a101fa69fb252e58119732bf51384d5dbd95@1247 bb9bf1cf-960d-0410-9a3a-baeba60cf407

--- Projects/Axiom/Source/Engine/Core/ResourceGroupManager.cs
+++ Projects/Axiom/Source/Engine/Core/ResourceGroupManager.cs
@@ -789,6 +789,12 @@
         public void InitializeAllResourceGroups()
         {
             LogManager.Instance.Write( "Initializing all resource groups:" );
+
+			// Initialize Built-in groups first
+			InitializeResourceGroup( ResourceGroupManager.AutoDetectResourceGroupName );
+			if ( resourceGroups.ContainsKey( ResourceGroupManager.BootstrapResourceGroupName ) )
+				InitializeResourceGroup( ResourceGroupManager.BootstrapResourceGroupName );
+
             // Intialise all declared resource groups
             foreach ( KeyValuePair<string, ResourceGroup> pair in resourceGroups )
             {


Removes Validating DB message from environment list. After analysis has completed, the displayed status will be Completion DB needs refresh while the filesystem is checked.

--- Python/Product/PythonTools/PythonTools/InterpreterView.cs
+++ Python/Product/PythonTools/PythonTools/InterpreterView.cs
@@ -28,7 +28,6 @@
         private DateTime _expectFirstUpdateBy;
         private bool _startedRunning;
         private bool _isRunning;
-        private bool _refreshingStatusAfterRunning;

         public static IEnumerable<InterpreterView> GetInterpreters(
             IInterpreterOptionsService interpreterService = null
@@ -85,11 +84,6 @@
             if (withDb != null) {
                 IsCurrent = withDb.IsCurrent;
                 IsCurrentReason = withDb.GetFriendlyIsCurrentReason(CultureInfo.CurrentUICulture);
-            }
-            if (_refreshingStatusAfterRunning) {
-                _refreshingStatusAfterRunning = false;
-                Message = string.Empty;
-                IsRunning = false;
             }
         }

@@ -127,13 +121,12 @@
                         Message = "Starting refresh DB";
                     }));
                 }
-            } else if (!_refreshingStatusAfterRunning && IsRunning && DateTime.Now > _expectFirstUpdateBy) {
+            } else if (IsRunning && DateTime.Now > _expectFirstUpdateBy) {
                 // We've finished running
+                Message = string.Empty;
+                IsRunning = false;
+
                 if (!_startedRunning) {
-                    // Notifying about the new DB will trigger RefreshIsCurrent,
-                    // so wait for that to complete before changise IsRunning.
-                    _refreshingStatusAfterRunning = true;
-                    Message = "Validating DB";
                     // Weren't started by this process, so we need to notify
                     // the interpreter to reload its DB.
                     withDb.NotifyNewDatabase();
@@ -160,14 +153,7 @@
                     IsRunning = _startedRunning = true;
                     withDb.GenerateCompletionDatabase(GenerateDatabaseOptions.SkipUnchanged, exitCode => {
                         _startedRunning = false;
-                        if (exitCode == 0) {
-                            // Ensure the progress bar stays visible until
-                            // RefreshIsCurrent completes.
-                            _refreshingStatusAfterRunning = true;
-                            Message = "Validating DB";
-                        } else {
-                            IsRunning = false;
-                        }
+                        IsRunning = false;
                     });
                 }
             } else {


Rename vars

Rename vars

--- R7.University/Commands/UpdateEduProgramDivisionCommand.cs
+++ R7.University/Commands/UpdateEduProgramDivisionCommand.cs
@@ -1,24 +1,3 @@
-//
-//  UpdateEduProgramDivisionsCommand.cs
-//
-//  Author:
-//       Roman M. Yagodin <roman.yagodin@gmail.com>
-//
-//  Copyright (c) 2017-2018 Roman M. Yagodin
-//
-//  This program is free software: you can redistribute it and/or modify
-//  it under the terms of the GNU Affero General Public License as published by
-//  the Free Software Foundation, either version 3 of the License, or
-//  (at your option) any later version.
-//
-//  This program is distributed in the hope that it will be useful,
-//  but WITHOUT ANY WARRANTY; without even the implied warranty of
-//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-//  GNU Affero General Public License for more details.
-//
-//  You should have received a copy of the GNU Affero General Public License
-//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
 using System.Collections.Generic;
 using R7.Dnn.Extensions.Models;
 using R7.University.EditModels;
@@ -36,21 +15,21 @@
             ModelContext = modelContext;
         }

-        public void Update (IEnumerable<IEditModel<EduProgramDivisionInfo>> epDocs, ModelType modelType, int itemId)
+        public void Update (IEnumerable<IEditModel<EduProgramDivisionInfo>> epDivs, ModelType modelType, int itemId)
         {
-            foreach (var epDoc in epDocs) {
-                var epd = epDoc.CreateModel ();
-                switch (epDoc.EditState) {
-                case ModelEditState.Added:
-                    epd.SetModelId (modelType, itemId);
-                    ModelContext.Add (epd);
-                    break;
-                case ModelEditState.Modified:
-                    ModelContext.UpdateExternal (epd);
-                    break;
-                case ModelEditState.Deleted:
-                    ModelContext.RemoveExternal (epd);
-                    break;
+            foreach (var epDiv in epDivs) {
+                var epd = epDiv.CreateModel ();
+                switch (epDiv.EditState) {
+                    case ModelEditState.Added:
+                        epd.SetModelId (modelType, itemId);
+                        ModelContext.Add (epd);
+                        break;
+                    case ModelEditState.Modified:
+                        ModelContext.UpdateExternal (epd);
+                        break;
+                    case ModelEditState.Deleted:
+                        ModelContext.RemoveExternal (epd);
+                        break;
                 }
             }
         }


moving from vm to real machine

moving from vm to real machine

--- Rezolver/Rezolver.Tests/LifeTimeRezolverContainerTests.cs
+++ Rezolver/Rezolver.Tests/LifeTimeRezolverContainerTests.cs
@@ -15,6 +15,7 @@

 		public class DisposableType : ITestDisposable
 		{
+			public static int TotalDisposeCount = 0;
 			int _disposeCount = 0;

 			public int DisposeCount
@@ -27,6 +28,7 @@

 			public void Dispose()
 			{
+				++TotalDisposeCount;
 				++_disposeCount;
 				if (!_disposed)
 				{
@@ -35,12 +37,18 @@
 			}
 		}

+		private static Mock<IRezolverContainer> CreateMock()
+		{
+			Mock<IRezolverContainer> parentContainerMock = new Mock<IRezolverContainer>();
+			parentContainerMock.Setup(c => c.CreateLifetimeContainer()).Returns(() => new LifetimeRezolverContainer(parentContainerMock.Object));
+			parentContainerMock.Setup(c => c.Resolve(typeof(ITestDisposable), null, null)).Returns(() => new DisposableType());
+			return parentContainerMock;
+		}
+
 		[TestMethod]
 		public void ShouldDisposeOnceOly()
 		{
-			Mock<IRezolverContainer> parentContainerMock = new Mock<IRezolverContainer>();
-			parentContainerMock.Setup(c => c.CreateLifetimeContainer()).Returns(() => new LifetimeRezolverContainer(parentContainerMock.Object));
-			parentContainerMock.Setup(c => c.Resolve(typeof (ITestDisposable), null, null)).Returns(() => new DisposableType());
+			Mock<IRezolverContainer> parentContainerMock = CreateMock();
 			ITestDisposable instance = null;
 			using (var lifetime = parentContainerMock.Object.CreateLifetimeContainer())
 			{
@@ -49,9 +57,42 @@

 			Assert.IsTrue(instance.Disposed);
 			Assert.AreEqual(1, instance.DisposeCount);
+		}

+		[TestMethod]
+		public void ShouldDisposeTwoInstances()
+		{
+			var mockContainer = CreateMock();
+			int totalInstanceCount = DisposableType.TotalDisposeCount;
+			ITestDisposable instance = null;
+			ITestDisposable instance2 = null;
+			using(var lifetime = mockContainer.Object.CreateLifetimeContainer())
+			{
+				instance = (ITestDisposable)lifetime.Resolve(typeof(ITestDisposable));
+				instance2 = (ITestDisposable)lifetime.Resolve(typeof(ITestDisposable));
+				Assert.AreNotSame(instance, instance2);
+			}

+			Assert.IsTrue(instance.Disposed);
+			Assert.IsTrue(instance2.Disposed);
+			Assert.AreEqual(1, instance.DisposeCount);
+			Assert.AreEqual(1, instance2.DisposeCount);
+			Assert.AreEqual(totalInstanceCount + 2, DisposableType.TotalDisposeCount);
+		}

+		[TestMethod]
+		public void ShouldDisposeNestedScope()
+		{
+			var mockContainer = CreateMock();
+			ITestDisposable instance = null;
+			using(var lifetime = mockContainer.Object.CreateLifetimeContainer())
+			{
+				var lifetime2 = lifetime.CreateLifetimeContainer();
+				instance = (ITestDisposable)lifetime2.Resolve(typeof(ITestDisposable));
+			}
+
+			Assert.IsTrue(instance.Disposed);
+			Assert.AreEqual(1, instance.DisposeCount);
 		}
 	}
 }


IRenderProcess - IncludeExceptionDetailInFaults=true

--- CefSharp.BrowserSubprocess/CefRenderProcess.cs
+++ CefSharp.BrowserSubprocess/CefRenderProcess.cs
@@ -8,7 +8,7 @@

 namespace CefSharp.BrowserSubprocess
 {
-    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
+    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults=true)]
     public class CefRenderProcess : CefSubProcess, IRenderProcess
     {
         private int? parentBrowserId;


Upload files fix

Upload files fix

--- Signum.Web.Extensions/Files/Controllers/FileController.cs
+++ Signum.Web.Extensions/Files/Controllers/FileController.cs
@@ -137,7 +137,7 @@
             sb.AppendLine("<script type='text/javascript'>");
             sb.AppendLine("var parDoc = window.parent.document;");

-            if (/*file.TryCS(f => f.IdOrNull) != null ||*/ !shouldHaveSaved)
+            if (file.BinaryFile == null /* If file has been saved */ || !shouldHaveSaved)
             {
                 RuntimeInfo ri = file is EmbeddedEntity ? new RuntimeInfo((EmbeddedEntity)file) : new RuntimeInfo((IIdentifiable)file);


fixed cookiebar, it was not appearing at all

--- Site/Areas/Core/Views/Entity/CookieNotificationBar.cshtml
+++ Site/Areas/Core/Views/Entity/CookieNotificationBar.cshtml
@@ -1,5 +1,5 @@
 @model Sdl.Web.Mvc.Models.Notification
-

+

@Model.Headline


Update AddField.cs

Update AddField.cs

--- Solutions/PowerShell.Commands/Commands/Fields/AddField.cs
+++ Solutions/PowerShell.Commands/Commands/Fields/AddField.cs
@@ -12,6 +12,9 @@
     [CmdletExample(
      Code = @"PS:> Add-SPOField -List ""Demo list"" -DisplayName ""Location"" -InternalName ""SPSLocation"" -Type Choice -Group ""Demo Group"" -AddToDefaultView -Choices ""Stockholm"",""Helsinki"",""Oslo""",
      Remarks = @"This will add field of type Choice to a the list ""Demo List"".", SortOrder = 1)]
+    [CmdletExample(
+     Code = @"PS:>Add-SPOField -List ""Demo list"" -DisplayName ""Speakers"" -InternalName ""SPSSpeakers"" -Type MultiChoice -Group ""Demo Group"" -AddToDefaultView -Choices ""Obiwan Kenobi"",""Darth Vader"", ""Anakin Skywalker""",
+Remarks = @"This will add field of type Multiple Choice to a the list ""Demo List"". (you can pick several choices for the same item)", SortOrder = 2)]
     public class AddField : SPOWebCmdlet, IDynamicParameters
     {
         [Parameter(Mandatory = false, ValueFromPipeline = true, ParameterSetName = "ListPara")]


Fixed part sync when staging

Fixed part sync when staging

--- Client/Systems/VesselProtoSys/VesselUpdater.cs
+++ Client/Systems/VesselProtoSys/VesselUpdater.cs
@@ -36,7 +36,7 @@
         /// </summary>
         public static readonly Dictionary<string, List<string>> FieldsToIgnore = new Dictionary<string, List<string>>()
         {
-            ["ModuleEnginesFX"] = new List<string>{ "currentThrottle" }
+            ["ModuleEnginesFX"] = new List<string> { "currentThrottle" }
         };

         /// <summary>
@@ -60,9 +60,12 @@

             //Never do vessel.protoVessel = protoVessel; not even if the vessel is not loaded as when it gets loaded the parts are created in the active vessel and not on the target vessel

-            //Run trough all the vessel parts. vessel.parts will be empty if vessel is unloaded
-            foreach (var part in vessel.parts)
+            //Run trough all the vessel parts. vessel.parts will be empty if vessel is unloaded.
+            //Do not do a foreach as vessel parts can change and will result in a modified collection...
+            //ReSharper disable once ForCanBeConvertedToForeach
+            for (var i = 0; i < vessel.parts.Count; i++)
             {
+                var part = vessel.parts[i];
                 var partSnapshot = protoVessel.protoPartSnapshots.FirstOrDefault(ps => ps.missionID == part.missionID && ps.craftID == part.craftID);
                 if (partSnapshot == null) //Part does not exist in the protovessel definition so kill it
                 {


Better date format

Better date format

--- Client/Windows/Screenshots/ScreenshotWindow.cs
+++ Client/Windows/Screenshots/ScreenshotWindow.cs
@@ -99,7 +99,7 @@
                 if (_selectedImage > 0 && System.DownloadedImages.ContainsKey(_selectedFolder))
                 {
                     _imageWindowRect = FixWindowPos(GUILayout.Window(6721 + MainSystem.WindowOffset, _imageWindowRect,
-                        DrawImageContent, $"{DateTime.FromBinary(_selectedImage).ToLongDateString()} - {DateTime.FromBinary(_selectedImage).ToLongTimeString()} UTC", WindowStyle));
+                        DrawImageContent, $"{DateTime.FromBinary(_selectedImage):yyyy/MM/dd HH:mm:ss} UTC", WindowStyle));
                 }
             }


Fix opposing volume issues

Fix opposing volume issues

--- ATSPM.Application.Reports/Business/LeftTurnGapReport/LeftTurnVolumeAnalysis.cs
+++ ATSPM.Application.Reports/Business/LeftTurnGapReport/LeftTurnVolumeAnalysis.cs
@@ -55,7 +55,7 @@
             double crossVolumeProduct = GetCrossProduct(leftTurnVolume, opposingVolume);
             leftTurnVolumeValue.CrossProductValue = crossVolumeProduct;
             leftTurnVolumeValue.LeftTurnVolume = leftTurnVolume;
-            leftTurnVolumeValue.OpposingThroughVolume = opposingPhase;
+            leftTurnVolumeValue.OpposingThroughVolume = opposingVolume;
             leftTurnVolumeValue.CrossProductReview = GetCrossProductReview(crossVolumeProduct, leftTurnVolumeValue.OpposingLanes);
             ApproachType approachType = GetApproachType(approach);
             SetDecisionBoundariesReview(leftTurnVolumeValue, leftTurnVolume, opposingVolume, approachType);
@@ -92,7 +92,7 @@
                             .Approaches
                             .Where(a => a.ProtectedPhaseNumber == opposingPhase)
                             .SelectMany(a => a.Detectors)
-                            .Where(d => d.MovementTypeId.HasValue && movementTypes.Contains(d.MovementTypeId.Value))
+                            .Where(d => d.MovementTypeId.HasValue && movementTypes.Contains(d.MovementTypeId.Value) && d.DetectionTypeDetectors.First().DetectionTypeId == 4)
                             .ToList();
         }


Lookup CurrentLanguage based on a key rather than saving a reference

This fixes potential issues like when Updating languages, where the
referenced language was older than the ones updated on disk. In general,
removing the currentLanguage member just helps avoid caching issues.

--- Assets/RedBlueGames/MulliganRenamer/Editor/Localization/LocalizationManager.cs
+++ Assets/RedBlueGames/MulliganRenamer/Editor/Localization/LocalizationManager.cs
@@ -67,7 +67,14 @@
         {
             get
             {
-                return this.currentLanguage;
+                return this.GetLanguageByKey(currentLanguageKey);
+            }
+            set
+            {
+                if (value != null)
+                {
+                    this.currentLanguageKey = value.Key;
+                }
             }
         }

@@ -79,7 +86,7 @@
             }
         }

-        private Language currentLanguage;
+        private string currentLanguageKey;

         private List<Language> allLanguages;

@@ -133,10 +140,10 @@
         /// <param name="languageKey">LanguageKey to change to</param>
         public void ChangeLanguage(string languageKey)
         {
-            var language = this.allLanguages.FirstOrDefault(x => x.Key == languageKey);
+            var language = this.GetLanguageByKey(languageKey);
             if (language != null)
             {
-                this.currentLanguage = language;
+                this.CurrentLanguage = language;

                 if (this.LanguageChanged != null)
                 {
@@ -187,9 +194,9 @@
                 return string.Empty;
             }

-            if (this.currentLanguage != null)
-            {
-                return this.currentLanguage.GetValue(languageKey);
+            if (this.CurrentLanguage != null)
+            {
+                return this.CurrentLanguage.GetValue(languageKey);
             }
             else
             {
@@ -212,7 +219,7 @@
         {
             var report = new LanguageUpdateReport();
             report.Language = newLanguage;
-            Language existingLanguage = this.allLanguages.FirstOrDefault((l) => l.Key == newLanguage.Key);
+            Language existingLanguage = this.GetLanguageByKey(newLanguage.Key);
             if (existingLanguage == null)
             {
                 report.Result = LanguageUpdateReport.UpdateResult.Added;
@@ -230,14 +237,6 @@
                 report.Result = LanguageUpdateReport.UpdateResult.NoChange;
             }

-            // newLanguage is a new language instance, even if it's the same "language", so
-            // we need to update the reference for the CurrentLanguage to the new one.
-            // Note this is not really "changing languages" so we don't fire the callback or update PrefKey
-            if (this.CurrentLanguage.Key == newLanguage.Key)
-            {
-                this.currentLanguage = newLanguage;
-            }
-
             return report;
         }

@@ -291,6 +290,11 @@
             return System.IO.Path.GetDirectoryName(pathToFirstLanguage);
         }

+        private Language GetLanguageByKey(string languagekey)
+        {
+            return this.allLanguages.FirstOrDefault(x => x.Key == languagekey);
+        }
+
         public class LanguageUpdateReport
         {
             public Language Language { get; set; }


Populated interface with methods.

Populated interface with methods.

--- FOAASClient/IFoaasClient.cs
+++ FOAASClient/IFoaasClient.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Runtime.CompilerServices;
 using System.Text;
 using System.Threading.Tasks;

@@ -52,5 +53,36 @@
         Task<Response> Thumbs(string who, string from);
         Task<Response> Retard(string from);
         Task<Response> Greed(string noun, string from);
+        Task<Response> Anyway(string company, string from);
+        Task<Response> Back(string name, string from);
+        Task<Response> Bag(string from);
+        Task<Response> Blackadder(string name, string from);
+        Task<Response> BravoMike(string name, string from);
+        Task<Response> Cocksplat(string name, string from);
+        Task<Response> Dalton(string name, string from);
+        Task<Response> Deraadt(string name, string from);
+        Task<Response> GolfFoxtrotYankee(string name, string from);
+        Task<Response> Give(string from);
+        Task<Response> Horse(string from);
+        Task<Response> FuckingOff(string name, string from);
+        Task<Response> Keep(string name, string from);
+        Task<Response> Look(string name, string from);
+        Task<Response> Looking(string from);
+        Task<Response> Maybe(string from);
+        Task<Response> Me(string from);
+        Task<Response> No(string from);
+        Task<Response> OffWith(string behaviour, string from);
+        Task<Response> Particular(string obj, string from);
+        Task<Response> Problem(string name, string from);
+        Task<Response> Pulp(string language, string from);
+        Task<Response> Ridiculous(string from);
+        Task<Response> ReadTheManual(string from);
+        Task<Response> Sake(string from);
+        Task<Response> Shit(string from);
+        Task<Response> Single(string from);
+        Task<Response> Think(string name, string from);
+        Task<Response> Thinking(string name, string from);
+        Task<Response> Too(string from);
+        Task<Response> Zero(string from);
     }
 }


Fix bug with Basis.Transposed()

Fix bug with Basis.Transposed()

Fix bug where Basis.Transposed() incorrectly updated local basis, and
returned an unmodified copy. This also fixes Transform.Inverse().


Fixes Mono color creation from string.

Fixes Mono color creation from string.

Fixes #15468

Also improves the error messages if the string isn't hex, because saying that the color value is negative is just a side effect of the implementation and tells you nothing.

--- modules/mono/glue/cs_files/Color.cs
+++ modules/mono/glue/cs_files/Color.cs
@@ -336,7 +336,7 @@
             this.r = (rgba & 0xFF) / 255.0f;
         }

-        private static float _parse_col(string str, int ofs)
+        private static int _parse_col(string str, int ofs)
         {
             int ig = 0;

@@ -415,17 +415,17 @@

             if (alpha)
             {
-                if ((int)_parse_col(color, 0) < 0)
+                if (_parse_col(color, 0) < 0)
                     return false;
             }

             int from = alpha ? 2 : 0;

-            if ((int)_parse_col(color, from + 0) < 0)
+            if (_parse_col(color, from + 0) < 0)
                 return false;
-            if ((int)_parse_col(color, from + 2) < 0)
+            if (_parse_col(color, from + 2) < 0)
                 return false;
-            if ((int)_parse_col(color, from + 4) < 0)
+            if (_parse_col(color, from + 4) < 0)
                 return false;

             return true;
@@ -467,10 +467,10 @@

             if (alpha)
             {
-                a = _parse_col(rgba, 0);
+                a = _parse_col(rgba, 0) / 255f;

                 if (a < 0)
-                    throw new ArgumentOutOfRangeException("Invalid color code. Alpha is " + a + " but zero or greater is expected: " + rgba);
+                    throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba);
             }
             else
             {
@@ -479,20 +479,20 @@

             int from = alpha ? 2 : 0;

-            r = _parse_col(rgba, from + 0);
+            r = _parse_col(rgba, from + 0) / 255f;

             if (r < 0)
-                throw new ArgumentOutOfRangeException("Invalid color code. Red is " + r + " but zero or greater is expected: " + rgba);
-
-            g = _parse_col(rgba, from + 2);
+                throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba);
+
+            g = _parse_col(rgba, from + 2) / 255f;

             if (g < 0)
-                throw new ArgumentOutOfRangeException("Invalid color code. Green is " + g + " but zero or greater is expected: " + rgba);
-
-            b = _parse_col(rgba, from + 4);
+                throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba);
+
+            b = _parse_col(rgba, from + 4) / 255f;

             if (b < 0)
-                throw new ArgumentOutOfRangeException("Invalid color code. Blue is " + b + " but zero or greater is expected: " + rgba);
+                throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba);
         }

         public static bool operator ==(Color left, Color right)


Changing the host to get the last item of the list, instead of getting the second one. So whenever we only have one address in the address list we should keep getting it.

--- Derivco.Orniscient/Derivco.Orniscient.Viewer/Clients/GrainClientInitializer.cs
+++ Derivco.Orniscient/Derivco.Orniscient.Viewer/Clients/GrainClientInitializer.cs
@@ -2,6 +2,7 @@
 using Orleans;
 using Orleans.Runtime.Configuration;
 using System.Collections.Generic;
+using System.Linq;
 using System.Net;
 using System.Threading.Tasks;

@@ -32,7 +33,7 @@
             lock (_lock)
             {
                 var host = Dns.GetHostEntry(address);
-                var ipAddress = host.AddressList[1];
+                var ipAddress = host.AddressList.Last();
                 var ipEndpoint = new IPEndPoint(ipAddress, port);
                 var config = new ClientConfiguration();
                 config.Gateways = new List<IPEndPoint>();


Forgot to hit save.

Forgot to hit save.

--- proj.unity/Assets/UnityIO/AssetDatabase.cs
+++ proj.unity/Assets/UnityIO/AssetDatabase.cs
@@ -11,7 +11,7 @@
 using UnityEngine;
 using System.IO;

-namespace UnityIO.Database
+namespace UnityIO.AssetDatabaseWrapper
 {
     internal static class AssetDatabase
     {


fix antitod

fix antitod

--- mogate.Shared/Layers/PlayerLayer.cs
+++ mogate.Shared/Layers/PlayerLayer.cs
@@ -59,7 +59,7 @@
 				player.Register (new Armor (Archetypes.Armors [gameState.PlayerArmorID] ["defence"], gameState.PlayerArmorID));
 			}
 			player.Get<Consumable<ConsumableTypes>> ().Refill (ConsumableTypes.Money, gameState.PlayerMoney);
-			player.Get<Consumable<ConsumableTypes>> ().Refill (ConsumableTypes.Money, gameState.PlayerAntitodPotions);
+			player.Get<Consumable<ConsumableTypes>> ().Refill (ConsumableTypes.Antitod, gameState.PlayerAntitodPotions);

 			player.Get<Clickable> ().OnLeftButtonPressed += OnMoveToPosition;
 			player.Get<Clickable> ().OnMoved += OnMoveToPosition;


Use FindEntry API

Use FindEntry API

--- GUI/Utils/FileExtensions.cs
+++ GUI/Utils/FileExtensions.cs
@@ -25,7 +25,7 @@
                 var absoluteByteCount = Math.Abs(byteCount);
                 var place = Convert.ToInt32(Math.Floor(Math.Log(absoluteByteCount, 1024)));
                 var num = Math.Round(absoluteByteCount / Math.Pow(1024, place), 1);
-                result = string.Format("{0} {1}", (Math.Sign(byteCount) * num), suf[place]);
+                result = string.Format("{0} {1}", Math.Sign(byteCount) * num, suf[place]);
             }

             return result;
@@ -33,18 +33,15 @@

         public static bool LoadFileByAnyMeansNecessary(Resource resource, string file, string currentFullPath, Package currentPackage)
         {
-            if (currentPackage != null)
+            var entry = currentPackage?.FindEntry(file);
+
+            if (entry != null)
             {
-                var entry = FindPackageEntry(currentPackage, file);
+                byte[] output;
+                currentPackage.ReadEntry(entry, out output);
+                resource.Read(new MemoryStream(output));

-                if (entry != null)
-                {
-                    byte[] output;
-                    currentPackage.ReadEntry(entry, out output);
-                    resource.Read(new MemoryStream(output));
-
-                    return true;
-                }
+                return true;
             }

             var path = FindResourcePath(file, currentFullPath);
@@ -57,20 +54,6 @@
             resource.Read(path);

             return true;
-        }
-
-        public static PackageEntry FindPackageEntry(Package currentPackage, string file)
-        {
-            var extension = Path.GetExtension(file).Substring(1);
-
-            if (!currentPackage.Entries.ContainsKey(extension))
-            {
-                return null;
-            }
-
-            file = file.Replace("/", "\\");
-
-            return currentPackage.Entries[extension].FirstOrDefault(x => x.GetFullPath() == file);
         }

         public static string FindResourcePath(string file, string currentFullPath = null)


bugfix - workitems could be translated to a new Id and then this new Id could be translated again and again - furthermore only initial substring of "#" + Id.ToString() could be translated in the case that Id.ToString() had different lengths

--- GitTfs/Core/GitTfsRemote.cs
+++ GitTfs/Core/GitTfsRemote.cs
@@ -459,16 +459,10 @@
         {
             if (ExportMetadatas)
             {
-                if (changeset.Summary.Workitems.Any())
-                {
-                    log.Log += "\nwork-items: " + string.Join(", ", changeset.Summary.Workitems.Select(wi => "#" + wi.Id)); ;
-                }
-
-                if (ExportWorkitemsMapping.Count != 0)
-                {
-                    foreach (var mapping in ExportWorkitemsMapping)
-                    {
-                        log.Log = log.Log.Replace("#" + mapping.Key, "#" + mapping.Value);
+                if (changeset.Summary.Workitems.Any()) {
+                    var workItemIds = TranslateWorkItems(changeset.Summary.Workitems.Select(wi => wi.Id.ToString()));
+                    if (workItemIds != null) {
+                        log.Log += "\nwork-items: " + string.Join(", ", workItemIds.Select(s => "#" + s));
                     }
                 }

@@ -529,6 +523,25 @@
             return commitSha;
         }

+        private IEnumerable<string> TranslateWorkItems(IEnumerable<string> workItemsOriginal) {
+            if (ExportWorkitemsMapping.Count != 0) {
+                List<string> workItemsTranslated = new List<string>();
+                if (workItemsOriginal != null) {
+                    foreach (var oldWorkItemId in workItemsOriginal) {
+                        string translatedWorkItemId = null;
+                        if (oldWorkItemId != null && !ExportWorkitemsMapping.TryGetValue(oldWorkItemId, out translatedWorkItemId)) {
+                            translatedWorkItemId = oldWorkItemId;
+                        }
+                        if (translatedWorkItemId != null) {
+                            workItemsTranslated.Add(translatedWorkItemId);
+                        }
+                    }
+                }
+                workItemsOriginal = workItemsTranslated;
+            }
+            return workItemsOriginal;
+        }
+
         private string FindRootRemoteAndFetch(int parentChangesetId, IRenameResult renameResult = null)
         {
             string omittedParentBranch;


comment added

comment added

--- Chip8Emulator/Chip8.cs
+++ Chip8Emulator/Chip8.cs
@@ -204,7 +204,7 @@
                     switch (_currentOpCode & 0x00FF)
                     {
                         //0xFx33: The interpreter takes the decimal value of Vx, and places the hundreds digit in memory at location in I,
-                        //the tens digit at location I+1, and the ones digit at location I+2.
+                        //the tens digit at location I+1, and the ones digit at location I+2. Representation for the BCD format.
                         case 0x0033:
                             _memory[_indexRegister] = (byte) (_generalPurposeRegistersV[(_currentOpCode & 0x0F00) >> 8]/100);
                             _memory[_indexRegister + 1] = (byte) ((byte)(_generalPurposeRegistersV[(_currentOpCode & 0x0F00) >> 8] / 10) % 10);


Resend recovered tourists that haven't toured yet

--- Client/VesselWorker.cs
+++ Client/VesselWorker.cs
@@ -1793,8 +1793,8 @@
                 }
                 foreach (ProtoCrewMember pcm in part.protoModuleCrew)
                 {
-                    if (pcm.type != ProtoCrewMember.KerbalType.Tourist)
-                        SendKerbalIfDifferent(pcm);
+                    // Ignore the tourists except those that haven't yet toured
+                    if (pcm.type != ProtoCrewMember.KerbalType.Tourist || (pcm.type == ProtoCrewMember.KerbalType.Tourist && !pcm.hasToured)) SendKerbalIfDifferent(pcm);
                 }
             }
         }
@@ -1817,8 +1817,8 @@
                 }
                 foreach (ProtoCrewMember pcm in part.protoModuleCrew)
                 {
-                    if (pcm.type != ProtoCrewMember.KerbalType.Tourist)
-                        SendKerbalIfDifferent(pcm);
+                    // Ignore the tourists except those that haven't yet toured
+                    if (pcm.type != ProtoCrewMember.KerbalType.Tourist || (pcm.type == ProtoCrewMember.KerbalType.Tourist && !pcm.hasToured)) SendKerbalIfDifferent(pcm);
                 }
             }
         }


Dodge actiongroup controls (Brakes, SAS, RCS, Lights, Gear) last used values so they aren't disabled, Fixes #70.

--- Client/VesselWorker.cs
+++ Client/VesselWorker.cs
@@ -1185,10 +1185,12 @@
             {
                 //Fix the kerbals (Tracking station bug)
                 checkProtoNodeCrew(ref vesselNode);
+                DodgeVesselActionGroups(ref vesselNode);

                 //Can be used for debugging incoming vessel config nodes.
                 //vesselNode.Save(Path.Combine(KSPUtil.ApplicationRootPath, Path.Combine("DMP-RX", Planetarium.GetUniversalTime() + ".txt")));
                 ProtoVessel currentProto = new ProtoVessel(vesselNode, HighLogic.CurrentGame);
+
                 if (currentProto != null)
                 {
                     if (currentProto.vesselType == VesselType.SpaceObject)
@@ -1309,6 +1311,40 @@
             {
                 DarkLog.Debug("vesselNode is null!");
             }
+        }
+
+        private void DodgeVesselActionGroups(ref ConfigNode vesselNode)
+        {
+            if (vesselNode != null)
+            {
+                ConfigNode actiongroupNode = vesselNode.GetNode("ACTIONGROUPS");
+                if (actiongroupNode != null)
+                {
+                    foreach (string keyName in actiongroupNode.values.DistinctNames())
+                    {
+                        string valueCurrent = actiongroupNode.GetValue(keyName);
+                        string valueDodge = DodgeValueIfNeeded(valueCurrent);
+                        if (valueCurrent != valueDodge)
+                        {
+                            DarkLog.Debug("Dodged actiongroup " + keyName);
+                            actiongroupNode.SetValue(keyName, valueDodge);
+                        }
+                    }
+                }
+            }
+        }
+
+        private string DodgeValueIfNeeded(string input)
+        {
+            string boolValue = input.Substring(0, input.IndexOf(", "));
+            string timeValue = input.Substring(input.IndexOf(", ") + 1);
+            double vesselPlanetTime = Double.Parse(timeValue);
+            double currentPlanetTime = Planetarium.GetUniversalTime();
+            if (vesselPlanetTime > currentPlanetTime)
+            {
+                return boolValue + ", " + currentPlanetTime;
+            }
+            return input;
         }

         public void OnVesselDestroyed(Vessel dyingVessel)


Adding back Behavior.Fire

Adding back Behavior.Fire

--- sodium/Behavior.cs
+++ sodium/Behavior.cs
@@ -98,6 +98,16 @@
             var behavior = evt.Behavior;
             behavior.RegisterFinalizer(evt);
             return behavior;
+        }
+
+        /// <summary>
+        /// Fire the given value on the underlying Event
+        /// </summary>
+        /// <param name="firing">The value to fire</param>
+        /// <returns>True if fired, false otherwise</returns>
+        public bool Fire(T firing)
+        {
+            return this.Source.Fire(firing);
         }

         /// <summary>


bugfix PullRequestCommentJsonImplのデシリアライズでエラー #85

--- src/Backlog4net/Internal/Json/PullRequestCommentJsonImpl.cs
+++ src/Backlog4net/Internal/Json/PullRequestCommentJsonImpl.cs
@@ -33,7 +33,7 @@
         [JsonProperty(ItemConverterType = typeof(StarJsonImpl.JsonConverter))]
         public Star[] Stars { get; private set; }

-        [JsonProperty(ItemConverterType = typeof(NotificationInfoJsonImpl.JsonConverter))]
+        [JsonProperty(ItemConverterType = typeof(NotificationJsonImpl.JsonConverter))]
         public Notification[] Notifications { get; private set; }
     }
 }


Adding OfficerId to the search officer response object.

--- src/CompaniesHouse/Response/Search/OfficerSearch/Officer.cs
+++ src/CompaniesHouse/Response/Search/OfficerSearch/Officer.cs
@@ -30,5 +30,10 @@

         [JsonProperty(PropertyName = "title")]
         public string Title { get; set; }
+
+        public string OfficerId
+        {
+            get { return Links.Self.Split('/')[2]; }
+        }
     }
 }


Annotate Binder_Initializers

Annotate Binder_Initializers

--- src/Compilers/CSharp/Portable/Binder/Binder_Initializers.cs
+++ src/Compilers/CSharp/Portable/Binder/Binder_Initializers.cs
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
+#nullable enable

 using System.Collections.Immutable;
 using System.Diagnostics;
@@ -18,7 +19,7 @@
             internal ImmutableArray<BoundInitializer> BoundInitializers { get; set; }
             internal BoundStatement LoweredInitializers { get; set; }
             internal bool HasErrors { get; set; }
-            internal ImportChain FirstImportChain { get; set; }
+            internal ImportChain? FirstImportChain { get; set; }
         }

         internal static void BindFieldInitializers(
@@ -29,7 +30,7 @@
             ref ProcessedFieldInitializers processedInitializers)
         {
             var diagsForInstanceInitializers = DiagnosticBag.GetInstance();
-            ImportChain firstImportChain;
+            ImportChain? firstImportChain;
             processedInitializers.BoundInitializers = BindFieldInitializers(compilation, scriptInitializerOpt, fieldInitializers, diagsForInstanceInitializers, out firstImportChain);
             processedInitializers.HasErrors = diagsForInstanceInitializers.HasAnyErrors();
             processedInitializers.FirstImportChain = firstImportChain;
@@ -42,7 +43,7 @@
             SynthesizedInteractiveInitializerMethod scriptInitializerOpt,
             ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
             DiagnosticBag diagnostics,
-            out ImportChain firstImportChain)
+            out ImportChain? firstImportChain)
         {
             if (initializers.IsEmpty)
             {
@@ -71,7 +72,7 @@
             ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
             ArrayBuilder<BoundInitializer> boundInitializers,
             DiagnosticBag diagnostics,
-            out ImportChain firstDebugImports)
+            out ImportChain? firstDebugImports)
         {
             firstDebugImports = null;

@@ -80,7 +81,7 @@
                 // All sibling initializers share the same parent node and tree so we can reuse the binder
                 // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                 // individual fields might have their own binders (e.g. because of being declared unsafe).
-                BinderFactory binderFactory = null;
+                BinderFactory? binderFactory = null;

                 foreach (FieldOrPropertyInitializer initializer in siblingInitializers)
                 {
@@ -129,7 +130,7 @@
             ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers,
             ArrayBuilder<BoundInitializer> boundInitializers,
             DiagnosticBag diagnostics,
-            out ImportChain firstDebugImports)
+            out ImportChain? firstDebugImports)
         {
             firstDebugImports = null;

@@ -140,9 +141,9 @@
                 // All sibling initializers share the same parent node and tree so we can reuse the binder
                 // factory across siblings.  Unfortunately, we cannot reuse the binder itself, because
                 // individual fields might have their own binders (e.g. because of being declared unsafe).
-                BinderFactory binderFactory = null;
+                BinderFactory? binderFactory = null;
                 // Label instances must be shared across all global statements.
-                ScriptLocalScopeBinder.Labels labels = null;
+                ScriptLocalScopeBinder.Labels? labels = null;

                 for (int j = 0; j < siblingInitializers.Length; j++)
                 {
@@ -169,7 +170,7 @@
                     }

                     Binder scriptClassBinder = binderFactory.GetBinder(syntax);
-                    Debug.Assert(((NamedTypeSymbol)scriptClassBinder.ContainingMemberOrLambda).IsScriptClass);
+                    Debug.Assert(scriptClassBinder.ContainingMemberOrLambda is NamedTypeSymbol { IsScriptClass: true });

                     if (firstDebugImports == null)
                     {
@@ -182,7 +183,7 @@
                         new ScriptLocalScopeBinder(labels, scriptClassBinder));

                     BoundInitializer boundInitializer;
-                    if ((object)fieldSymbol != null)
+                    if ((object?)fieldSymbol != null)
                     {
                         boundInitializer = BindFieldInitializer(
                             parentBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.FieldInitializer, fieldSymbol),
@@ -221,7 +222,7 @@
                     // insert an implicit conversion for the submission return type (if needed):
                     var expression = InitializerRewriter.GetTrailingScriptExpression(statement);
                     if (expression != null &&
-                        ((object)expression.Type == null || !expression.Type.IsVoidType()))
+                        ((object?)expression.Type == null || !expression.Type.IsVoidType()))
                     {
                         var submissionResultType = scriptInitializer.ResultType;
                         expression = binder.GenerateConversionForAssignment(submissionResultType, expression, diagnostics);
@@ -256,7 +257,7 @@
             var fieldsBeingBound = binder.FieldsBeingBound;

             var sourceField = fieldSymbol as SourceMemberFieldSymbolFromDeclarator;
-            bool isImplicitlyTypedField = (object)sourceField != null && sourceField.FieldTypeInferred(fieldsBeingBound);
+            bool isImplicitlyTypedField = (object?)sourceField != null && sourceField.FieldTypeInferred(fieldsBeingBound);

             // If the type is implicitly typed, the initializer diagnostics have already been reported, so ignore them here:
             // CONSIDER (tomat): reusing the bound field initializers for implicitly typed fields.


SQLMETAL.EXE compatibility.

SQLMETAL.EXE compatibility.

If no provider and no schema loader type is provided, then default to using
the SQL Server provider.

Question: should this be conditional on MONO_STRICT (for sqlmetal)?

git-svn-id: 1800f71f313d917366f95485fa960eed04b40598@1288 33146b6e-df29-0410-a1ca-39be37fb9416

--- src/DbMetal/Generator/Implementation/SchemaLoaderFactory.cs
+++ src/DbMetal/Generator/Implementation/SchemaLoaderFactory.cs
@@ -270,6 +270,12 @@
                 databaseConnectionType = parameters.DatabaseConnectionProvider;
                 sqlDialectType         = parameters.SqlDialectType;
             }
+            if (string.IsNullOrEmpty(dbLinqSchemaLoaderType))
+            {
+                // No provider specified, not explicitly provided either
+                // Default to using SQL Server for sqlmetal.exe compatibility
+                GetLoaderAndConnection("SqlServer", out dbLinqSchemaLoaderType, out databaseConnectionType, out sqlDialectType);
+            }
         }

     }


Remove CSharpIndentationStrategy because it does not work as expected

--- src/DotNetPad/DotNetPad.Presentation/Controls/CodeEditor.cs
+++ src/DotNetPad/DotNetPad.Presentation/Controls/CodeEditor.cs
@@ -39,7 +39,6 @@
         public CodeEditor()
         {
             HighlightingManager.Instance.RegisterHighlighting("C#", new[] { ".cs" }, CreateCSharpHighlightingDefinition);
-            TextArea.IndentationStrategy = new CSharpIndentationStrategy(Options);
             SearchPanel.Install(TextArea);
             completionCancellation = new CancellationTokenSource();
             updateTextTask = Task.FromResult((object)null);


Set EnableTcpStats/ThreadPoolStats in RequestConfiguration ctor

--- src/Elasticsearch.Net/Configuration/RequestConfiguration.cs
+++ src/Elasticsearch.Net/Configuration/RequestConfiguration.cs
@@ -197,6 +197,8 @@
 			Self.OpaqueId = config?.OpaqueId;
 			Self.TransferEncodingChunked = config?.TransferEncodingChunked;
 			Self.Headers = config?.Headers;
+			Self.EnableTcpStats = config?.EnableTcpStats;
+			Self.EnableThreadPoolStats = config?.EnableThreadPoolStats;
 		}

 		string IRequestConfiguration.Accept { get; set; }


Update class that was missed in the last commit

--- src/Glimpse.Agent.AspNet.Mvc/Messages/AfterActionMessage.cs
+++ src/Glimpse.Agent.AspNet.Mvc/Messages/AfterActionMessage.cs
@@ -1,7 +1,7 @@

 namespace Glimpse.Agent.AspNet.Mvc.Messages
 {
-    public class ActionInvokedMessage
+    public class AfterActionMessage
     {
         public string ActionId { get; set; }


Fix initialization of ExternalAuthentication

--- src/Lime.Protocol/Client/EstablishedClientChannelBuilder.cs
+++ src/Lime.Protocol/Client/EstablishedClientChannelBuilder.cs
@@ -188,9 +188,11 @@
                 throw new ArgumentNullException(nameof(token));
             }

-            var authentication = new ExternalAuthentication();
-            authentication.SetToBase64Token(token);
-            authentication.Issuer = issuer;
+            var authentication = new ExternalAuthentication
+            {
+                Token = token,
+                Issuer = issuer
+            };
             return WithAuthentication(authentication);
         }


Lucene.Net.Tests.Memory.Index.Memory.MemoryIndexTest: Changed locale of QueryParser to invariant to ensure the ambient culture doesn't affect the result.

--- src/Lucene.Net.Tests.Memory/Index/Memory/MemoryIndexTest.cs
+++ src/Lucene.Net.Tests.Memory/Index/Memory/MemoryIndexTest.cs
@@ -2,8 +2,6 @@
 using Lucene.Net.Analysis.TokenAttributes;
 using Lucene.Net.Codecs.Lucene41;
 using Lucene.Net.Documents;
-using Lucene.Net.Index;
-using Lucene.Net.Index.Memory;
 using Lucene.Net.QueryParsers.Classic;
 using Lucene.Net.Search;
 using Lucene.Net.Search.Spans;
@@ -13,6 +11,7 @@
 using NUnit.Framework;
 using System;
 using System.Collections.Generic;
+using System.Globalization;
 using System.IO;
 using System.Text;

@@ -210,11 +209,17 @@
             IndexReader reader = DirectoryReader.Open(ramdir);
             IndexSearcher ram = NewSearcher(reader);
             IndexSearcher mem = memory.CreateSearcher();
-            QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer);
+            QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer)
+            {
+                // LUCENENET specific - to avoid random failures, set the culture
+                // of the QueryParser to invariant
+                Locale = CultureInfo.InvariantCulture
+            };
             foreach (string query in queries)
             {
                 TopDocs ramDocs = ram.Search(qp.Parse(query), 1);
                 TopDocs memDocs = mem.Search(qp.Parse(query), 1);
+
                 assertEquals(query, ramDocs.TotalHits, memDocs.TotalHits);
             }
             reader.Dispose();


Adds new functions that were added to the IInteractiveWindow interface.

--- Common/Tests/Utilities/Mocks/MockReplWindow.cs
+++ Common/Tests/Utilities/Mocks/MockReplWindow.cs
@@ -294,6 +294,20 @@
             return new Span(start, _output.Length - start);
         }

+        // TODO: Make explicit implementation after dropping Dev14 RC support
+        public Span WriteError(string text) {
+            var start = _error.Length;
+            _error.Append(text);
+            return new Span(start, _error.Length - start);
+        }
+
+        // TODO: Make explicit implementation after dropping Dev14 RC support
+        public Span WriteErrorLine(string text) {
+            var start = _error.Length;
+            _error.AppendLine(text);
+            return new Span(start, _error.Length - start);
+        }
+
         public Task SubmitAsync(IEnumerable<string> inputs) {
             throw new NotImplementedException();
         }


バグを修正

バグを修正

--- FelicaCashingSystemV2/FelicaCashingSystemV2/Views/DormitoryProfileViewModel.cs
+++ FelicaCashingSystemV2/FelicaCashingSystemV2/Views/DormitoryProfileViewModel.cs
@@ -11,11 +11,20 @@
 {
     class DormitoryProfileViewModel : MetroWindowViewModelBase
     {
-        private readonly FelicaData.User user = App.Current.User.Clone();
+        private FelicaData.User user = App.Current.User.Clone();

         public DormitoryProfileViewModel()
         {
             this.SaveCommand = new DelegateCommand(this.Save);
+            App.Current.UserChanged += Current_UserChanged;
+        }
+
+        private void Current_UserChanged(object sender, FelicaData.User e)
+        {
+            if (App.Current.User != null)
+            {
+                this.user = App.Current.User.Clone();
+            }
         }

         public string DormitoryRoomNo


Missed literal stig replacement

Missed literal stig replacement

--- Glav.CognitiveServices.FluentApi.Core/Operations/OperationStatusQueryEngine.cs
+++ Glav.CognitiveServices.FluentApi.Core/Operations/OperationStatusQueryEngine.cs
@@ -52,7 +52,7 @@
                 return result;
             }

-            _analysisSettings.ConfigurationSettings.DiagnosticLogger.LogInfo("Waiting for operation status to complete...", "OperationStatus");
+            _analysisSettings.ConfigurationSettings.DiagnosticLogger.LogInfo("Waiting for operation status to complete...", LoggingTopic);

             var stopWatch = new Stopwatch();
             stopWatch.Start();


Times() more lenient towards being applied on negative numbers.

--- Sandra/UtilityExtensions.cs
+++ Sandra/UtilityExtensions.cs
@@ -38,16 +38,11 @@

         /// <summary>
         /// Iterates an action a number of times.
+        /// If the number of iterations is zero or lower, the action won't get executed at all.
         /// </summary>
         public static void Times(this int numberOfIterations, Action action)
         {
-            if (numberOfIterations < 0)
-            {
-                throw new ArgumentOutOfRangeException(nameof(numberOfIterations),
-                                                      "Number of iterations cannot be lower than 0.");
-            }
-
-            for (int i = numberOfIterations; i != 0; --i) action();
+            for (int i = numberOfIterations; i > 0; --i) action();
         }
     }
 }


* Removed redundant logging.

* Removed redundant logging.

--- Services/v1/TextToSpeech.cs
+++ Services/v1/TextToSpeech.cs
@@ -319,7 +319,7 @@
             if (speechReq == null)
                 throw new WatsonException("Wrong type of request object.");

-            Log.Debug( "TextToSpeech", "Request completed in {0} seconds.", resp.ElapsedTime );
+            //Log.Debug( "TextToSpeech", "Request completed in {0} seconds.", resp.ElapsedTime );

             AudioClip clip = resp.Success ? ProcessResponse( speechReq.TextId, resp.Data ) : null;
             if ( clip == null )


Fix inverted logic on is-this-precompiled check Revert erroneous change (my logic was correct; the implementation of getS was wrong).

--- SharpLua/LuaCore/VM/lapi.cs
+++ SharpLua/LuaCore/VM/lapi.cs
@@ -1049,16 +1049,14 @@

             // Look ahead to see if it's something we're interested in.
             int peek_char = plr.peek(L, plr);
-            if (peek_char != LUA_SIGNATURE[0]) return; // if it's empty, or there's no binary value, there's no work to be done.
+            if (peek_char == LUA_SIGNATURE[0]) return; // if it's empty, or there's no binary value, there's no work to be done.

             // Okay, we are.  Read the whole thing into memory RIGHT NOW
             char[] cur_buffer = null;
             int cur_buffer_size = 0;
             CharPtr next_data;
             uint _next_data_size;
-            while ( (next_data = reader(L, data, out _next_data_size)) != null
-                    && _next_data_size > 0
-                )
+            while ( (next_data = reader(L, data, out _next_data_size)) != null )
             {
                 int next_data_size = checked((int) _next_data_size);
                 if (next_data_size == 0) continue;


Removed unused code.

Removed unused code.

--- SharprWowApi/GetDataBase.cs
+++ SharprWowApi/GetDataBase.cs
@@ -18,25 +18,5 @@
         internal string _Host { get; set; }

         internal string _Realm { get; set; }
-
-        internal string UrlStringBuilder(string param, string name, CharacterOptions characterOptions, string realm)
-        {
-            this._Realm = realm;
-
-            var uriBuilder = new UriBuilder();
-            uriBuilder.Host = this._Host;
-            uriBuilder.Path = string.Format(
-                @"{0}/wow/character/{1}/{2}?locale={3}{4}&apikey={5}",
-                this._Host,
-                realm,
-                name,
-                this._Locale,
-                CharacterUtility.BuildOptionalFields(characterOptions),
-                this._APIKey);
-
-            uriBuilder.Scheme = "Https";
-
-            return uriBuilder.ToString();
-        }
     }
 }


HYPER ÜBAH SUPA authorization bug solved

--- MasDev.Common/Rest/MasDev.Common.Rest.Mono/Source/Auth/Base/BaseAuthManager.cs
+++ MasDev.Common/Rest/MasDev.Common.Rest.Mono/Source/Auth/Base/BaseAuthManager.cs
@@ -16,8 +16,7 @@
 				var decompressed = TokenCompressor.Decompress (headerValue);
 				var unprotected = TokenProtector.Unprotect (decompressed);
 				return TokenSerializer.Deserialize (unprotected);
-			} catch
-			{
+			} catch {
 				return null;
 			}
 		}
@@ -53,7 +52,8 @@
 			if (roles == null)
 				return token.Scope;

-			if ((roles & issuedCredentials.Roles) == 0)
+			var rolesIntersection = roles & issuedCredentials.Roles;
+			if (rolesIntersection != roles)
 				throw new UnauthorizedException ("Invald authorization level");

 			return token.Scope;
@@ -122,12 +122,12 @@
 			repository.Update (credentials);
 		}

-	    public void ClearCache()
-	    {
-	        _issued.Clear();
-	    }
+		public void ClearCache ()
+		{
+			_issued.Clear ();
+		}

-	    public AuthManagerOptions Options { get; set; }
+		public AuthManagerOptions Options { get; set; }

 		const string _tokenType = "bearer";


Fixed unhandled exception thrown then hotkey fails to unregister (was unregistered earlier)

--- ComConsole/MainForm.cs
+++ ComConsole/MainForm.cs
@@ -171,17 +171,20 @@
             int globalHotkeyId = Int32.Parse(this.listView1.SelectedItems[0].SubItems[2].Text);
             GlobalHotkey ghToRemove = null;

+            // we are looking for the gh to delete
             foreach (GlobalHotkey gh in this.ghList) {
                 if (gh.Id.Equals(globalHotkeyId)) {
                     ghToRemove = gh;
                 }
             }

+            // then we find it's index in a List, remove it and call Dispose() to unregister
             int i = 0;
             while (i < this.ghList.Count) {
                 GlobalHotkey currentGh = this.ghList[i];
                 if (ghToRemove.Equals(currentGh)) {
                     this.ghList.RemoveAt(i);
+                    ghToRemove.Dispose();
                     break;
                 }
                 i++;
@@ -294,10 +297,7 @@
             foreach (GlobalHotkey gh in this.ghList) {
                 try {
                     gh.Unregister();
-                } catch {
-                    // even if we can't unregister this damn hotkey
-                    // there is nothing we can do about it
-                }
+                } catch { }
             }
         }


Refs #1436 - unit test voor synchronisatie verwijderd voorkeursadres

--- Solution/TestProjecten/Chiro.Gap.Services.Test/GelieerdePersonenServiceTest.cs
+++ Solution/TestProjecten/Chiro.Gap.Services.Test/GelieerdePersonenServiceTest.cs
@@ -680,5 +680,63 @@
             adressenSyncMock.Verify(src => src.StandaardAdressenBewaren(It.IsAny<IEnumerable<PersoonsAdres>>()),
                                     Times.AtLeastOnce());
         }
+
+        /// <summary>
+        /// Als het voorkeursadres van een persoon verandert na het verwijderen van een adres,
+        /// dan moet die wijziging gesynct worden. Een unit test.
+        ///</summary>
+        // TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
+        // http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
+        // whether you are testing a page, web service, or a WCF service.
+        [TestMethod()]
+        public void AdresVerwijderenVanPersonenTest()
+        {
+            // ARRANGE
+
+            var voorkeursAdres = new BelgischAdres {ID = 2};
+            var anderAdres = new BelgischAdres {ID = 3};
+
+            var gelieerdePersoon = new GelieerdePersoon {Persoon = new Persoon {ID = 1, AdInAanvraag = true}};
+
+            var voorkeursPa = new PersoonsAdres {Persoon = gelieerdePersoon.Persoon, Adres = voorkeursAdres};
+            var anderPa = new PersoonsAdres { Persoon = gelieerdePersoon.Persoon, Adres = anderAdres };
+
+            // wat gepruts om alle relaties goed te leggen
+
+            gelieerdePersoon.Persoon.PersoonsAdres.Add(voorkeursPa);
+            gelieerdePersoon.Persoon.PersoonsAdres.Add(anderPa);
+            gelieerdePersoon.PersoonsAdres = voorkeursPa;   // persoonsadres gelieere persoon bepaalt voorkeursadres
+            voorkeursAdres.PersoonsAdres.Add(voorkeursPa);
+            anderAdres.PersoonsAdres.Add(anderPa);
+            voorkeursPa.GelieerdePersoon.Add(gelieerdePersoon);
+            anderPa.GelieerdePersoon.Add(gelieerdePersoon);
+
+
+            // Dependency injection synchronisatie
+
+            var adressenSyncMock = new Mock<IAdressenSync>();
+            adressenSyncMock.Setup(src => src.StandaardAdressenBewaren(It.IsAny<IEnumerable<PersoonsAdres>>()))
+                            .Verifiable();
+            Factory.InstantieRegistreren(adressenSyncMock.Object);
+
+            // Dependency injection data access
+
+            var repositoryProviderMock = new Mock<IRepositoryProvider>();
+            repositoryProviderMock.Setup(src => src.RepositoryGet<Adres>())
+                                  .Returns(new DummyRepo<Adres>(new List<Adres> {voorkeursAdres, anderAdres}));
+            repositoryProviderMock.Setup(src => src.RepositoryGet<PersoonsAdres>())
+                                  .Returns(new DummyRepo<PersoonsAdres>(new List<PersoonsAdres> {voorkeursPa, anderPa}));
+            Factory.InstantieRegistreren(repositoryProviderMock.Object);
+
+            // ACT
+
+            var target = Factory.Maak<GelieerdePersonenService>();
+            target.AdresVerwijderenVanPersonen(new [] {gelieerdePersoon.Persoon.ID}, voorkeursAdres.ID);
+
+            // ASSERT
+
+            adressenSyncMock.Verify(src => src.StandaardAdressenBewaren(It.IsAny<IEnumerable<PersoonsAdres>>()),
+                                    Times.AtLeastOnce());
+        }
     }
 }


Remove condition check for always-true condition

--- StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1125UnitTests.cs
+++ StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1125UnitTests.cs
@@ -86,12 +86,8 @@
             string testCode = string.Format(template, longForm);
             string fixedCode = string.Format(template, shortForm);

-            if (testCode != fixedCode)
-            {
-                DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(6, 55);
-                await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
-            }
-
+            DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(6, 55);
+            await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
             await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None);
         }

@@ -161,12 +157,8 @@
             string testCode = string.Format(template, longForm);
             string fixedCode = string.Format(template, shortForm);

-            if (testCode != fixedCode)
-            {
-                DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(7, 9);
-                await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
-            }
-
+            DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(7, 9);
+            await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
             await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None);
         }

@@ -197,12 +189,8 @@
             string testCode = string.Format(template, longForm);
             string fixedCode = string.Format(template, shortForm);

-            if (testCode != fixedCode)
-            {
-                DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(9, 41);
-                await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
-            }
-
+            DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(9, 41);
+            await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
             await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None);
         }

@@ -310,12 +298,8 @@
             string testCode = string.Format(template, longForm);
             string fixedCode = string.Format(template, shortForm);

-            if (testCode != fixedCode)
-            {
-                DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(8, 43);
-                await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
-            }
-
+            DiagnosticResult expected = this.CSharpDiagnostic().WithLocation(8, 43);
+            await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None);
             await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None);
         }


check the session is running before allowing gap messages to play

--- CrewChiefV2/Timings.cs
+++ CrewChiefV2/Timings.cs
@@ -73,19 +73,19 @@
         {
             if (eventSubType == QueuedMessage.compoundMessageIdentifier + "Timings/gap_in_front")
             {
-                return CommonData.racingSameCarInFront;
+                return CommonData.isSessionRunning && CommonData.racingSameCarInFront;
             }
             else if (eventSubType == QueuedMessage.compoundMessageIdentifier + "Timings/gap_behind")
             {
-                return CommonData.racingSameCarBehind;
+                return CommonData.isSessionRunning && CommonData.racingSameCarBehind;
             }
             else if (eventSubType == folderBeingHeldUp)
             {
-                return CommonData.racingSameCarInFront;
+                return CommonData.isSessionRunning && CommonData.racingSameCarInFront;
             }
             else if (eventSubType == folderBeingPressured)
             {
-                return CommonData.racingSameCarBehind;
+                return CommonData.isSessionRunning && CommonData.racingSameCarBehind;
             }
             else
             {


stub in the tests

stub in the tests

--- api/test/BellRichM.Weather.Api.Test/Repositories/ObservationRepositorySpecs.cs
+++ api/test/BellRichM.Weather.Api.Test/Repositories/ObservationRepositorySpecs.cs
@@ -155,6 +155,16 @@
             observation.Should().BeEquivalentTo(originalObservation);
     }

+    internal class When_getting_observations : ObservationRepositorySpecs
+    {
+        Because of = () => { };
+    }
+
+    internal class When_getting_observation_datetimes : ObservationRepositorySpecs
+    {
+        Because of = () => { };
+    }
+
     internal class When_updating_an_observation : ObservationRepositorySpecs
     {
         protected static int rowCount;


Housekeeping

Housekeeping

--- src/Merchello.Core/Persistence/Factories/CustomerFactory.cs
+++ src/Merchello.Core/Persistence/Factories/CustomerFactory.cs
@@ -1,9 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Merchello.Core.Models;
+using Merchello.Core.Models;
 using Merchello.Core.Models.Rdbms;

 namespace Merchello.Core.Persistence.Factories


NDC London bug fix! , changing environment variable name

--- src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
+++ src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
@@ -8,7 +8,7 @@
     internal class ConfigureHostingEnvironment : IConfigureHostingEnvironment
     {
         private IConfiguration _config;
-        private const string EnvironmentKey = "KRE_ENV";
+        private const string EnvironmentKey = "ASPNET_ENV";

         public ConfigureHostingEnvironment(IConfiguration config)
         {


Stop NPCs steering around non-hard fixtures (#8668)

--- Content.Server/AI/Steering/AiSteeringSystem.cs
+++ Content.Server/AI/Steering/AiSteeringSystem.cs
@@ -660,7 +660,8 @@
                     // So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction
                     // i.e. towards the right
                     if (EntityManager.TryGetComponent(physicsEntity, out IPhysBody? otherPhysics) &&
-                        Vector2.Dot(otherPhysics.LinearVelocity, direction) > 0)
+                        (!otherPhysics.Hard ||
+                        Vector2.Dot(otherPhysics.LinearVelocity, direction) > 0))
                     {
                         continue;
                     }


guh (#12474)

guh (#12474)

Co-authored-by: moonheart08 <00e70cb4f2e196463eb43c2776855f8722acb98e@users.noreply.github.com>


Added some loggin to ControlServer.

Added some loggin to ControlServer.

--- src/Mono.Upnp/Mono.Upnp/Mono.Upnp.Internal/ControlServer.cs
+++ src/Mono.Upnp/Mono.Upnp/Mono.Upnp.Internal/ControlServer.cs
@@ -74,11 +74,17 @@
                             new SoapEnvelope<Arguments> (new Arguments (service_type, action.Name, action.Execute (arguments.Values), true)),
                             context.Response.OutputStream
                         );
+
+                        Log.Information (string.Format ("{0} invoked {1} on {2}.",
+                            context.Request.RemoteEndPoint, arguments.ActionName, context.Request.Url));
                     } catch (Exception e) {
                         // TODO handle faults
                     }
                 } else {
-                    // TODO report fault
+                    Log.Error (string.Format (
+                        "{0} attempted to invoke the non-existant action {1} on {2}.",
+                        context.Request.RemoteEndPoint, arguments.ActionName, context.Request.Url));
+                    // TODO generate fault
                 }
             }
         }


Set a TCP keep alive to hopefully fix an issue with azure: http://blogs.msdn.com/b/granth/archive/2013/02/13/tfs-load-balancers-idle-timeout-settings-and-tcp-keep-alives.aspx  http://blogs.msdn.com/b/cie/archive/2014/02/14/connection-timeout-for-windows-azure-cloud-service-roles-web-worker.aspx

--- Source/Core/Bootstrapper.cs
+++ Source/Core/Bootstrapper.cs
@@ -11,6 +11,7 @@

 using System;
 using System.Configuration;
+using System.Net;
 using Exceptionless.Core.Dependency;
 using Exceptionless.Core.AppStats;
 using Exceptionless.Core.Billing;
@@ -67,6 +68,7 @@
                 return server.GetDatabase(databaseName);
             });

+            ServicePointManager.SetTcpKeepAlive(true, TimeSpan.FromMinutes(1).Seconds, TimeSpan.FromSeconds(5).Seconds);
             container.RegisterSingle<IElasticClient>(() => GetElasticClient(new Uri(Settings.Current.ElasticSearchConnectionString)));

             if (Settings.Current.EnableRedis) {


Fix test

Fix test

--- src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs
+++ src/NSwag.CodeGeneration.CSharp.Tests/FormParameterTests.cs
@@ -76,8 +76,8 @@

             //// Assert
             Assert.Contains("FileParameter file", code);
-            Assert.Contains("var content_ = new System.Net.Http.MultipartFormDataContent(boundary_);", code);
-            Assert.Contains("content_.Add(new System.Net.Http.StreamContent(file.Data), \"file\"", code);
+            Assert.Contains("var content_file_ = new System.Net.Http.StreamContent(file.Data);", code);
+            Assert.Contains("content_.Add(content_file_, \"file\", file.FileName ??", code);
         }

         [Fact]


Add default index for events.

Add default index for events.

--- Source/Core/Bootstrapper.cs
+++ Source/Core/Bootstrapper.cs
@@ -144,6 +144,7 @@
             });
             settings.MapDefaultTypeNames(m => m.Add(typeof(PersistentEvent), "events").Add(typeof(Stack), "stacks"));
             settings.MapDefaultTypeIndices(m => m.Add(typeof(Stack), ElasticSearchRepository<Stack>.StacksIndexName));
+            settings.MapDefaultTypeIndices(m => m.Add(typeof(PersistentEvent), ElasticSearchRepository<PersistentEvent>.EventsIndexName + "-*"));
             settings.SetDefaultPropertyNameInferrer(p => p.ToLowerUnderscoredWords());

             var client = new ElasticClient(settings);


very small refactoring

very small refactoring

--- src/OpenSage.Game/Gui/Apt/ActionScript/InstructionStream.cs
+++ src/OpenSage.Game/Gui/Apt/ActionScript/InstructionStream.cs
@@ -28,12 +28,7 @@
         /// <returns></returns>
         public InstructionBase GetInstruction()
         {
-            if (_index < 0)
-            {
-                throw new IndexOutOfRangeException();
-            }
-
-            if (_index - 1 > _instructions.Count)
+            if (_index < 0 || _instructions.Count < _index - 1)
             {
                 throw new IndexOutOfRangeException();
             }


Delete DrainageBasinGrid.cs

Delete DrainageBasinGrid.cs

--- Source/DrainageBasinGrid.cs
+++ Source/DrainageBasinGrid.cs
@@ -1,357 +0,0 @@
-using System;
-using System.Collections.Generic;
-using ColossalFramework;
-using UnityEngine;
-
-namespace Rainfall
-{
-    public static class DrainageBasinGrid
-    {
-
-        private static bool awake = false;
-
-
-        private static readonly int waterSourceLimit = 65535;
-        public static readonly int gridCoefficient = 270;
-        private static readonly int magicNumber = 17280;
-        public static readonly float gridQuotient = (float)magicNumber / (float)gridCoefficient;
-        public static readonly float gridAddition = gridCoefficient / 2f;
-        private static readonly float gridArea = gridQuotient * gridQuotient;
-        private static readonly float areaGridCellSize = 1920f;
-        private static readonly int areaGridResolution = 5;
-        private static readonly int tiles = areaGridResolution * areaGridResolution;
-        private static readonly float totalTileArea = areaGridCellSize * tiles;
-        public static readonly int gridResolution = (int)Math.Ceiling(totalTileArea / gridArea);
-        private static readonly int gridMinimum = 14;
-        private static readonly int gridMaximum = 256;
-        private static List<int> selectedTiles = new List<int>();
-        private static gridOption selectedGridOption = gridOption.OwnedTiles;
-        private static GameAreaManager gameAreaManager = Singleton<GameAreaManager>.instance;
-
-        public enum gridOption {
-            None,
-            OwnedTiles,
-            AdjacentTiles,
-            AdjacentAndDiagonalTiles,
-            TwentyFiveTiles,
-            FortyNineTiles,
-            FortyNineTilesPlus,
-        }
-        public static readonly Dictionary<gridOption, string> gridOptionNames = new Dictionary<gridOption, string>()
-        {
-            {gridOption.None, "None"  },
-            {gridOption.OwnedTiles, "Owned Tiles" },
-            {gridOption.AdjacentTiles, "Adjacent Tiles" },
-            {gridOption.AdjacentAndDiagonalTiles, "Adjacent and Diagonal Tiles" },
-            {gridOption.TwentyFiveTiles, "25 Tiles" },
-            {gridOption.FortyNineTiles, "49 Tiles (Requires 81 tiles)" },
-            {gridOption.FortyNineTilesPlus, "49 Tiles + Edges (Requires 81 tiles)" }
-        };
-        //private static gridOption[] gridOptions = new gridOption[] { gridOption.None, gridOption.OwnedTiles, gridOption.AdjacentTiles, gridOption.AdjacentAndDiagonalTiles, gridOption.TwentyFiveTiles };
-
-        private static Dictionary<int, DrainageBasin> drainageBasinDictionary = new Dictionary<int, DrainageBasin>();
-
-        private static Dictionary<uint, int> drainageBasinWaterSourceCatalog = new Dictionary<uint, int>();
-
-        //private static readonly int gridDimension = gridCoefficient^2;
-        public static void Awake()
-        {
-            generateDraiangeBasinGrid();
-            awake = true;
-        }
-
-        public static void Clear()
-        {
-            if (LoadingFunctions.loaded)
-            {
-                List<ushort> previousStormWaterSourceIDs = new List<ushort>();
-                WaterSimulation _waterSimulation = Singleton<TerrainManager>.instance.WaterSimulation;
-                for (int i = 0; i < _waterSimulation.m_waterSources.m_size; i++)
-                {
-                    WaterSource ws = _waterSimulation.m_waterSources.m_buffer[i];
-                    if (isWaterSourceAssociatedWithADrainageBasin((uint)i))
-                    {
-
-                        previousStormWaterSourceIDs.Add((ushort)(i + 1));
-                    }
-                }
-                foreach (ushort id in previousStormWaterSourceIDs)
-                {
-                    _waterSimulation.ReleaseWaterSource(id);
-                }
-                drainageBasinDictionary.Clear();
-                drainageBasinWaterSourceCatalog.Clear();
-                awake = false;
-            }
-        }
-
-        public static bool areYouAwake()
-        {
-            return awake;
-        }
-        public static int CheckGridX(Vector3 position)
-        {
-
-            return Mathf.Clamp(Mathf.FloorToInt(position.x / gridQuotient + gridAddition), 0, gridCoefficient - 1);
-        }
-        public static int CheckGridZ(Vector3 position)
-
-        {
-            return Mathf.Clamp(Mathf.FloorToInt(position.z / gridQuotient + gridAddition), 0, gridCoefficient - 1);
-        }
-        public static void generateDraiangeBasinGrid()
-        {
-
-            drainageBasinDictionary.Clear();
-
-            selectedGridOption = getGridOptionFromInt(OptionHandler.getDropdownSetting("SelectedGridOption")); //need to find setting unique name
-            selectedTiles = generateListOfGameAreas(selectedGridOption);
-            bool logging = false;
-            foreach (int tile in selectedTiles)
-            {
-                if (logging)
-                {
-                    Debug.Log("[RF]DrainageBasinGrid.generateDraiangeBasinGrid generatingDrainageBasinsForTile " + tile.ToString());
-                }
-                generateDrainageBasinsForTile(tile, logging);
-            }
-            Debug.Log("[RF]DrainageBasinGrid.generateDraiangeBasinGrid drainageBasinDiction.Count = " + drainageBasinDictionary.Count);
-            return;
-
-        }
-        private static void generateDrainageBasinsForTile(int tile, bool logging)
-        {
-            float iterator = DrainageBasinGrid.gridQuotient; //64
-            Vector3 position = new Vector3(0, 0, 0);
-            int x = 0;
-            int z = 0;
-            GetTileXZ(tile, out x, out z);
-            gameAreaManager.GetAreaBounds(x, z, out float startX, out float startZ, out float endX, out float endZ);
-            for (position.z = startZ; position.z < endZ; position.z += iterator)   {
-                for (position.x = startX; position.x < endX; position.x += iterator)   {
-                    int gridX = Mathf.Clamp(Mathf.FloorToInt(position.x / gridQuotient + gridAddition), 0, gridCoefficient - 1);
-                    int gridZ = Mathf.Clamp(Mathf.FloorToInt(position.z / gridQuotient + gridAddition), 0, gridCoefficient - 1);
-                    int gridLocation = gridZ * gridCoefficient + gridX;
-                    if (gridX >= gridMinimum && gridX <= gridMaximum && gridZ >= gridMinimum && gridZ <= gridMaximum)
-                    {
-                        if (!drainageBasinDictionary.ContainsKey(gridLocation) && drainageBasinDictionary.Count < 60000)
-                        {
-                            drainageBasinDictionary.Add(gridLocation, new DrainageBasin(gridLocation, position));
-                            recordWaterSourceForDrainageBasin(drainageBasinDictionary[gridLocation].getWaterSourceID(), gridLocation);
-                            if (logging)
-                            {
-                                Debug.Log("[RF]DrainageBasinGrid.generateDrainageBasinsForTile Added Drainage Basin to Grid at Grid Location " + gridLocation.ToString() + " and position " + position.ToString());
-                            }
-                        }
-
-                    }
-                }
-            }
-
-        }
-
-        public static void updateDrainageBasinGridForNewTile(bool logging)
-        {
-            List<int> newSelectedTiles = generateListOfGameAreas(selectedGridOption);
-
-            if (newSelectedTiles.Equals(selectedTiles))
-            {
-                return;
-            }
-            foreach(int tile in newSelectedTiles)
-            {
-                if (selectedTiles.Contains(tile))
-                {
-                    continue;
-                }
-                if (logging)
-                {
-                    Debug.Log("[RF]DrainageBasinGrid.updateDrainageBasinGridForNewTile generatingDrainageBasinsForTile " + tile.ToString());
-                }
-                generateDrainageBasinsForTile(tile, false);
-            }
-            selectedTiles = newSelectedTiles;
-
-        }
-        private static List<int> generateListOfGameAreas(gridOption selectedGridOption)
-        {
-            List<int> selectedTiles = new List<int>();
-            bool logging = false;
-            if (selectedGridOption == gridOption.None)
-            {
-                return selectedTiles;
-            }
-            if (logging == true) Debug.Log("[RF]DBG.generateListOfGameAreas gameAreaManager.m_areaGrid.Length " + gameAreaManager.m_areaGrid.Length);
-
-
-            if (gameAreaManager.m_areaGrid.Length == 25 && selectedGridOption == gridOption.FortyNineTiles || gameAreaManager.m_areaGrid.Length == 25 && selectedGridOption == gridOption.FortyNineTilesPlus)
-            {
-                selectedGridOption = gridOption.TwentyFiveTiles;
-            }
-
-            int areaGridResolution = 5;
-            if (gameAreaManager.m_areaGrid.Length == 81)
-            {
-                areaGridResolution = 9;
-            }
-            for (int z = 0; z < areaGridResolution; z++)   {
-                for (int x = 0; x < areaGridResolution; x++)   {
-                    if (gameAreaManager.m_areaGrid.Length == 25 && selectedGridOption == gridOption.TwentyFiveTiles)
-                    {
-                        selectedTiles.Add(z * areaGridResolution + x);
-                        continue;
-                    } else if (gameAreaManager.m_areaGrid.Length == 81 && selectedGridOption == gridOption.TwentyFiveTiles)
-                    {
-                        if (x >= 2 && x <= 6 && z >= 2 && z <= 6)
-                        {
-                            selectedTiles.Add(z * areaGridResolution + x);
-                        }
-                        if (logging == true) Debug.Log("[RF]DrainageBasinGrid.generateListOfGameAreas 81 tiles enabled and Twenty Five Tiles Selected! Maybe this will work?");
-                        continue;
-                    } else if (gameAreaManager.m_areaGrid.Length == 81 && selectedGridOption == gridOption.FortyNineTiles)
-                    {
-                        if (x >= 1 && x <= 7 && z >= 1 && z <= 7)
-                        {
-                            selectedTiles.Add(z * areaGridResolution + x);
-                        }
-                        if (logging == true) Debug.Log("[RF]DrainageBasinGrid.generateListOfGameAreas 81 tiles enabled and Forty Nine Tiles Selected! Maybe this will work?");
-                        continue;
-                    } else if (gameAreaManager.m_areaGrid.Length == 81 && selectedGridOption == gridOption.FortyNineTilesPlus)
-                    {
-                        selectedTiles.Add(z * areaGridResolution + x);
-                        if (logging == true) Debug.Log("[RF]DrainageBasinGrid.generateListOfGameAreas 81 tiles enabled and Forty Nine Tiles Plus Selected! Maybe this will work?");
-                        continue;
-                    }
-                    //to make it to this point it must be Owned, Adjacent or Adjacent + diagonal
-                    if (gameAreaManager.IsUnlocked(x, z))
-                    {
-                        selectedTiles.Add(z * areaGridResolution + x); //For Owned, Adjacent, and Adjacent+Diagonal add Owned Tiles
-                        continue;
-                    } else if (selectedGridOption == gridOption.OwnedTiles) {
-                        continue;
-                    }
-
-                    //to make it to this point it must be Adjacent or Adjacent+Diagonal
-                    if (gameAreaManager.IsUnlocked(x+1, z) || gameAreaManager.IsUnlocked(x-1, z) || gameAreaManager.IsUnlocked(x, z-1) || gameAreaManager.IsUnlocked(x, z+1))
-                    {
-                        selectedTiles.Add(z * areaGridResolution + x); //For Adjacent, and Adjacent+Diagonal add Adjacent to Owned Tiles
-                        continue;
-                    } else if (selectedGridOption == gridOption.AdjacentTiles)
-                    {
-                        continue;
-                    }
-                    //to make it to this point it must be Adjacent+Diagonal
-                    if (gameAreaManager.IsUnlocked(x + 1, z+1) || gameAreaManager.IsUnlocked(x + 1, z - 1) || gameAreaManager.IsUnlocked(x - 1, z - 1) || gameAreaManager.IsUnlocked(x - 1, z + 1))
-                    {
-                        selectedTiles.Add(z * areaGridResolution + x); //For Adjacent+Diagonal add Diagonal to Owned Tiles
-                    }
-                }
-            }
-            if (logging == true) {
-                Debug.Log("[RF]DrainageBasinGrid.GenerateListOfGameAreas selected tiles as followed: ");
-                foreach (int tile in selectedTiles)
-                {
-                    Debug.Log("[RF]DrainageBasinGrid.GenerateListOfGameAreas " + tile.ToString());
-                }
-            }
-
-            return selectedTiles;
-        }
-
-        public static bool recalculateCompositeRunoffCoefficentForBasinAtGridLocation(int gridLocation)
-        {
-            if (drainageBasinDictionary != null)
-            {
-                if (drainageBasinDictionary.ContainsKey(gridLocation))
-                {
-                    bool logging = false;
-                    drainageBasinDictionary[gridLocation].recalculateCompositeRunoffCoefficent(logging);
-                    return true;
-                }
-            }
-            return false;
-        }
-
-        public static bool recordWaterSourceForDrainageBasin(uint waterSourceID, int drainageBasinID)
-        {
-            bool logging = false;
-            if (!drainageBasinWaterSourceCatalog.ContainsKey(waterSourceID) && drainageBasinDictionary.ContainsKey(drainageBasinID))
-            {
-                if (drainageBasinDictionary[drainageBasinID].getWaterSourceID() == waterSourceID)
-                {
-                    if (logging)
-                    {
-                        Debug.Log("[RF]DrainageBasinGrid.recordWaterSourceForDrainageBasin Added WaterSourceID " + waterSourceID.ToString() + " to drainageBasin " + drainageBasinID.ToString());
-                    }
-                    drainageBasinWaterSourceCatalog.Add(waterSourceID, drainageBasinID);
-                    return true;
-                }
-                if (logging)
-                {
-                    Debug.Log("[RF]DrainageBasinGrid.recordWaterSourceForDrainageBasin drainageBasinDictionary[drainageBasinID].getWaterSourceID() != waterSourceID");
-                    Debug.Log("[RF]DrainageBasinGrid.recordWaterSourceForDrainageBasin Couldn't Add WaterSourceID " + waterSourceID.ToString() + " to drainageBasin " + drainageBasinID.ToString());
-
-                }
-                return false;
-            }
-            if (logging)
-            {
-                Debug.Log("[RF]DrainageBasinGrid.recordWaterSourceForDrainageBasin drainageBasinWaterSourceCatalog.ContainsKey(waterSourceID) || !drainageBasinDictionary.ContainsKey(drainageBasinID)");
-                Debug.Log("[RF]DrainageBasinGrid.recordWaterSourceForDrainageBasin Couldn't Add WaterSourceID " + waterSourceID.ToString() + " to drainageBasin " + drainageBasinID.ToString());
-            }
-            return false;
-        }
-        public static bool isWaterSourceAssociatedWithADrainageBasin(uint waterSourceID)
-        {
-            if (drainageBasinWaterSourceCatalog.ContainsKey(waterSourceID))
-            {
-                if (drainageBasinDictionary[drainageBasinWaterSourceCatalog[waterSourceID]].getWaterSourceID() == waterSourceID)
-                {
-                    return true;
-                }
-                return false;
-            }
-            return false;
-        }
-        public static int getDrainageBasinIDfromWaterSource(uint waterSourceID)
-        {
-            if (isWaterSourceAssociatedWithADrainageBasin(waterSourceID))
-            {
-                return drainageBasinWaterSourceCatalog[waterSourceID];
-            }
-            return -1;
-        }
-        public static float getCompositeRunoffCoefficientForDrainageBasin(int drainageBasinID)
-        {
-            if (drainageBasinDictionary.ContainsKey(drainageBasinID)) {
-               return drainageBasinDictionary[drainageBasinID].getCompositeRunoffCoefficient();
-            }
-            return 0f;
-        }
-
-        public static gridOption getGridOptionFromInt(int selection)
-        {
-            if (selection == 0) return gridOption.None;
-            if (selection == 1) return gridOption.OwnedTiles;
-            if (selection == 2) return gridOption.AdjacentTiles;
-            if (selection == 3) return gridOption.AdjacentAndDiagonalTiles;
-            if (selection == 4) return gridOption.TwentyFiveTiles;
-            if (selection == 5) return gridOption.FortyNineTiles;
-            if (selection == 6) return gridOption.FortyNineTilesPlus;
-            return gridOption.OwnedTiles;
-        }
-
-        public static void GetTileXZ(int tile, out int x, out int z)
-        {
-            int areaGridResolution = 5;
-            if (gameAreaManager.m_areaGrid.Length == 81)
-            {
-                areaGridResolution = 9;
-            }
-            //begin mod
-            x = tile % areaGridResolution;
-            z = tile / areaGridResolution;
-            //end mod
-        }
-    }
-}


Separate ToDictionary and ToDictionaryTyped so objects get reflected properly

--- DNX.Helpers/Reflection/ReflectionExtensions.cs
+++ DNX.Helpers/Reflection/ReflectionExtensions.cs
@@ -313,14 +313,30 @@
         /// <param name="instance">The instance.</param>
         /// <param name="bindingFlags">The binding flags.</param>
         /// <returns>IDictionary<System.String, System.Object>.</returns>
-        public static IDictionary<string, object> ToDictionary<T>(this T instance, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
+        public static IDictionary<string, object> ToDictionaryTyped<T>(this T instance, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
         {
             if (instance == null)
             {
                 return null;
             }

-            var properties = typeof(T).GetProperties(bindingFlags);
+            return instance.ToDictionary();
+        }
+
+        /// <summary>
+        /// Serialises an object instance to a Dictionary
+        /// </summary>
+        /// <param name="instance">The instance.</param>
+        /// <param name="bindingFlags">The binding flags.</param>
+        /// <returns>IDictionary<System.String, System.Object>.</returns>
+        public static IDictionary<string, object> ToDictionary(this object instance, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
+        {
+            if (instance == null)
+            {
+                return null;
+            }
+
+            var properties = instance.GetType().GetProperties(bindingFlags);

             var dict = new Dictionary<string, object>();


Added model metadata providers

Added model metadata providers

--- DbLocalizationProvider/AppBuilderExtensions.cs
+++ DbLocalizationProvider/AppBuilderExtensions.cs
@@ -1,5 +1,7 @@
 using System;
+using System.Web.Mvc;
 using DbLocalizationProvider.Commands;
+using DbLocalizationProvider.DataAnnotations;
 using DbLocalizationProvider.Queries;
 using DbLocalizationProvider.Sync;
 using Owin;
@@ -26,6 +28,47 @@

             var synchronizer = new ResourceSynchronizer();
             synchronizer.DiscoverAndRegister();
+
+            // set model metadata providers
+            if(ConfigurationContext.Current.ModelMetadataProviders.ReplaceProviders)
+            {
+                // set current provider
+                if(ModelMetadataProviders.Current == null)
+                {
+                    if(ConfigurationContext.Current.ModelMetadataProviders.UseCachedProviders)
+                    {
+                        ModelMetadataProviders.Current = new CachedLocalizedMetadataProvider();
+                    }
+                    else
+                    {
+                        ModelMetadataProviders.Current = new LocalizedMetadataProvider();
+                    }
+                }
+                else
+                {
+                    if (ConfigurationContext.Current.ModelMetadataProviders.UseCachedProviders)
+                    {
+                        ModelMetadataProviders.Current = new CompositeModelMetadataProvider<CachedLocalizedMetadataProvider>(ModelMetadataProviders.Current);
+                    }
+                    else
+                    {
+                        ModelMetadataProviders.Current = new CompositeModelMetadataProvider<LocalizedMetadataProvider>(ModelMetadataProviders.Current);
+                    }
+                }
+
+                for (var i = 0; i < ModelValidatorProviders.Providers.Count; i++)
+                {
+                    var provider = ModelValidatorProviders.Providers[i];
+                    if (!(provider is DataAnnotationsModelValidatorProvider))
+                    {
+                        continue;
+                    }
+
+                    ModelValidatorProviders.Providers.RemoveAt(i);
+                    ModelValidatorProviders.Providers.Insert(i, new LocalizedModelValidatorProvider());
+                    break;
+                }
+            }
         }
     }
 }


[Tests]: Move xhtml elements testing to a separate test

--- Source/Tests/ParserTests.cs
+++ Source/Tests/ParserTests.cs
@@ -176,6 +176,15 @@
         }

         [TestMethod]
+        public void XhtmlElementsTest()
+        {
+            string testString = "Test <empty/>string";
+            string[] expectedResult = { "", "", "Test ", "<empty/>", "", "string", "", "", "" };
+            string[] actualResult = Parser.ParseXhtmlText(testString).XhtmlElements.ToArray();
+            CollectionAssert.AreEqual(expectedResult, actualResult);
+        }
+
+        [TestMethod]
         public void XhtmlTokensCompoundTokensTest()
         {
             string testString = "
Hello, world!
";
@@ -187,8 +196,7 @@
                 new Tuple<string, TokenKind>("world", TokenKind.Alphabetic),
                 new Tuple<string, TokenKind>("!", TokenKind.Symbol)
             };
-            string[] expectedXhtmlElements = {"
", "Hello, ", "", "w", "", "orld!", "
"};
-            ParseXhtmlAndTestTokens(testString, expectedTokens, expectedXhtmlElements);
+            ParseXhtmlAndTestTokens(testString, expectedTokens);
         }

         [TestMethod]
@@ -202,8 +210,7 @@
                 new Tuple<string, TokenKind>("c", TokenKind.Alphabetic),
                 new Tuple<string, TokenKind>("d", TokenKind.Alphabetic)
             };
-            string[] expectedXhtmlElements = { "", "
", "a", "
", "
", "b", "
", "
", "c", "
","
", "d", "
", "" };
-            ParseXhtmlAndTestTokens(testString, expectedTokens, expectedXhtmlElements);
+            ParseXhtmlAndTestTokens(testString, expectedTokens);
         }

         [TestMethod]
@@ -273,13 +280,12 @@
             CollectionAssert.AreEqual(expectedTags, actualTags);
         }

-        private static void ParseXhtmlAndTestTokens(string testString, Tuple<string, TokenKind>[] expectedTokens, string[] expectedXhtmlElements)
+        private static void ParseXhtmlAndTestTokens(string testString, Tuple<string, TokenKind>[] expectedTokens)
         {
             ParsedText parsedText = Parser.ParseXhtmlText(testString);
             Tuple<string, TokenKind>[] actualTokens = GetTokensFromParsedText(parsedText);
             List<string> actualXhtmlElements = parsedText.XhtmlElements;
             CollectionAssert.AreEqual(expectedTokens, actualTokens);
-            CollectionAssert.AreEqual(expectedXhtmlElements, actualXhtmlElements);
         }

         private static void ParseXhtmlAndTestTags(string testString, string[] expectedTags)