POI：bug 60128: close opened resources to avoid leaks; add exception as cause where available for more context for raised exceptions.

--- openxml4Net/OPC/ZipPackage.cs
+++ openxml4Net/OPC/ZipPackage.cs
@@ -18,7 +18,8 @@
      */
     public class ZipPackage : OPCPackage
     {
-
+        private static String MIMETYPE = "mimetype";
+        private static String SETTINGS_XML = "settings.xml";
         private static POILogger logger = POILogFactory.GetLogger(typeof(ZipPackage));

         /**
@@ -204,7 +205,7 @@
                     }
                     catch (IOException e)
                     {
-                        throw new InvalidFormatException(e.Message);
+                        throw new InvalidFormatException(e.Message, e);
                     }
                     break;
                 }
@@ -221,11 +222,11 @@
                 while (entries.MoveNext())
                 {
                     ZipEntry entry = entries.Current as ZipEntry;
-                    if (entry.Name.Equals("mimetype"))
+                    if (entry.Name.Equals(MIMETYPE))
                     {
                         hasMimetype = true;
                     }
-                    if (entry.Name.Equals("settings.xml"))
+                    if (entry.Name.Equals(SETTINGS_XML))
                     {
                         hasSettingsXML = true;
                     }
@@ -265,12 +266,12 @@
                 {
                     try
                     {
-                        partList[partName] = new ZipPackagePart(this, entry,
-                            partName, contentType);
+                        PackagePart part = new ZipPackagePart(this, entry, partName, contentType);
+                        partList[partName] = part;
                     }
                     catch (InvalidOperationException e)
                     {
-                        throw new InvalidFormatException(e.Message);
+                        throw new InvalidFormatException(e.Message, e);
                     }
                 }
             }
@@ -283,8 +284,7 @@
                 PackagePartName partName = BuildPartName(entry);
                 if (partName == null) continue;

-                String contentType = contentTypeManager
-                        .GetContentType(partName);
+                String contentType = contentTypeManager.GetContentType(partName);
                 if (contentType != null && contentType.Equals(ContentTypes.RELATIONSHIPS_PART))
                 {
                     // Already handled
@@ -293,12 +293,12 @@
                 {
                     try
                     {
-                        partList[partName] = new ZipPackagePart(this, entry,
-                                partName, contentType);
+                        PackagePart part = new ZipPackagePart(this, entry, partName, contentType);
+                        partList[partName] = part;
                     }
                     catch (InvalidOperationException e)
                     {
-                        throw new InvalidFormatException(e.Message);
+                        throw new InvalidFormatException(e.Message, e);
                     }
                 }
                 else
@@ -425,25 +425,29 @@
                     // Save the final package to a temporary file
                     try
                     {
-                        FileStream fs = File.OpenWrite(fi.FullName);
-                        Save(fs);
-                        if(zipArchive!=null)
-                            this.zipArchive.Close(); // Close the zip archive to be
-                        fs.Close();
-                        // able to delete it
-                        FileHelper.CopyFile(fi.FullName, this.originalPackagePath);
+                        Save(tempfilePath);
                     }
                     finally
                     {
-                        // Either the save operation succeed or not, we delete the
-                        // temporary file
-                        File.Delete(fi.FullName);
-
+                        try
+                        {
+                            if (zipArchive != null)
+                                this.zipArchive.Close(); // Close the zip archive to be
+                                                         // able to delete it
+                            FileHelper.CopyFile(fi.FullName, this.originalPackagePath);
+                        }
+                        finally
+                        {
+                            // Either the save operation succeed or not, we delete the
+                            // temporary file
+                            File.Delete(fi.FullName);
+
                             logger
                                     .Log(POILogger.WARN, "The temporary file: '"
                                             + tempfilePath
                                             + "' cannot be deleted ! Make sure that no other application use it.");
-
+
+                        }
                     }
                 }
                 else


added tests for name type

added tests for name type

--- Tests/NameFilterTest.cs
+++ Tests/NameFilterTest.cs
@@ -120,6 +120,16 @@
             Assert.IsTrue(names.All(s => result.Select(name => name.Data).Contains(s)));
         }

+        [Test]
+        public void NameFilter_Arg_LastNames() {
+            string[] names = {
+                "Green", "Wood", "Pavlov", "Bogdanov", "Volkov", "Rusu", "Ceban", "Nagy", "Salo", "Niemi", "Koppel",
+                "Urbonas", "Torres", "Calvo", "Romero", "Johnson", "Salas", "Vargas"
+            };
+            var result = NameFilter.FilterBy(FilterArg.Lastname);
+            Assert.IsTrue(names.All(s => result.Select(name => name.Data).Contains(s)));
+        }
+
         #endregion

         #endregion


Don't display expired playlist items

Don't display expired playlist items

--- osu.Game/Online/Rooms/Room.cs
+++ osu.Game/Online/Rooms/Room.cs
@@ -148,6 +148,12 @@
             if (EndDate.Value != null && DateTimeOffset.Now >= EndDate.Value)
                 Status.Value = new RoomStatusEnded();

+            // Todo: This is not the best way/place to do this, but the intention is to display all playlist items when the room has ended,
+            // and display only the non-expired playlist items while the room is still active.
+            // In order to achieve this, all expired items are removed from the source Room.
+            if (!(Status.Value is RoomStatusEnded))
+                other.Playlist.RemoveAll(i => i.Expired);
+
             if (!Playlist.SequenceEqual(other.Playlist))
             {
                 Playlist.Clear();


Add required properties for compatibility with existing code

--- osu.Game/Scoring/ScoreInfo.cs
+++ osu.Game/Scoring/ScoreInfo.cs
@@ -3,11 +3,17 @@

 using System;
 using System.Collections.Generic;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Linq;
+using Newtonsoft.Json;
 using osu.Framework.Testing;
 using osu.Game.Beatmaps;
 using osu.Game.Database;
 using osu.Game.Models;
+using osu.Game.Online.API;
 using osu.Game.Rulesets;
+using osu.Game.Rulesets.Mods;
+using osu.Game.Rulesets.Scoring;
 using osu.Game.Users;
 using Realms;

@@ -80,5 +86,132 @@
         IBeatmapInfo IScoreInfo.Beatmap => Beatmap;
         IUser IScoreInfo.User => User;
         IEnumerable<INamedFileUsage> IHasNamedFiles.Files => Files;
+
+        #region Properties required to make things work with existing usages
+
+        private APIMod[]? localAPIMods;
+
+        private Mod[]? mods;
+
+        [Ignored]
+        public List<HitEvent> HitEvents { get; set; } = new List<HitEvent>();
+
+        public ScoreInfo DeepClone()
+        {
+            var clone = (ScoreInfo)MemberwiseClone();
+
+            clone.Statistics = new Dictionary<HitResult, int>(clone.Statistics);
+
+            return clone;
+        }
+
+        [Ignored]
+        public bool Passed { get; set; } = true;
+
+        /// <summary>
+        /// The position of this score, starting at 1.
+        /// </summary>
+        [Ignored]
+        public int? Position { get; set; } // TODO: remove after all calls to `CreateScoreInfo` are gone.
+
+        /// <summary>
+        /// Whether this <see cref="EFScoreInfo"/> represents a legacy (osu!stable) score.
+        /// </summary>
+        [Ignored]
+        public bool IsLegacyScore => Mods.OfType<ModClassic>().Any();
+
+        [Ignored]
+        public Mod[] Mods
+        {
+            get
+            {
+                var rulesetInstance = Ruleset.CreateInstance();
+
+                Mod[] scoreMods = Array.Empty<Mod>();
+
+                if (mods != null)
+                    scoreMods = mods;
+                else if (localAPIMods != null)
+                    scoreMods = APIMods.Select(m => m.ToMod(rulesetInstance)).ToArray();
+
+                return scoreMods;
+            }
+            set
+            {
+                localAPIMods = null;
+                mods = value;
+            }
+        }
+
+        // Used for API serialisation/deserialisation.
+        [Ignored]
+        public APIMod[] APIMods
+        {
+            get
+            {
+                if (localAPIMods != null)
+                    return localAPIMods;
+
+                if (mods == null)
+                    return Array.Empty<APIMod>();
+
+                return localAPIMods = mods.Select(m => new APIMod(m)).ToArray();
+            }
+            set
+            {
+                localAPIMods = value;
+
+                // We potentially can't update this yet due to Ruleset being late-bound, so instead update on read as necessary.
+                mods = null;
+            }
+        }
+
+        // Used for database serialisation/deserialisation.
+        [Column("Mods")]
+        public string ModsJson
+        {
+            get => JsonConvert.SerializeObject(APIMods);
+            set => APIMods = JsonConvert.DeserializeObject<APIMod[]>(value) ?? Array.Empty<APIMod>();
+        }
+
+        public IEnumerable<HitResultDisplayStatistic> GetStatisticsForDisplay()
+        {
+            foreach (var r in Ruleset.CreateInstance().GetHitResults())
+            {
+                int value = Statistics.GetValueOrDefault(r.result);
+
+                switch (r.result)
+                {
+                    case HitResult.SmallTickHit:
+                    {
+                        int total = value + Statistics.GetValueOrDefault(HitResult.SmallTickMiss);
+                        if (total > 0)
+                            yield return new HitResultDisplayStatistic(r.result, value, total, r.displayName);
+
+                        break;
+                    }
+
+                    case HitResult.LargeTickHit:
+                    {
+                        int total = value + Statistics.GetValueOrDefault(HitResult.LargeTickMiss);
+                        if (total > 0)
+                            yield return new HitResultDisplayStatistic(r.result, value, total, r.displayName);
+
+                        break;
+                    }
+
+                    case HitResult.SmallTickMiss:
+                    case HitResult.LargeTickMiss:
+                        break;
+
+                    default:
+                        yield return new HitResultDisplayStatistic(r.result, value, null, r.displayName);
+
+                        break;
+                }
+            }
+        }
+
+        #endregion
     }
 }


Move activity setup to BDL.

Move activity setup to BDL.

--- osu.Game/Screens/OsuScreen.cs
+++ osu.Game/Screens/OsuScreen.cs
@@ -137,6 +137,9 @@
         private void load(OsuGame osu, AudioManager audio)
         {
             sampleExit = audio.Samples.Get(@"UI/screen-back");
+
+            if (Activity.Value == null)
+                Activity.Value = InitialActivity;
         }

         public override void OnResuming(IScreen last)
@@ -160,9 +163,6 @@
             applyArrivingDefaults(false);

             backgroundStack?.Push(localBackground = CreateBackground());
-
-            if (Activity.Value == null)
-                Activity.Value = InitialActivity;

             base.OnEntering(last);
         }


Fallback to default skin if instantiation fails

--- osu.Game/Skinning/SkinInfo.cs
+++ osu.Game/Skinning/SkinInfo.cs
@@ -47,7 +47,17 @@
                 ? typeof(LegacySkin)
                 : Type.GetType(InstantiationInfo).AsNonNull();

-            return (Skin)Activator.CreateInstance(type, this, resources);
+            try
+            {
+                return (Skin)Activator.CreateInstance(type, this, resources);
+            }
+            catch
+            {
+                // This defaults to triangles to catch the case where a user has a modified triangles skin.
+                // If we ever add more default skins in the future this will need some kind of proper migration rather than
+                // a single catch.
+                return new DefaultSkinTriangles(this, resources);
+            }
         }

         public IList<RealmNamedFileUsage> Files { get; } = null!;


CLI/package: Rename cfg options '[debugtoken]/author' & '/token' to more correct '[core]/author_name' & '/author_id'

--- tooling/Package.cs
+++ tooling/Package.cs
@@ -139,8 +139,8 @@
 				xml.WriteElementString ("buildId", Math.Abs ((short)assembly.GetName ().Version.Revision).ToString ());

 				if (devMode) {
-					xml.WriteElementString ("author", Application.Configuration.Get ("debugtoken", "author"));
-					xml.WriteElementString ("authorId", Application.Configuration.Get ("debugtoken", "token"));
+					xml.WriteElementString ("author", Application.Configuration.Get ("author_name"));
+					xml.WriteElementString ("authorId", Application.Configuration.Get ("author_id"));
 				}

 				xml.WriteStartElement ("initialWindow");


Resolving empty values in in language files to default parents value.

--- unity/Assets/Scripts/Content/DictionaryI18n.cs
+++ unity/Assets/Scripts/Content/DictionaryI18n.cs
@@ -318,7 +318,7 @@
             if (!KeyExists(key)) return key;

             // Check current language first
-            if (data.ContainsKey(currentLanguage) && data[currentLanguage].ContainsKey(key))
+            if (data.ContainsKey(currentLanguage) && data[currentLanguage].ContainsKey(key) && data[currentLanguage][key].Length > 0)
             {
                 return data[currentLanguage][key];
             }


Updated breadcrumb display template

Updated breadcrumb display template

--- source/MvcNavigation.DisplayTemplates/Views/Shared/DisplayTemplates/MvcNavigationBreadcrumb.cshtml
+++ source/MvcNavigation.DisplayTemplates/Views/Shared/DisplayTemplates/MvcNavigationBreadcrumb.cshtml
@@ -2,13 +2,16 @@

 @if (@Model.Any())
 {
-	var currentNode = @Model.First;
-	@Html.ActionLink(currentNode)
+	Html.Raw("<nav>");
+		<text>You are here:</text>
+		var currentNode = @Model.First;
+		@Html.ActionLink(currentNode)

-	while (currentNode.Next != null)
-	{
-		<text> › </text>
-		@Html.ActionLink(currentNode.Next)
-		currentNode = currentNode.Next;
-	}
+		while (currentNode.Next != null)
+		{
+			<text> › </text>
+			@Html.ActionLink(currentNode.Next)
+			currentNode = currentNode.Next;
+		}
+	Html.Raw("</nav>");
 }


feat(ArucoMarkerTracker.cs): draw axes of detected tracked markers if required by the user.

--- src/aruco_unity_package/Assets/ArucoUnity/Scripts/Controllers/ObjectTrackers/ArucoMarkerTracker.cs
+++ src/aruco_unity_package/Assets/ArucoUnity/Scripts/Controllers/ObjectTrackers/ArucoMarkerTracker.cs
@@ -197,12 +197,28 @@

         bool updatedCameraImage = false;
         Cv.Mat[] cameraImages = arucoTracker.ArucoCamera.Images;
-
-        // Draw the detected markers
-        // TODO: draw only markers in ArucoObjects list + add option to draw all the detected markers
+        CameraParameters cameraParameters = arucoTracker.ArucoCamera.CameraParameters;
+
         if (arucoTracker.DrawDetectedMarkers && DetectedMarkers[cameraId][dictionary] > 0)
         {
+          // Draw all the detected markers
+          // TODO: draw only markers in ArucoObjects list + add option to draw all the detected markers
           Aruco.DrawDetectedMarkers(cameraImages[cameraId], MarkerCorners[cameraId][dictionary], MarkerIds[cameraId][dictionary]);
+
+          // Draw axes of detected tracked markers
+          if (arucoTracker.DrawAxes)
+          {
+            for (uint i = 0; i < DetectedMarkers[cameraId][dictionary]; i++)
+            {
+              ArucoObject foundArucoObject;
+              int detectedMarkerHashCode = ArucoMarker.GetArucoHashCode(MarkerIds[cameraId][dictionary].At(i));
+              if (arucoTracker.ArucoObjects[dictionary].TryGetValue(detectedMarkerHashCode, out foundArucoObject))
+              {
+                Aruco.DrawAxis(cameraImages[cameraId], cameraParameters.CameraMatrices[cameraId], cameraParameters.DistCoeffs[cameraId],
+                MarkerRvecs[cameraId][dictionary].At(i), MarkerTvecs[cameraId][dictionary].At(i), foundArucoObject.MarkerSideLength);
+              }
+            }
+          }
           updatedCameraImage = true;
         }


Try to fix code page issues: #1062

Try to fix code page issues: #1062

--- src/main/Program.cs
+++ src/main/Program.cs
@@ -9,6 +9,7 @@
 using PKISharp.WACS.Plugins.TargetPlugins;
 using PKISharp.WACS.Services;
 using System;
+using System.Diagnostics;

 namespace PKISharp.WACS
 {
@@ -33,11 +34,35 @@
             // System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

             // Enable international character rendering
+            var originalCodePage = Console.OutputEncoding.CodePage;
+            SetCodePage(65001);
             Console.OutputEncoding = System.Text.Encoding.UTF8;

             // Load main instance
             var wacs = new Wacs(container);
             wacs.Start();
+
+            // Restore original code page
+            SetCodePage(originalCodePage);
+        }
+
+        internal static void SetCodePage(int codePage)
+        {
+            var cmd = new Process
+            {
+                StartInfo =
+                {
+                    FileName = "cmd.exe",
+                    RedirectStandardInput = true,
+                    RedirectStandardOutput = true,
+                    CreateNoWindow = true,
+                    UseShellExecute = false
+                }
+            };
+            cmd.Start();
+            cmd.StandardInput.WriteLine($"chcp {codePage}");
+            cmd.StandardInput.Flush();
+            cmd.StandardInput.Close();
         }

         internal static IContainer GlobalScope(string[] args)


Adjusted to build PCL nuget version

Adjusted to build PCL nuget version

--- build.cake
+++ build.cake
@@ -95,7 +95,7 @@
     .IsDependentOn("Build")
     .Does(() =>
     {
-        var target = nugetRoot + Directory("lib") + Directory("net45");
+        var target = nugetRoot + Directory("lib") + Directory("portable-windows8+net45+windowsphone8+wpa+monoandroid+monotouch");
         CreateDirectory(target);
         CopyFiles(new FilePath[]
         {


Fix version

Fix version


Fix build script

Fix build script

--- build.cake
+++ build.cake
@@ -202,7 +202,7 @@
 	{
 		try
 		{
-			var path = MakeAbsolute(sln).GetDirectory().FullPath;
+			var path = MakeAbsolute(new DirectoryPath("./")).FullPath;
 			using (var repo = new LibGit2Sharp.Repository(path))
 			{
 				var origin = repo.Network.Remotes.FirstOrDefault(
@@ -221,7 +221,7 @@

 bool IsTagged()
 {
-	var path = MakeAbsolute(sln).GetDirectory().FullPath;
+	var path = MakeAbsolute(new DirectoryPath("./")).FullPath;
 	using (var repo = new LibGit2Sharp.Repository(path))
 	{
 		var head = repo.Head;


Added "Package" task

Added "Package" task


Create build.cake

Create build.cake


Cake script now uses xUnit to run the tests instead of Fixie

--- build.cake
+++ build.cake
@@ -1,4 +1,4 @@
-#tool "nuget:?package=Fixie"
+#tool "nuget:?package=xunit.runner.console"

 var target = Argument( "target", "Default" );
 var configuration = Argument( "configuration", "Release" );
@@ -52,7 +52,7 @@
       "./src/ArguMint/ArguMint.TestCommon/bin/" + Directory( configuration ) + "/ArguMint.TestCommon.dll"
    };

-   Fixie( testAssemblies );
+   XUnit2( testAssemblies );
 } );

 //===========================================================================


make sure you only build .net core on non Windows

--- build.cake
+++ build.cake
@@ -22,8 +22,13 @@
         var settings = new DotNetCoreBuildSettings
         {
             Configuration = configuration
-            // Runtime = IsRunningOnWindows() ? null : "unix-x64"
         };
+
+        if (!IsRunningOnWindows())
+        {
+            Information("Not running on Windows - skipping build for full .NET Framework");
+            settings.Framework = "netcoreapp1.0";
+        }

 	    DotNetCoreBuild(project.GetDirectory().FullPath, settings);
     }


test error handle on failed build in build server

--- build.cake
+++ build.cake
@@ -6,10 +6,17 @@
 var configuration = Argument("configuration", "Debug");
 var framework = Argument("framework", "net-4.5");
 var legacyOutputXml = Argument("LegacyOutputXml", "false");
+var UseNUnit2Ouput = System.Convert.ToBoolean(legacyOutputXml);
+
+//////////////////////////////////////////////////////////////////////
+// SET ERROR LEVELS
+//////////////////////////////////////////////////////////////////////
+var ErrorState = false;
+
 //////////////////////////////////////////////////////////////////////
 // SET PACKAGE VERSION
 //////////////////////////////////////////////////////////////////////
-var UseNUnit2Ouput = System.Convert.ToBoolean(legacyOutputXml);
+
 var version = "3.1.0";
 var modifier = "";
 var displayVersion = "3.1";
@@ -160,8 +167,10 @@
 //////////////////////////////////////////////////////////////////////
 Task("TestAllFrameworks")
   .IsDependentOn("Build")
-    .ContinueOnError()
-	.Does(() =>
+    .OnError(exception =>
+{
+    HandleTestRunEror(exception);
+}).Does(() =>
 	{
 		foreach(string runtime in AllFrameworks)
 		{
@@ -179,7 +188,10 @@

 Task("TestFramework")
   .IsDependentOn("Build")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
 	.Does(() =>
 	{
 		RunTest(BIN_DIR + File(framework + "/" + NUNITLITE_RUNNER), BIN_DIR + "/" + framework, FRAMEWORK_TESTS);
@@ -187,7 +199,10 @@

 Task("TestNUnitLite")
   .IsDependentOn("BuildFramework")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
 	.Does(() =>
 	{
 			if (framework == "sl-5.0")
@@ -198,14 +213,20 @@

 Task("TestEngine")
   .IsDependentOn("Build")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
   .Does(() =>
 	{
 		RunTest(NUNIT3_CONSOLE, BIN_DIR, ENGINE_TESTS);
 	});

 Task("TestAddins")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
   .IsDependentOn("Build")
   .Does(() =>
 	{
@@ -214,7 +235,10 @@

 Task("TestV2Driver")
   .IsDependentOn("Build")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
   .Does(() =>
 	{
 		RunTest(NUNIT3_CONSOLE, BIN_DIR, V2_DRIVER_TESTS);
@@ -222,7 +246,10 @@

 Task("TestConsole")
   .IsDependentOn("Build")
-    .ContinueOnError()
+    .OnError(exception =>
+            {
+                HandleTestRunEror(exception);
+            })
   .Does(() =>
 	{
 		RunTest(NUNIT3_CONSOLE, BIN_DIR, CONSOLE_TESTS);
@@ -609,6 +636,10 @@
 		Arguments = arguments
 	});
 }
+void HandleTestRunEror(Exception exception)
+{
+ErrorState=true;
+}

 //////////////////////////////////////////////////////////////////////
 // TASK TARGETS


Download cache - Use ReadAsByteArrayAsync when no ProgressDownload is needed #449

--- source/FFImageLoading.Common/Cache/DownloadCache.cs
+++ source/FFImageLoading.Common/Cache/DownloadCache.cs
@@ -105,37 +105,35 @@
                             {
                                 cancelReadTimeoutToken.CancelAfter(TimeSpan.FromSeconds(Configuration.HttpReadTimeout));

-                                int total = (int)(response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L);
+                                int total = (int)((progressAction != null && response.Content.Headers.ContentLength.HasValue) ? response.Content.Headers.ContentLength.Value : -1);
                                 var canReportProgress = total != -1 && progressAction != null;

                                 try
                                 {
                                     return await Task.Run(async () =>
                                     {
-                                        using (var outputStream = new MemoryStream())
-                                        using (var sourceStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
+                                        if (canReportProgress)
                                         {
-                                            int totalRead = 0;
-                                            var buffer = new byte[4096];
+                                            using (var outputStream = new MemoryStream())
+                                            using (var sourceStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
+                                            {
+                                                int totalRead = 0;
+                                                var buffer = new byte[4096];

-                                            int read;
-                                            while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
-                                            {
-                                                token.ThrowIfCancellationRequested();
-
-                                                outputStream.Write(buffer, 0, read);
-
-                                                totalRead += read;
-
-                                                if (canReportProgress)
+                                                int read = 0;
+                                                while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                                                 {
+                                                    token.ThrowIfCancellationRequested();
+                                                    outputStream.Write(buffer, 0, read);
+                                                    totalRead += read;
                                                     progressAction(new DownloadProgress() { Total = total, Current = totalRead });
                                                 }
+
+                                                return outputStream.ToArray();
                                             }
-
-                                            return outputStream.ToArray();
                                         }

+                                        return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                                     }, cancelReadTimeoutToken.Token).ConfigureAwait(false);
                                 }
                                 catch (OperationCanceledException)


Cleans up the code for VisitAssignmentExpression a bit.

--- ProjectHekate.Grammar.Implementation/HekateScriptVisitor.cs
+++ ProjectHekate.Grammar.Implementation/HekateScriptVisitor.cs
@@ -174,16 +174,7 @@
             else { // b
                 code.Add(codeToAdd); // i
                 code.Add(Visit(context.expression())); // ii
-
-                // iii
-                switch (context.Operator.Type) {
-                    case HekateParser.MUL_ASSIGN: code.Add(Instruction.OperatorMultiply); break;
-                    case HekateParser.DIV_ASSIGN: code.Add(Instruction.OperatorDivide); break;
-                    case HekateParser.ADD_ASSIGN: code.Add(Instruction.OperatorAdd); break;
-                    case HekateParser.SUB_ASSIGN: code.Add(Instruction.OperatorSubtract); break;
-                    default:
-                        throw new InvalidOperationException("You forgot to add a case for a compound assignment operator! Check the code for VisitAssignmentExpression.");
-                }
+                code.Add(GetCompoundAssignmentOperatorFromContext(context)); // iii
             }

             // 2,3
@@ -265,6 +256,19 @@
             }
         }

+        private Instruction GetCompoundAssignmentOperatorFromContext(HekateParser.AssignmentExpressionContext context)
+        {
+            switch (context.Operator.Type)
+            {
+                case HekateParser.MUL_ASSIGN:   return Instruction.OperatorMultiply;
+                case HekateParser.DIV_ASSIGN:   return Instruction.OperatorDivide;
+                case HekateParser.ADD_ASSIGN:   return Instruction.OperatorAdd;
+                case HekateParser.SUB_ASSIGN:   return Instruction.OperatorSubtract;
+                default:
+                    throw new InvalidOperationException(
+                        "You forgot to add a case for a compound assignment operator! Check the code for GetCompoundAssignmentOperatorFromContext.");
+            }
+        }

         #endregion


Fixed last commit.

Fixed last commit.

--- PsISEProjectExplorer.Tests/UI/ViewModel/IconProviderTest.cs
+++ PsISEProjectExplorer.Tests/UI/ViewModel/IconProviderTest.cs
@@ -78,7 +78,7 @@
             foreach (var name in namesToTest)
             {
                 Console.WriteLine("IconProvider " + name);
-                ImageSource result = iconProvider.GetImageSourceForPowershellItemEntry(name);
+                ImageSource result = iconProvider.GetImageSourceBasingOnNodeType(name);
                 Assert.That(result, Is.Not.Null);
             }
         }
@@ -86,7 +86,7 @@
         [Test]
         public void GetImageSourceForPowershellItemEntryShouldReturnNullWhenNodeTypeIsNotValid()
         {
-            ImageSource result = iconProvider.GetImageSourceForPowershellItemEntry("x");
+            ImageSource result = iconProvider.GetImageSourceBasingOnNodeType("x");
             Assert.That(result, Is.Null);
         }
     }


Removed finalizer and unused Clear method, whose implementation was incomplete (it wasn't unadvising for dir changes).

--- Python/Product/PythonTools/PythonTools/SearchPathManager.cs
+++ Python/Product/PythonTools/PythonTools/SearchPathManager.cs
@@ -41,10 +41,6 @@
             GC.SuppressFinalize(this);
         }

-        ~SearchPathManager() {
-            Dispose(false);
-        }
-
         protected virtual void Dispose(bool disposing) {
             if (disposing) {
                 lock (_paths) {
@@ -177,18 +173,6 @@

             lock (_paths) {
                 return _paths.Any(p => p.Persisted == isPersisted && p.Path.Equals(absolutePath, StringComparison.OrdinalIgnoreCase));
-            }
-        }
-
-        public void Clear() {
-            bool any;
-            lock (_paths) {
-                any = _paths.Any();
-                _paths.Clear();
-            }
-
-            if (any) {
-                Changed?.Invoke(this, EventArgs.Empty);
             }
         }


added token parameter to management portal

--- src/Obsidian/Controllers/ViewControllers/ManageController.cs
+++ src/Obsidian/Controllers/ViewControllers/ManageController.cs
@@ -8,8 +8,12 @@
     public class ManageController : Controller
     {
         [Route("[controller]/{*path}")]
-        public IActionResult Index(string path = "")
+        public IActionResult Index([FromQuery(Name = "access_token")]string accessToken = "", string path = "")
         {
+            if (string.IsNullOrWhiteSpace(accessToken))
+            {
+                //Redirect to oauth login.
+            }
             ViewData["FrontendRoute"] = path;
             return View();
         }


Enable SCE parameters to be modified from R package - earlier version used defaults

--- R/pkgs/mh/src/CSIRO.Metaheuristics.R.pkg/OptimizerHelper.cs
+++ R/pkgs/mh/src/CSIRO.Metaheuristics.R.pkg/OptimizerHelper.cs
@@ -16,7 +16,7 @@
             var helper = getHelper();
             var t = sysConfigType ?? template.GetType();
             if (terminationCondition == null) terminationCondition = CreateMaxWalltime(t);
-            return invokeGenericMethod("internalCreateSceOptimizer", t, new object[] { evaluator, template, terminationCondition });
+            return invokeGenericMethod("internalCreateSceOptimizer", t, new object[] { evaluator, template, terminationCondition, sceParams });
         }

         public static object CreateMaxWalltime(Type sysConfigType, double maxHours = 0.1)
@@ -52,12 +52,12 @@
             return helper;
         }

-        private static ShuffledComplexEvolution<T> internalCreateSceOptimizer<T>(IClonableObjectiveEvaluator<T> evaluator, T template, ITerminationCondition<T> terminationCondition)
+        private static ShuffledComplexEvolution<T> internalCreateSceOptimizer<T>(IClonableObjectiveEvaluator<T> evaluator, T template, ITerminationCondition<T> terminationCondition , SceParameters SceParams)
             where T : ICloneableSystemConfiguration, IHyperCube<double>
         {
             var populationInitializer = new UniformRandomSamplingFactory<T>(new CSIRO.Metaheuristics.RandomNumberGenerators.BasicRngFactory(0), template);
             var sce = new ShuffledComplexEvolution<T>(evaluator, populationInitializer,
-                terminationCondition: terminationCondition);
+                terminationCondition: terminationCondition, sceParameters: SceParams);
             return sce;

         }


Typo in message

Typo in message

--- RESTServer/TicketingSystem/Controllers/TicketsController.cs
+++ RESTServer/TicketingSystem/Controllers/TicketsController.cs
@@ -208,7 +208,7 @@
             this.context.SaveChanges();
             return this.Json(new
             {
-                Message = "Successfully activated",
+                Message = "Successfully activated.",
                 ExpiresOn = ticket.ExpiresOn
             });
         }


added method to add custom query parameters

--- source/XeroApi/Model/Reporting/DynamicReportBase.cs
+++ source/XeroApi/Model/Reporting/DynamicReportBase.cs
@@ -10,15 +10,21 @@
     {
         protected const string ReportDateFormatString = "yyyy-MM-dd";

+        protected readonly NameValueCollection _queryStringParams = new NameValueCollection();
+
+        public virtual void AddQueryStrimgParam(string key, string value)
+        {
+            _queryStringParams.Add(key, value);
+        }
+
         /// <summary>
         /// Gets the query string param collection.
         /// </summary>
         /// <returns></returns>
         internal NameValueCollection GetQueryStringParamCollection()
         {
-            NameValueCollection queryStringParams = new NameValueCollection();
-            GenerateQuerystringParams(queryStringParams);
-            return queryStringParams;
+            GenerateQuerystringParams(_queryStringParams);
+            return _queryStringParams;
         }

         /// <summary>


refined dictionary lookup for getting the table name

--- Modules/DataModule.cs
+++ Modules/DataModule.cs
@@ -1,7 +1,7 @@
 using System;
 using Nancy.Extensions;
 using Nancy;
-using Nancy.Json;
+using System.Web.Script.Serialization;
 using Simple.Data;

@@ -17,17 +17,24 @@
                 var json = Request.Body.AsString();

                 var jss = new JavaScriptSerializer();
-                var formRow = jss.Deserialize<dynamic>(json);
+                var formRow = jss.Deserialize<dynamic>(json); // the data we get back is a dictionary

                 try
                 {
-                    // get the table name. There must always be one
-                    string tableName = formRow.tablename;

-                    var db = Database.Open(); // open db with Simple.Data
+                    const string KeyName = "tablename";

-                    // insert the row and get the new Id back, Simple.Data should return back the new row with new Id
-                    var newRow = db[tableName].Insert(formRow);
+                    // find the table name in the dictionary. There must always be one
+                    if (formRow.ContainsKey(KeyName))
+                    {
+                        var value = formRow[KeyName];
+                        var db = Database.Open(); // open db with Simple.Data
+
+                        // insert the row and get the new Id back, Simple.Data should return back the new row with new Id
+                        // we pass in the table name 'value' and Simple.Data is smart enough to recognise it
+                        var newRow = db[value].Insert(formRow);
+                    }
+

                 }

@@ -37,16 +44,6 @@
                     return Response.AsJson("{\"message\":\"" + ex.Message + "\"}");
                 }

-                // now we can dynamically update the table with the passed in table name and the new object
-                //string tableToUse = "MyTable";
-                //var test = db[tableToUse].All();
-
-                // or look stuff up by a passed in field name (use another route such as /data/get)
-                // var table = "MyTable";
-                //var keyColumn = "Id";
-                //int id = 42;
-                //var entity = db[table].Find(db[table][keyColumn] == id);
-
                 return Response.AsJson("{message: Success!}");

             };


adding debug messages

adding debug messages

--- Modules/Wow/WowApi.cs
+++ Modules/Wow/WowApi.cs
@@ -230,7 +230,9 @@
                     new KeyValuePair<string, string>("client_id", username),
                     new KeyValuePair<string, string>("client_secret", password)
                 });
+                System.Console.WriteLine("before post");
                 var result =  client.PostAsync("https://us.battle.net/oauth/token", content);
+                System.Console.WriteLine("after post");
                 var contentString =  result.Result.Content.ReadAsStringAsync();
                 ApiResponse response = JsonConvert.DeserializeObject<ApiResponse>(contentString.Result);
                 token = response.AccessToken;


Connection parser now returns :memory: instead of null when fulluri=:memory: is used.

--- SQLite.CodeFirst/Internal/Utility/ConnectionStringParser.cs
+++ SQLite.CodeFirst/Internal/Utility/ConnectionStringParser.cs
@@ -17,17 +17,20 @@

         public static string GetDataSource(string connectionString)
         {
-            // Check if the datasource token exists and return Null if it doesn't.
-            // This will allow connection strings with FullUri to work.
+            // If the datasource token does not exists this is a FullUri connection string.
             IDictionary<string, string> strings = ParseConnectionString(connectionString);
             if (strings.ContainsKey(DataSourceToken))
             {
                 var path = ExpandDataDirectory(ParseConnectionString(connectionString)[DataSourceToken]);
                 // remove quotation mark if exists
-                path = path.Trim('"');
-                return path;
+                return path.Trim('"');
             }
-            return null;
+            // TODO: Implement FullUri parsing.
+            if (connectionString.Contains(":memory:"))
+            {
+                return ":memory:";
+            }
+            throw new NotSupportedException("FullUri format is currently only supported for :memory:.");
         }

         [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "ToUppercase makes no sense.")]


Added file path check

Added file path check

--- SS.Integration.Adapter.Model/ModuleConfigurationProvider.cs
+++ SS.Integration.Adapter.Model/ModuleConfigurationProvider.cs
@@ -41,10 +41,11 @@
         private static Configuration ReadInternal(Assembly assembly, string filename)
         {
             var filepath = Path.Combine(Path.GetDirectoryName(assembly.Location), filename);
-            var filemap = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
-
-            var conf = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
-            return conf;
+
+            var fileMap = new ExeConfigurationFileMap {ExeConfigFilename = File.Exists(filepath) ? filepath : filename};
+            var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
+
+            return configuration;
         }
     }
 }


rename route

rename route

--- SignInCheckIn/SignInCheckIn/Controllers/FamilyController.cs
+++ SignInCheckIn/SignInCheckIn/Controllers/FamilyController.cs
@@ -37,8 +37,8 @@

         [HttpPost]
         [ResponseType(typeof(int))]
-        [VersionedRoute(template: "signin/newfamily", minimumVersion: "1.0.0")]
-        [Route("signin/newfamily")]
+        [VersionedRoute(template: "family", minimumVersion: "1.0.0")]
+        [Route("family")]
         public IHttpActionResult CreateNewFamily(List<NewParentDto> newParents)
         {
             return Authorized(token =>


matrix- using local coordinates for scaling areas if no parent

--- Source/Engine/AGS.Engine/Objects/AGSModelMatrixComponent.cs
+++ Source/Engine/AGS.Engine/Objects/AGSModelMatrixComponent.cs
@@ -507,11 +507,20 @@
         {
             var room = _room?.Room;
             if (room == null || (_drawable?.IgnoreScalingArea ?? false)) return NoScaling;
-            foreach (IArea area in room.GetMatchingAreas(_worldPosition.WorldXY, _entity.ID))
+
+            //Problem: we'd like to always use the world position when checking if the entity is standing
+            //in a scaling area. However, the world position is calculated from the bounding box, which
+            //in itself is calculated from the matrix, which is calculated here...
+            //So at best this will always be in one frame delay, and at worst can cause real scaling jittering issues.
+            //So this is why we're checking and in cases the entity doesn't have a parent (which is the vast majority of scenarios)
+            //we'll continue using the local coordinates, at least until a better solution is found.
+            var position = _tree.TreeNode.Parent == null ? _translate.Location.XY : _worldPosition.WorldXY;
+
+            foreach (IArea area in room.GetMatchingAreas(position, _entity.ID))
             {
                 IScalingArea scaleArea = area.GetComponent<IScalingArea>();
                 if (scaleArea == null || (!scaleArea.ScaleObjectsX && !scaleArea.ScaleObjectsY)) continue;
-                float scale = scaleArea.GetScaling(scaleArea.Axis == ScalingAxis.X ? _worldPosition.WorldX : _worldPosition.WorldY);
+                float scale = scaleArea.GetScaling(scaleArea.Axis == ScalingAxis.X ? position.X : position.Y);
                 return new PointF(scaleArea.ScaleObjectsX ? scale : 1f, scaleArea.ScaleObjectsY ? scale : 1f);
             }
             return NoScaling;


GSF.TimeSeries: In DataSubscriber, fixed foreign key constraint that occurs during metadata synchronization when a device record fails to synchronize because another record already exists that is not safe to overwrite.

git-tfs-id: [https://tfs.codeplex.com/tfs/TFS07]$/gsf/Main;C86483

--- Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs
+++ Source/Libraries/GSF.TimeSeries/Transport/DataSubscriber.cs
@@ -2603,12 +2603,12 @@
                                         {
                                             selectSql = database.ParameterizedQueryString("SELECT COUNT(*) FROM Device WHERE UniqueID = {0} AND ParentID <> {1}", "deviceGuid", "parentID");

+                                            // Safety check to preserve device records which are not safe to overwrite
+                                            if (Convert.ToInt32(command.ExecuteScalar(selectSql, m_metadataSynchronizationTimeout, database.Guid(uniqueID), parentID)) > 0)
+                                                continue;
+
                                             // Update existing device record
-                                            if (Convert.ToInt32(command.ExecuteScalar(selectSql, m_metadataSynchronizationTimeout, database.Guid(uniqueID), parentID)) > 0)
-                                            {
-                                                OnProcessException(new InvalidOperationException(string.Format("Unable to synchronize metadata for device '{0}'. Another device with the same unique ID already exists.", row.Field<string>("Acronym"))));
-                                            }
-                                            else if (m_internal)
+                                            if (m_internal)
                                             {
                                                 // Gateway is assuming ownership of the device records when the "internal" flag is true - this means the device's measurements can be forwarded to another party.
                                                 // From a device record perspective, ownership is inferred by setting 'OriginalSource' to null.
@@ -2627,8 +2627,8 @@
                                     }

                                     // Capture local device ID auto-inc value for measurement association
-                                    selectSql = database.ParameterizedQueryString("SELECT ID FROM Device WHERE UniqueID = {0} AND ParentID = {1}", "deviceGuid", "parentID");
-                                    deviceIDs[row.Field<string>("Acronym")] = Convert.ToInt32(command.ExecuteScalar(selectSql, m_metadataSynchronizationTimeout, database.Guid(uniqueID), parentID));
+                                    selectSql = database.ParameterizedQueryString("SELECT ID FROM Device WHERE UniqueID = {0}", "deviceGuid");
+                                    deviceIDs[row.Field<string>("Acronym")] = Convert.ToInt32(command.ExecuteScalar(selectSql, m_metadataSynchronizationTimeout, database.Guid(uniqueID)));
                                 }

                                 // Remove any device records associated with this subscriber that no longer exist in the meta-data


int32 ct evaluation

int32 ct evaluation

--- src/Peachpie.CodeAnalysis/FlowAnalysis/ExpressionAnalysis.cs
+++ src/Peachpie.CodeAnalysis/FlowAnalysis/ExpressionAnalysis.cs
@@ -1054,6 +1054,11 @@
                 {
                     case SpecialType.System_Double:
                         return ConstantValue.Create(-value.DoubleValue);
+
+                    case SpecialType.System_Int32:
+                        return value.Int32Value != int.MinValue
+                            ? ConstantValue.Create(-value.Int32Value)   // (- Int32.MinValue) overflows to int64
+                            : ConstantValue.Create(-(long)value.Int32Value);

                     case SpecialType.System_Int64:
                         return (value.Int64Value != long.MinValue)  // (- Int64.MinValue) overflows to double
@@ -2206,9 +2211,7 @@

         public override T VisitExpressionStatement(BoundExpressionStatement x)
         {
-            base.VisitExpressionStatement(x);
-
-            return default;
+            return base.VisitExpressionStatement(x);
         }

         public override T VisitReturn(BoundReturnStatement x)


HtmlViewer measure positions fix.

HtmlViewer measure positions fix.

--- src/AppStudio.Uwp/Controls/HtmlViewer/HtmlViewer.cs
+++ src/AppStudio.Uwp/Controls/HtmlViewer/HtmlViewer.cs
@@ -88,7 +88,7 @@
             _clip.Rect = new Rect(0, 0, this.ActualWidth - 10, this.ActualHeight);

             MeasureLayout();
-            await Task.Delay(50);
+            await Task.Delay(500);
             await SetHtmlDocumentMargin();
         }


Use UpdateSourceTrigger in 8.1 bindings

Use UpdateSourceTrigger in 8.1 bindings

--- src/Caliburn.Micro.Silverlight/ConventionManager.cs
+++ src/Caliburn.Micro.Silverlight/ConventionManager.cs
@@ -191,7 +191,7 @@
                 info,
                 binding
                 );
-#elif !WinRT
+#elif !(WinRT && !WinRT81)
             binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
 #endif
         };


turn off detailed export log by default

turn off detailed export log by default

--- AlembicImporter/Packages/com.unity.formats.alembic/Runtime/Scripts/Exporter/AlembicExporter_impl.cs
+++ AlembicImporter/Packages/com.unity.formats.alembic/Runtime/Scripts/Exporter/AlembicExporter_impl.cs
@@ -137,7 +137,7 @@
         }

         [SerializeField]
-        private bool detailedLog = true;
+        private bool detailedLog = false;
         public bool DetailedLog
         {
             get { return detailedLog; }


More fixes.

More fixes.

--- Sources/Silphid.Extensions/Sources/System/TypeExtensions.cs
+++ Sources/Silphid.Extensions/Sources/System/TypeExtensions.cs
@@ -60,6 +60,9 @@
 #else
         public static Type GetBaseType(this Type This) =>
             This.BaseType;
+
+        public static bool IsGenericType(this Type This) =>
+            This.IsGenericType;
 #endif
     }
 }


Use persistentDataPath.

Use persistentDataPath.

--- Sources/Silphid.Injexit/Sources/Installers/RootInstaller.cs
+++ Sources/Silphid.Injexit/Sources/Installers/RootInstaller.cs
@@ -13,7 +13,7 @@
         private static string DataPath =>
             Application.isEditor
                 ? Path.Combine(Application.dataPath, "../AppData")
-                : Application.dataPath;
+                : Application.persistentDataPath;

         protected override IContainer CreateContainer() =>
             new Container(new Reflector(), ShouldInject);


[Package Explorer] Support semi-colon separated value in Nuspec file.

--- Tools/NuGet/NuGetPackageExplorer/Core/Authoring/Manifest.cs
+++ Tools/NuGet/NuGetPackageExplorer/Core/Authoring/Manifest.cs
@@ -92,6 +92,9 @@
             var serializer = new XmlSerializer(typeof(Manifest));
             var manifest = (Manifest)serializer.Deserialize(document.CreateReader());

+            // Convert <file source="Foo.cs;.\src\bar.cs" target="content" /> to multiple individual items.
+            manifest.SplitManifestFiles();
+
             // Validate before returning
             Validate(manifest);

@@ -106,6 +109,23 @@
             manifest.Metadata.Tags = manifest.Metadata.Tags.SafeTrim();

             return manifest;
+        }
+
+        private void SplitManifestFiles() {
+            if (Files == null) {
+                return;
+            }
+            int length = Files.Count;
+            for (int i = 0; i < length; i++) {
+                var manifestFile = Files[i];
+                // Multiple sources can be specified by using semi-colon separated values.
+                var sources = manifestFile.Source.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
+                // Set the source value of the current manifest file to the first item in the list of values
+                manifestFile.Source = sources.FirstOrDefault();
+                // Add a ManifestFile for all other items
+                Files.AddRange(from item in sources.Skip(1)
+                               select new ManifestFile { Source = item, Target = manifestFile.Target });
+            }
         }

         public static Manifest Create(IPackageMetadata metadata) {


Hey git, actually apply the change correctly.

Git for some reason DID NOT move the } on the commit closing #106, leaving it just as broken as before.

--- TwitchPlaysAssembly/Src/ComponentSolvers/ComponentSolver.cs
+++ TwitchPlaysAssembly/Src/ComponentSolvers/ComponentSolver.cs
@@ -217,8 +217,8 @@
 						CoroutineCanceller.ResetCancel();
 						if (!string.IsNullOrEmpty(match.Groups[1].Value))
 							IRCConnection.Instance.SendMessage($"Sorry @{userNickName}, {match.Groups[1].Value.Trim()}");
-					}
 						break;
+					}
 				}
 				else if (currentString.RegexMatch(out match, "^trycancelsequence((?: (?:.|\\n)+)?)$"))
 				{


GenerateRandomNumber方法實作

GenerateRandomNumber方法實作

GenerateRandomNumber方法實作

--- UartOscilloscopeTests/CSharpFiles/WaveDataStructureTests.cs
+++ UartOscilloscopeTests/CSharpFiles/WaveDataStructureTests.cs
@@ -87,12 +87,10 @@
 			int[] Result = new int[0];                                          //	宣告回傳結果
 			Array.Resize<int>(ref Result, NumberOfRandomNumber);				//	配置記憶體位置
 			for(int LoopNum = 0; LoopNum < NumberOfRandomNumber; LoopNum++)		//	以for迴圈依序填入亂數
-			{																	//	進入for迴圈
-
+			{                                                                   //	進入for迴圈
+				Result[LoopNum] = rnd.Next(-1000, 1000);						//	生成亂數
 			}																	//	結束for迴圈
-			int month = rnd.Next(-1000, 1000);									//
-
-			return Result;
+			return Result;														//	回傳結果
 		}                                                                       //	結束GenerateRandomNumber方法
 	}                                                                           //	結束WaveDataStructureTests類別
 }                                                                               //	結束命名空間


Modified DataSubscriber to properly reconstruct data packets that were broken up over a UDP connection.

git-tfs-id: [https://tfs.codeplex.com/tfs/TFS07]$/TimeSeriesFramework/Main;C67936

--- Source/OldCode/TimeSeriesFramework/Source/Libraries/TimeSeriesFramework/Transport/DataSubscriber.cs
+++ Source/OldCode/TimeSeriesFramework/Source/Libraries/TimeSeriesFramework/Transport/DataSubscriber.cs
@@ -70,6 +70,7 @@
         private volatile long[] m_baseTimeOffsets;
         private volatile byte[][][] m_keyIVs;
         private volatile bool m_authenticated;
+        private byte[] m_measurementDataBuffer;
         private List<ServerCommand> m_requests;
         private bool m_synchronizedSubscription;
         private bool m_requireAuthentication;
@@ -756,32 +757,42 @@
                             count = EndianOrder.BigEndian.ToInt32(buffer, responseIndex);
                             responseIndex += 4;

-                            // Deserialize measurements
-                            for (int i = 0; i < count; i++)
+                            try
                             {
-                                if (compactMeasurementFormat)
+                                // Deserialize measurements
+                                for (int i = 0; i < count; i++)
                                 {
-                                    // Deserialize compact measurement format
-                                    slimMeasurement = new CompactMeasurement(m_signalIndexCache, !synchronizedMeasurements, m_baseTimeOffsets, m_keyIVs);
-                                    responseIndex += slimMeasurement.Initialize(buffer, responseIndex, length - responseIndex);
-
-                                    // Apply timestamp from frame if not included in transmission
-                                    if (!slimMeasurement.IncludeTime)
-                                        slimMeasurement.Timestamp = timestamp;
-
-                                    measurements.Add(slimMeasurement);
+                                    if (compactMeasurementFormat)
+                                    {
+                                        // Deserialize compact measurement format
+                                        slimMeasurement = new CompactMeasurement(m_signalIndexCache, !synchronizedMeasurements, m_baseTimeOffsets, m_keyIVs);
+                                        responseIndex += slimMeasurement.Initialize(buffer, responseIndex, length - responseIndex);
+
+                                        // Apply timestamp from frame if not included in transmission
+                                        if (!slimMeasurement.IncludeTime)
+                                            slimMeasurement.Timestamp = timestamp;
+
+                                        measurements.Add(slimMeasurement);
+                                    }
+                                    else
+                                    {
+                                        // Deserialize full measurement format
+                                        measurement = new SerializableMeasurement();
+                                        responseIndex += measurement.Initialize(buffer, responseIndex, length - responseIndex);
+                                        measurements.Add(measurement);
+                                    }
                                 }
+
+                                // Expose new measurements to consumer
+                                OnNewMeasurements(measurements);
+                            }
+                            catch (InvalidOperationException)
+                            {
+                                if (m_dataChannel != null)
+                                    m_measurementDataBuffer = buffer.BlockCopy(0, length);
                                 else
-                                {
-                                    // Deserialize full measurement format
-                                    measurement = new SerializableMeasurement();
-                                    responseIndex += measurement.Initialize(buffer, responseIndex, length - responseIndex);
-                                    measurements.Add(measurement);
-                                }
+                                    throw;
                             }
-
-                            // Expose new measurements to consumer
-                            OnNewMeasurements(measurements);
                             break;
                         case ServerResponse.UpdateSignalIndexCache:
                             // Deserialize new signal index cache
@@ -971,7 +982,22 @@

         private void m_dataChannel_ReceiveDataComplete(object sender, EventArgs<byte[], int> e)
         {
-            ProcessServerResponse(e.Argument1, e.Argument2);
+            byte[] measurementData;
+            int length;
+
+            if (m_measurementDataBuffer == null)
+            {
+                measurementData = e.Argument1;
+                length = e.Argument2;
+            }
+            else
+            {
+                measurementData = m_measurementDataBuffer.Combine(0, m_measurementDataBuffer.Length, e.Argument1, 0, e.Argument2);
+                length = measurementData.Length;
+                m_measurementDataBuffer = null;
+            }
+
+            ProcessServerResponse(measurementData, length);
         }

         private void m_dataChannel_ConnectionException(object sender, EventArgs<Exception> e)


Add indexer, IEnumerable, and Add for easier creation of HasArbitraryKey objects

--- Rollbar.Net/HasArbitraryKeys.cs
+++ Rollbar.Net/HasArbitraryKeys.cs
@@ -1,7 +1,8 @@
+using System.Collections;
 using System.Collections.Generic;

 namespace Rollbar {
-    public abstract class HasArbitraryKeys {
+    public abstract class HasArbitraryKeys : IEnumerable<KeyValuePair<string, object>> {
         protected HasArbitraryKeys(Dictionary<string, object> additionalKeys) {
             AdditionalKeys = additionalKeys ?? new Dictionary<string, object>();
         }
@@ -11,6 +12,24 @@
         public abstract Dictionary<string, object> Denormalize();

         public Dictionary<string, object> AdditionalKeys { get; private set; }
+
+        public void Add(string key, object value) {
+            AdditionalKeys.Add(key, value);
+            Normalize();
+        }
+
+        public object this[string key] {
+            get { return Denormalize()[key]; }
+            set { Add(key, value); }
+        }
+
+        public IEnumerator<KeyValuePair<string, object>> GetEnumerator() {
+            return Denormalize().GetEnumerator();
+        }
+
+        IEnumerator IEnumerable.GetEnumerator() {
+            return GetEnumerator();
+        }
     }

     public static class HasArbitraryKeysExtension {


resolve conflict

resolve conflict

--- Web/Areas/EarlyWarning/Views/ReliefRequisition/Index.cshtml
+++ Web/Areas/EarlyWarning/Views/ReliefRequisition/Index.cshtml
@@ -23,11 +23,9 @@

Relief Requisition

 }
-<<<<<<>>>>>> a6db427e0b88c7b47daa7a6697c22fc2e1855708
+
 @(Html.Kendo().Grid<Cats.Areas.EarlyWarning.Models.ReliefRequisitionViewModel>().Name("Grid").Columns(columns =>
 {
     columns.Template(t => { }).Title("No").ClientTemplate("#= renderNumber(data) #").Width(50);


Removed All unsupported options from index creation, so migration will work on Sql Azure

--- Website/Migrations/201111080816426_DisplayPackageIndexes.cs
+++ Website/Migrations/201111080816426_DisplayPackageIndexes.cs
@@ -36,7 +36,7 @@
                 [IsLatestStable],
                 [Listed],
                 [IsPrerelease],
-                [ReleaseNotes]) WITH (STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]");
+                [ReleaseNotes]) WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]");
         }

         public override void Down()


Improved error handling

Improved error handling

--- example_project/Assets/MonsterLove/StateMachine/StateMachine.cs
+++ example_project/Assets/MonsterLove/StateMachine/StateMachine.cs
@@ -182,9 +182,9 @@

 		static TDriver CreateDriver(Func<bool> callback, List<FieldInfo> fieldInfos)
 		{
-			if (fieldInfos == null)
-			{
-				throw new ArgumentException(string.Format("Arguments cannot be null. Mapping fieldInfos {0}", fieldInfos));
+			if (callback == null || fieldInfos == null)
+			{
+				throw new ArgumentException(string.Format("Arguments cannot be null. Callback {0} fieldInfos {1}", callback, fieldInfos));
 			}

 			TDriver driver = new TDriver();


Students should only be able to edit their own data.

--- src/StudentFollowingSystem/Controllers/StudentsController.cs
+++ src/StudentFollowingSystem/Controllers/StudentsController.cs
@@ -203,10 +203,11 @@
             return View(model);
         }

-        [AuthorizeStudent, Route("gegevens-wijzigen/{id}")]
-        public ActionResult EditInfo(int id)
-        {
-            var student = StudentRepository.GetById(id);
+        [AuthorizeStudent, Route("gegevens-wijzigen")]
+        public ActionResult EditInfo()
+        {
+            // Get the currently logged in student.
+            var student = Student;
             if (student == null)
             {
                 return RedirectToAction("Index", "Home");
@@ -217,13 +218,18 @@
             return View(model);
         }

-        [AuthorizeStudent, HttpPost, ValidateAntiForgeryToken, Route("gegevens-wijzigen/{id}")]
+        [AuthorizeStudent, HttpPost, ValidateAntiForgeryToken, Route("gegevens-wijzigen")]
         public ActionResult EditInfo(StudentInfoModel model)
         {
             if (ModelState.IsValid)
             {
-                var student = StudentRepository.GetById(model.Id);
+                // Get the currently logged in student.
+                var student = Student;
+
+                // Map the new values from the view model to the current student.
                 Mapper.Map(model, student);
+
+                // Updat the student in the database.
                 StudentRepository.Update(student);

                 return RedirectToAction("Dashboard");


And this one too!

And this one too!

--- src/KeyWatcher/KeyWatcher.Orleans.Client/Program.cs
+++ src/KeyWatcher/KeyWatcher.Orleans.Client/Program.cs
@@ -23,7 +23,7 @@
 		private const string AzureUri = "http://keywatcher.azurewebsites.net/api/keywatcher";

 		static void Main(string[] args) =>
-			Program.UseOrleansViaWebApi(Program.LocalUri);
+			Program.UseOrleansViaWebApi(Program.AzureUri);
 		//Program.UseOrleansLocally();

 		private static void UseOrleansLocally()
@@ -63,6 +63,7 @@
 			var user = GrainClient.GrainFactory.GetGrain<IUserGrain>(Program.userName);
 			var keys = e.Keys.ToArray();

+			// TODO: Must be awaited!
 			user.ProcessAsync(new UserKeysMessage(Program.userName, keys));
 			var message = new string(keys);


Don't log query result to avoid confusion

The query result will always be -1, as the result is the amount of rows affected, but that is not applicable in these create queries. This may cause confusion as devs may wonder why for example 'CreatedIndex' is -1. This also seemed to be the only place where we actually use the result of `database.Execute`.

--- src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs
+++ src/Umbraco.Core/Migrations/Install/DatabaseSchemaCreator.cs
@@ -445,14 +445,14 @@
             }

             //Execute the Create Table sql
-            var created = _database.Execute(new Sql(createSql));
-                    _logger.Info<DatabaseSchemaCreator>("Create Table {TableName} ({Created}): \n {Sql}", tableName, created, createSql);
+            _database.Execute(new Sql(createSql));
+            _logger.Info<DatabaseSchemaCreator>("Create Table {TableName}: \n {Sql}", tableName, createSql);

             //If any statements exists for the primary key execute them here
             if (string.IsNullOrEmpty(createPrimaryKeySql) == false)
             {
-                var createdPk = _database.Execute(new Sql(createPrimaryKeySql));
-                _logger.Info<DatabaseSchemaCreator>("Create Primary Key ({CreatedPk}):\n {Sql}", createdPk, createPrimaryKeySql);
+                _database.Execute(new Sql(createPrimaryKeySql));
+                _logger.Info<DatabaseSchemaCreator>("Create Primary Key:\n {Sql}", createPrimaryKeySql);
             }

             if (SqlSyntax.SupportsIdentityInsert() && tableDefinition.Columns.Any(x => x.IsIdentity))
@@ -469,24 +469,24 @@
             //Loop through index statements and execute sql
             foreach (var sql in indexSql)
             {
-                var createdIndex = _database.Execute(new Sql(sql));
-                _logger.Info<DatabaseSchemaCreator>("Create Index ({CreatedIndex}):\n {Sql}", createdIndex, sql);
+                _database.Execute(new Sql(sql));
+                _logger.Info<DatabaseSchemaCreator>("Create Index:\n {Sql}", sql);
             }

             //Loop through foreignkey statements and execute sql
             foreach (var sql in foreignSql)
             {
-                var createdFk = _database.Execute(new Sql(sql));
-                _logger.Info<DatabaseSchemaCreator>("Create Foreign Key ({CreatedFk}):\n {Sql}", createdFk, sql);
+                _database.Execute(new Sql(sql));
+                _logger.Info<DatabaseSchemaCreator>("Create Foreign Key:\n {Sql}", sql);
             }

             if (overwrite)
             {
-                        _logger.Info<Database>("Table {TableName} was recreated", tableName);
+                _logger.Info<Database>("Table {TableName} was recreated", tableName);
             }
             else
             {
-                        _logger.Info<Database>("New table {TableName} was created", tableName);
+                _logger.Info<Database>("New table {TableName} was created", tableName);

             }
         }


Switch on numeric class ID, not class name string

--- src/LfMerge/DataConverters/PartOfSpeechConverter.cs
+++ src/LfMerge/DataConverters/PartOfSpeechConverter.cs
@@ -89,19 +89,19 @@

 		public static IPartOfSpeech FromMSA(IMoMorphSynAnalysis msa)
 		{
-			switch (msa.GetType().Name)
-			{
-			case "MoDerivAffMsa":
+			switch (msa.ClassID)
+			{
+			case MoDerivAffMsaTags.kClassId:
 				// TODO: Turn this into a log message, and try to make the log message a little clearer to non-linguists, if possible.
 				Console.WriteLine("For derivational affix {0}, arbitrarily picking \"To\" part of speech instead of the \"From\" part of speech.", msa.GetGlossOfFirstSense());
 				return ((IMoDerivAffMsa)msa).ToPartOfSpeechRA;
-			case "MoDerivStepMsa":
+			case MoDerivStepMsaTags.kClassId:
 				return ((IMoDerivStepMsa)msa).PartOfSpeechRA;
-			case "MoInflAffMsa":
+			case MoInflAffMsaTags.kClassId:
 				return ((IMoInflAffMsa)msa).PartOfSpeechRA;
-			case "MoStemMsa":
+			case MoStemMsaTags.kClassId:
 				return ((IMoStemMsa)msa).PartOfSpeechRA;
-			case "MoUnclassifiedAffixMsa":
+			case MoUnclassifiedAffixMsaTags.kClassId:
 				return ((IMoUnclassifiedAffixMsa)msa).PartOfSpeechRA;
 			default:
 				// TODO: Make this a log message, not Console.WriteLine
@@ -113,23 +113,23 @@
 		public static void SetPartOfSpeech(IMoMorphSynAnalysis msa, IPartOfSpeech pos)
 		{
 			Console.WriteLine("Setting part of speech {0} ({1}) in msa {2}", pos.NameHierarchyString, pos.Guid, msa.Guid);
-			switch (msa.GetType().Name)
-			{
-			case "MoDerivAffMsa":
+			switch (msa.ClassID)
+			{
+			case MoDerivAffMsaTags.kClassId:
 				// TODO: Turn this into a log message, and try to make the log message a little clearer to non-linguists, if possible.
 				Console.WriteLine("For derivational affix {0}, arbitrarily picking \"To\" part of speech instead of the \"From\" part of speech.", msa.GetGlossOfFirstSense());
 				((IMoDerivAffMsa)msa).ToPartOfSpeechRA = pos;
 				break;
-			case "MoDerivStepMsa":
+			case MoDerivStepMsaTags.kClassId:
 				((IMoDerivStepMsa)msa).PartOfSpeechRA = pos;
 				break;
-			case "MoInflAffMsa":
+			case MoInflAffMsaTags.kClassId:
 				((IMoInflAffMsa)msa).PartOfSpeechRA = pos;
 				break;
-			case "MoStemMsa":
+			case MoStemMsaTags.kClassId:
 				((IMoStemMsa)msa).PartOfSpeechRA = pos;
 				break;
-			case "MoUnclassifiedAffixMsa":
+			case MoUnclassifiedAffixMsaTags.kClassId:
 				((IMoUnclassifiedAffixMsa)msa).PartOfSpeechRA = pos;
 				break;
 			default:


fixes virtual path

fixes virtual path

--- src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
+++ src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
@@ -3,6 +3,7 @@
 using Microsoft.AspNetCore.Routing;
 using System.Reflection;
 using Umbraco.Web.Common.Install;
+using Umbraco.Core.Hosting;

 namespace Umbraco.Extensions
 {
@@ -13,7 +14,7 @@
         /// </summary>
         /// <param name="url"></param>
         /// <returns></returns>
-        public static string GetBackOfficeUrl(this LinkGenerator linkGenerator)
+        public static string GetBackOfficeUrl(this LinkGenerator linkGenerator, IHostingEnvironment hostingEnvironment)
         {

             Type backOfficeControllerType;
@@ -24,7 +25,7 @@
             }
             catch (Exception)
             {
-                return "/"; // this would indicate that the installer is installed without the back office
+                return hostingEnvironment.ApplicationVirtualPath; // this would indicate that the installer is installed without the back office
             }

             return linkGenerator.GetPathByAction("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea });


Added one more test.

Added one more test.

--- src/Lucene.Net.Tests/core/Util/TestPriorityQueue.cs
+++ src/Lucene.Net.Tests/core/Util/TestPriorityQueue.cs
@@ -59,6 +59,28 @@
             }
         }

+        private class MyType
+        {
+            public MyType(int field)
+            {
+                Field = field;
+            }
+            public int Field { get; set; }
+        }
+
+        private class MyQueue : PriorityQueue<MyType>
+        {
+            public MyQueue(int count)
+                : base(count)
+            {
+            }
+
+            public override bool LessThan(MyType a, MyType b)
+            {
+                return (a.Field < b.Field);
+            }
+        }
+
         [Ignore] // Increase heap size to run this test
         [Test]
         public static void TestMaxSizeBounds()
@@ -252,6 +274,35 @@
         }

         [Test]
+        public static void TestUpdateTop()
+        {
+            // Mostly to reflect the usage of UpdateTop
+            int maxSize = 10;
+            PriorityQueue<MyType> pq = new MyQueue(maxSize);
+
+            pq.Add(new MyType(1));
+            pq.Add(new MyType(20));
+            pq.Add(new MyType(1));
+            pq.Add(new MyType(15));
+            pq.Add(new MyType(4));
+            pq.Add(new MyType(12));
+            pq.Add(new MyType(1000));
+            pq.Add(new MyType(-300));
+
+            Assert.AreEqual(pq.Top().Field, -300);
+            MyType topElement = pq.Top();
+            topElement.Field = 25;  // Now this should no longer be at the top of the queue
+            pq.UpdateTop();         // Hence we need to update the top queue
+            Assert.AreEqual(pq.Top().Field, 1);
+
+            // The less eficient way to do this is the following
+            topElement = pq.Pop();
+            topElement.Field = 678;
+            pq.Add(topElement);
+            Assert.AreEqual(pq.Top().Field, 1);
+        }
+
+        [Test]
         public static void TestOverflow()
         {
             // Tests adding elements to full queues
@@ -286,53 +337,6 @@
             catch (IndexOutOfRangeException)
             {
             }
-        }
-
-        [Test]
-        public static void TestStress()
-        {
-            int maxSize = AtLeast(100000);
-
-            PriorityQueue<int?> pq = new IntegerQueue(maxSize);
-            int sum = 0, sum2 = 0;
-
-            DateTime start, end;
-            TimeSpan total;
-            start = DateTime.Now;
-
-            // Add a lot of elements
-            for (int i = 0; i < maxSize; i++)
-            {
-                int next = Random().Next();
-                sum += next;
-                pq.Add(next);
-            }
-
-            end = DateTime.Now;
-            total = end - start;
-            // Note that this measurement considers the random number generation
-            System.Console.WriteLine("Total adding time: {0} ticks or {1}ms", total.Ticks, total.Milliseconds);
-            System.Console.WriteLine("Time per add: {0} ticks", total.Ticks / maxSize);
-
-            // Pop them and check that the elements are taken in sorted order
-            start = DateTime.Now;
-            int last = int.MinValue;
-            for (int i = 0; i < maxSize; i++)
-            {
-                int? next = pq.Pop();
-                Assert.IsTrue((int)next >= last);
-                last = (int)next;
-                sum2 += last;
-            }
-
-            end = DateTime.Now;
-            total = end - start;
-            // Note that this measurement considers the random number generation
-            System.Console.WriteLine("Total poping time: {0} ticks or {1}ms", total.Ticks, total.Milliseconds);
-            System.Console.WriteLine("Time per pop: {0} ticks", total.Ticks / maxSize);
-
-            // Loose checking that we didn't lose data in the process
-            Assert.AreEqual(sum, sum2);
         }

         [Test]
@@ -394,5 +398,52 @@
             pq.Pop();
             Assert.AreEqual((int?)7, pq.Top());
         }
+
+        [Test]
+        public static void TestStress()
+        {
+            int maxSize = AtLeast(100000);
+
+            PriorityQueue<int?> pq = new IntegerQueue(maxSize);
+            int sum = 0, sum2 = 0;
+
+            DateTime start, end;
+            TimeSpan total;
+            start = DateTime.Now;
+
+            // Add a lot of elements
+            for (int i = 0; i < maxSize; i++)
+            {
+                int next = Random().Next();
+                sum += next;
+                pq.Add(next);
+            }
+
+            end = DateTime.Now;
+            total = end - start;
+            // Note that this measurement considers the random number generation
+            System.Console.WriteLine("Total adding time: {0} ticks or {1}ms", total.Ticks, total.Milliseconds);
+            System.Console.WriteLine("Time per add: {0} ticks", total.Ticks / maxSize);
+
+            // Pop them and check that the elements are taken in sorted order
+            start = DateTime.Now;
+            int last = int.MinValue;
+            for (int i = 0; i < maxSize; i++)
+            {
+                int? next = pq.Pop();
+                Assert.IsTrue((int)next >= last);
+                last = (int)next;
+                sum2 += last;
+            }
+
+            end = DateTime.Now;
+            total = end - start;
+            // Note that this measurement considers the random number generation
+            System.Console.WriteLine("Total poping time: {0} ticks or {1}ms", total.Ticks, total.Milliseconds);
+            System.Console.WriteLine("Time per pop: {0} ticks", total.Ticks / maxSize);
+
+            // Loose checking that we didn't lose data in the process
+            Assert.AreEqual(sum, sum2);
+        }
     }
 }


Issue#284: Fixing pagination in UsersClient GetPermissionsAsync

--- src/Auth0.ManagementApi/Clients/UsersClient.cs
+++ src/Auth0.ManagementApi/Clients/UsersClient.cs
@@ -341,11 +341,14 @@
             return Connection.GetAsync<IPagedList<Permission>>("users/{id}/permissions",
                 new Dictionary<string, string>
                 {
-                        {"id", id},
-                        {"page", pagination.PageNo.ToString()},
-                        {"per_page", pagination.PerPage.ToString()},
-                        {"include_totals", pagination.IncludeTotals.ToString().ToLower()}
-                }, null, null, new PagedListConverter<Permission>("users"));
+                     {"id", id}
+                },
+                new Dictionary<string, string>
+                {
+                    {"page", pagination.PageNo.ToString()},
+                    {"per_page", pagination.PerPage.ToString()},
+                    {"include_totals", pagination.IncludeTotals.ToString().ToLower()}
+                }, null, new PagedListConverter<Permission>("users"));
         }

         /// <summary>


Add fix

Add fix

--- src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs
+++ src/Workspaces/Core/Portable/Editing/DeclarationModifiers.cs
@@ -66,6 +66,7 @@
             {
                 var field = symbol as IFieldSymbol;
                 var property = symbol as IPropertySymbol;
+                var method = symbol as IMethodSymbol;

                 return new DeclarationModifiers(
                     isStatic: symbol.IsStatic,
@@ -77,7 +78,8 @@
                     isConst: field != null && field.IsConst,
                     isUnsafe: symbol.RequiresUnsafeModifier(),
                     isVolatile: field != null && field.IsVolatile,
-                    isExtern: symbol.IsExtern);
+                    isExtern: symbol.IsExtern,
+                    isAsync: method?.IsAsync == true);
             }

             // Only named types, members of named types, and local functions have modifiers.


Don't try to preview App.xaml

Don't try to preview App.xaml

--- src/Avalonia.DesignerSupport/DesignerAssist.cs
+++ src/Avalonia.DesignerSupport/DesignerAssist.cs
@@ -115,7 +115,7 @@
                         {
                             Children =
                             {
-                                new TextBlock {Text = "Styles can't be edited without Design.PreviewWith. Add"},
+                                new TextBlock {Text = "Styles can't be previewed without Design.PreviewWith. Add"},
                                 new TextBlock {Text = "<Design.PreviewWith>"},
                                 new TextBlock {Text = "    <Border Padding=20><!-- YOUR CONTROL FOR PREVIEW HERE--></Border>"},
                                 new TextBlock {Text = "<Design.PreviewWith>"},
@@ -123,6 +123,8 @@
                             }
                         };
                 }
+                if (loaded is Application)
+                    control = new TextBlock {Text = "Application can't be previewed in design view"};
                 else
                     control = (Control) loaded;


add async to method names, extract base url

--- src/PerformanceTests/LeaderboardLoadTest/Program.cs
+++ src/PerformanceTests/LeaderboardLoadTest/Program.cs
@@ -18,6 +18,9 @@
             {"devadmin", "devadmin"}
         };

+        private static string baseUrl = "http://localhost:5000";
+        private static string route = "/api/leaderboard";
+
         private static Random s_r = new Random();

         public static void Main(string[] args)
@@ -33,15 +36,15 @@
             foreach (var userEntry in users)
             {
                 // login to the game
-                var tokenResponse = await gamerLogin(userEntry);
+                var tokenResponse = await gamerLoginAsync(userEntry);

                 // simulate leaderboard activity
-                var task = Task.Factory.StartNew(() => simulateGame(tokenResponse, cancellationToken));
+                var task = Task.Factory.StartNew(() => simulateGameAsync(tokenResponse, cancellationToken));
             }
             Console.Read();
         }

-        private static async Task simulateGame(TokenResponse tokenResponse, CancellationToken cancellationToken)
+        private static async Task simulateGameAsync(TokenResponse tokenResponse, CancellationToken cancellationToken)
         {
             var accessToken = tokenResponse.AccessToken;

@@ -53,46 +56,54 @@
                 for (int i = 0; i < count; i++)
                 {
                     // send game score (POST)
-                    await postScore(accessToken);
+                    // TODO - handle execption
+                    await postScoreAsync(accessToken);
                     Thread.Sleep(s_r.Next(1000, 10000));
                 }

                 // ask for leaderboard scores (GET)
-                await getScores(accessToken);
+                // TODO - handle execption
+                await getScoresAsync(accessToken);
                 Thread.Sleep(s_r.Next(1000, 10000));
             }
         }

-        private static async Task getScores(string accessToken)
+        private static async Task getScoresAsync(string accessToken)
         {
             var client = new HttpClient();
             client.SetBearerToken(accessToken);
-            var response = await client.GetAsync("http://localhost:5000/api/leaderboard");
+            var response = await client.GetAsync(baseUrl + route);

             if (!response.IsSuccessStatusCode)
             {
-                Console.WriteLine(response.StatusCode);
+                Console.WriteLine("Failed to get score: " + response.StatusCode);
             }

             var content = response.Content.ReadAsStringAsync().Result;
             Console.WriteLine(content);
         }

-        private static async Task postScore(string accessToken)
+        private static async Task postScoreAsync(string accessToken)
         {
-            int score = s_r.Next(1500);
-            Console.WriteLine("Post Score: " + score);
+            int score = s_r.Next(1500);

             var client = new HttpClient();
             client.SetBearerToken(accessToken);
-            var response = await client.PostAsJsonAsync("http://localhost:5000/api/leaderboard", new { country = "missing", customTag = "testclient", score = score });
+            var response = await client.PostAsJsonAsync(baseUrl + route, new { country = "missing", customTag = "testclient", score = score });

-            response.EnsureSuccessStatusCode();
+            if (!response.IsSuccessStatusCode)
+            {
+                Console.WriteLine("Failed to post score: " + response.StatusCode);
+            }
+            else
+            {
+                Console.WriteLine("Post Score: " + score);
+            }
         }

-        private static async Task<TokenResponse> gamerLogin(KeyValuePair<string, string> userEntry)
+        private static async Task<TokenResponse> gamerLoginAsync(KeyValuePair<string, string> userEntry)
         {
-            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
+            var disco = await DiscoveryClient.GetAsync(baseUrl);

             // request token
             var tokenClient = new TokenClient(disco.TokenEndpoint, "resourceowner-test", "devsecret");


Check enabled state as well as visibility.

WPF and Avalonia's `IsEnabled` properties are slightly different.

In WPF if reflects both the enabled state of the actual control and the effectively enabled state which comes from ancestor controls. In Avalonia that effectively enabled state is exposed on a different property: `IsEffectivelyEnabled`. When I ported the tab navigation code from WPF, I didn't take that into account.

WPF's visibility property however doesn't reflect the state of a control's owners and so tab navigation for invisible controls works correctly. Take advantage of this fact by changing any checks for `IsVisible` to also check `IsEnabled`.

--- src/Avalonia.Input/Navigation/TabNavigation.cs
+++ src/Avalonia.Input/Navigation/TabNavigation.cs
@@ -234,7 +234,7 @@
             // Return the first visible element.
             var uiElement = e as InputElement;

-            if (uiElement is null || uiElement.IsVisible)
+            if (uiElement is null || IsVisibleAndEnabled(uiElement))
             {
                 if (e is IVisual elementAsVisual)
                 {
@@ -245,7 +245,7 @@
                     {
                         if (children[i] is InputElement ie)
                         {
-                            if (ie.IsVisible)
+                            if (IsVisibleAndEnabled(ie))
                                 return ie;
                             else
                             {
@@ -270,7 +270,7 @@
             // Return the last visible element.
             var uiElement = e as InputElement;

-            if (uiElement == null || uiElement.IsVisible)
+            if (uiElement == null || IsVisibleAndEnabled(uiElement))
             {
                 var elementAsVisual = e as IVisual;

@@ -283,7 +283,7 @@
                     {
                         if (children[i] is InputElement ie)
                         {
-                            if (ie.IsVisible)
+                            if (IsVisibleAndEnabled(ie))
                                 return ie;
                             else
                             {
@@ -600,7 +600,7 @@
                     var vchild = children[i];
                     if (vchild == elementAsVisual)
                         break;
-                    if (vchild.IsVisible == true && vchild is IInputElement ie)
+                    if (vchild is IInputElement ie && IsVisibleAndEnabled(ie))
                         prev = ie;
                 }
                 return prev;
@@ -668,5 +668,6 @@
         }

         private static bool IsTabStopOrGroup(IInputElement e) => IsTabStop(e) || IsGroup(e);
+        private static bool IsVisibleAndEnabled(IInputElement e) => e.IsVisible && e.IsEnabled;
     }
 }


prebuilt pipeline

prebuilt pipeline

--- experimental/Slabs.Experimental.Console/Pipe/PipeTestStartup.cs
+++ experimental/Slabs.Experimental.Console/Pipe/PipeTestStartup.cs
@@ -1,15 +1,15 @@
-using System;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using System;
 using System.Collections.Generic;
 using System.Diagnostics;
 using System.Threading.Tasks;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-using Slabs.Experimental.ConsoleClient.Testify;

 namespace Slabs.Experimental.ConsoleClient.Pipe
 {
-	// prebuilt pipe
-	// able to get args
+	// able to get args/result (cache pipe)
+	// change Func<Task> (invoke param) to PipelineContext
+
 	public class PipeTestStartup
 	{
 		private readonly ILogger _logger;
@@ -24,13 +24,17 @@
 		public async Task Run()
 		{
 			_logger.LogInformation("Init Pipe Test...");
+			var pipeBuilder = _pipeBuilderFactory.Create()
+				.Add<TimerPipe>()
+				// .Add<CachePipe>()
+				;
+
 			var result = await GetFruit();

-			var pipeBuilder = _pipeBuilderFactory.Create()
-				.Add<TimerPipe>();
-
-			await pipeBuilder.Run(GetFruit);
-			await pipeBuilder.Run(GetFruit);
+			var pipeline = pipeBuilder.Build();
+			await pipeline.Run(GetFruit);
+			await pipeline.Run(GetFruit);
+			//var result = await pipeline.Run(GetFruit);

 			_logger.LogInformation($"[Pipe] Result={result}");
 		}
@@ -70,14 +74,12 @@
 			return this;
 		}

-		public async Task Run(PipeDelegate action)
+		public PipeRuntime Build()
 		{
 			if (_pipes.Count == 0)
-			{
-				await action();
-				return;
-			}
+				throw new InvalidOperationException("Cannot build with zero pipes.");

+			Add<ActionExecutePipe>();
 			IPipe previous = null;
 			for (int i = _pipes.Count; i-- > 0;)
 			{
@@ -85,8 +87,8 @@
 				var isLast = _pipes.Count - 1 == i;
 				var isFirst = i == 0;

-				var next = isLast
-					? action
+				PipeDelegate next = isLast
+					? (PipeDelegate)Stub
 					: previous.Invoke;

 				object[] ctor;
@@ -101,15 +103,27 @@

 				IPipe instance = (IPipe)ActivatorUtilities.CreateInstance(_serviceProvider, pipe.Type, ctor);
 				if (isFirst)
-					await instance.Invoke(); // todo: arg
-				else
-					previous = instance;
+					return new PipeRuntime(instance);
+				previous = instance;
+			}
+			throw new InvalidOperationException("Something went wrong!");

-			}
+			Task Stub(Func<Task> action) => Task.CompletedTask;
 		}
-
 	}
-
+
+	public class PipeRuntime
+	{
+		private readonly IPipe _pipeline;
+
+		public PipeRuntime(IPipe pipline)
+		{
+			_pipeline = pipline;
+		}
+
+		public Task Run(Func<Task> action) => _pipeline.Invoke(action);
+	}
+
 	public class PipeConfig
 	{
 		public Type Type { get; set; }
@@ -119,7 +133,7 @@
 		public PipeConfig()
 		{
 		}
-
+
 		public PipeConfig(Type type, object[] args)
 		{
 			Type = type;
@@ -134,29 +148,41 @@

 	public interface IPipe
 	{
-		Task Invoke();
+		Task Invoke(Func<Task> action);
 	}
-	public delegate Task PipeDelegate();
-
+	public delegate Task PipeDelegate(Func<Task> action);
+
 	public class TimerPipe : IPipe
 	{
 		private readonly PipeDelegate _next;
 		private readonly ILogger _logger;
-
+
 		public TimerPipe(PipeDelegate next, ILogger<TimerPipe> logger)
 		{
 			_next = next;
 			_logger = logger;
 		}
-
-		public async Task Invoke()
+
+		public async Task Invoke(Func<Task> action)
 		{
 			var watch = Stopwatch.StartNew();
-			await _next();
+			await _next(action);
 			var elapsed = watch.Elapsed;
-
+
 			if (_logger.IsEnabled(LogLevel.Information))
-				_logger.LogInformation("Executed action in {timeTakenMillis}ms", elapsed.TotalMilliseconds);
+				_logger.LogInformation("Executed action in {timeTakenMillis}ms", elapsed.TotalMilliseconds);
+		}
+	}
+	public class ActionExecutePipe : IPipe
+	{
+		public ActionExecutePipe(PipeDelegate next)
+		{
+			_next = next;
+		}
+
+		public async Task Invoke(Func<Task> action)
+		{
+			await action();
 		}
 	}
 }


test cleanup

test cleanup

--- LinqEditor.Core.CodeAnalysis.Tests/TemplateCodeAnalysisTests.cs
+++ LinqEditor.Core.CodeAnalysis.Tests/TemplateCodeAnalysisTests.cs
@@ -48,10 +48,8 @@
     }
 }
 ";
-        [TestFixtureSetUp]
-        public void Initialize()
-        {
-            var programSource = @"
+
+        string _advancedProgram = @"
 using System;
 using System.Linq;
 using System.Collections.Generic;
@@ -64,6 +62,7 @@
         public int Bar { get; set; }
         public int Baz() { return 42; }
     }
+
 }

 namespace Another.Generated
@@ -81,9 +80,13 @@
     }
 }
 ";
-            var m = new Mock<ITemplateService>();
-            m.Setup(s => s.GenerateQuery(It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>())).Returns(programSource);
-            m.Setup(s => s.GenerateCodeStatements(It.IsAny<Guid>(), It.IsAny<string>())).Returns(programSource);
+
+        [TestFixtureSetUp]
+        public void Initialize()
+        {
+            var m = new Mock<ITemplateService>();
+            m.Setup(s => s.GenerateQuery(It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>())).Returns(_advancedProgram);
+            m.Setup(s => s.GenerateCodeStatements(It.IsAny<Guid>(), It.IsAny<string>())).Returns(_advancedProgram);
             _templateService = m.Object;

             var docMock = new Mock<IDocumentationService>();
@@ -108,7 +111,6 @@

             var editor = new TemplateCodeAnalysis(_templateService, _mockDocumentationService);
             editor.Initialize();
-            //_context.UpdateContext("", ""); // fire bogus event to init class
             var result = editor.Analyze(src, src.Length - offset);
             Assert.AreEqual(editContex, result.Context);
         }
@@ -176,13 +178,13 @@
         [TestCase(VSDocumentationTestData.VarDeclerationOfHashSet, 5, UserContext.Unknown)] // => var name
         [TestCase(VSDocumentationTestData.VarDeclerationOfQueryable, 30, UserContext.Unknown)] // => method
         [TestCase(VSDocumentationTestData.VarDeclerationOfGenericIntList, 18, UserContext.Unknown)] // => int type
-        public void Can_Corrrect_Return_ToolTip_Context_Information_For_Variables(string testDataKey, int offset, UserContext ctx)
+        public void Returns_Correct_UserContext_For_VariableDeclarations(string testDataKey, int offset, UserContext ctx)
         {
             var m = new Mock<ITemplateService>();
             m.Setup(s => s.GenerateQuery(It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>())).Returns(_simpleProgramWithAllUsings);
             m.Setup(s => s.GenerateCodeStatements(It.IsAny<Guid>(), It.IsAny<string>())).Returns(_simpleProgramWithAllUsings);

-            var editor = new TemplateCodeAnalysis(m.Object, _realDocumentationService);
+            var editor = new TemplateCodeAnalysis(m.Object, _mockDocumentationService);
             editor.Initialize();
             var testData = VSDocumentationTestData.Data[testDataKey];

@@ -191,5 +193,21 @@
             Assert.AreEqual(ctx, result.Context);
         }

-    }
-}
+        //[Test]
+        public void Can_Find_Inherited_Members_On_This()
+        {
+            var m = new Mock<ITemplateService>();
+            m.Setup(s => s.GenerateQuery(It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>())).Returns(_simpleProgram);
+            m.Setup(s => s.GenerateCodeStatements(It.IsAny<Guid>(), It.IsAny<string>())).Returns(_simpleProgram);
+
+            var editor = new TemplateCodeAnalysis(m.Object, _mockDocumentationService);
+            editor.Initialize();
+
+            var stub = "var x = new List<int>();x.";
+
+            var result = editor.Analyze(stub, stub.Length - 1);
+
+            Assert.IsNotNull(result.MemberCompletions.FirstOrDefault(x => x.Value == "Dump" && x.Kind == MemberKind.ExtensionMethod));
+        }
+    }
+}


Neil #886 - change to pdf export to export html

--- src/StockportWebapp/Controllers/GroupsController.cs
+++ src/StockportWebapp/Controllers/GroupsController.cs
@@ -167,7 +167,7 @@
         [HttpGet]
         [Route("/groups/{slug}/exportpdf")]
         [ResponseCache(NoStore = true)]
-        public async Task<IActionResult> ExportPdf([FromServices] INodeServices nodeServices, string slug)
+        public async Task<IActionResult> ExportPdf([FromServices] INodeServices nodeServices, string slug, [FromQuery] bool returnHtml = false)
         {
             ViewBag.CurrentUrl = Request?.GetUri();

@@ -179,17 +179,20 @@

             var renderedExportStyles = _viewRender.Render("Shared/ExportStyles", string.Concat(Request?.Scheme, "://", Request?.Host));
             var renderedHtml = _viewRender.Render("Shared/GroupDetail", group);
-
-            var result = await nodeServices.InvokeAsync<byte[]>("./pdf", new { data = string.Concat(renderedExportStyles, renderedHtml), delay = 1000 });
+            var joinedHtml = string.Concat(renderedExportStyles, renderedHtml);
+
+            // if raw html is requested, simply return the html ins
+            if (returnHtml) return Content(joinedHtml, "text/html");
+
+            var result = await nodeServices.InvokeAsync<byte[]>("./pdf", new { data = joinedHtml, delay = 1000 });

             if (result == null) _logger.LogError(string.Concat("Failed to export group ", slug, " to pdf"));

             HttpContext.Response.ContentType = "application/pdf";
-
-            var filename = @"group.pdf";
-            HttpContext.Response.Headers.Add("x-filename", filename);
+            HttpContext.Response.Headers.Add("x-filename", "group.pdf");
             HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
             HttpContext.Response.Body.Write(result, 0, result.Length);
+
             return new ContentResult();
         }


need another build

need another build

--- src/Umbraco.Web/Editors/AuthenticationController.cs
+++ src/Umbraco.Web/Editors/AuthenticationController.cs
@@ -66,6 +66,7 @@
             return provider.GetConfiguration(Services.UserService);
         }

+
         /// <summary>
         /// Checks if a valid token is specified for an invited user and if so logs the user in and returns the user object
         /// </summary>


Changes the admin lookup back to just use the id

--- src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs
+++ src/Umbraco.Web/Mvc/AdminTokenAuthorizeAttribute.cs
@@ -43,9 +43,7 @@
         /// <returns></returns>
         public static string GetAuthHeaderTokenVal(ApplicationContext appContext)
         {
-            int numberOfUsers;
-            var users = appContext.Services.UserService.GetAll(0, 25, out numberOfUsers);
-            var admin = users.FirstOrDefault(u => u.UserType.Alias == "admin" && u.RawPasswordValue != string.Empty && u.RawPasswordValue.InvariantEquals("default") == false);
+            var admin = appContext.Services.UserService.GetUserById(0);

             if (admin == null)
                 return string.Empty;


fix sizetocontent on win32.

fix sizetocontent on win32.

--- src/Windows/Avalonia.Win32/WindowImpl.AppWndProc.cs
+++ src/Windows/Avalonia.Win32/WindowImpl.AppWndProc.cs
@@ -402,6 +402,8 @@
                 case WindowsMessage.WM_GETMINMAXINFO:
                     {
                         MINMAXINFO mmi = Marshal.PtrToStructure<MINMAXINFO>(lParam);
+
+                        _maxTrackSize = mmi.ptMaxTrackSize;

                         if (_minSize.Width > 0)
                         {


feat(manager)

feat(manager)

add method for spy score

--- src/csharp-steamgaug-es-api-core/Manager/SteamgaugManager.cs
+++ src/csharp-steamgaug-es-api-core/Manager/SteamgaugManager.cs
@@ -200,6 +200,15 @@
             }
         }

+        public int GetSpyScore(Game game)
+        {
+            if (game != Game.TeamFortress)
+            {
+                throw new GameNotSupportedException();
+            }
+            return _steamgaugResponseModel.SteamGameCoordinator["440"].Stats.SpyScore;
+        }
+
         private bool IsOnline(int status)
         {
             if (status == 1)