Include a ConfigureAwait checker on all APIs

--- tools/Google.Cloud.Tools.ProjectGenerator/ApiMetadata.cs
+++ tools/Google.Cloud.Tools.ProjectGenerator/ApiMetadata.cs
@@ -48,6 +48,7 @@
             }
             string targetFrameworks = TargetFrameworks;
             var dependencies = new SortedList<string, string>(Dependencies);
+            dependencies.Add("ConfigureAwaitChecker.Analyzer", "1.0.0-beta4");
             switch (Type)
             {
                 case "rest":
@@ -182,7 +183,9 @@
                         new XAttribute("Version", d.Value),
                         // Make references to Grpc.Core deploy native dependencies
                         // See https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/1066
-                        d.Key == "Grpc.Core" ? new XElement("PrivateAssets", "None") : null)
+                        d.Key == "Grpc.Core" ? new XElement("PrivateAssets", "None") : null,
+                        // Make references to ConfigureAwaitChecker effectively private
+                        d.Key == "ConfigureAwaitChecker.Analyzer" ? new XElement("PrivateAssets", "All") : null)
                     )
             );
     }


Always validate first_layer_height

Always validate first_layer_height

--- MatterControlLib/ApplicationView/SettingsValidation.cs
+++ MatterControlLib/ApplicationView/SettingsValidation.cs
@@ -70,7 +70,8 @@
 								Error = "{0} must be greater than 0.".Localize().FormatWith(GetSettingsName(SettingsKey.layer_height)),
 							});
 					}
-					else if (settings.GetValue<double>(SettingsKey.first_layer_height) > settings.GetValue<double>(SettingsKey.nozzle_diameter))
+
+					if (settings.GetValue<double>(SettingsKey.first_layer_height) > settings.GetValue<double>(SettingsKey.nozzle_diameter))
 					{
 						var details = "{0} = {1}\n{2} = {3}".FormatWith(
 							GetSettingsName(SettingsKey.first_layer_height),


Minor change to names of variables

Minor change to names of variables

--- src/DataStructuresAlgorithms/Algorithms/ArraySorting.cs
+++ src/DataStructuresAlgorithms/Algorithms/ArraySorting.cs
@@ -9,18 +9,18 @@
     {
         public static void BubbleSort(int[] arr)
         {
-            int jOut = arr.Length - 1, jIn;
+            int o = arr.Length - 1, i;
             bool swapped;
             do
             {
                 swapped = false;
-                for (jIn = 0; jIn < jOut; jIn++)
-                    if (arr[jIn] > arr[jIn + 1])
+                for (i = 0; i < o; i++)
+                    if (arr[i] > arr[i + 1])
                     {
-                        Swap(ref arr[jIn], ref arr[jIn + 1]);
+                        Swap(ref arr[i], ref arr[i + 1]);
                         swapped = true;
                     }
-                jOut--;
+                o--;
             }
             while (swapped);
         }
@@ -34,33 +34,33 @@

         public static void SelectionSort(int[] arr)
         {
-            int jOut, jIn, min;
-            for(jOut = 0; jOut < arr.Length - 1; jOut++)
+            int o, i, min;
+            for(o = 0; o < arr.Length - 1; o++)
             {
-                min = jOut;
-                for(jIn = jOut + 1; jIn < arr.Length; jIn++)
+                min = o;
+                for(i = o + 1; i < arr.Length; i++)
                 {
-                    if(arr[jIn] < arr[min])
+                    if(arr[i] < arr[min])
                     {
-                        min = jIn;
+                        min = i;
                     }
                 }
-                // Invariant: arr[min] smallest of arr[jOut:]
-                Swap(ref arr[jOut], ref arr[min]);
-                // Invariant: arr[:jOut] in final position
+                // Invariant: arr[min] smallest of arr[o:]
+                Swap(ref arr[o], ref arr[min]);
+                // Invariant: arr[:o] in final position
             }
         }

         public static void InsertionSort(int[] arr)
         {
-            int jIn, jOut;
-            for(jOut = 1; jOut < arr.Length; jOut++)
+            int i, o;
+            for(o = 1; o < arr.Length; o++)
             {
-                for(jIn = jOut; jIn > 0 && arr[jIn] < arr[jIn - 1]; jIn--)
+                for(i = o; i > 0 && arr[i] < arr[i - 1]; i--)
                 {
-                    Swap(ref arr[jIn], ref arr[jIn - 1]);
+                    Swap(ref arr[i], ref arr[i - 1]);
                 }
-                // Invariant: arr[:jOut] is sorted
+                // Invariant: arr[:o] is sorted
             }
         }
     }


add mvc template

add mvc template

--- src/DependencyInjection/ApplicationBuilderExtensions.cs
+++ src/DependencyInjection/ApplicationBuilderExtensions.cs
@@ -84,5 +84,32 @@
             if (app.ApplicationServices.GetService(typeof(DetectionMarkerService)) == null)
                 throw new InvalidOperationException("AddDetection() is not added to ConfigureServices(...)");
         }
+
+        private static void VerifyEndpointRoutingMiddlewareIsNotRegistered(IApplicationBuilder app)
+        {
+            if (!app.Properties.TryGetValue(EndpointRouteBuilder, out var obj))
+            {
+                var message =
+                    $"{nameof(EndpointRoutingMiddleware)} matches endpoints setup by {nameof(EndpointMiddleware)} and so must be added to the request " +
+                    $"execution pipeline before {nameof(EndpointMiddleware)}. " +
+                    $"Please add {nameof(EndpointRoutingMiddleware)} by calling '{nameof(IApplicationBuilder)}.{nameof(UseRouting)}' inside the call " +
+                    $"to 'Configure(...)' in the application startup code.";
+                throw new InvalidOperationException(message);
+            }
+
+            // If someone messes with this, just let it crash.
+            endpointRouteBuilder = (DefaultEndpointRouteBuilder)obj;
+
+            // This check handles the case where Map or something else that forks the pipeline is called between the two
+            // routing middleware.
+            if (!object.ReferenceEquals(app, endpointRouteBuilder.ApplicationBuilder))
+            {
+                var message =
+                    $"The {nameof(EndpointRoutingMiddleware)} and {nameof(EndpointMiddleware)} must be added to the same {nameof(IApplicationBuilder)} instance. " +
+                    $"To use Endpoint Routing with 'Map(...)', make sure to call '{nameof(IApplicationBuilder)}.{nameof(UseRouting)}' before " +
+                    $"'{nameof(IApplicationBuilder)}.{nameof(UseEndpoints)}' for each branch of the middleware pipeline.";
+                throw new InvalidOperationException(message);
+            }
+        }
     }
 }


fix: DefaultWebSocket can now correctly close

This resolves a bug where disconnecting the socket client would not
actually close the websocket. Bots would appear to remain online in the
discord client until their connection to discord eventually timed out.

The underlying cause of this issue sourced from the cancellation token
passed into the websocket's ReceiveAsync method - when entering the
disconnect process, the first step is to cancel out all of the
connection tokens. Unfortunately, the standard ClientWebSocket handles a
token cancellation by aborting the socket, rendering it inoperable for a
safe closure.

This change removes the inner cancellation token passed into
ReceiveAsync. The cancellation token is still retained for use in the
receive loop, so the receive task should gracefully complete once some
event satisfies the ClientWebSocket's blocking receive.

To ensure that all clients succesfully close, regardless of their
traffic, the disconnect procedure was rearranged such that awaiting the
receive task now occurs last, after the socket has been closed. Closing
the socket will propagate an event up to the ClientWebSocket's receive
method, which will allow the loop to iterate and gracefully complete.

So far, I have validated this change against basic connection opening
and closing, for both the gateway and voice clients. I have not yet
validated against unplanned connection interruptions, though I believe
that this change might actually improve some of those connection bugs,
since the ClientWebSocket should never find itself in an aborted state.

--- src/Discord.Net.WebSocket/Net/DefaultWebSocketClient.cs
+++ src/Discord.Net.WebSocket/Net/DefaultWebSocketClient.cs
@@ -108,28 +108,30 @@
         }
         private async Task DisconnectInternalAsync(bool isDisposing = false)
         {
-            try { _disconnectTokenSource.Cancel(false); } catch { }
+            try { _disconnectTokenSource.Cancel(false); }
+            catch { }

             _isDisconnecting = true;
+
+            if (_client != null)
+            {
+                if (!isDisposing)
+                {
+                    try { await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", new CancellationToken()); }
+                    catch { }
+                }
+                try { _client.Dispose(); }
+                catch { }
+
+                _client = null;
+            }
+
             try
             {
                 await (_task ?? Task.Delay(0)).ConfigureAwait(false);
                 _task = null;
             }
             finally { _isDisconnecting = false; }
-
-            if (_client != null)
-            {
-                if (!isDisposing)
-                {
-                    try { await _client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", new CancellationToken()); }
-                    catch { }
-                }
-                try { _client.Dispose(); }
-                catch { }
-
-                _client = null;
-            }
         }
         private async Task OnClosed(Exception ex)
         {
@@ -198,7 +200,7 @@
             {
                 while (!cancelToken.IsCancellationRequested)
                 {
-                    WebSocketReceiveResult socketResult = await _client.ReceiveAsync(buffer, cancelToken).ConfigureAwait(false);
+                    WebSocketReceiveResult socketResult = await _client.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false);
                     byte[] result;
                     int resultCount;


Fixing method signature on RedeemRefreshTokenAsync

--- MicrosoftAccount.WindowsForms/MicrosoftAccountOAuth.cs
+++ MicrosoftAccount.WindowsForms/MicrosoftAccountOAuth.cs
@@ -27,11 +27,11 @@
             return tokens;
         }

-        public static async Task<AppTokenResult> RedeemRefreshTokenAsync(string clientId, string clientSecret, string redirectUri, string refreshToken)
+        public static async Task<AppTokenResult> RedeemRefreshTokenAsync(string clientId, string clientSecret, string refreshToken)
         {
             var queryBuilder = new QueryStringBuilder();
             queryBuilder.Add("client_id", clientId);
-            queryBuilder.Add("redirect_uri", redirectUri);
+            queryBuilder.Add("redirect_uri", FormMicrosoftAccountAuth.OAuthDesktopEndPoint);
             queryBuilder.Add("client_secret", clientSecret);
             queryBuilder.Add("refresh_token", refreshToken);
             queryBuilder.Add("grant_type", "refresh_token");
@@ -41,7 +41,7 @@

         private static async Task<AppTokenResult> PostToTokenEndPoint(QueryStringBuilder queryBuilder)
         {
-            HttpWebRequest request = WebRequest.CreateHttp("https://login.live.com/oauth20_token.srf");
+            HttpWebRequest request = WebRequest.CreateHttp(FormMicrosoftAccountAuth.OAuthMSATokenService);
             request.Method = "POST";
             request.ContentType = "application/x-www-form-urlencoded";


completed SearchableQA

completed SearchableQA

--- Code/UnitTests/Epic.Query.Object.UnitTests/SearchableQA.cs
+++ Code/UnitTests/Epic.Query.Object.UnitTests/SearchableQA.cs
@@ -194,6 +194,85 @@
             Assert.AreSame(initialCriterion, ((OrderCriteria<ICargo>)((Order<ICargo>)deferArguments[0]).Criterion).ElementAt(0));
             Assert.AreSame(secondCriterion, ((OrderCriteria<ICargo>)((Order<ICargo>)deferArguments[0]).Criterion).ElementAt(1));
         }
+        [Test]
+        public void Skip_withAOrderedSearch_deferrsANewLimitedSearch()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> expression = new Order<ICargo>(sourceExpression, criterion);
+            IDeferrer deferrer = MockRepository.GenerateStrictMock<IDeferrer>();
+            deferrer.Expect(d => d.Defer<ILimitedSearch<ICargo, TrackingId>, IEnumerable<ICargo>>(null)).IgnoreArguments()
+                .WhenCalled(m => deferArguments = m.Arguments)
+                .Return(deferResult).Repeat.Once();
+            IOrderedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<IOrderedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Once();
+            search.Expect(s => s.Deferrer).Return(deferrer).Repeat.Once();
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Skip(10);
+
+            // assert:
+            Assert.AreSame(deferResult, result);
+            Assert.AreEqual(1, deferArguments.Length);
+            Assert.IsInstanceOf<Cut<ICargo>>(deferArguments[0]);
+            Assert.AreSame(expression, ((Cut<ICargo>)deferArguments[0]).Source);
+            Assert.AreEqual(uint.MaxValue, ((Cut<ICargo>)deferArguments[0]).TakingAtMost);
+            Assert.AreEqual(10, ((Cut<ICargo>)deferArguments[0]).Skipping);
+        }
+
+        [Test]
+        public void Skip_withALimitedSearch_deferrsANewLimitedSearch()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> orderedExpression = new Order<ICargo>(sourceExpression, criterion);
+            Cut<ICargo> expression = new Cut<ICargo>(orderedExpression, 5, 10);
+            IDeferrer deferrer = MockRepository.GenerateStrictMock<IDeferrer>();
+            deferrer.Expect(d => d.Defer<ILimitedSearch<ICargo, TrackingId>, IEnumerable<ICargo>>(null)).IgnoreArguments()
+                .WhenCalled(m => deferArguments = m.Arguments)
+                .Return(deferResult).Repeat.Once();
+            ILimitedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Times(3);
+            search.Expect(s => s.Deferrer).Return(deferrer).Repeat.Once();
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Skip(7);
+
+            // assert:
+            Assert.AreSame(deferResult, result);
+            Assert.AreEqual(1, deferArguments.Length);
+            Assert.IsInstanceOf<Cut<ICargo>>(deferArguments[0]);
+            Assert.AreSame(orderedExpression, ((Cut<ICargo>)deferArguments[0]).Source);
+            Assert.AreEqual(5, ((Cut<ICargo>)deferArguments[0]).TakingAtMost);
+            Assert.AreEqual(7, ((Cut<ICargo>)deferArguments[0]).Skipping);
+        }
+
+        [Test]
+        public void Skip_withAnEquivalentLimitedSearch_returnsTheSameInstance()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> orderedExpression = new Order<ICargo>(sourceExpression, criterion);
+            Cut<ICargo> expression = new Cut<ICargo>(orderedExpression, 5, 10);
+            ILimitedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Times(2);
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Skip(10);
+
+            // assert:
+            Assert.AreSame(search, result);
+            Assert.IsNull(deferArguments);
+        }

         [Test]
         public void Skip_withoutASearch_throwsArgumentNullException()
@@ -209,6 +288,86 @@
             Assert.Throws<ArgumentNullException>(delegate {
                 Searchable.Skip<ICargo, TrackingId>(limitedSearch, 1);
             });
+        }
+
+        [Test]
+        public void Take_withAnEquivalentLimitedSearch_returnsTheSameInstance()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> orderedExpression = new Order<ICargo>(sourceExpression, criterion);
+            Cut<ICargo> expression = new Cut<ICargo>(orderedExpression, 5, 10);
+            ILimitedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Times(2);
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Take(5);
+
+            // assert:
+            Assert.AreSame(search, result);
+            Assert.IsNull(deferArguments);
+        }
+
+        [Test]
+        public void Take_withAOrderedSearch_deferrsANewLimitedSearch()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> expression = new Order<ICargo>(sourceExpression, criterion);
+            IDeferrer deferrer = MockRepository.GenerateStrictMock<IDeferrer>();
+            deferrer.Expect(d => d.Defer<ILimitedSearch<ICargo, TrackingId>, IEnumerable<ICargo>>(null)).IgnoreArguments()
+                .WhenCalled(m => deferArguments = m.Arguments)
+                .Return(deferResult).Repeat.Once();
+            IOrderedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<IOrderedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Once();
+            search.Expect(s => s.Deferrer).Return(deferrer).Repeat.Once();
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Take(10);
+
+            // assert:
+            Assert.AreSame(deferResult, result);
+            Assert.AreEqual(1, deferArguments.Length);
+            Assert.IsInstanceOf<Cut<ICargo>>(deferArguments[0]);
+            Assert.AreSame(expression, ((Cut<ICargo>)deferArguments[0]).Source);
+            Assert.AreEqual(10, ((Cut<ICargo>)deferArguments[0]).TakingAtMost);
+            Assert.AreEqual(0, ((Cut<ICargo>)deferArguments[0]).Skipping);
+        }
+
+        [Test]
+        public void Take_withALimitedSearch_deferrsANewLimitedSearch()
+        {
+            // arrange:
+            OrderCriterion<ICargo> criterion = GeneratePartialMock<OrderCriterion<ICargo>>();
+            ILimitedSearch<ICargo, TrackingId> deferResult = GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            object[] deferArguments = null;
+            Expression<IEnumerable<ICargo>> sourceExpression = MockRepository.GeneratePartialMock<Expression<IEnumerable<ICargo>>>();
+            Order<ICargo> orderedExpression = new Order<ICargo>(sourceExpression, criterion);
+            Cut<ICargo> expression = new Cut<ICargo>(orderedExpression, 5, 10);
+            IDeferrer deferrer = MockRepository.GenerateStrictMock<IDeferrer>();
+            deferrer.Expect(d => d.Defer<ILimitedSearch<ICargo, TrackingId>, IEnumerable<ICargo>>(null)).IgnoreArguments()
+                .WhenCalled(m => deferArguments = m.Arguments)
+                .Return(deferResult).Repeat.Once();
+            ILimitedSearch<ICargo, TrackingId> search = MockRepository.GenerateStrictMock<ILimitedSearch<ICargo, TrackingId>>();
+            search.Expect(s => s.Expression).Return(expression).Repeat.Times(3);
+            search.Expect(s => s.Deferrer).Return(deferrer).Repeat.Once();
+
+            // act:
+            ILimitedSearch<ICargo, TrackingId> result = search.Take(7);
+
+            // assert:
+            Assert.AreSame(deferResult, result);
+            Assert.AreEqual(1, deferArguments.Length);
+            Assert.IsInstanceOf<Cut<ICargo>>(deferArguments[0]);
+            Assert.AreSame(orderedExpression, ((Cut<ICargo>)deferArguments[0]).Source);
+            Assert.AreEqual(7, ((Cut<ICargo>)deferArguments[0]).TakingAtMost);
+            Assert.AreEqual(10, ((Cut<ICargo>)deferArguments[0]).Skipping);
         }

         [Test]


Fix to close returned XmlReader of ReadSubtree.

--- NBug/Core/Util/Serialization/SerializableDictionary.cs
+++ NBug/Core/Util/Serialization/SerializableDictionary.cs
@@ -50,7 +50,9 @@
 				return;
 			}*/

-			var xElement = XElement.Load(reader.ReadSubtree());
+			var inner = reader.ReadSubtree();
+
+			var xElement = XElement.Load(inner);
 			if (xElement.HasElements)
 			{
 				foreach (var element in xElement.Elements())
@@ -58,6 +60,8 @@
 					this.Add((TKey)Convert.ChangeType(element.Name.ToString(), typeof(TKey)), (TValue)Convert.ChangeType(element.Value, typeof(TValue)));
 				}
 			}
+
+			inner.Close();

 			reader.ReadEndElement();
 		}


fixing error incorrect-phase => invalid-phase

--- NTumbleBit.TumblerServer/Controllers/MainController.cs
+++ NTumbleBit.TumblerServer/Controllers/MainController.cs
@@ -104,7 +104,7 @@
 			int keyIndex;
 			var key = Repository.GetNextKey(cycle.Start, out keyIndex);
 			if(!cycle.IsInPhase(CyclePhase.ClientChannelEstablishment, height))
-				return BadRequest("incorrect-phase");
+				return BadRequest("invalid-phase");
 			return Json(new TumblerEscrowKeyResponse { PubKey = key.PubKey, KeyIndex = keyIndex });
 		}

@@ -124,7 +124,7 @@
 			var cycle = Parameters.CycleGenerator.GetCycle(request.ClientEscrowInformation.Cycle);
 			var height = Services.BlockExplorerService.GetCurrentHeight();
 			if(!cycle.IsInPhase(CyclePhase.ClientChannelEstablishment, height))
-				return BadRequest("incorrect-phase");
+				return BadRequest("invalid-phase");

 			AliceServerChannelNegotiation aliceNegotiation = new AliceServerChannelNegotiation(Parameters, Runtime.TumblerKey, Runtime.VoucherKey);
 			var key = Repository.GetKey(cycle.Start, request.KeyReference);
@@ -172,7 +172,7 @@
 			BobServerChannelNegotiation session = CreateBobServerChannelNegotiation(request.CycleStart);
 			var cycle = session.GetCycle();
 			if(!cycle.IsInPhase(CyclePhase.TumblerChannelEstablishment, height))
-				return BadRequest("incorrect-phase");
+				return BadRequest("invalid-phase");
 			var fee = Services.FeeService.GetFeeRate();
 			try
 			{


Updated tests to use the Core ConfigReader

--- src/Noobot.Tests.Unit/Core/Slack/SlackConnectorTests.cs
+++ src/Noobot.Tests.Unit/Core/Slack/SlackConnectorTests.cs
@@ -1,6 +1,6 @@
 using Noobot.Core;
+using Noobot.Core.Configuration;
 using Noobot.Core.Logging;
-using Noobot.Runner.Configuration;
 using Noobot.Tests.Unit.Stubs.MessagingPipeline;
 using NUnit.Framework;


Added a reference link to the vulnerability description

--- src/NugetAuditor/NugetAuditor.VSIX/NugetAuditManager.cs
+++ src/NugetAuditor/NugetAuditor.VSIX/NugetAuditManager.cs
@@ -248,7 +248,7 @@
                             {
                                 Priority = affecting ? TaskPriority.Normal : TaskPriority.Low,
                                 ErrorCategory = affecting ? TaskErrorCategory.Error : TaskErrorCategory.Message,
-                                Text = string.Format("{0}: {1}\n{2}", packageReference.PackageId, vulnerability.Title, vulnerability.Description),
+                                Text = string.Format("{0}: {1}\nReference: https://ossindex.net/resource/vulnerability/{2}\n{3}", packageReference.PackageId, vulnerability.Title, vulnerability.Id, vulnerability.Description),
                                 HierarchyItem = projectHierarchy,
                                 Category = TaskCategory.Misc,
                                 Document = packageReference.File,


bug: fixed Zero bug pointed out by Andriy

--- src/Numerics/LinearAlgebra/Generic/Matrix.Arithmetic.cs
+++ src/Numerics/LinearAlgebra/Generic/Matrix.Arithmetic.cs
@@ -174,7 +174,7 @@
                 return Clone();
             }

-            if (scalar.Equals(0.0))
+            if (scalar.Equals(Zero))
             {
                 return CreateMatrix(RowCount, ColumnCount);
             }
@@ -236,7 +236,7 @@
                 return Clone();
             }

-            if (scalar.Equals(0.0))
+            if (scalar.Equals(Zero))
             {
                 throw new DivideByZeroException();
             }
@@ -276,7 +276,7 @@
                 return;
             }

-            if (scalar.Equals(0.0))
+            if (scalar.Equals(Zero))
             {
                 throw new DivideByZeroException();
             }
@@ -1026,8 +1026,7 @@
         /// <remarks>The condition number is calculated using singular value decomposition.</remarks>
         public virtual T ConditionNumber()
         {
-            throw new NotImplementedException();
-            //return Svd<T>.Create(this, false).ConditionNumber;
+            return Svd<T>.Create(this, false).ConditionNumber;
         }

         /// <summary>Computes the determinant of this matrix.</summary>


Patching SO when running title migrations

--- src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs
+++ src/OrchardCore.Modules/OrchardCore.Title/Migrations.cs
@@ -45,11 +45,11 @@
             // We are patching all content item versions by moving the Title to DisplayText
             // This step doesn't need to be executed for a brand new site

-            var lastDodcumentId = 0;
+            var lastDocumentId = 0;

             for(;;)
             {
-                var contentItemVersions = await _session.Query<ContentItem, ContentItemIndex>(x => x.DocumentId > lastDodcumentId).Take(10).ListAsync();
+                var contentItemVersions = await _session.Query<ContentItem, ContentItemIndex>(x => x.DocumentId > lastDocumentId).Take(10).ListAsync();

                 if (!contentItemVersions.Any())
                 {
@@ -59,13 +59,14 @@

                 foreach(var contentItemVersion in contentItemVersions)
                 {
-                    if (UpdateTitleAndBody(contentItemVersion.Content))
+                    if (String.IsNullOrEmpty(contentItemVersion.DisplayText)
+                        && UpdateTitleAndBody(contentItemVersion.Content))
                     {
                         _session.Save(contentItemVersion);
                         _logger.LogInformation($"A content item version's Title was upgraded: '{contentItemVersion.ContentItemVersionId}'");
                     }

-                    lastDodcumentId = contentItemVersion.Id;
+                    lastDocumentId = contentItemVersion.Id;
                 }

                 await _session.CommitAsync();


More efficient and logical assembly search


Expand the scope of duplicate item name disabling when moving and renaming

This is needed for https://github.com/kamsar/Unicorn/commit/87b0f6a64add96d6d021ef26a1a1b9247479e947 which causes YAML items to be reflected back to the data store, and calling GetChildren() on them would trigger the dupe detection.

Ref: https://github.com/kamsar/Unicorn/issues/209

--- src/Rainbow/Storage/SerializationFileSystemDataStore.cs
+++ src/Rainbow/Storage/SerializationFileSystemDataStore.cs
@@ -104,13 +104,13 @@

 						// if we saved an item that was a former child of the item we want to keep it when we're doing deletions
 						if (oldPathItemAndDescendants.ContainsKey(savedPath)) oldPathItemAndDescendants.Remove(savedPath);
-					}
-
-					var children = parent.GetChildren();
-
-					foreach (var child in children)
-					{
-						saveQueue.Enqueue(child);
+
+						var children = parent.GetChildren();
+
+						foreach (var child in children)
+						{
+							saveQueue.Enqueue(child);
+						}
 					}
 				}
 			}


Open .csx from any location file using RoslynPad #222 - Adding `OpenDocumentFromCommentLine` method, check file exists

--- src/RoslynPad.Common.UI/ViewModels/MainViewModelBase.cs
+++ src/RoslynPad.Common.UI/ViewModels/MainViewModelBase.cs
@@ -115,6 +115,7 @@
                 RoslynHostReferences.Default.With(typeNamespaceImports: new[] { typeof(Runtime.ObjectExtensions) })))
                 .ConfigureAwait(true);

+            OpenDocumentFromCommandLine();
             await OpenAutoSavedDocuments().ConfigureAwait(true);

             if (HasCachedUpdate())
@@ -126,6 +127,32 @@
                 // ReSharper disable once UnusedVariable
                 var task = Task.Run(CheckForUpdates);
             }
+        }
+
+        private void OpenDocumentFromCommandLine()
+        {
+            var openDocument = GetOpenDocumentViewModel(null);
+
+            string[] args = Environment.GetCommandLineArgs();
+
+            if (args.Count() > 1)
+            {
+                string filePath = args[1];
+
+                if (File.Exists(filePath))
+                {
+                    var document = DocumentViewModel.FromPath(filePath);
+                    openDocument = GetOpenDocumentViewModel(document);
+                }
+            }
+
+            else
+            {
+                openDocument = GetOpenDocumentViewModel(null);
+            }
+
+            OpenDocuments.Add(openDocument);
+            CurrentOpenDocument = openDocument;
         }

         private async Task OpenAutoSavedDocuments()
@@ -352,20 +379,6 @@
         public void CreateNewDocument()
         {
             var openDocument = GetOpenDocumentViewModel(null);
-
-            string[] args = Environment.GetCommandLineArgs();
-
-            if(args.Count() > 1 && args[1] != null)
-            {
-                string filePath = args[1];
-                var document = DocumentViewModel.FromPath(filePath);
-                openDocument = GetOpenDocumentViewModel(document);
-            }
-
-            else
-            {
-                openDocument = GetOpenDocumentViewModel(null);
-            }

             OpenDocuments.Add(openDocument);
             CurrentOpenDocument = openDocument;


Update agreement view to render partial and have signed info at top

--- src/SFA.DAS.EAS.Web/Views/EmployerAgreement/View.cshtml
+++ src/SFA.DAS.EAS.Web/Views/EmployerAgreement/View.cshtml
@@ -5,24 +5,46 @@

 @model OrchestratorResponse<SFA.DAS.EAS.Web.ViewModels.EmployerAgreementViewModel>
 @{ViewBag.Title = "Employer agreement";}
-
-
+
+

+

+
@Model.Data.EmployerAgreement.LegalEntityName

+
Your SFA agreement

+

+

-

-
-
Employer agreement

-
@Model.Data.EmployerAgreement.LegalEntityName

-
@Model.Data.EmployerAgreement.LegalEntityAddress

-
@Html.Raw(Model.Data.EmployerAgreement.TemplatePartialViewName)

-
-

-

-            @section breadcrumb {
-

-

-
Home

-
Your organisations and agreements

-
Employer agreement

-

-

-            }
+

+

+

+                Accepted by:
+                @Model.Data.EmployerAgreement.SignedByName
+

+

+                On behalf of:
+                @Model.Data.EmployerAgreement.LegalEntityName
+

+

+                Address:
+                @Model.Data.EmployerAgreement.LegalEntityAddress
+

+

+                Accepted on:
+                @Model.Data.EmployerAgreement.SignedDate.Value.ToLongDateString()
+

+

+

+

+

+

+        @Html.Partial(Model.Data.EmployerAgreement.TemplatePartialViewName)
+

+

+@section breadcrumb {
+

+

+
Home

+
Your organisations and agreements

+
Employer agreement

+

+

+}


Update properties on WebAppSettings to be virtual for testing/mocking

--- src/Scissorhands.Core/Models/Settings/WebAppSettings.cs
+++ src/Scissorhands.Core/Models/Settings/WebAppSettings.cs
@@ -15,22 +15,22 @@
         /// <summary>
         /// Gets or sets the base URL of the website. eg) http://getscissorhands.net
         /// </summary>
-        public string BaseUrl { get; set; }
+        public virtual string BaseUrl { get; set; }

         /// <summary>
         /// Gets or sets the base path of the website. Trailing slash is optional. eg) /blog or /blog/
         /// </summary>
-        public string BasePath { get; set; }
+        public virtual string BasePath { get; set; }

         /// <summary>
         /// Gets or sets the list of <see cref="Author"/> objects.
         /// </summary>
-        public List<Author> Authors { get; set; }
+        public virtual List<Author> Authors { get; set; }

         /// <summary>
         /// Gets or sets the list of <see cref="FeedType"/> values.
         /// </summary>
-        public List<FeedType> FeedTypes { get; set; }
+        public virtual List<FeedType> FeedTypes { get; set; }

         /// <summary>
         /// Gets or sets the theme.


Small fix

Small fix

--- src/Squidex.Read.MongoDb/Contents/MongoContentEntity.cs
+++ src/Squidex.Read.MongoDb/Contents/MongoContentEntity.cs
@@ -26,6 +26,7 @@
 {
     public sealed class MongoContentEntity : MongoEntity, IContentEntity
     {
+        private const int MaxLength = 1024 * 1024;
         private ContentData contentData;

         [BsonRequired]
@@ -112,7 +113,14 @@
                 }
             }

-            return stringBuilder.ToString().Substring(1024 * 1024);
+            var result = stringBuilder.ToString();
+
+            if (result.Length > MaxLength)
+            {
+                result = result.Substring(MaxLength);
+            }
+
+            return result;
         }
     }
 }


Added more placeholder members to Utf8String

These are needed by consumers of the previous Utf8String

--- src/System.Text.Utf8/src/System/Text/Utf8/Utf8String.cs
+++ src/System.Text.Utf8/src/System/Text/Utf8/Utf8String.cs
@@ -1,20 +1,24 @@
 // Copyright (c) Microsoft. All rights reserved.
 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+using System;

 namespace System.Text
 {
     public struct Utf8String : IEquatable<Utf8String>, IComparable<Utf8String>
     {
+        static readonly Utf8String s_empty = new Utf8String(Array.Empty<byte>());
+
         byte[] _array;
         unsafe byte* _buffer;
-        int _bufferLength;
+        int _length;

         [CLSCompliant(false)]
         public unsafe Utf8String(byte* utf8, int length)
         {
             _array = null;
             _buffer = utf8;
-            _bufferLength = length;
+            _length = length;
         }

         public Utf8String(byte[] utf8)
@@ -23,28 +27,42 @@
             {
                 _buffer = null;
             }
-            _bufferLength = utf8.Length;
+            _length = utf8.Length;
             _array = utf8;
         }

-        public int Length { get { return _array == null ? _bufferLength : _array.Length; } }
+        public Utf8String(string utf16) : this(Encoding.UTF8.GetBytes(utf16))
+        {
+        }
+
+        public static Utf8String Empty
+        {
+            get { return s_empty; }
+        }
+
+        public int Length { get { return _length; } }

         public int CompareTo(Utf8String other) { throw new NotImplementedException(); }

-        public bool Equals(Utf8String other) {
+        public bool Equals(Utf8String other)
+        {
+            if (Length != other.Length)
+            {
+                return false;
+            }
+
             unsafe
             {
-                if (_buffer != null || other._buffer != null) {
+                if (_buffer != null || other._buffer != null)
+                {
                     throw new NotImplementedException();
                 }
             }

-            if(_array.Length != other._array.Length) {
-                return false;
-            }
-
-            for(int i=0; i<_array.Length; i++) {
-                if(_array[i] != other._array[i]) {
+            for (int i = 0; i < _array.Length; i++)
+            {
+                if (_array[i] != other._array[i])
+                {
                     return false;
                 }
             }
@@ -55,9 +73,49 @@

         public int CompareTo(string other) { throw new NotImplementedException(); }

-        public byte[] ToArray() { throw new NotImplementedException(); }
+        // operators
+        public static bool operator==(Utf8String left, Utf8String right) {
+            return left.Equals(right);
+        }
+        public static bool operator!=(Utf8String left, Utf8String right)
+        {
+            return !left.Equals(right);
+        }
+        public static bool operator ==(Utf8String left, string right)
+        {
+            return left.Equals(right);
+        }
+        public static bool operator !=(Utf8String left, string right)
+        {
+            return !left.Equals(right);
+        }
+        public static bool operator==(string left, Utf8String right)
+        {
+            return right.Equals(left);
+        }
+        public static bool operator !=(string left, Utf8String right)
+        {
+            return !right.Equals(left);
+        }

-        public override string ToString() { throw new NotImplementedException(); }
+        public byte[] CopyBytes() {
+            unsafe
+            {
+                if (_buffer != null) { throw new NotImplementedException(); }
+            }
+
+            var copy = new byte[_array.Length];
+            _array.CopyTo(copy, 0);
+            return copy;
+        }
+
+        public override string ToString() {
+            unsafe
+            {
+                if (_buffer != null) { throw new NotImplementedException(); }
+            }
+            return Encoding.UTF8.GetString(_array, 0, _array.Length);
+        }

         public override bool Equals(object obj)
         {
@@ -80,3 +138,4 @@
 }

+


Fix TaskStatusTests.TaskStatus3

Fix TaskStatusTests.TaskStatus3

Fixes #14839:
- This test is failing occasionally
- The parent task's status verification did not account for the child and parent tasks completing just before the verification

--- src/System.Threading.Tasks/tests/Task/TaskStatusTest.cs
+++ src/System.Threading.Tasks/tests/Task/TaskStatusTest.cs
@@ -172,11 +172,21 @@
                         {
                             //we may have reach this point too soon, let's keep spinning until the status changes.
                             while (_task.Status == TaskStatus.Running)
-                                ;
+                            {
+                                Task.Delay(1).Wait();
+                            }
+
                             //
-                            // If we're still waiting for children our Status should reflect so
+                            // If we're still waiting for children our Status should reflect so. For this verification, read the
+                            // parent task's status before the child task's status to make the child task's status more recent,
+                            // since the child task may complete during the status reads.
                             //
-                            if (_task.Status != TaskStatus.WaitingForChildrenToComplete)
+                            TaskStatus taskStatus = _task.Status;
+                            Interlocked.MemoryBarrier();
+                            TaskStatus childTaskStatus = _childTask.Status;
+                            if (taskStatus != TaskStatus.WaitingForChildrenToComplete &&
+                                childTaskStatus != TaskStatus.RanToCompletion &&
+                                childTaskStatus != TaskStatus.Faulted)
                             {
                                 Assert.True(false, string.Format("Expecting currrent Task status to be WaitingForChildren but getting {0}", _task.Status.ToString()));
                             }


Ajusts

Ajusts

--- src/TITcs.SharePoint.SSOM/ActiveDirectory/SearchUser.cs
+++ src/TITcs.SharePoint.SSOM/ActiveDirectory/SearchUser.cs
@@ -24,11 +24,11 @@

                     var principalSearcher = new PrincipalSearcher(userPrincipal);

-                    foreach (var found in principalSearcher.FindAll())
+                    foreach (var result in principalSearcher.FindAll())
                     {
-                        if (found is UserPrincipal)
+                        if (result is UserPrincipal)
                         {
-                            var foundUserPrincipal = (UserPrincipal) found;
+                            var foundUserPrincipal = (UserPrincipal) result;

                             var user = bindUser(foundUserPrincipal);

@@ -51,11 +51,11 @@

                     var principalSearcher = new PrincipalSearcher(userPrincipal);

-                    foreach (var found in principalSearcher.FindAll())
+                    foreach (var result in principalSearcher.FindAll())
                     {
-                        if (found is UserPrincipal)
+                        if (result is UserPrincipal)
                         {
-                            var foundUserPrincipal = (UserPrincipal)found;
+                            var foundUserPrincipal = (UserPrincipal)result;

                             var user = bindUser(foundUserPrincipal);

@@ -93,9 +93,9 @@
                 {
                     PrincipalSearcher principalSearcher = new PrincipalSearcher(groupPrincipal);

-                    var found = principalSearcher.FindAll().SingleOrDefault(i => i.Name == name);
+                    var result = principalSearcher.FindAll().SingleOrDefault(i => i.Name == name);

-                    var foundGroupPrincipal = (GroupPrincipal) found;
+                    var foundGroupPrincipal = (GroupPrincipal) result;

                     var group = new Group()
                     {


[tests] Enable and fix tests that failed on mono-osx

      Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.Miscellaneous.DefaultAllowedRelatedFileExtensionsAreUsed [FAIL]
      Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.Miscellaneous.NoFrameworkDirectoriesStillCopyLocal [FAIL]
      Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.Miscellaneous.InputAllowedRelatedFileExtensionsAreUsed [FAIL]

--- src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs
+++ src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs
@@ -813,7 +813,6 @@
         /// by default.
         /// </summary>
         [Fact]
-        [Trait("Category", "mono-osx-failing")]
         public void DefaultAllowedRelatedFileExtensionsAreUsed()
         {
             // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
@@ -827,7 +826,7 @@
             // Construct a list of assembly files.
             ITaskItem[] assemblies = new TaskItem[]
             {
-                new TaskItem(@"c:\AssemblyFolder\SomeAssembly.dll")
+                new TaskItem(s_assemblyFolder_SomeAssemblyDllPath)
             };

             // Now, pass feed resolved primary references into ResolveAssemblyReference.
@@ -840,7 +839,7 @@
             Execute(t);

             Assert.Equal(1, t.ResolvedFiles.Length);
-            Assert.True(t.ResolvedFiles[0].ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.dll"));
+            Assert.True(t.ResolvedFiles[0].ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.dll")));

             // Process the related files.
             Assert.Equal(3, t.RelatedFiles.Length);
@@ -851,15 +850,15 @@

             foreach (ITaskItem item in t.RelatedFiles)
             {
-                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.pdb"))
+                if (item.ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.pdb")))
                 {
                     pdbFound = true;
                 }
-                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.xml"))
+                if (item.ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.xml")))
                 {
                     xmlFound = true;
                 }
-                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.pri"))
+                if (item.ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.pri")))
                 {
                     priFound = true;
                 }
@@ -913,7 +912,6 @@
         /// RAR should use any given related file extensions.
         /// </summary>
         [Fact]
-        [Trait("Category", "mono-osx-failing")]
         public void InputAllowedRelatedFileExtensionsAreUsed()
         {
             // This WriteLine is a hack.  On a slow machine, the Tasks unittest fails because remoting
@@ -927,7 +925,7 @@
             // Construct a list of assembly files.
             ITaskItem[] assemblies = new TaskItem[]
             {
-                new TaskItem(@"c:\AssemblyFolder\SomeAssembly.dll")
+                new TaskItem(s_assemblyFolder_SomeAssemblyDllPath)
             };

             // Now, pass feed resolved primary references into ResolveAssemblyReference.
@@ -941,7 +939,7 @@
             Execute(t);

             Assert.Equal(1, t.ResolvedFiles.Length);
-            Assert.True(t.ResolvedFiles[0].ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.dll"));
+            Assert.True(t.ResolvedFiles[0].ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.dll")));

             // Process the related files.
             Assert.Equal(2, t.RelatedFiles.Length);
@@ -950,11 +948,11 @@
             bool xmlFound = false;
             foreach (ITaskItem item in t.RelatedFiles)
             {
-                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.licenses"))
+                if (item.ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.licenses")))
                 {
                     licensesFound = true;
                 }
-                if (item.ItemSpec.EndsWith(@"AssemblyFolder\SomeAssembly.xml"))
+                if (item.ItemSpec.EndsWith(Path.Combine("AssemblyFolder", "SomeAssembly.xml")))
                 {
                     xmlFound = true;
                 }
@@ -3517,7 +3515,6 @@
         /// If we have no framework directories passed in and an assembly is found outside of the GAC then it should be able to be copy local.
         /// </summary>
         [Fact]
-        [Trait("Category", "mono-osx-failing")]
         public void NoFrameworkDirectoriesStillCopyLocal()
         {
             // Create the engine.
@@ -3526,7 +3523,7 @@
             // Also construct a set of assembly names to pass in.
             ITaskItem[] assemblyNames = new TaskItem[]
             {
-                new TaskItem(@"C:\AssemblyFolder\SomeAssembly.dll"),
+                new TaskItem(s_assemblyFolder_SomeAssemblyDllPath)
             };

             // Now, pass feed resolved primary references into ResolveAssemblyReference.


Change FindRepetitionInterval to start with one previous encoding

--- osu.Game.Rulesets.Taiko/Difficulty/Preprocessing/Colour/Data/CoupledColourEncoding.cs
+++ osu.Game.Rulesets.Taiko/Difficulty/Preprocessing/Colour/Data/CoupledColourEncoding.cs
@@ -60,14 +60,14 @@
         /// </summary>
         public void FindRepetitionInterval()
         {
-            if (Previous?.Previous == null)
+            if (Previous == null)
             {
                 RepetitionInterval = max_repetition_interval + 1;
                 return;
             }

-            CoupledColourEncoding? other = Previous.Previous;
-            int interval = 2;
+            CoupledColourEncoding? other = Previous;
+            int interval = 1;

             while (interval < max_repetition_interval)
             {


Fix unauth'd / requests failing on non-browsers

--- src/Tgstation.Server.Host/Controllers/HomeController.cs
+++ src/Tgstation.Server.Host/Controllers/HomeController.cs
@@ -109,8 +109,7 @@
 				  databaseContext,
 				  authenticationContextFactory,
 				  logger,
-				  (browserResolver ?? throw new ArgumentNullException(nameof(browserResolver))).Browser.Type != BrowserType.Generic
-				  && !(controlPanelConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(controlPanelConfigurationOptions))).Enable)
+				  false)
 		{
 			this.tokenFactory = tokenFactory ?? throw new ArgumentNullException(nameof(tokenFactory));
 			this.systemIdentityFactory = systemIdentityFactory ?? throw new ArgumentNullException(nameof(systemIdentityFactory));


Fix user controller includes

Fix user controller includes

--- src/Tgstation.Server.Host/Controllers/UserController.cs
+++ src/Tgstation.Server.Host/Controllers/UserController.cs
@@ -225,6 +225,7 @@
 					.Include(x => x.CreatedBy)
 					.Include(x => x.OAuthConnections)
 					.Include(x => x.Group)
+						.ThenInclude(x => x.PermissionSet)
 					.Include(x => x.PermissionSet)
 					.FirstOrDefaultAsync(cancellationToken)
 					.ConfigureAwait(false);
@@ -375,8 +376,10 @@
 							.AsQueryable()
 							.Where(x => x.CanonicalName != Models.User.CanonicalizeName(Models.User.TgsSystemUserName))
 							.Include(x => x.CreatedBy)
+							.Include(x => x.PermissionSet)
 							.Include(x => x.OAuthConnections)
-							.Include(x => x.Group))),
+							.Include(x => x.Group)
+								.ThenInclude(x => x.PermissionSet))),
 				null,
 				page,
 				pageSize,
@@ -408,6 +411,8 @@
 				.Include(x => x.CreatedBy)
 				.Include(x => x.OAuthConnections)
 				.Include(x => x.Group)
+					.ThenInclude(x => x.PermissionSet)
+				.Include(x => x.PermissionSet)
 				.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
 			if (user == default)
 				return NotFound();


Remove test paths to umbraco_client - makes no sense to test for this path as it no longer exists

--- src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs
+++ src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs
@@ -67,8 +67,6 @@
             Assert.IsTrue(globalSettings.IsReservedPathOrUrl(url));
         }

-        [TestCase("/umbraco_client/Tree/treeIcons.css")]
-        [TestCase("/umbraco_client/Tree/Themes/umbraco/style.css")]
         [TestCase("/base/somebasehandler")]
         [TestCase("/")]
         [TestCase("/home.aspx")]


Add glimpse back to musicStore

Add glimpse back to musicStore

--- sample/MusicStore/Startup.cs
+++ sample/MusicStore/Startup.cs
@@ -35,7 +35,7 @@

         public void ConfigureServices(IServiceCollection services)
         {
-            //services.AddGlimpse();
+            services.AddGlimpse();

             services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

@@ -99,7 +99,7 @@
         //The allowed values are Development,Staging and Production
         public void ConfigureDevelopment(IApplicationBuilder app, ILoggerFactory loggerFactory)
         {
-            //app.UseGlimpse();
+            app.UseGlimpse();

             loggerFactory.AddConsole(minLevel: LogLevel.Information);

@@ -119,7 +119,7 @@
         //The allowed values are Development,Staging and Production
         public void ConfigureStaging(IApplicationBuilder app, ILoggerFactory loggerFactory)
         {
-            //app.UseGlimpse();
+            app.UseGlimpse();

             loggerFactory.AddConsole(minLevel: LogLevel.Warning);

@@ -135,7 +135,7 @@
         //The allowed values are Development,Staging and Production
         public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory)
         {
-            //app.UseGlimpse();
+            app.UseGlimpse();

             loggerFactory.AddConsole(minLevel: LogLevel.Warning);


Behold the power of Modulus!

Behold the power of Modulus!

The remainder of the division of the x/y over the chunk dimensions is
the location of the x/y in the chunk.


Remove unnecessary file

Remove unnecessary file


Download the latest nuget package - Delete file after download

--- src/test/Test.FAKECore/NugetFeed/FeedSpecs.cs
+++ src/test/Test.FAKECore/NugetFeed/FeedSpecs.cs
@@ -46,6 +46,10 @@
         Establish context = () => _package = NuGetHelper.getLatestPackage(NuGetHelper.getRepoUrl(), "FAKE");
         Because of = () => _fileName = NuGetHelper.downloadPackage(NugetData.OutputDir, _package);

-        It should_have_downloaded_the_file = () => File.Exists(_fileName).ShouldBeTrue();
+        It should_have_downloaded_the_file = () =>
+        {
+            File.Exists(_fileName).ShouldBeTrue();
+            File.Delete(_fileName);
+        };
     }
 }


Port to winRT

Port to winRT

--- cocos2d/Win8IOExtensions.cs
+++ cocos2d/Win8IOExtensions.cs
@@ -30,3 +30,13 @@
 		}
 	}
 }
+namespace System {
+    public class Console {
+        public static void WriteLine(string message) {
+            System.Diagnostics.Debug.WriteLine(message);
+        }
+        public static void WriteLine(string message, params object[] args){
+            System.Diagnostics.Debug.WriteLine(message, args);
+        }
+    }
+}


Just changed the warning in case no API key

--- GoogleMapsApi.Test/IntegrationTests/BaseTestIntegration.cs
+++ GoogleMapsApi.Test/IntegrationTests/BaseTestIntegration.cs
@@ -3,7 +3,7 @@

 namespace GoogleMapsApi.Test.IntegrationTests
 {
-    //  Note:	The tests below run against the real Google API web
+    //  Note:	The integration tests run against the real Google API web
     //			servers and count towards your query limit. Also, the tests
     //			require a working internet connection in order to pass.
     //			Their run time may vary depending on your connection,
@@ -19,7 +19,7 @@
             {
                 if (string.IsNullOrWhiteSpace(apiKey))
                 {
-                    Assert.Inconclusive("API key not specified");
+                    Assert.Inconclusive("API key not specified, please set it in the 'app.config' file");
                 }

                 return apiKey;
@@ -27,16 +27,10 @@
             private set { apiKey = value; }
         }

-

-        public BaseTestIntegration()
+        protected BaseTestIntegration()
         {
             ApiKey = ConfigurationManager.AppSettings["ApiKey"];
-
         }
-
-
     }
-
-
 }


Add workaround for AggInputMethod mouse events

--- PlatformWin32/win32/HookWindowsInputAndSendToWidget.cs
+++ PlatformWin32/win32/HookWindowsInputAndSendToWidget.cs
@@ -7,6 +7,7 @@
 	public class HookWindowsInputAndSendToWidget
 	{
 		protected WidgetForWindowsFormsAbstract widgetToSendTo;
+		public static bool EnableInputHook = true;

 		public HookWindowsInputAndSendToWidget(ContainerControl controlToHook, WidgetForWindowsFormsAbstract widgetToSendTo)
 		{
@@ -98,6 +99,12 @@

 		private void formToHook_MouseMove(object sender, System.Windows.Forms.MouseEventArgs windowsMouseEvent)
 		{
+			// TODO: Remove short term workaround for automation issues where mouse events fire differently if mouse is within window region
+			if (!EnableInputHook)
+			{
+				return;
+			}
+
 			widgetToSendTo.OnMouseMove(ConvertWindowsMouseEventToAggMouseEvent(windowsMouseEvent));
 		}


Refactoring.

Refactoring.

--- ProgramSynthesis/ProseFunctions/Spg.Witness/Context.cs
+++ ProgramSynthesis/ProseFunctions/Spg.Witness/Context.cs
@@ -1,13 +1,10 @@
 using System.Collections.Generic;
 using System.Linq;
-using System.Windows.Forms;
 using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
 using Microsoft.ProgramSynthesis;
 using Microsoft.ProgramSynthesis.Rules;
 using Microsoft.ProgramSynthesis.Specifications;
 using ProseFunctions.Spg.Bean;
-using ProseFunctions.Substrings;
 using TreeEdit.Spg.Match;
 using TreeEdit.Spg.TreeEdit.Update;
 using TreeElement.Spg.Node;


Mouse cursor hidden

Mouse cursor hidden

--- Project/Basketball/Assets/Scripts/GameManagerScript.cs
+++ Project/Basketball/Assets/Scripts/GameManagerScript.cs
@@ -15,6 +15,7 @@
 		scorePlayer1 = 0;
 		scorePlayer2 = 0;
 		scoreText.SetScores(scorePlayer1, scorePlayer2);
+		Cursor.visible = false;

 	}


refactoring

refactoring

--- HCsbLib/HCsbLib/HTLib2.Mathematica/Mathematica.ToString.cs
+++ HCsbLib/HCsbLib/HTLib2.Mathematica/Mathematica.ToString.cs
@@ -16,6 +16,12 @@
                 return _ToString(null, objs[0]);
             return _ToString(null, (IEnumerable<object>)objs);
         }
+        public static string ToString(string format, params object[] objs)
+        {
+            if(objs.Length == 1)
+                return _ToString(format, objs[0]);
+            return _ToString(format, (IEnumerable<object>)objs);
+        }
         public static string ToString_Nearest<T, U>(IEnumerable<KeyValuePair<T,U>> objs, bool ignore_null)
         {
             StringBuilder text = new StringBuilder();
@@ -51,6 +57,10 @@
         public static string ToString(object obj)
         {
             return _ToString(null, obj);
+        }
+        public static string ToString(string format, object obj)
+        {
+            return _ToString(format, obj);
         }
         public static string ToString<T>(T[] objs)
         {
@@ -74,7 +84,7 @@
                 {
                     if(addcomma) text.Append(", ");
                     else addcomma = true;
-                    text.Append(_ToString(null, obj));
+                    text.Append(_ToString(format, obj));
                 }
             text.Append("}");
             return text.ToString();
@@ -94,7 +104,7 @@
                 for(int j=0; j<objs.GetLength(1); j++)
                 {
                     if(j != 0) text.Append(", ");
-                    text.Append(_ToString(null, objs[i, j]));
+                    text.Append(_ToString(format, objs[i, j]));
                 }
                 text.Append("}");
             }
@@ -116,7 +126,7 @@
                     for(int k=0; k<objs.GetLength(2); k++)
                     {
                         if(k != 0) text.Append(", ");
-                        text.Append(_ToString(null, objs[i, j, k]));
+                        text.Append(_ToString(format, objs[i, j, k]));
                     }
                     text.Append("}");
                 }
@@ -149,9 +159,9 @@
             HDebug.Assert(delims.Length == 3);
             StringBuilder text = new StringBuilder();
             text.Append(delims[0]);
-            text.Append(_ToString(null, obj.Key));
+            text.Append(_ToString(format, obj.Key));
             text.Append(delims[1]);
-            text.Append(_ToString(null, obj.Value));
+            text.Append(_ToString(format, obj.Value));
             text.Append(delims[2]);
             return text.ToString();
         }


linting fixes.

linting fixes.

linting fixes.

--- dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs
+++ dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs
@@ -81,7 +81,7 @@
             var parameterGroup = await CreateDbParameterGroup(parameterGroupFamily);

             var parameters = await DescribeParametersInGroup(parameterGroup.DBParameterGroupName,
-                new List<string>(){ "auto_increment_offset", "auto_increment_increment" });
+                new List<string>{"auto_increment_offset", "auto_increment_increment"});

             await ModifyParameters(parameterGroup.DBParameterGroupName, parameters);


NTFS: Fix encoding of Zero in DataRuns - store a zero byte, not zero length.

--- src/Ntfs/DataRun.cs
+++ src/Ntfs/DataRun.cs
@@ -115,20 +115,15 @@

         private static int WriteVarLong(byte[] buffer, int offset, long val)
         {
-            bool isPositive = val > 0;
+            bool isPositive = val >= 0;

             int pos = 0;
-            while (val != 0)
+            do
             {
                 buffer[offset + pos] = (byte)(val & 0xFF);
                 val >>= 8;
                 pos++;
-
-                if (val == -1L)
-                {
-                    break;
-                }
-            }
+            } while (val != 0 && val != -1);

             // Avoid appearing to have a negative number that is actually positive,
             // record an extra empty byte if needed.
@@ -148,21 +143,17 @@

         private static int VarLongSize(long val)
         {
-            bool isPositive = val > 0;
+            bool isPositive = val >= 0;
             bool lastByteHighBitSet = false;

             int len = 0;
-            while (val != 0)
+            do
             {
                 lastByteHighBitSet = ((val & 0x80) != 0);
                 val >>= 8;
                 len++;
+            } while (val != 0 && val != -1) ;

-                if (val == -1L)
-                {
-                    break;
-                }
-            }

             if ((isPositive && lastByteHighBitSet) || (!isPositive && !lastByteHighBitSet))
             {


Use autoprops and expression-bodied properties

--- src/VisualStudio/Core/SolutionExplorerShim/AnalyzersFolderItem/AnalyzersFolderItem.cs
+++ src/VisualStudio/Core/SolutionExplorerShim/AnalyzersFolderItem/AnalyzersFolderItem.cs
@@ -2,7 +2,6 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.

-using System.Linq;
 using Microsoft.CodeAnalysis;
 using Microsoft.Internal.VisualStudio.PlatformUI;
 using Microsoft.VisualStudio.Imaging;
@@ -18,9 +17,6 @@

     internal partial class AnalyzersFolderItem : BaseItem
     {
-        private readonly Workspace _workspace;
-        private readonly ProjectId _projectId;
-        private readonly IVsHierarchyItem _parentItem;
         private readonly IContextMenuController _contextMenuController;

         public AnalyzersFolderItem(
@@ -30,42 +26,20 @@
             IContextMenuController contextMenuController)
             : base(SolutionExplorerShim.Analyzers)
         {
-            _workspace = workspace;
-            _projectId = projectId;
-            _parentItem = parentItem;
+            Workspace = workspace;
+            ProjectId = projectId;
+            ParentItem = parentItem;
             _contextMenuController = contextMenuController;
         }

-        public override ImageMoniker IconMoniker
-        {
-            get
-            {
-                return KnownMonikers.CodeInformation;
-            }
-        }
+        public override ImageMoniker IconMoniker => KnownMonikers.CodeInformation;
+        public override ImageMoniker ExpandedIconMoniker => KnownMonikers.CodeInformation;

-        public override ImageMoniker ExpandedIconMoniker
-        {
-            get
-            {
-                return KnownMonikers.CodeInformation;
-            }
-        }
+        public Workspace Workspace { get; }

-        public Workspace Workspace
-        {
-            get { return _workspace; }
-        }
+        public ProjectId ProjectId { get; }

-        public ProjectId ProjectId
-        {
-            get { return _projectId; }
-        }
-
-        public IVsHierarchyItem ParentItem
-        {
-            get { return _parentItem; }
-        }
+        public IVsHierarchyItem ParentItem { get; }

         public override object GetBrowseObject()
         {
@@ -82,13 +56,13 @@
         /// </summary>
         private VSProject3? GetVSProject()
         {
-            var vsWorkspace = _workspace as VisualStudioWorkspace;
+            var vsWorkspace = Workspace as VisualStudioWorkspace;
             if (vsWorkspace == null)
             {
                 return null;
             }

-            var hierarchy = vsWorkspace.GetHierarchy(_projectId);
+            var hierarchy = vsWorkspace.GetHierarchy(ProjectId);
             if (hierarchy == null)
             {
                 return null;


Fix null ref in C# expander when adding cast to lambda return statement

Fixes #9576

In the C# expander, we added a step to expand return statement expressions within lambda bodies to aid in conflict resolution for refactoring. However, we failed to account for the fact that lambda return statements can legally have no expression. A simple null-ref is all that's necessary to fix the crash.

Note: This bug was introduced (by me!) in #6432. It was not included in Update 1, so this is a newly-introduced regression in Update 2.

--- src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs
+++ src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs
@@ -141,17 +141,19 @@
                 if (newNode is ReturnStatementSyntax)
                 {
                     var newReturnStatement = (ReturnStatementSyntax)newNode;
-
-                    var parentLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>();
-                    if (parentLambda != null)
-                    {
-                        var returnType = (_semanticModel.GetSymbolInfo(parentLambda).Symbol as IMethodSymbol)?.ReturnType;
-                        if (returnType != null)
-                        {
-                            ExpressionSyntax newExpressionWithCast;
-                            if (TryCastTo(returnType, node.Expression, newReturnStatement.Expression, out newExpressionWithCast))
+                    if (newReturnStatement.Expression != null)
+                    {
+                        var parentLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>();
+                        if (parentLambda != null)
+                        {
+                            var returnType = (_semanticModel.GetSymbolInfo(parentLambda).Symbol as IMethodSymbol)?.ReturnType;
+                            if (returnType != null)
                             {
-                                newNode = newReturnStatement.WithExpression(newExpressionWithCast);
+                                ExpressionSyntax newExpressionWithCast;
+                                if (TryCastTo(returnType, node.Expression, newReturnStatement.Expression, out newExpressionWithCast))
+                                {
+                                    newNode = newReturnStatement.WithExpression(newExpressionWithCast);
+                                }
                             }
                         }
                     }


Remove extension

Remove extension

--- src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs
+++ src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/TaskExtensions.cs
@@ -191,23 +191,6 @@
         [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
         public static Task<TNResult> ContinueWithAfterDelay<TNResult>(
             this Task task,
-            Func<TNResult> continuationFunction,
-            CancellationToken cancellationToken,
-            int millisecondsDelay,
-            TaskContinuationOptions taskContinuationOptions,
-            TaskScheduler scheduler)
-        {
-            Contract.ThrowIfNull(continuationFunction, nameof(continuationFunction));
-
-            return task.SafeContinueWith(t =>
-                Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith(
-                    _ => continuationFunction(), cancellationToken, TaskContinuationOptions.None, scheduler),
-                cancellationToken, taskContinuationOptions, scheduler).Unwrap();
-        }
-
-        [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method.")]
-        public static Task<TNResult> ContinueWithAfterDelay<TNResult>(
-            this Task task,
             Func<Task, TNResult> continuationFunction,
             CancellationToken cancellationToken,
             int millisecondsDelay,


Revert "Use dot instead of dash to separate build metadata"

This reverts commit 9567abb6ce15b29cc59ab36c0172d31aa9c661fe.

--- build/version.cake
+++ build/version.cake
@@ -14,7 +14,7 @@
         var vsixVersion = gitVersion.MajorMinorPatch;

         if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
-            semVersion += "." + gitVersion.BuildMetaData;
+            semVersion += "-" + gitVersion.BuildMetaData;
             vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
         }


Implemented nestable locking and delegated impersonation to the locking model.

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

--- src/Appender/FileAppender.cs
+++ src/Appender/FileAppender.cs
@@ -88,6 +88,8 @@

 			private Stream m_realStream=null;
 			private LockingModelBase m_lockingModel=null;
+			private int m_readTotal=-1;
+			private int m_lockLevel=0;

 			public LockingStream(LockingModelBase locking) : base()
 			{
@@ -103,7 +105,10 @@
 			// Methods
 			public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 			{
-				throw new NotSupportedException("Read operations are not supported on the LockingStream");
+				AssertLocked();
+				IAsyncResult ret=m_realStream.BeginRead(buffer,offset,count,callback,state);
+				m_readTotal=EndRead(ret);
+				return ret;
 			}

 			/// <summary>
@@ -124,12 +129,12 @@

 			public override int EndRead(IAsyncResult asyncResult)
 			{
-				throw new NotSupportedException("Read operations are not supported on the LockingStream");
+				AssertLocked();
+				return m_readTotal;
 			}
 			public override void EndWrite(IAsyncResult asyncResult)
 			{
-				AssertLocked();
-				m_realStream.EndWrite(asyncResult);
+				//No-op, it's already been handled
 			}
 			public override void Flush()
 			{
@@ -138,11 +143,11 @@
 			}
 			public override int Read(byte[] buffer, int offset, int count)
 			{
-				throw new NotSupportedException("Read operations are not supported on the LockingStream");
+				return m_realStream.Read(buffer,offset,count);
 			}
 			public override int ReadByte()
 			{
-				throw new NotSupportedException("Read operations are not supported on the LockingStream");
+				return m_realStream.ReadByte();
 			}
 			public override long Seek(long offset, SeekOrigin origin)
 			{
@@ -224,23 +229,31 @@
 				}
 			}

-			public void AcquireLock()
-			{
+			public bool AcquireLock()
+			{
+				bool ret=false;
 				lock(this)
 				{
-					if (m_realStream == null)
+					if (m_lockLevel==0)
 					{
 						// If lock is already acquired, nop
 						m_realStream=m_lockingModel.AcquireLock();
 					}
-				}
+					if (m_realStream!=null)
+					{
+						m_lockLevel++;
+						ret=true;
+					}
+				}
+				return ret;
 			}

 			public void ReleaseLock()
 			{
 				lock(this)
 				{
-					if (m_realStream != null)
+					m_lockLevel--;
+					if (m_lockLevel==0)
 					{
 						// If already unlocked, nop
 						m_lockingModel.ReleaseLock();
@@ -266,7 +279,7 @@
 		/// </remarks>
 		public abstract class LockingModelBase
 		{
-			private IErrorHandler m_errorHandler=null;
+			private FileAppender m_appender=null;

 			/// <summary>
 			/// Open the output file
@@ -319,34 +332,12 @@
 			public abstract void ReleaseLock();

 			/// <summary>
-			/// Gets or sets the <see cref="IErrorHandler"/> for this appender.
-			/// </summary>
-			/// <value>The <see cref="IErrorHandler"/> of the appender</value>
-			/// <remarks>
-			/// <para>
-			/// The <see cref="AppenderSkeleton"/> provides a default
-			/// implementation for the <see cref="ErrorHandler"/> property.
-			/// </para>
-			/// </remarks>
-			virtual public IErrorHandler ErrorHandler
-			{
-				get { return this.m_errorHandler; }
-				set
-				{
-					lock(this)
-					{
-						if (value == null)
-						{
-							// We do not throw exception here since the cause is probably a
-							// bad config file.
-							LogLog.Warn("AppenderSkeleton: You have tried to set a null error-handler.");
-						}
-						else
-						{
-							m_errorHandler = value;
-						}
-					}
-				}
+			/// The appender we are related to. Used to identify the security context to work within, and the error handler to use.
+			/// </summary>
+			public FileAppender CurrentAppender
+			{
+				get { return m_appender; }
+				set { m_appender=value; }
 			}
 		}

@@ -381,22 +372,25 @@
 			{
 				try
 				{
-					// Ensure that the directory structure exists
-					string directoryFullName = Path.GetDirectoryName(filename);
-
-					// Only create the directory if it does not exist
-					// doing this check here resolves some permissions failures
-					if (!Directory.Exists(directoryFullName))
+					using(CurrentAppender.SecurityContext.Impersonate(this))
 					{
-						Directory.CreateDirectory(directoryFullName);
+						// Ensure that the directory structure exists
+						string directoryFullName = Path.GetDirectoryName(filename);
+
+						// Only create the directory if it does not exist
+						// doing this check here resolves some permissions failures
+						if (!Directory.Exists(directoryFullName))
+						{
+							Directory.CreateDirectory(directoryFullName);
+						}
+
+						FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create;
+						m_stream = new FileStream(filename, fileOpenMode, FileAccess.Write, FileShare.Read);
 					}
-
-					FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create;
-					m_stream = new FileStream(filename, fileOpenMode, FileAccess.Write, FileShare.Read);
 				}
 				catch (Exception e1)
 				{
-					ErrorHandler.Error("Unable to acquire lock on file "+filename+". "+e1.Message);
+					CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+filename+". "+e1.Message);
 				}
 			}

@@ -410,7 +404,10 @@
 			/// </remarks>
 			public override void CloseFile()
 			{
-				m_stream.Close();
+				using(CurrentAppender.SecurityContext.Impersonate(this))
+				{
+					m_stream.Close();
+				}
 			}

 			/// <summary>
@@ -508,23 +505,26 @@
 				{
 					try
 					{
-						// Ensure that the directory structure exists
-						string directoryFullName = Path.GetDirectoryName(m_filename);
-
-						// Only create the directory if it does not exist
-						// doing this check here resolves some permissions failures
-						if (!Directory.Exists(directoryFullName))
+						using(CurrentAppender.SecurityContext.Impersonate(this))
 						{
-							Directory.CreateDirectory(directoryFullName);
+							// Ensure that the directory structure exists
+							string directoryFullName = Path.GetDirectoryName(m_filename);
+
+							// Only create the directory if it does not exist
+							// doing this check here resolves some permissions failures
+							if (!Directory.Exists(directoryFullName))
+							{
+								Directory.CreateDirectory(directoryFullName);
+							}
+
+							FileMode fileOpenMode = m_append ? FileMode.Append : FileMode.Create;
+							m_stream = new FileStream(m_filename, fileOpenMode, FileAccess.Write, FileShare.Read);
+							m_append=true;
 						}
-
-						FileMode fileOpenMode = m_append ? FileMode.Append : FileMode.Create;
-						m_stream = new FileStream(m_filename, fileOpenMode, FileAccess.Write, FileShare.Read);
-						m_append=true;
 					}
 					catch (Exception e1)
 					{
-						ErrorHandler.Error("Unable to acquire lock on file "+m_filename+". "+e1.Message);
+						CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+m_filename+". "+e1.Message);
 					}
 				}
 				return m_stream;
@@ -541,8 +541,11 @@
 			/// </remarks>
 			public override void ReleaseLock()
 			{
-				m_stream.Close();
-				m_stream=null;
+				using(CurrentAppender.SecurityContext.Impersonate(this))
+				{
+					m_stream.Close();
+					m_stream=null;
+				}
 			}
 		}

@@ -740,7 +743,7 @@
 				m_lockingModel = new FileAppender.ExclusiveLock();
 			}

-			m_lockingModel.ErrorHandler = this.ErrorHandler;
+			m_lockingModel.CurrentAppender=this;

 			using(SecurityContext.Impersonate(this))
 			{
@@ -806,14 +809,16 @@
 		/// </remarks>
 		override protected void Append(LoggingEvent loggingEvent)
 		{
-			m_stream.AcquireLock();
-			try
-			{
-				base.Append(loggingEvent);
-			}
-			finally
-			{
-				m_stream.ReleaseLock();
+			if (m_stream.AcquireLock())
+			{
+				try
+				{
+					base.Append(loggingEvent);
+				}
+				finally
+				{
+					m_stream.ReleaseLock();
+				}
 			}
 		}

@@ -854,14 +859,16 @@
 		{
 			if (m_stream!=null)
 			{
-				m_stream.AcquireLock();
-				try
-				{
-					base.WriteHeader();
-				}
-				finally
-				{
-					m_stream.ReleaseLock();
+				if (m_stream.AcquireLock())
+				{
+					try
+					{
+						base.WriteHeader();
+					}
+					finally
+					{
+						m_stream.ReleaseLock();
+					}
 				}
 			}
 		}
@@ -976,12 +983,9 @@
 				m_fileName = fileName;
 				m_appendToFile = append;

-				using(SecurityContext.Impersonate(this))
-				{
-					LockingModel.ErrorHandler=this.ErrorHandler;
-					LockingModel.OpenFile(fileName,append,m_encoding);
-					m_stream=new LockingStream(LockingModel);
-				}
+				LockingModel.CurrentAppender=this;
+				LockingModel.OpenFile(fileName,append,m_encoding);
+				m_stream=new LockingStream(LockingModel);

 				if (m_stream != null)
 				{


Modulo MIDISendSysex, MidiServices is done

--- src/CoreMidi/MidiServices.cs
+++ src/CoreMidi/MidiServices.cs
@@ -20,12 +20,6 @@
 // MIDIObjectGetProperties -- needs cfpropertylist
 //
 // MIDISendSysex
-//
-// MIDIGetDestination
-// MIDIGetNumberOfDestinations
-// MIDIGetNumberOfSources
-// MIDIGetSource
-// MIDISourceCreate
 //
 //
 //
@@ -778,6 +772,10 @@
 		extern static int MIDIClientCreate (IntPtr str, MidiNotifyProc callback, IntPtr context, out IntPtr handle);
 		[DllImport (Constants.CoreMidiLibrary)]
 		extern static int MIDIClientDispose (IntPtr handle);
+
+		[DllImport (Constants.CoreMidiLibrary)]
+		extern static int MIDISourceCreate (IntPtr handle, IntPtr name, out IntPtr endpoint);
+
 		GCHandle gch;

 		internal override void DisposeHandle ()
@@ -807,6 +805,17 @@
 		public override string ToString ()
 		{
 			return Name;
+		}
+
+		public MidiEndpoint CreateVirtualSource (string name)
+		{
+			using (var nsstr = new NSString (name)){
+				IntPtr ret;
+				var code = MIDISourceCreate (handle, nsstr.Handle, out ret);
+				if (code != 0)
+					return null;
+				return new MidiEndpoint (ret);
+			}
 		}

 		public MidiPort CreateInputPort (string name)
@@ -1098,6 +1107,17 @@
 		[DllImport (Constants.CoreMidiLibrary)]
 		extern static MidiError MIDIReceived (IntPtr handle, IntPtr packetList);

+		[DllImport (Constants.CoreMidiLibrary)]
+		extern static IntPtr MIDIGetSource (int sourceIndex);
+
+		[DllImport (Constants.CoreMidiLibrary)]
+		extern static IntPtr MIDIGetDestination (int destinationIndex);
+
+		[DllImport (Constants.CoreMidiLibrary)]
+		extern static int MIDIGetNumberOfDestinations ();
+		[DllImport (Constants.CoreMidiLibrary)]
+		extern static int MIDIGetNumberOfSources ();
+
 		internal override void DisposeHandle ()
 		{
 			if (handle != IntPtr.Zero){
@@ -1112,6 +1132,40 @@
 		internal MidiEndpoint (IntPtr handle) : base (handle)
 		{
 			EndpointName = "Endpoint from Lookup";
+		}
+
+		internal MidiEndpoint (IntPtr handle, string endpointName) : base (handle)
+		{
+			EndpointName = endpointName;
+		}
+
+
+		public static MidiEndpoint GetSource (int sourceIndex)
+		{
+			var h = MIDIGetSource (sourceIndex);
+			if (h == IntPtr.Zero)
+				return null;
+			return new MidiEndpoint (h, "Source" + sourceIndex);
+		}
+
+		public static MidiEndpoint GetDestination (int destinationIndex)
+		{
+			var h = MIDIGetDestination (destinationIndex);
+			if (h == IntPtr.Zero)
+				return null;
+			return new MidiEndpoint (h, "Destination" + destinationIndex);
+		}
+
+		public static int DestinationCount {
+			get {
+				return MIDIGetNumberOfDestinations ();
+			}
+		}
+
+		public static int SourceCount {
+			get {
+				return MIDIGetNumberOfSources ();
+			}
 		}

 		internal MidiEndpoint (MidiClient client, string name)


Fix constructors and properties.

Fix constructors and properties.

--- Libraries/Forms/Sources/Behaviors/Lint/PathLintBehavior.cs
+++ Libraries/Forms/Sources/Behaviors/Lint/PathLintBehavior.cs
@@ -44,18 +44,36 @@
         /// the specified control.
         /// </summary>
         ///
-        /// <param name="src">Textbox control.</param>
-        ///
-        /* ----------------------------------------------------------------- */
-        public PathLintBehavior(TextBox src)
-        {
-            _tips.ToolTipTitle = "Path cannot contain any of the following characters";
-            _tips.IsBalloon    = false;
-            _tips.InitialDelay = 100;
-            _tips.ReshowDelay  = 100;
-            _tips.AutoPopDelay = 1000;
-
+        /// <param name="src">TextBox control.</param>
+        ///
+        /* ----------------------------------------------------------------- */
+        public PathLintBehavior(TextBox src) : this(src, new()
+        {
+            ToolTipTitle = "Path cannot contain any of the following characters",
+            IsBalloon    = false,
+            InitialDelay = 100,
+            ReshowDelay  = 100,
+            AutoPopDelay = 1000,
+        }) { }
+
+        /* ----------------------------------------------------------------- */
+        ///
+        /// PathLintBehavior
+        ///
+        /// <summary>
+        /// Initializes a new instance of the PathLintBehavior class with
+        /// the specified controls.
+        /// </summary>
+        ///
+        /// <param name="src">TextBox control.</param>
+        /// <param name="tips">ToolTip control.</param>
+        ///
+        /* ----------------------------------------------------------------- */
+        public PathLintBehavior(TextBox src, ToolTip tips)
+        {
             _source = src;
+            _tips   = tips;
+
             _source.TextChanged -= WhenTextChanged;
             _source.TextChanged += WhenTextChanged;
             _source.Click -= WhenClick;
@@ -70,14 +88,14 @@

         /* ----------------------------------------------------------------- */
         ///
-        /// Message
+        /// Text
         ///
         /// <summary>
         /// Get or set the message when entering an invalid character.
         /// </summary>
         ///
         /* ----------------------------------------------------------------- */
-        public string Message
+        public string Text
         {
             get => _tips.ToolTipTitle;
             set => _tips.ToolTipTitle = value;
@@ -182,7 +200,7 @@

         #region Fields
         private readonly TextBox _source;
-        private readonly ToolTip _tips = new();
+        private readonly ToolTip _tips;
         private bool _focus = false;
         #endregion
     }


Avoid resize

Avoid resize

--- LmpClient/Systems/VesselSyncSys/VesselSyncMessageSender.cs
+++ LmpClient/Systems/VesselSyncSys/VesselSyncMessageSender.cs
@@ -32,7 +32,7 @@
             }

             if (msgData.VesselIds.Length < msgData.VesselsCount)
-                Array.Resize(ref msgData.VesselIds, msgData.VesselsCount);
+                msgData.VesselIds = new Guid[msgData.VesselsCount];

             Array.Copy(vesselIds, msgData.VesselIds, msgData.VesselsCount);


changed dispose method - it was causing reshaper tests to hang

--- source/RedisInside/Redis.cs
+++ source/RedisInside/Redis.cs
@@ -1,6 +1,8 @@
 using System;
 using System.Diagnostics;
+using System.Net;
 using System.Text;
+using System.Threading.Tasks;
 using ElasticsearchInside.Executables;
 using PdfExtract;

@@ -41,34 +43,40 @@
             process.BeginOutputReadLine();
         }

-        public string Node
+        public EndPoint Endpoint
         {
-            get { return "127.0.0.1:" + config.port; }
+            get {return new IPEndPoint(IPAddress.Loopback, config.port);}
         }
-

         protected virtual void Dispose(bool disposing)
         {
             if (_disposed)
                 return;
+
+
             try
             {
+                process.CancelOutputRead();
                 process.Kill();
                 process.WaitForExit(2000);

-                if (executable != null)
+                if (disposing)
+                {
+                    process.Dispose();
                     executable.Dispose();
-
+                }
+
             }
             catch (Exception ex)
             {
                 config.logger.Invoke(ex.ToString());
             }
+
             _disposed = true;

         }

-         ~Redis()
+        ~Redis()
         {
             Dispose(false);
         }


Ensure test actually fails

Ensure test actually fails

--- tests/OmniSharp.DotNetTest.Tests/AbstractRunTestFacts.cs
+++ tests/OmniSharp.DotNetTest.Tests/AbstractRunTestFacts.cs
@@ -27,7 +27,7 @@

         public abstract bool UseLegacyDotNetCli { get; }

-        protected async Task RunDotNetTestAsync(string projectName, string methodName, string testFramework, bool shouldPass)
+        protected async Task<RunTestResponse> RunDotNetTestAsync(string projectName, string methodName, string testFramework, bool shouldPass, bool expectResults = true)
         {
             using (var testProject = await TestAssets.Instance.GetTestProjectAsync(projectName))
             using (var host = CreateOmniSharpHost(testProject.Directory, useLegacyDotNetCli: UseLegacyDotNetCli))
@@ -43,6 +43,11 @@

                 var response = await service.Handle(request);

+                if (expectResults)
+                {
+                    Assert.True(response.Results?.Length > 0, "Expected test to return results.");
+                }
+
                 if (shouldPass)
                 {
                     Assert.True(response.Pass, "Expected test to pass but it failed");
@@ -51,6 +56,8 @@
                 {
                     Assert.False(response.Pass, "Expected test to fail but it passed");
                 }
+
+                return response;
             }
         }
     }


Added misc tests

Added misc tests

--- tests/SoftwareEngineeringProblems.Tests/Problems/Misc.cs
+++ tests/SoftwareEngineeringProblems.Tests/Problems/Misc.cs
@@ -54,6 +54,7 @@
             foreach(var str in daStr) {
                 Assert.Equal(ans[i++], str);
             }
+            Assert.Throws<ArgumentOutOfRangeException>(() => daStr[10]);
         }

         [Fact]
@@ -107,6 +108,7 @@
             Assert.Equal(x.Find("two"), x.Last.Previous);
             Assert.Equal(x.FindLast("two"), x.Last.Previous);
             Assert.Equal(x.Find("xyz"), null);
+            Assert.True(x.First.Next.Previous == x.First);
         }

         [Fact]
@@ -160,5 +162,46 @@
             foreach(var v in x.Values)
                 Assert.True(ansVals.Contains(v));
         }
+
+        [Fact]
+        public void TestTextMisc()
+        {
+            Assert.Equal("ABCD", "A"+'B'+'C'+"D");
+            var ansChars = new char[]{'a', 'b', 'c', 'd'};
+            string str = "abcd";
+            var i = 0;
+            foreach(var c in str)
+            {
+                Assert.Equal(c, ansChars[i++]);
+            }
+            Assert.Equal(4, "dogs".Length);
+            Assert.Equal(4, ("d"+'o'+'c'+"g").Length);
+
+            Assert.True("" == "emptiness".Substring(9));
+            Assert.Throws<ArgumentOutOfRangeException>(
+                () => "emptiness".Substring(10));
+            Assert.Throws<ArgumentOutOfRangeException>(
+                () => "emptiness".Substring(2, 8));
+            Assert.True("" == "emptiness".Substring(0, 0));
+        }
+
+        [Fact]
+        public void TestArrayConstruction()
+        {
+            int[] x = new int[4];
+            var y = new int[4];
+            Assert.True(true);
+        }
+
+        [Fact]
+        public void TestStatementsMisc()
+        {
+            int[] data = null;
+            var i = 1;
+            if(data != null && i < data.Length && data[i] != -1)
+            {
+                Assert.True(false);
+            }
+        }
     }
 }


Remove some unneeded debug spew.

Remove some unneeded debug spew.

--- server/Mango.Server/IOLoop.cs
+++ server/Mango.Server/IOLoop.cs
@@ -52,7 +52,6 @@
 					break;

 				var new_events = Syscall.epoll_wait (epfd, timeout);
-				Console.WriteLine ("new events:  {0}  {1}", new_events, new_events.Length);
 				RunHandlers (new_events);
 			}
 			running = false;


Ignore leading whitespaces

Ignore leading whitespaces

--- source/xcite.clip/Parser.cs
+++ source/xcite.clip/Parser.cs
@@ -35,6 +35,10 @@
             if (optionTypes == null || optionTypes.Length == 0) throw new ArgumentNullException(nameof(optionTypes));
             if (args == null || args.Length == 0) return PrintUsageWithError("Missing arguments.", optionTypes, null);

+            const char whitespaceTk = ' ';
+            const char dblQuoteTk = '"';
+            const char minusTk = '-';
+
             string argLine;

             // See explanation at property
@@ -44,24 +48,27 @@
                 int k = 0;
                 while (true) {
                     char c = originalCl[k++];
-                    if (c == '"') {
+                    if (c == dblQuoteTk) {
                         dqc--;
                     }

                     if (dqc == 0) break;
                 }

-                argLine = originalCl.Substring(k + 1);
+                // Find the first non-whitespace character
+                while (k != originalCl.Length && originalCl[k++] == whitespaceTk) {
+                    // Just go ahead
+                }
+
+                argLine = originalCl.Substring(k - 1);
             } else {
                 argLine = string.Join(" ", args);
             }

+            if (string.IsNullOrEmpty(argLine)) return PrintUsageWithError("Missing arguments.", optionTypes, null);
+
             char[] argLineChars = argLine.ToCharArray();
             int maxChars = argLineChars.Length;
-
-            const char whitespaceTk = ' ';
-            const char dblQuoteTk = '"';
-            const char minusTk = '-';

             // Modes
             //   (i) No-verb mode starting with -


work in progress

work in progress

--- Assets/Scripts/MapzenGoWrappers/Plugins/SessionManager.cs
+++ Assets/Scripts/MapzenGoWrappers/Plugins/SessionManager.cs
@@ -158,6 +158,7 @@
             }
             if (!found)
             {
+
                 var cursor = cursors.Find(u => u.name == user.Id + "-Cursor");
                 if (cursor == null)
                 {
@@ -169,19 +170,19 @@
                 else
                     user.Cursor = cursor;
                 users.Add(user);
+                if (user.SelectedFeature != null)
+                    UpdateUserSelection(existingUser.SelectedFeature, user);
+
             }
             else
             {
                 if (user.Cursor == null)
                     user.Cursor = users[i].Cursor;
-            }
-            if ( user.SelectedFeature != null && existingUser.SelectedFeature != null && user.SelectedFeature.id != existingUser.SelectedFeature.id )
-            {
-                UpdateUserSelection(existingUser.SelectedFeature, user);
-            }
-
-            users[i] = user;
-
+                if (user.SelectedFeature != null && existingUser.SelectedFeature != null)// && user.SelectedFeature.id != existingUser.SelectedFeature.id)
+                    UpdateUserSelection(existingUser.SelectedFeature, user);
+                users[i] = user;
+
+            }
         }

         /// <summary>
@@ -247,7 +248,8 @@

         #endregion Room management

-        public void UpdateLayer(Layer layer) {
+        public void UpdateLayer(Layer layer)
+        {
             var subtopic = string.Format("layers/{0}", layer.Title);
             SendJsonMessage(subtopic, layer.ToJSON());
         }
@@ -261,7 +263,7 @@
         protected void SendJsonMessage(string subtopic, string json, bool retain = true)
         {
             Debug.Log(string.Format("Sending JSON message to topic {0}/{1}: {2}", sessionName, subtopic, json));
-            client.Publish(string.Format("{0}/{1}", sessionName, subtopic), Encoding.UTF8.GetBytes(json), uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, retain);
+            client.Publish(string.Format("{0}/{1}", sessionName, subtopic), Encoding.UTF8.GetBytes(json), uPLibrary.Networking.M2Mqtt.Messages.MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, retain);
         }
     }
 }


Added missing type to BsonCOnfig.

Added missing type to BsonCOnfig.

--- Naos.Deployment.Persistence/DeploymentBsonConfiguration.cs
+++ Naos.Deployment.Persistence/DeploymentBsonConfiguration.cs
@@ -51,6 +51,7 @@
                                                                                typeof(InstanceTargeterBase),
                                                                                typeof(InstanceType),
                                                                                typeof(ItsConfigOverride),
+                                                                                typeof(OperatingSystemDescriptionBase),
                                                                                typeof(PackageDescriptionWithDeploymentStatus),
                                                                                typeof(PackageDescriptionWithOverrides),
                                                                                typeof(PostDeploymentStrategy),


Add help option for all commands (#364)

Add help option for all commands (#364)

--- src/Dotnet.Script/Program.cs
+++ src/Dotnet.Script/Program.cs
@@ -80,7 +80,8 @@
             var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray();
             var argsAfterDoubleHyphen  = args.SkipWhile(a => a != "--").Skip(1).ToArray();

-            app.HelpOption("-? | -h | --help");
+            const string helpOptionTemplate = "-? | -h | --help";
+            app.HelpOption(helpOptionTemplate);

             app.VersionOption("-v | --version", GetVersion);

@@ -91,6 +92,7 @@
                 c.Description = "Execute CSX code.";
                 var code = c.Argument("code", "Code to execute.");
                 var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue);
+                c.HelpOption(helpOptionTemplate);
                 c.OnExecute(async () =>
                 {
                     int exitCode = 0;
@@ -113,6 +115,7 @@
                 c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
                 var fileName = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
                 var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
+                c.HelpOption(helpOptionTemplate);
                 c.OnExecute(() =>
                 {
                     var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
@@ -127,6 +130,7 @@
                 c.Description = "Creates a new script file";
                 var fileNameArgument = c.Argument("filename", "The script file name");
                 var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
+                c.HelpOption(helpOptionTemplate);
                 c.OnExecute(() =>
                 {
                     var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
@@ -151,7 +155,7 @@
                 var commandConfig = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue);
                 var publishDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                 var runtime = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue);
-
+                c.HelpOption(helpOptionTemplate);
                 c.OnExecute(() =>
                 {
                     if (fileNameArgument.Value == null)
@@ -202,6 +206,7 @@
                 c.Description = "Run a script from a DLL.";
                 var dllPath = c.Argument("dll", "Path to DLL based script");
                 var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
+                c.HelpOption(helpOptionTemplate);
                 c.OnExecute(async () =>
                 {
                     int exitCode = 0;


Adding new check for expected behavior in UsersControllerTests

--- BTCPayServer/Controllers/RestApi/Users/UsersController.cs
+++ BTCPayServer/Controllers/RestApi/Users/UsersController.cs
@@ -86,16 +86,19 @@
                                     : true;
             // You need to be admin to create an admin
             if (request.IsAdministrator is true && !isAdmin)
-            {
                 return Forbid(AuthenticationSchemes.ApiKey);
-            }

+            var canCreateUser = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanCreateUser.Key))).Succeeded;
             if (!isAdmin && policies.LockSubscription)
             {
                 // If we are not admin and subscriptions are locked, we need to check the Policies.CanCreateUser.Key permission
-                if (!isAuth || !(await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanCreateUser.Key))).Succeeded)
+                if (!isAuth || !canCreateUser)
                     return Forbid(AuthenticationSchemes.ApiKey);
             }
+
+            // Forbid non-admin users without CanCreateUser permission to create accounts
+            if (isAuth && !isAdmin && !canCreateUser)
+                return Forbid(AuthenticationSchemes.ApiKey);

             var user = new ApplicationUser
             {