Fix bug in IV initialization.

Fix bug in IV initialization.

--- Turing/Turing.cs
+++ Turing/Turing.cs
@@ -30,6 +30,7 @@
         {
             LegalKeySizesValue = s_legalKeySizes;
             LegalBlockSizesValue = s_legalBlockSizes;
+            BlockSizeValue = TableTuringTransform.BlockSizeBytes;
         }

         public static void Register()
@@ -54,7 +55,7 @@

         byte [] GetRandomBytes(int size)
         {
-            var data = new byte[KeySize / 8];
+            var data = new byte[size];
             SecureRandom.GetBytes(data);
             return data;
         }
@@ -72,7 +73,7 @@
             if (Key == null || KeySize <= 0)
                 throw new InvalidOperationException("Failed to find a key.");

-            IV = GetRandomBytes((TuringTransform.KeySizeMaxBits - KeySize) / 8);
+            IVValue = GetRandomBytes((TuringTransform.KeyIVMaxBits - KeySize) / 8);
         }

         public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV)


Cleanup comments.

Cleanup comments.

--- src/ExRam.Gremlinq.Core/Extensions/AddStepHandlerExtensions.cs
+++ src/ExRam.Gremlinq.Core/Extensions/AddStepHandlerExtensions.cs
@@ -3,15 +3,6 @@

 namespace ExRam.Gremlinq.Core
 {
-    //targetQuery
-    //    .Continue()                     //ContinuationBuilder
-    //    .FromSource(sourceQuery)        //ContinuationBuilder mit anderer Source
-    //    .With(continuation1)            //SingleConrinuationBuilder
-    //    .With(continuation2)            //MultiContinuationBuilder
-    //    .WithSteps(targetQuery / targetQueries => Step / Step[]) // 2 Overloads für Single, 2 für Multi
-    //    .As<TTargetQuery>()             //-> TargetQuery
-    //    .AsSourceQuery
-
     internal static class AddStepHandlerExtensions
     {
         public static StepStack AddSteps<TStep>(this IAddStepHandler addStepHandler, StepStack stepStack, IEnumerable<TStep> steps, IGremlinQueryEnvironment env)


Dispose

Dispose

--- src/FujiyBlog.Web/Areas/Admin/Controllers/SettingController.cs
+++ src/FujiyBlog.Web/Areas/Admin/Controllers/SettingController.cs
@@ -252,8 +252,12 @@
             var targets = LogManager.GetCurrentClassLogger().Factory.Configuration.ConfiguredNamedTargets;
             DirectoryInfo logDirectory = new FileInfo(((FileTarget)((NLog.Targets.Wrappers.AsyncTargetWrapper)targets[0]).WrappedTarget).FileName.Render(new LogEventInfo())).Directory;
             FileInfo fileInfo = logDirectory.GetFiles(file).Single();
-            string content = fileInfo.OpenText().ReadToEnd();
-            return Content("
" + Server.HtmlEncode(content) + "
");
+
+            using (StreamReader reader = fileInfo.OpenText())
+            {
+                string content = reader.ReadToEnd();
+                return Content("
" + Server.HtmlEncode(content) + "
");
+            }
         }

         public virtual ActionResult LogDelete(string file)


Use Rx to marshal onto main thread

Use Rx to marshal onto main thread

--- src/GitHub.InlineReviews/Services/PullRequestSessionManager.cs
+++ src/GitHub.InlineReviews/Services/PullRequestSessionManager.cs
@@ -3,6 +3,7 @@
 using System.ComponentModel.Composition;
 using System.IO;
 using System.Linq;
+using System.Reactive;
 using System.Reactive.Disposables;
 using System.Reactive.Linq;
 using System.Reactive.Threading.Tasks;
@@ -66,18 +67,15 @@
             this.connectionManager = connectionManager;
             this.modelServiceFactory = modelServiceFactory;

-            RepoChanged(teamExplorerContext.ActiveRepository).Forget();
-            teamExplorerContext.StatusChanged += (s, e) =>
-            {
-                RepoChanged(teamExplorerContext.ActiveRepository).Forget();
-            };
-            teamExplorerContext.PropertyChanged += (s, e) =>
-            {
-                if (e.PropertyName == nameof(teamExplorerContext.ActiveRepository))
-                {
-                    RepoChanged(teamExplorerContext.ActiveRepository).Forget();
-                }
-            };
+            Observable.FromEventPattern(teamExplorerContext, nameof(teamExplorerContext.StatusChanged))
+                .StartWith((EventPattern<object>)null)
+                .ObserveOn(RxApp.MainThreadScheduler)
+                .Subscribe(_ => RepoChanged(teamExplorerContext.ActiveRepository).Forget());
+
+            teamExplorerContext.WhenAnyValue(x => x.ActiveRepository)
+                .Skip(1)
+                .ObserveOn(RxApp.MainThreadScheduler)
+                .Subscribe(x => RepoChanged(x).Forget());
         }

         /// <inheritdoc/>
@@ -196,8 +194,6 @@
         {
             try
             {
-                await ThreadingHelper.SwitchToMainThreadAsync();
-
                 if (localRepositoryModel != repository)
                 {
                     repository = localRepositoryModel;


Reintroduce Environment.NewLine use.

Reintroduce Environment.NewLine use.

--- src/GitHub.Unity/Assets/Plugins/GitHub/Editor/GitCommitTask.cs
+++ src/GitHub.Unity/Assets/Plugins/GitHub/Editor/GitCommitTask.cs
@@ -32,7 +32,7 @@
 		public GitCommitTask(string message, string body, Action onSuccess = null, Action onFailure = null)
 		{
 			arguments = "commit ";
-			arguments += string.Format(@" -m ""{0}\n{1}""", message, body);
+			arguments += string.Format(@" -m ""{0}{1}{2}""", message, Environment.NewLine, body);

 			this.onSuccess = onSuccess;
 			this.onFailure = onFailure;


Added help link

Added help link

--- src/LoginNavigationExample/LoginNavigationExample/Constants.cs
+++ src/LoginNavigationExample/LoginNavigationExample/Constants.cs
@@ -7,6 +7,7 @@
 		public static string AppId = "XXXXXXXXXXXXXXXXX";
 		public static string AppSecretId = "XXXXXXXXXXXXXXXXXXXXX";
 		public static string ExtendedPermissions = "wl.basic";
+		public static string ExtendedPermissions = "wl.basic"; // help: https://msdn.microsoft.com/en-us/library/office/dn631845.aspx
 		public static string AuthorizeUrl = "https://login.live.com/oauth20_authorize.srf";
 		public static string RedirectUrl = "https://login.live.com/oauth20_desktop.srf";
 		public static string TokenUrl = "https://login.live.com/oauth20_token.srf";


Changed MiddlewareFilter accessibility to internal (#5455)

Fixes #5432

--- src/Microsoft.AspNetCore.Mvc.Core/Internal/MiddlewareFilter.cs
+++ src/Microsoft.AspNetCore.Mvc.Core/Internal/MiddlewareFilter.cs
@@ -11,7 +11,7 @@
     /// <summary>
     /// A filter which executes a user configured middleware pipeline.
     /// </summary>
-    public class MiddlewareFilter : IAsyncResourceFilter
+    internal class MiddlewareFilter : IAsyncResourceFilter
     {
         private readonly RequestDelegate _middlewarePipeline;


Control-flow simplification in Frame.CreateResponseHeader() (#1168).

--- src/Microsoft.AspNetCore.Server.Kestrel/Internal/Http/Frame.cs
+++ src/Microsoft.AspNetCore.Server.Kestrel/Internal/Http/Frame.cs
@@ -865,13 +865,16 @@

             responseHeaders.SetReadOnly();

-            if (!_keepAlive && !hasConnection)
-            {
-                responseHeaders.SetRawConnection("close", _bytesConnectionClose);
-            }
-            else if (_keepAlive && !hasConnection && _httpVersion == Http.HttpVersion.Http10)
-            {
-                responseHeaders.SetRawConnection("keep-alive", _bytesConnectionKeepAlive);
+            if (!hasConnection)
+            {
+                if (!_keepAlive)
+                {
+                    responseHeaders.SetRawConnection("close", _bytesConnectionClose);
+                }
+                else if (_httpVersion == Http.HttpVersion.Http10)
+                {
+                    responseHeaders.SetRawConnection("keep-alive", _bytesConnectionKeepAlive);
+                }
             }

             if (ServerOptions.AddServerHeader && !responseHeaders.HasServer)


Update comments

Update comments

--- src/Microsoft.Diagnostics.Runtime/src/Common/ClrStaticField.cs
+++ src/Microsoft.Diagnostics.Runtime/src/Common/ClrStaticField.cs
@@ -12,7 +12,7 @@
         /// <summary>
         /// Returns whether this static field has been initialized in a particular AppDomain
         /// or not.  If a static variable has not been initialized, then its class constructor
-        /// may have not been run yet.  Calling GetFieldValue on an uninitialized static
+        /// may have not been run yet.  Calling any of the Read* methods on an uninitialized static
         /// will result in returning either NULL or a value of 0.
         /// </summary>
         /// <param name="appDomain">The AppDomain to see if the variable has been initialized.</param>


fixed a composite target sorting issue

fixed a composite target sorting issue

--- src/NDock.Base/CompositeTargtes/SingleResultCompositeTarget.cs
+++ src/NDock.Base/CompositeTargtes/SingleResultCompositeTarget.cs
@@ -123,7 +123,7 @@

             var configValue = ConfigSelector(config);

-            var lazyFactory = factories.FirstOrDefault(
+            var lazyFactory = Sort(factories).FirstOrDefault(
                 f => string.IsNullOrEmpty(configValue) || MetadataNameEqual(f.Metadata, configValue));

             if (lazyFactory == null)


Fix conditional in interface

Fix conditional in interface

--- src/OneDriveSdk.Common/Authentication/IAuthenticationResult.cs
+++ src/OneDriveSdk.Common/Authentication/IAuthenticationResult.cs
@@ -43,7 +43,7 @@

         UserInfo UserInfo { get; }

-#if !WINFORMS
+#if WINRT
         string Error { get; }

         string ErrorDescription { get; }


Decoding media urls containing %xx in their names during upgrade

--HG--
branch : 1.x

--- src/Orchard.Web/Modules/Upgrade/Controllers/MediaController.cs
+++ src/Orchard.Web/Modules/Upgrade/Controllers/MediaController.cs
@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
+using System.Web;
 using System.Web.Mvc;
 using Orchard;
 using Orchard.Environment.Features;
@@ -103,7 +104,8 @@
                 _orchardServices.Notifier.Information(T("Importing {0}.", mediaFile.MediaPath));
                 var storageFile = _storageProvider.GetFile(mediaFile.MediaPath.Substring(trim));
                 using (var stream = storageFile.OpenRead()) {
-                    _mediaLibraryService.ImportStream(mediaLibraryFolder.TermId, stream, Path.GetFileName(mediaFile.MediaPath));
+                    var filename = HttpUtility.UrlDecode(mediaFile.MediaPath);
+                    _mediaLibraryService.ImportStream(mediaLibraryFolder.TermId, stream, Path.GetFileName(filename));
                 }
             }
             catch(Exception e) {


Add some comments to DataMigration (#8623)

--- src/OrchardCore/OrchardCore.Data.Abstractions/DataMigration.cs
+++ src/OrchardCore/OrchardCore.Data.Abstractions/DataMigration.cs
@@ -3,8 +3,23 @@
 namespace OrchardCore.Data.Migration
 {
     /// <summary>
-    /// Represents a database migration.
+    /// A <see cref="DataMigration"/> is discovered through method reflection
+    /// and runs sequentially from the Create() method through UpdateFromX().
     /// </summary>
+    /// <example>
+    /// Usage of method implementations:
+    /// <code>
+    /// public class Migrations : DataMigration
+    /// {
+    ///     public void Create() { return 1; } // or
+    ///     public Task CreateAsync() { return 1; }
+    ///     public void UpdateFrom1() { return 2; } // or
+    ///     public Task UpdateFrom1Async() { return 2; }
+    ///     public void Uninstall() { } // or
+    ///     public Task UninstallAsync() { }
+    /// }
+    /// </code>
+    /// </example>
     public abstract class DataMigration : IDataMigration
     {
         /// <inheritdocs />


Рекомендация Сонара

Рекомендация Сонара

--- src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs
+++ src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs
@@ -58,7 +58,7 @@
         [ContextMethod("Количество", "Count")]
         public int Count()
         {
-            return _rows.Count();
+            return _rows.Count;
         }

         /// <summary>


оптимизация метода Свернуть

оптимизация метода Свернуть

--- src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs
+++ src/ScriptEngine.HostedScript/Library/ValueTable/ValueTable.cs
@@ -345,9 +345,6 @@
         [ContextMethod("Свернуть", "GroupBy")]
         public void GroupBy(string groupColumnNames, string aggregateColumnNames = null)
         {
-
-            // TODO: Сворачиваем за N^2. Переделать на N*log(N)
-
             List<ValueTableColumn> GroupColumns = GetProcessingColumnList(groupColumnNames, true);
             List<ValueTableColumn> AggregateColumns = GetProcessingColumnList(aggregateColumnNames, true);

@@ -355,72 +352,78 @@
                 if ( AggregateColumns.Find(x => x.Name==group_column.Name)!=null )
                     throw ColumnsMixedException(group_column.Name);

-            List<ValueTableRow> new_rows = new List<ValueTableRow>();
+            var uniqueRows = new Dictionary<ValueTableRow, ValueTableRow>(new RowsByColumnsEqComparer(GroupColumns) );
+            int new_idx = 0;

             foreach (ValueTableRow row in _rows)
             {
-
-                StructureImpl search = new StructureImpl();
-
-                foreach (ValueTableColumn Column in GroupColumns)
-                    search.Insert(Column.Name, row.Get(Column));
-
-                ValueTableRow new_row = null;
-
-                foreach (ValueTableRow nrow in new_rows)
-                {
-                    if (CheckFilterCriteria(nrow, search))
+                if (uniqueRows.ContainsKey(row))
+                {
+                    ValueTableRow old_row = uniqueRows[row];
+
+                    foreach (var Column in AggregateColumns)
                     {
-                        new_row = nrow;
-                        break;
+                        IValue current = row.Get(Column);
+                        if (current.DataType == DataType.Number)
+                        {
+                            decimal sum = old_row.Get(Column).AsNumber() + current.AsNumber();
+                            old_row.Set(Column, ValueFactory.Create(sum));
+                        }
                     }
                 }
-
-                if (new_row == null)
-                {
-                    new_row = new ValueTableRow(this);
-                    foreach (ValueTableColumn Column in GroupColumns)
+                else
+                {
+                    uniqueRows.Add(row, row);
+
+                    ValueTableRow new_row = _rows[new_idx++];
+
+                    foreach (var Column in GroupColumns)
                         new_row.Set(Column, row.Get(Column));

-                    new_rows.Add(new_row);
-                }
-
-                foreach (ValueTableColumn Column in AggregateColumns)
-                {
-                    IValue old = new_row.Get(Column);
-                    decimal d_old;
-
-                    if (old.DataType != Machine.DataType.Number)
-                        d_old = 0;
-                    else
-                        d_old = old.AsNumber();
-
-                    IValue current = row.Get(Column);
-                    decimal d_current;
-
-                    if (current.DataType != Machine.DataType.Number)
-                        d_current = 0;
-                    else
-                        d_current = current.AsNumber();
-
-                    new_row.Set(Column, ValueFactory.Create(d_old + d_current));
-                }
-
-            }
-
-            _rows.Clear();
-            _rows.AddRange(new_rows);
-
-            {
-                int i = 0;
-                while (i < _columns.Count())
-                {
-                    ValueTableColumn Column = _columns.FindColumnByIndex(i);
-                    if (GroupColumns.IndexOf(Column) == -1 && AggregateColumns.IndexOf(Column) == -1)
-                        _columns.Delete(Column);
-                    else
-                        ++i;
-                }
+                    foreach (var Column in AggregateColumns)
+                        if (new_row.Get(Column).DataType != DataType.Number)
+                            new_row.Set(Column, ValueFactory.Create(0));
+                }
+            }
+
+            _rows.RemoveRange(new_idx, _rows.Count()-new_idx);
+
+            int i = 0;
+            while (i < _columns.Count())
+            {
+                ValueTableColumn Column = _columns.FindColumnByIndex(i);
+                if (GroupColumns.IndexOf(Column) == -1 && AggregateColumns.IndexOf(Column) == -1)
+                    _columns.Delete(Column);
+                else
+                    ++i;
+            }
+        }
+
+        private class RowsByColumnsEqComparer : IEqualityComparer<ValueTableRow>
+        {
+            private List<ValueTableColumn> _columns;
+
+            public RowsByColumnsEqComparer(List<ValueTableColumn> columns)
+            {
+                _columns = columns;
+            }
+
+            public bool Equals(ValueTableRow row1, ValueTableRow row2)
+            {
+                foreach (var column in _columns)
+                {
+                    if (!row1.Get(column).Equals(row2.Get(column)))
+                        return false;
+                }
+                return true;
+            }
+
+            public int GetHashCode(ValueTableRow row)
+            {
+                int hash = 0;
+                foreach (var column in _columns)
+                    hash ^= row.Get(column).AsString().GetHashCode();
+                return hash;
             }
         }


Change HttpListener to write ErrorResponses into the preferred ContentType instead of hard-coded JSON

--- src/ServiceStack/WebHost.Endpoints/Support/HttpListenerBase.cs
+++ src/ServiceStack/WebHost.Endpoints/Support/HttpListenerBase.cs
@@ -15,6 +15,7 @@
 using ServiceStack.IO;
 using ServiceStack.Logging;
 using ServiceStack.ServiceHost;
+using ServiceStack.ServiceInterface.ServiceModel;
 using ServiceStack.ServiceModel.Serialization;
 using ServiceStack.Text;
 using ServiceStack.WebHost.Endpoints.Extensions;
@@ -237,39 +238,53 @@

 			RaiseReceiveWebRequest(context);

-			try
-			{
-				this.ProcessRequest(context);
-			}
-			catch (Exception ex)
-			{
-				var error = string.Format("Error this.ProcessRequest(context): [{0}]: {1}", ex.GetType().Name, ex.Message);
-				Log.ErrorFormat(error);
-
-				try
-				{
-					var sb = new StringBuilder();
-					sb.AppendLine("{");
-					sb.AppendLine("\"ResponseStatus\":{");
-					sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.GetType().Name.EncodeJson());
-					sb.AppendFormat(" \"Message\":{0},\n", ex.Message.EncodeJson());
-					sb.AppendFormat(" \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson());
-					sb.AppendLine("}");
-					sb.AppendLine("}");
-
-					context.Response.StatusCode = 500;
-					context.Response.ContentType = ContentType.Json;
-					var sbBytes = sb.ToString().ToUtf8Bytes();
-					context.Response.OutputStream.Write(sbBytes, 0, sbBytes.Length);
-					context.Response.Close();
-				}
-				catch (Exception errorEx)
-				{
-					error = string.Format("Error this.ProcessRequest(context)(Exception while writing error to the response): [{0}]: {1}", errorEx.GetType().Name, errorEx.Message);
-					Log.ErrorFormat(error);
-
-				}
-			}
+            try
+            {
+	            this.ProcessRequest(context);
+            }
+            catch (Exception ex)
+            {
+                var error = string.Format("Error this.ProcessRequest(context): [{0}]: {1}", ex.GetType().Name, ex.Message);
+                Log.ErrorFormat(error);
+
+                try
+                {
+	                var errorResponse = new ErrorResponse
+	                {
+                        ResponseStatus = new ResponseStatus
+                        {
+                            ErrorCode = ex.GetType().Name,
+                            Message = ex.Message,
+                            StackTrace = ex.StackTrace,
+                        }
+	                };
+
+                    var operationName = context.Request.GetOperationName();
+                    var httpReq = new HttpListenerRequestWrapper(operationName, context.Request);
+                    var httpRes = new HttpListenerResponseWrapper(context.Response);
+	                var requestCtx = new HttpRequestContext(httpReq, httpRes, errorResponse);
+	                var contentType = requestCtx.ResponseContentType;
+
+	                var serializer = EndpointHost.ContentTypeFilter.GetResponseSerializer(contentType);
+                    if (serializer == null)
+                    {
+                        contentType = EndpointHost.Config.DefaultContentType;
+                        serializer = EndpointHost.ContentTypeFilter.GetResponseSerializer(contentType);
+                    }
+
+                    httpRes.StatusCode = 500;
+                    httpRes.ContentType = contentType;
+
+	                serializer(requestCtx, errorResponse, httpRes);
+
+                    httpRes.Close();
+                }
+                catch (Exception errorEx)
+                {
+	                error = string.Format("Error this.ProcessRequest(context)(Exception while writing error to the response): [{0}]: {1}", errorEx.GetType().Name, errorEx.Message);
+	                Log.ErrorFormat(error);
+                }
+            }

             //System.Diagnostics.Debug.WriteLine("End: " + requestNumber + " at " + DateTime.UtcNow);
 		}


Correct order of params in diff highlighter tests

--- src/Shouldly.Tests/InternalTests/StringDiffHighlighterTests.cs
+++ src/Shouldly.Tests/InternalTests/StringDiffHighlighterTests.cs
@@ -18,13 +18,13 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public static void Should_throw_exception_when_expected_arg_is_null()
         {
-            _sut.HighlightDifferences("not null", null);
+            _sut.HighlightDifferences(null, "not null");
         }
         [Test]
         [ExpectedException(typeof(ArgumentNullException))]
         public static void Should_throw_exception_when_actual_arg_is_null()
         {
-            _sut.HighlightDifferences(null, "not null");
+            _sut.HighlightDifferences("not null", null);
         }
     }
 }


Start removing SpecsFor from SayTests

Start removing SpecsFor from SayTests

--- src/SlackConnector.Tests.Unit/SlackConnectionTests/SayTests.cs
+++ src/SlackConnector.Tests.Unit/SlackConnectionTests/SayTests.cs
@@ -1,9 +1,10 @@
 using System;
 using System.Collections.Generic;
+using System.Threading.Tasks;
 using Moq;
 using NUnit.Framework;
+using Ploeh.AutoFixture.NUnit3;
 using SlackConnector.Connections;
-using SlackConnector.Connections.Clients;
 using SlackConnector.Connections.Clients.Chat;
 using SlackConnector.Connections.Sockets;
 using SlackConnector.Exceptions;
@@ -12,46 +13,35 @@

 namespace SlackConnector.Tests.Unit.SlackConnectionTests
 {
-    public static class SayTests
+    internal class SayTests
     {
-        internal class given_valid_bot_message : SpecsFor<SlackConnection>
+        [Test, AutoMoqData]
+        public async Task should_send_message([Frozen]Mock<IConnectionFactory> connectionFactory,
+            Mock<IChatClient> chatClient, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
         {
-            private string SlackKey = "doobeedoo";
-            private BotMessage Message { get; set; }
+            // given
+            const string slackKey = "key-yay";

-            protected override void Given()
+            var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
+            await slackConnection.Initialise(connectionInfo);
+
+            connectionFactory
+                .Setup(x => x.CreateChatClient())
+                .Returns(chatClient.Object);
+
+            var message = new BotMessage
             {
-                Message = new BotMessage
-                {
-                    Text = "some text",
-                    ChatHub = new SlackChatHub { Id = "channel-id" },
-                    Attachments = new List<SlackAttachment>()
-                };
+                Text = "some text",
+                ChatHub = new SlackChatHub { Id = "channel-id" },
+                Attachments = new List<SlackAttachment>()
+            };

-                GetMockFor<IConnectionFactory>()
-                    .Setup(x => x.CreateChatClient())
-                    .Returns(GetMockFor<IChatClient>().Object);
+            // when
+            await slackConnection.Say(message);

-                var connectionInfo = new ConnectionInformation
-                {
-                    SlackKey = SlackKey,
-                    WebSocket = GetMockFor<IWebSocketClient>().Object
-                };
-
-                SUT.Initialise(connectionInfo).Wait();
-            }
-
-            protected override void When()
-            {
-                SUT.Say(Message).Wait();
-            }
-
-            [Test]
-            public void then_should_call_messenger()
-            {
-                GetMockFor<IChatClient>()
-                    .Verify(x => x.PostMessage(SlackKey, Message.ChatHub.Id, Message.Text, Message.Attachments), Times.Once);
-            }
+            // then
+            chatClient
+                .Verify(x => x.PostMessage(slackKey, message.ChatHub.Id, message.Text, message.Attachments), Times.Once);
         }

         internal class given_no_valid_chathub_id : SpecsFor<SlackConnection>


IDisposable support on WorkerTaskScheduler.

--- src/TWCore/WorkerTaskScheduler.cs
+++ src/TWCore/WorkerTaskScheduler.cs
@@ -30,12 +30,14 @@
     /// Worker Task Scheduler
     /// </summary>
     [IgnoreStackFrameLog]
-    public class WorkerTaskScheduler : TaskScheduler
+    public class WorkerTaskScheduler : TaskScheduler, IDisposable
     {
         private readonly BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
         private readonly int _concurrency;
         private readonly Thread[] _threads;
         private readonly TaskFactory _factory;
+        private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
+        private readonly ManualResetEventSlim _finalizerEvent = new ManualResetEventSlim();

         #region .ctor
         /// <summary>
@@ -88,6 +90,7 @@
         [IgnoreStackFrameLog]
         public Task Run(Func<Task> func)
         {
+            if (_tokenSource.IsCancellationRequested) return Task.FromCanceled(_tokenSource.Token);
             return _factory.StartNew(func).Unwrap();
         }
         /// <summary>
@@ -99,6 +102,7 @@
         [IgnoreStackFrameLog]
         public Task<T> Run<T>(Func<Task<T>> func)
         {
+            if (_tokenSource.IsCancellationRequested) return Task.FromCanceled<T>(_tokenSource.Token);
             return _factory.StartNew(func).Unwrap();
         }
         /// <summary>
@@ -110,6 +114,7 @@
         [IgnoreStackFrameLog]
         public Task Run(Action func)
         {
+            if (_tokenSource.IsCancellationRequested) return Task.FromCanceled(_tokenSource.Token);
             return _factory.StartNew(func);
         }
         /// <summary>
@@ -121,6 +126,7 @@
         [IgnoreStackFrameLog]
         public Task<T> Run<T>(Func<T> func)
         {
+            if (_tokenSource.IsCancellationRequested) return Task.FromCanceled<T>(_tokenSource.Token);
             return _factory.StartNew(func);
         }
         #endregion
@@ -144,21 +150,56 @@
         private static void ThreadExecutor(object state)
         {
             var scheduler = (WorkerTaskScheduler)state;
-            while (true)
+            var token = scheduler._tokenSource.Token;
+            while (!token.IsCancellationRequested)
             {
-                if (scheduler._tasks.TryTake(out var task, Timeout.Infinite))
+                try
                 {
-                    try
+                    if (scheduler._tasks.TryTake(out var task, Timeout.Infinite, token))
                     {
-                        scheduler.TryExecuteTask(task);
-                    }
-                    catch (Exception ex)
-                    {
-                        Core.Log.Write(ex);
+                        try
+                        {
+                            scheduler.TryExecuteTask(task);
+                        }
+                        catch (Exception ex)
+                        {
+                            Core.Log.Write(ex);
+                        }
                     }
                 }
+                catch(OperationCanceledException)
+                {
+                    //
+                }
             }
-        }
+            scheduler._finalizerEvent.Set();
+        }
+
+        #region IDisposable Support
+        private bool disposedValue = false; // Para detectar llamadas redundantes
+
+        /// <inheritdoc />
+        protected virtual void Dispose(bool disposing)
+        {
+            if (!disposedValue)
+            {
+                if (disposing)
+                {
+                    // TODO: eliminse el estado administrado (objetos administrados).
+                    _tokenSource.Cancel();
+                    _finalizerEvent.Wait();
+                }
+                disposedValue = true;
+            }
+        }
+
+        // Este código se agrega para implementar correctamente el patrón descartable.
+        /// <inheritdoc />
+        public void Dispose()
+        {
+            Dispose(true);
+        }
+        #endregion
         #endregion
     }
 }


disable IDNA tests on full framework

disable IDNA tests on full framework

--- src/System.Net.Http/tests/FunctionalTests/IdnaProtocolTests.cs
+++ src/System.Net.Http/tests/FunctionalTests/IdnaProtocolTests.cs
@@ -134,7 +134,7 @@
     public sealed class HttpClientHandler_IdnaProtocolTests : IdnaProtocolTests
     {
         // WinHttp on Win7 does not support IDNA
-        protected override bool SupportsIdna => !PlatformDetection.IsWindows7;
+        protected override bool SupportsIdna => !PlatformDetection.IsWindows7 && !PlatformDetection.IsFullFramework;
     }

     public sealed class ManagedHandler_IdnaProtocolTests : IdnaProtocolTests


Fix tests to match exception output change (#38145)

--- src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
+++ src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
@@ -232,7 +232,6 @@
                 handle.Process = null;
                 p.WaitForExit();
                 string consoleOutput = p.StandardError.ReadToEnd();
-                Assert.Contains("Exception details:", consoleOutput);
                 Assert.Contains("ArgumentException:", consoleOutput);
                 Assert.Contains("bad arg", consoleOutput);
             }
@@ -256,7 +255,6 @@
                 handle.Process = null;
                 p.WaitForExit();
                 string consoleOutput = p.StandardError.ReadToEnd();
-                Assert.Contains("Exception details:", consoleOutput);
                 Assert.Contains("StackOverflowException", consoleOutput);
                 Assert.Contains("SO exception", consoleOutput);
             }
@@ -280,7 +278,6 @@
                 handle.Process = null;
                 p.WaitForExit();
                 string consoleOutput = p.StandardError.ReadToEnd();
-                Assert.Contains("Exception details:", consoleOutput);
                 Assert.Contains("first exception", consoleOutput);
                 Assert.Contains("inner exception", consoleOutput);
                 Assert.Contains("ArgumentException", consoleOutput);


Fix unit test using compressing and decompressing streams in combination with serialization.

--- src/Test.II/SerializationTests.cs
+++ src/Test.II/SerializationTests.cs
@@ -254,10 +254,15 @@
             byte[] memory;

             using (MemoryStream stream = new MemoryStream())
-            using (Stream compressed = Compression.CompressingStream(stream))
-            {
-                SerializationHelper.Serialize(compressed, personA);
-                Assert.IsTrue(stream.Length > 0);
+            {
+                // compressing stream only forced to flush when the stream is closed
+                using (Stream compressed = Compression.CompressingStream(stream))
+                {
+                    SerializationHelper.Serialize(compressed, personA);
+                    Assert.IsTrue(stream.Length > 0);
+                }
+
+                // copy only after the compressing stream has been closed
                 memory = stream.ToArray();
             }


Code cleanup.  Removing redundant using namespaces.

--- src/IronFoundry.VcapClient/VcapClient.cs
+++ src/IronFoundry.VcapClient/VcapClient.cs
@@ -11,8 +11,8 @@
     using System.Net;
     using System.Text;
     using System.Text.RegularExpressions;
-    using IronFoundry.Extensions;
-    using IronFoundry.Models;
+    using Extensions;
+    using Models;

     public class VcapClient : IVcapClient
     {


Remove misleading comment as this has been moved out of the if statement

--- src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs
+++ src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs
@@ -361,7 +361,6 @@
             }

             //Look up (newest) entries by id in cmsDocument table to set newest = false
-            //NOTE: This is only relevant when a new version is created, which is why its done inside this if-statement.
             var documentDtos = Database.Fetch<DocumentDto>("WHERE nodeId = @Id AND newest = @IsNewest", new { Id = entity.Id, IsNewest = true });
             foreach (var documentDto in documentDtos)
             {


Add equality checks to Link annotation

Add equality checks to Link annotation

--- src/Konves.TextGraph/Annotations/Link.cs
+++ src/Konves.TextGraph/Annotations/Link.cs
@@ -14,5 +14,15 @@
 		public override string Subtype { get { return "link"; } }

 		public override string Type { get { return "navigation"; } }
+
+		public override bool Equals(object obj)
+		{
+			return base.Equals(obj) && (obj as Link).Uri == Uri;
+		}
+
+		public override int GetHashCode()
+		{
+			return GetHashCode(GetHashCode(), Uri);
+		}
 	}
 }


Don't lowercase the beginning of a string that was intended to remain uppercase.

--- src/Library/Impl/ScenarioTestMetadata.cs
+++ src/Library/Impl/ScenarioTestMetadata.cs
@@ -199,6 +199,13 @@
             {
                 return string.Empty;
             }
+
+            // string looks like it was intended to remain uppercase
+            if (str.TakeWhile(Char.IsLetterOrDigit).Count(Char.IsUpper) > 1)
+            {
+                return str;
+            }
+
             return string.Format("{0}{1}", char.ToLower(str[0]), str.Length == 1 ? null : str.Substring(1));
         }


Lucene.Net.Core.Util.IntBlockPool refactor: Changed Buffers and Buffer fields to public properties backed by private fields and decorated with WritableArray attribute

--- src/Lucene.Net.Core/Util/IntBlockPool.cs
+++ src/Lucene.Net.Core/Util/IntBlockPool.cs
@@ -71,7 +71,13 @@

         /// <summary>
         /// array of buffers currently used in the pool. Buffers are allocated if needed don't modify this outside of this class </summary>
-        public int[][] Buffers = new int[10][]; // LUCENENET TODO: make property ?
+        [WritableArray]
+        public int[][] Buffers
+        {
+            get { return buffers; }
+            set { buffers = value; }
+        }
+        private int[][] buffers = new int[10][];

         /// <summary>
         /// index into the buffers array pointing to the current buffer used as the head </summary>
@@ -83,7 +89,13 @@

         /// <summary>
         /// Current head buffer </summary>
-        public int[] Buffer; // LUCENENET TODO: make property ?
+        [WritableArray]
+        public int[] Buffer
+        {
+            get { return buffer; }
+            set { buffer = value; }
+        }
+        private int[] buffer;

         /// <summary>
         /// Current head offset </summary>
@@ -139,18 +151,18 @@
                     for (int i = 0; i < bufferUpto; i++)
                     {
                         // Fully zero fill buffers that we fully used
-                        Arrays.Fill(Buffers[i], 0);
+                        Arrays.Fill(buffers[i], 0);
                     }
                     // Partial zero fill the final buffer
-                    Arrays.Fill(Buffers[bufferUpto], 0, IntUpto, 0);
+                    Arrays.Fill(buffers[bufferUpto], 0, IntUpto, 0);
                 }

                 if (bufferUpto > 0 || !reuseFirst)
                 {
                     int offset = reuseFirst ? 1 : 0;
                     // Recycle all but the first buffer
-                    allocator.RecycleIntBlocks(Buffers, offset, 1 + bufferUpto);
-                    Arrays.Fill(Buffers, offset, bufferUpto + 1, null);
+                    allocator.RecycleIntBlocks(buffers, offset, 1 + bufferUpto);
+                    Arrays.Fill(buffers, offset, bufferUpto + 1, null);
                 }
                 if (reuseFirst)
                 {
@@ -158,14 +170,14 @@
                     bufferUpto = 0;
                     IntUpto = 0;
                     IntOffset = 0;
-                    Buffer = Buffers[0];
+                    buffer = buffers[0];
                 }
                 else
                 {
                     bufferUpto = -1;
                     IntUpto = INT_BLOCK_SIZE;
                     IntOffset = -INT_BLOCK_SIZE;
-                    Buffer = null;
+                    buffer = null;
                 }
             }
         }
@@ -178,13 +190,13 @@
         /// </summary>
         public void NextBuffer()
         {
-            if (1 + bufferUpto == Buffers.Length)
-            {
-                int[][] newBuffers = new int[(int)(Buffers.Length * 1.5)][];
-                Array.Copy(Buffers, 0, newBuffers, 0, Buffers.Length);
-                Buffers = newBuffers;
-            }
-            Buffer = Buffers[1 + bufferUpto] = allocator.GetIntBlock();
+            if (1 + bufferUpto == buffers.Length)
+            {
+                int[][] newBuffers = new int[(int)(buffers.Length * 1.5)][];
+                Array.Copy(buffers, 0, newBuffers, 0, buffers.Length);
+                buffers = newBuffers;
+            }
+            buffer = buffers[1 + bufferUpto] = allocator.GetIntBlock();
             bufferUpto++;

             IntUpto = 0;
@@ -199,12 +211,12 @@
             if (IntUpto > INT_BLOCK_SIZE - size)
             {
                 NextBuffer();
-                Debug.Assert(AssertSliceBuffer(Buffer));
+                Debug.Assert(AssertSliceBuffer(buffer));
             }

             int upto = IntUpto;
             IntUpto += size;
-            Buffer[IntUpto - 1] = 1;
+            buffer[IntUpto - 1] = 1;
             return upto;
         }

@@ -248,7 +260,7 @@
             if (IntUpto > INT_BLOCK_SIZE - newSize)
             {
                 NextBuffer();
-                Debug.Assert(AssertSliceBuffer(Buffer));
+                Debug.Assert(AssertSliceBuffer(buffer));
             }

             int newUpto = IntUpto;
@@ -258,7 +270,7 @@
             slice[sliceOffset] = offset;

             // Write new level:
-            Buffer[IntUpto - 1] = newLevel;
+            buffer[IntUpto - 1] = newLevel;

             return newUpto;
         }
@@ -289,14 +301,14 @@
             /// </summary>
             public virtual void WriteInt(int value) // LUCENENET TODO: rename WriteInt32 ?
             {
-                int[] ints = pool.Buffers[offset >> INT_BLOCK_SHIFT];
+                int[] ints = pool.buffers[offset >> INT_BLOCK_SHIFT];
                 Debug.Assert(ints != null);
                 int relativeOffset = offset & INT_BLOCK_MASK;
                 if (ints[relativeOffset] != 0)
                 {
                     // End of slice; allocate a new one
                     relativeOffset = pool.AllocSlice(ints, relativeOffset);
-                    ints = pool.Buffer;
+                    ints = pool.buffer;
                     offset = relativeOffset + pool.IntOffset;
                 }
                 ints[relativeOffset] = value;
@@ -361,7 +373,7 @@
                 upto = startOffset;
                 level = 1;

-                buffer = pool.Buffers[bufferUpto];
+                buffer = pool.buffers[bufferUpto];
                 upto = startOffset & INT_BLOCK_MASK;

                 int firstSize = IntBlockPool.LEVEL_SIZE_ARRAY[0];


Refactored and added DbType-property.

Refactored and added DbType-property.

--- src/Micro+/Attributes/ColumnAttribute.cs
+++ src/Micro+/Attributes/ColumnAttribute.cs
@@ -1,17 +1,17 @@
 using System;
+using System.Data;

 namespace MicroORM.Attributes
 {
     [AttributeUsage(AttributeTargets.Property)]
     public sealed class ColumnAttribute : NamedAttribute
     {
-        private bool _isNullable = true;
         //private bool _identifier;
-        private bool _autoNumber;
         private int _size = -1;

         public ColumnAttribute()
         {
+            this.IsNullable = true;
         }

         public ColumnAttribute(string columndName)
@@ -20,27 +20,21 @@
                 throw new ArgumentNullException("columnName");

             this.ColumnName = columndName;
+            this.IsNullable = true;
         }

         public override string ColumnName { get; set; }

+        public DbType? DbType { get; set; }
         //public bool Identifier
         //{
         //    get { return _identifier; }
         //    set { _identifier = value; }
         //}

-        public bool IsNullable
-        {
-            get { return _isNullable; }
-            set { _isNullable = value; }
-        }
+        public bool IsNullable { get; set; }

-        public bool AutoNumber
-        {
-            get { return _autoNumber; }
-            set { _autoNumber = value; }
-        }
+        public bool AutoNumber { get; set; }

         public int Size
         {


Removing reading OS from the environment

OS string was not being used anywhere.

--- demos/dotnet/dotnet/dotnet.cs
+++ demos/dotnet/dotnet/dotnet.cs
@@ -17,12 +17,12 @@
     static Log Log = new global::Log();

     // Arguments specifications used for parsing
-    static readonly List<String> commandFunctions = new List<String>() { "/new", "/clean", "/edit", "/?", "/help" };
-    static readonly List<String> commandSwitches = new List<String>() { "/log", "/optimize", "/unsafe" };
-    static readonly List<String> commandSwitchesWithSpecifications = new List<String>() { "/target", "/recurse", "/debug", "/platform" };
-    static readonly List<String> targetSpecifications = new List<String>() { "exe", "library" };
-    static readonly List<String> debugSpecifications = new List<String>() { "full", "pdbonly" };
-    static readonly List<String> platformSpecifications = new List<String>() { "anycpu", "anycpu32bitpreferred", "x64", "x86" };
+    static readonly List<string> commandFunctions = new List<string>() { "/new", "/clean", "/edit", "/?", "/help" };
+    static readonly List<string> commandSwitches = new List<string>() { "/log", "/optimize", "/unsafe" };
+    static readonly List<string> commandSwitchesWithSpecifications = new List<string>() { "/target", "/recurse", "/debug", "/platform" };
+    static readonly List<string> targetSpecifications = new List<string>() { "exe", "library" };
+    static readonly List<string> debugSpecifications = new List<string>() { "full", "pdbonly" };
+    static readonly List<string> platformSpecifications = new List<string>() { "anycpu", "anycpu32bitpreferred", "x64", "x86" };

     static void Main(string[] args)
     {
@@ -314,8 +314,6 @@

         string result = string.Empty;

-        var osName = GetOSName(Environment.OSVersion);
-
         var platformOption = Array.Find(args, element => element.StartsWith("/platform"));

         var platformOptionSpecicifcation = "x64";
@@ -430,32 +428,6 @@
         // platform - x86, x64, arm
         // os - win7, win8
         return "Microsoft.NETCore.Runtime.CoreCLR-" + platform.ToLower() + "\\1.0.0\\runtimes\\" + os.ToLower() + "-" + platform.ToLower() + "\\lib\\dotnet";
-    }
-
-    public static string GetOSName(OperatingSystem os)
-    {
-        var version = os.Version;
-        var build = version.Build;
-        var osname = "win7";
-        switch (build)
-        {
-            case 7600:
-            case 7601:
-                osname = "win7";
-                break;
-
-            case 9200:
-                osname = "win8";
-                break;
-
-            case 9600:
-                osname = "win10";
-                break;
-
-            default:
-                break;
-        }
-        return osname;
     }

     static void AddToListWithoutDuplicates(List<string> list, List<string> files)


[Src] Remove orphaned delegate

[Src] Remove orphaned delegate

--- Src/Ext/DebugReportCallbackExt.cs
+++ Src/Ext/DebugReportCallbackExt.cs
@@ -70,9 +70,6 @@
         private delegate Result CreateDebugReportCallbackExt(IntPtr instance,
             DebugReportCallbackCreateInfoExt.Native* createInfo, AllocationCallbacks.Native* allocator, long* callback);

-        private delegate Result CreateDebugReportCallbackExt2(IntPtr instance,
-            DebugReportCallbackCreateInfoExt.Native* createInfo, AllocationCallbacks.Native* allocator, long* callback);
-
         [UnmanagedFunctionPointer(CallConv)]
         private delegate Result DestroyDebugReportCallbackExt(IntPtr instance, long callback, AllocationCallbacks.Native* allocator);


#190 - SortButton is visible on Summary only when some data exists.

--- src/Money.UI.Blazor/Pages/Summary.cshtml
+++ src/Money.UI.Blazor/Pages/Summary.cshtml
@@ -10,12 +10,12 @@
 <div class="summary">
     <Loading Context="@Loading">

-        <SortButton TType="SummarySortType" bind-Current="@SortDescriptor" Changed="@OnSorted" />
-
         @if (Months != null)
         {
             if (Months.Count > 0)
             {
+                <SortButton TType="SummarySortType" bind-Current="@SortDescriptor" Changed="@OnSorted" />
+
                 <TabSet CssClass="months">
                     @foreach (var month in Months)
                     {


Even the smallest change can break a test

Make this a lesson to myself and any all those who read this commit message. ALWAYS
run the bloody tests :)

--- src/Nancy.Tests/Unit/MimeTypesFixture.cs
+++ src/Nancy.Tests/Unit/MimeTypesFixture.cs
@@ -8,7 +8,7 @@
         public void Should_return_appropriate_mime_for_common_extensions()
         {
             // Given, When, Then
-            MimeTypes.GetMimeType(".js").ShouldEqual("application/x-javascript");
+            MimeTypes.GetMimeType(".js").ShouldEqual("application/javascript");
             MimeTypes.GetMimeType(".css").ShouldEqual("text/css");
             MimeTypes.GetMimeType(".png").ShouldEqual("image/png");
             MimeTypes.GetMimeType(".gif").ShouldEqual("image/gif");
@@ -44,4 +44,4 @@
             MimeTypes.GetMimeType(".docx").ShouldEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
         }
     }
-}+}


Bug fix in CreateDirectory() which caused an attempt to create a directory twice when the path ended with a slash.

--- System.Net.FtpClient/FtpClient.cs
+++ System.Net.FtpClient/FtpClient.cs
@@ -2469,6 +2469,8 @@
             try {
                 m_lock.WaitOne();

+                path = path.GetFtpPath().TrimEnd('/');
+
                 if (force && !DirectoryExists(path.GetFtpDirectoryName())) {
 #if DEBUG
                     Debug.WriteLine(string.Format(


Procedural style

Procedural style

--- src/Peachpie.Library.XmlDom/XmlWriter.cs
+++ src/Peachpie.Library.XmlDom/XmlWriter.cs
@@ -818,6 +818,454 @@

         #endregion
     }
+
+    #region MethodsProceduralStyle
+
+    [PhpExtension("xmlwriter")]
+    public static class XMLWriterPS
+    {
+        #region Constants
+
+        private const string DefaultXmlVersion = "1.0";
+
+        #endregion
+
+        internal class XMLWriterResource : PhpResource
+        {
+            public XMLWriter Writer { get; }
+
+            public XMLWriterResource(XMLWriter writer) : base("xmlwriter")
+            {
+                Writer = writer;
+            }
+
+            protected override void FreeManaged()
+            {
+                //TODO: Dispose ??
+                base.FreeManaged();
+            }
+        }
+
+        private static XMLWriterResource ValidateXmlWriterResource(PhpResource context)
+        {
+            if (context is XMLWriterResource h && h.IsValid)
+            {
+                return h;
+            }
+
+            //
+            PhpException.Throw(PhpError.Warning, Pchp.Library.Resources.Resources.invalid_resource, context.TypeName);
+            return null;
+        }
+
+        #region Methods
+
+        [return: CastToFalse]
+        public static PhpResource xmlwriter_open_memory()
+        {
+            var writer = new XMLWriter();
+
+            if (writer.openMemory())
+                return new XMLWriterResource(writer);
+            else
+                return null;
+        }
+
+        [return: CastToFalse]
+        public static PhpResource xmlwriter_open_uri(Context ctx, string uri)
+        {
+            var writer = new XMLWriter();
+
+            if (writer.openUri(ctx, uri))
+                return new XMLWriterResource(writer);
+            else
+                return null;
+        }
+
+        [return: CastToFalse]
+        public static PhpString xmlwriter_output_memory(PhpResource xmlwriter, bool flush = true)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return null;
+
+            return resource.Writer.outputMemory(flush);
+        }
+
+        public static bool xmlwriter_end_attribute(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endAttribute();
+        }
+
+        public static bool xmlwriter_end_cdata(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endCdata();
+        }
+
+        public static bool xmlwriter_end_comment(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endComment();
+        }
+
+        public static bool xmlwriter_end_document(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endDocument();
+        }
+
+        public static bool xmlwriter_end_dtd_attlist(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endDtdAttlist();
+        }
+
+        public static bool xmlwriter_end_dtd_element(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endDtdElement();
+        }
+
+        public static bool xmlwriter_end_dtd_entity(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endDtdEntity();
+        }
+
+        public static bool xmlwriter_end_dtd(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endDtd();
+        }
+
+        public static bool xmlwriter_end_element(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endElement();
+        }
+
+        public static bool xmlwriter_end_pi(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.endPi();
+        }
+
+        public static PhpValue xmlwriter_flush(PhpResource xmlwriter, bool empty = true)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.flush(empty);
+        }
+
+        public static bool xmlwriter_full_end_element(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.fullEndElement();
+        }
+
+        public static bool xmlwriter_set_indent_string(PhpResource xmlwriter, string indentString)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.setIndentString(indentString);
+        }
+
+        public static bool xmlwriter_set_indent(PhpResource xmlwriter, bool indent)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.setIndent(indent);
+        }
+
+        public static bool xmlwriter_start_attribute_ns(PhpResource xmlwriter, string prefix, string name, string uri)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startAttributeNs(prefix, name, uri);
+        }
+
+        public static bool xmlwriter_start_attribute(PhpResource xmlwriter, string name)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startAttribute(name);
+        }
+
+        public static bool xmlwriter_start_cdata(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startCdata();
+        }
+
+        public static bool xmlwriter_start_comment(PhpResource xmlwriter)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startComment();
+        }
+
+        public static bool xmlwriter_start_document(PhpResource xmlwriter, string version = DefaultXmlVersion, string encoding = null, string standalone = null)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startDocument();
+        }
+
+        public static bool xmlwriter_start_dtd_attlist(PhpResource xmlwriter, string name)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startDtdAttlist(name);
+        }
+
+        public static bool xmlwriter_start_dtd_element(PhpResource xmlwriter, string name)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startDtdElement(name);
+        }
+
+        public static bool xmlwriter_start_dtd_entity(PhpResource xmlwriter, string name, bool isparam)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startDtdEntity(name, isparam);
+        }
+
+        public static bool xmlwriter_start_dtd(PhpResource xmlwriter, string qualifiedName, string publicId = null, string systemId = null)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startDtd(qualifiedName, publicId, systemId);
+        }
+
+        public static bool xmlwriter_start_element_ns(PhpResource xmlwriter, string prefix, string name, string uri)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startElementNs(prefix, name, uri);
+        }
+
+        public static bool xmlwriter_start_element(PhpResource xmlwriter, string name)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startElement(name);
+        }
+
+        public static bool xmlwriter_start_pi(PhpResource xmlwriter, string target)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.startPi(target);
+        }
+
+        public static bool xmlwriter_text(PhpResource xmlwriter, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.text(content);
+        }
+
+        public static bool xmlwriter_write_attribute_ns(PhpResource xmlwriter, string prefix, string name, string uri, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeAttributeNs(prefix, name, uri, content);
+        }
+
+        public static bool xmlwriter_write_attribute(PhpResource xmlwriter, string name, string value)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeAttribute(name, value);
+        }
+
+        public static bool xmlwriter_write_cdata(PhpResource xmlwriter, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeCdata(content);
+        }
+
+        public static bool xmlwriter_write_comment(PhpResource xmlwriter, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeComment(content);
+        }
+
+        public static bool xmlwriter_write_dtd_attlist(PhpResource xmlwriter, string name, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtdAttlist(name, content);
+        }
+
+        public static bool xmlwriter_write_dtd_element(PhpResource xmlwriter, string name, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtdElement(name, content);
+        }
+
+        public static bool xmlwriter_write_dtd_entity(PhpResource xmlwriter, string name, string content, bool pe = false)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtdEntity(name, content, pe);
+        }
+
+        public static bool xmlwriter_write_dtd_entity(PhpResource xmlwriter, string name, string content, bool pe, string pubid, string sysid)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtdEntity(name, content, pe, pubid, sysid);
+        }
+
+        public static bool xmlwriter_write_dtd_entity(PhpResource xmlwriter, string name, string content, bool pe, string pubid, string sysid, string ndataid)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtdEntity(name, content, pe, pubid, sysid, ndataid);
+        }
+
+        public static bool xmlwriter_write_dtd(PhpResource xmlwriter, string name, string publicId = null, string systemId = null, string subset = null)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeDtd(name, publicId, systemId, subset);
+        }
+
+        public static bool xmlwriter_write_element_ns(PhpResource xmlwriter, string prefix, string name, string uri, string content = null)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeElementNs(prefix, name, uri, content);
+        }
+
+        public static bool xmlwriter_write_element(PhpResource xmlwriter, string name, string content = null)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeElement(name, content);
+        }
+
+        public static bool xmlwriter_write_pi(PhpResource xmlwriter, string target, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writePi(target, content);
+        }
+
+        public static bool xmlwriter_write_raw(PhpResource xmlwriter, string content)
+        {
+            var resource = ValidateXmlWriterResource(xmlwriter);
+            if (resource == null)
+                return false;
+
+            return resource.Writer.writeRaw(content);
+        }
+
+        #endregion
+    }
+
+    #endregion
+
     public static class StringExtensions
     {
         public static string Escape(this string source, Dictionary<char, string> characters)


Fix #392: occasional "The operation was canceled" messages

--- src/ResXManager.Model/ResourceManager.cs
+++ src/ResXManager.Model/ResourceManager.cs
@@ -228,6 +228,10 @@
                 await Task.Run(Load).ConfigureAwait(true);
                 //*/
             }
+            catch (OperationCanceledException)
+            {
+                return false;
+            }
             catch (Exception ex)
             {
                 ResourceEntities.Clear();


Uaaa.Core v3.2

Uaaa.Core v3.2

--- src/Uaaa.Data.Sql.Tools/Module.cs
+++ src/Uaaa.Data.Sql.Tools/Module.cs
@@ -6,7 +6,7 @@
 {
     internal class Module : Autofac.Module
     {
-        private const string userSecretsId = "Uaaa.Data.Sql.Tools-47a0f8e2-6560-4a01-a378-f7643a99147f";
+        private const string UserSecretsId = "Uaaa.Data.Sql.Tools-47a0f8e2-6560-4a01-a378-f7643a99147f";
         protected override void Load(ContainerBuilder builder)
         {
             builder.RegisterType<UpdateCommandDataProvider>().As<UpdateCommand.IDataProvider>();
@@ -14,10 +14,13 @@
             builder.Register(context =>
             {
                 string settingsFilenameWithPath = Path.Combine(Directory.GetCurrentDirectory(), "settings.json");
+                string appSettingsFilenameWithPath = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
                 var config = new ConfigurationBuilder();
                 if (File.Exists(settingsFilenameWithPath))
                     config.AddJsonFile(settingsFilenameWithPath);
-                config.AddUserSecrets(userSecretsId);
+                if (File.Exists(appSettingsFilenameWithPath))
+                    config.AddJsonFile(appSettingsFilenameWithPath);
+                config.AddUserSecrets(UserSecretsId);
                 return config.Build();
             }).SingleInstance();
         }


Do a lock check on the index on startup and unlock it if it is, this is a safety check since we are now using the simplefs dir

--- src/Umbraco.Web/ExamineStartup.cs
+++ src/Umbraco.Web/ExamineStartup.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 using System.Linq;
 using Examine;
 using Examine.Config;
@@ -94,6 +95,17 @@
             foreach (var luceneIndexer in ExamineManager.Instance.IndexProviderCollection.OfType<LuceneIndexer>())
             {
                 luceneIndexer.WaitForIndexQueueOnShutdown = false;
+
+                //we should check if the index is locked ... it shouldn't be! We are using simple fs lock now and we are also ensuring that
+                //the indexes are not operational unless MainDom is true so if _disableExamineIndexing is false then we should be in charge
+                if (_disableExamineIndexing == false)
+                {
+                    var dir = luceneIndexer.GetLuceneDirectory();
+                    if (IndexWriter.IsLocked(dir))
+                    {
+                        IndexWriter.Unlock(dir);
+                    }
+                }
             }

             //Ok, now that everything is complete we'll check if we've stored any references to index that need rebuilding and run them


Added max response content buffer size for http client.

--- src/Web/App_Start/OAuth2Config.cs
+++ src/Web/App_Start/OAuth2Config.cs
@@ -25,7 +25,8 @@

         private static readonly HttpClient FacebookHttpClient = new HttpClient
         {
-            BaseAddress = new Uri("https://graph.facebook.com/me?fields=email")
+            BaseAddress = new Uri("https://graph.facebook.com/me?fields=email"),
+            MaxResponseContentBufferSize = 256
         };

         private static readonly double TokenExpire = TimeSpan.Parse(


修复较大物体交换出去时经由 AffectedObjects 的处理

修复较大物体交换出去时经由 AffectedObjects 的处理

--- uquadtree/uquadtree/UQuadtree.cs
+++ uquadtree/uquadtree/UQuadtree.cs
@@ -96,6 +96,15 @@
         }
     }

+    public bool Contains(IQtUserData userData)
+    {
+        if (_ownedObjects.Contains(userData))
+            return true;
+        if (_affectedObjects.Contains(userData))
+            return true;
+        return false;
+    }
+
     public void SwapIn()
     {
         foreach (var obj in _ownedObjects)
@@ -108,10 +117,6 @@
     {
         foreach (var obj in _ownedObjects)
             obj.SwapOut();
-
-        // only owned queue swap out
-        //foreach (var obj in _affectedObjects)
-        //    obj.SwapOut();
     }

     public bool IsSwapInCompleted()
@@ -136,13 +141,10 @@
             if (!obj.IsSwapOutCompleted())
                 return false;
         }
-        foreach (var obj in _affectedObjects)
-        {
-            if (!obj.IsSwapOutCompleted())
-                return false;
-        }
         return true;
     }
+
+    public List<IQtUserData> AffectedObjects { get { return _affectedObjects; } }

     private List<IQtUserData> _ownedObjects = new List<IQtUserData>();
     private List<IQtUserData> _affectedObjects = new List<IQtUserData>();
@@ -262,12 +264,33 @@
         {
             leaf.SwapOut();
             _holdingLeaves.Remove(leaf);
+
+            var affected = leaf.AffectedObjects;
+            foreach (var item in affected)
+            {
+                if (!IsHoldingUserData(item))
+                    item.SwapOut();
+            }
+
             _swapOutQueue.Add(leaf);
             if (CellSwapOut != null)
                 CellSwapOut(leaf);
         }
     }

+    private bool IsHoldingUserData(IQtUserData userData)
+    {
+        foreach (var hLeaf in _holdingLeaves)
+        {
+            if (hLeaf.Contains(userData))
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
     private void ProcessSwapQueues()
     {
         foreach (var leaf in _swapInQueue)


think it was the last test

think it was the last test

--- d60.Cirqus.Tests/Integration/VariousLoadingMethods.cs
+++ d60.Cirqus.Tests/Integration/VariousLoadingMethods.cs
@@ -127,7 +127,7 @@
             var exception = Assert.Throws<CommandProcessingException>(() => _commandProcessor.ProcessCommand(command));
             var invalidOperationException = (ArgumentException)exception.InnerException;

-            Assert.That(invalidOperationException.Message, Contains.Substring("does not exist"));
+            Assert.That(invalidOperationException.Message, Contains.Substring("it didn't exist"));
         }

         class GenericCommand : ExecutableCommand


Fix MessageBox text

Fix MessageBox text

--- Tabster/Forms/MainForm.Library.cs
+++ Tabster/Forms/MainForm.Library.cs
@@ -234,7 +234,7 @@

                     if (selectedPlaylist != null)
                     {
-                        if (MessageBox.Show(string.Format("Are you sure you want to remove this tab from the tablaturePlaylist?{0}{0}{1}",
+                        if (MessageBox.Show(string.Format("Are you sure you want to remove this tab from the playlist?{0}{0}{1}",
                             Environment.NewLine, selectedItem.File.ToFriendlyString()), "Remove Tab",
                             MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                         {


Fix off-by-one error in cron extensions evaluation of DOW

--- TaskService/TaskServiceCronExt.cs
+++ TaskService/TaskServiceCronExt.cs
@@ -60,10 +60,10 @@
 					dow = DaysOfTheWeek.AllDays;
 				else if (cron.DOW.range)
 					for (int i = cron.DOW.vals[0]; i <= cron.DOW.vals[1]; i += cron.DOW.step)
-						dow |= (DaysOfTheWeek)(1 << (i - 1));
+						dow |= (DaysOfTheWeek)(1 << i);
 				else
 					for (int i = 0; i < cron.DOW.vals.Length; i++)
-						dow |= (DaysOfTheWeek)(1 << (cron.DOW.vals[i] - 1));
+						dow |= (DaysOfTheWeek)(1 << (cron.DOW.vals[i]));

 				// Determine months
 				MonthsOfTheYear moy = 0;


Ensure current time changes before changing test file

--- Test/ProjectBase_UpToDateTests.cs
+++ Test/ProjectBase_UpToDateTests.cs
@@ -108,12 +108,18 @@

 		[Test]
 		public void InputChanges() {
-			Assert.True(ExecuteTwice(inputFile, outputFile, () => { inputFile.WriteAllText("Changed Input"); }));
+			Assert.True(ExecuteTwice(inputFile, outputFile, () => {
+				System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(1)).Wait();
+				inputFile.WriteAllText("Changed Input");
+			}));
 		}

 		[Test]
 		public void OutputChanges() {
-			Assert.True(ExecuteTwice(inputFile, outputFile, () => { outputFile.WriteAllText("Changed Output"); }));
+			Assert.True(ExecuteTwice(inputFile, outputFile, () => {
+				System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(1)).Wait();
+				outputFile.WriteAllText("Changed Output");
+			}));
 		}

 		[Test]


Update Tester class implementation due to the recent changes in Tester implementation

--- Tracer/Tester/SingleThreadTest.cs
+++ Tracer/Tester/SingleThreadTest.cs
@@ -4,6 +4,7 @@
 using System.Text;
 using System.Threading.Tasks;
 using Tracer;
+using System.Threading;
 namespace Tester
 {
     class SingleThreadTest : ITest
@@ -13,29 +14,30 @@
         {
             tracer.StartTrace();

-            RunCycle(204800000);
+            Thread.Sleep(500);
+            RunCycle(500);

             tracer.StopTrace();

-            TraceResult result = tracer.GetTraceResult();
-            result.PrintToConsole();
+            PrintTestResults();
         }

-        private void RunCycle(int repeatAmount)
+        private void RunCycle(int sleepTime)
         {
-            ITracer tracer = new Tracer.Tracer();
             tracer.StartTrace();

-            for (int i = 0; i < repeatAmount; i++)
-            {
-                int a = 1;
-                a += i;
-            }
+            Thread.Sleep(sleepTime);

             tracer.StopTrace();
+        }

-            TraceResult result = tracer.GetTraceResult();
-            result.PrintToConsole();
+        private void PrintTestResults()
+        {
+            var traceResult = tracer.GetTraceResult();
+            foreach (TraceResultItem analyzedItem in traceResult)
+            {
+                analyzedItem.PrintToConsole();
+            }
         }

     }


Fix the heap allocation on every update for LogEntry

--- deployments/UnityMixpanel/Assets/Mixpanel/Mixpanel.cs
+++ deployments/UnityMixpanel/Assets/Mixpanel/Mixpanel.cs
@@ -720,13 +720,12 @@
             }
         }

+        detail.Mixpanel.LogEntry le = new mixpanel.detail.Mixpanel.LogEntry();
         NetworkReachability reachability = NetworkReachability.ReachableViaLocalAreaNetwork;
         void Update()
         {
             if (tracking_enabled)
             {
-                detail.Mixpanel.LogEntry le = new mixpanel.detail.Mixpanel.LogEntry();
-
                 while (mp_interface.get_next_log_entry(le))
                 {
                     string msg = string.Format("Mixpanel[{0}]: {1}", le.level, le.message);


Background: Live Tile beta

Background: Live Tile beta

--- UWP.Background/LiveTileUpdater.cs
+++ UWP.Background/LiveTileUpdater.cs
@@ -3,11 +3,13 @@
 using System.Linq;
 using System.Runtime.InteropServices.WindowsRuntime;
 using System.Threading.Tasks;
+using UWP.Shared.Constants;
 using Windows.Data.Xml.Dom;
 using Windows.Foundation;
 using Windows.Graphics.Display;
 using Windows.Graphics.Imaging;
 using Windows.Storage;
+using Windows.UI;
 using Windows.UI.Notifications;
 using Windows.UI.StartScreen;
 using Windows.UI.Xaml;
@@ -34,7 +36,7 @@

         internal static async Task UpdateSecondaryTile(string crypto, UIElement chart = null) {
             hist = await GetHistoDupe.GetWeeklyHistAsync(crypto);
-            await RenderTileSVG();
+            await RenderTileSVG(crypto);

             XmlDocument content = await GenerateCoinTile(crypto);
             TileNotification notification = new TileNotification(content) { Tag = crypto };
@@ -84,32 +86,37 @@
                 return Math.Round(price, 6);
         }

-        private static async Task RenderTileSVG() {
+        private static async Task RenderTileSVG(string crypto) {
             var polyline = new Polyline();
-            polyline.Stroke = new SolidColorBrush(Windows.UI.Colors.Red);
-            polyline.StrokeThickness = 2;
+            polyline.Stroke = ColorConstants.GetBrush($"{crypto}_color");
+            polyline.Fill = ColorConstants.GetBrush($"{crypto}_color", 20);
+            polyline.FillRule = FillRule.Nonzero;
+            polyline.StrokeThickness = 0.5;
+            polyline.VerticalAlignment = VerticalAlignment.Bottom;

             var points = new PointCollection();
             int i = 0;
             var ordered = hist.OrderByDescending(x => x.Average);
             double min = ordered.LastOrDefault().Average;
             double max = ordered.FirstOrDefault().Average;
-            foreach (var h in hist)
-                points.Add(new Point(2*i++, 150 - (150 * ((h.Average - min) / (max - min)))));
+            foreach (var h in hist.GetRange(hist.Count - 150, 150))
+                points.Add(new Point(2 * ++i, 90 - (90 * ((h.Average - min) / (max - min)))));
+            points.Add(new Point(2 * i, 80 ));
+            points.Add(new Point(0, 80));
             polyline.Points = points;

-            //var grid = new Grid();
-            //grid.Children.Add(polyline);
-            //polyline.Height = 150;
-            //polyline.Width = 300;
+            var grid = new Grid() { Width = 300, Height = 150, Background = new SolidColorBrush(Color.FromArgb(0, 128, 128, 128)) };
+            polyline.VerticalAlignment = VerticalAlignment.Bottom;
+            grid.Children.Add(polyline);
+

             try {
                 var rtb = new RenderTargetBitmap();
-                await rtb.RenderAsync(polyline);
+                await rtb.RenderAsync(grid);
                 var pixelBuffer = await rtb.GetPixelsAsync();
                 var pixels = pixelBuffer.ToArray();
                 var displayInformation = DisplayInformation.GetForCurrentView();
-                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync($"testSVG.png",
+                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync($"tile-{crypto}.png",
                     CreationCollisionOption.ReplaceExisting);
                 using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) {
                     var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);


Bundle Text changes (added "# Table" comments)

--- UniLib/FieldInformationManager.cs
+++ UniLib/FieldInformationManager.cs
@@ -225,13 +225,33 @@
         {
             var sb = new StringBuilder();

-            var actionsText = from act in this.EnumerateActions()
-                              let toString = act.ToString()
-                              orderby toString
-                              select toString;
-
-            foreach (string actionText in actionsText)
-                sb.AppendLine(actionText);
+            //var actionsText = from act in this.EnumerateActions()
+            //                  let toString = act.ToString()
+            //                  orderby toString
+            //                  select toString;
+
+            //foreach (string actionText in actionsText)
+            //    sb.AppendLine(actionText);
+
+            var actions = from act in this.EnumerateActions()
+                          group act by act.TableName into tableActions
+                          orderby tableActions.Key
+                          select new {
+                              TableName = tableActions.Key,
+                              FieldActions = tableActions
+                                    .OrderBy(x => x.ToString())
+                                    .Select(x => x.ToString())
+                          };
+
+            //foreach(var tableName in actions.
+            foreach (var aTable in actions)
+            {
+                sb.AppendLine(String.Format("# Actions for {0} table", aTable.TableName));
+
+                foreach (var act in aTable.FieldActions) sb.AppendLine(act);
+
+                sb.AppendLine();
+            }

             return sb.ToString();
         }
@@ -264,6 +284,5 @@
             }
         }

-
     }
 }


GetBundleText small refactoring

GetBundleText small refactoring

--- UniLib/FieldInformationManager.cs
+++ UniLib/FieldInformationManager.cs
@@ -225,30 +225,23 @@
         {
             var sb = new StringBuilder();

-            //var actionsText = from act in this.EnumerateActions()
-            //                  let toString = act.ToString()
-            //                  orderby toString
-            //                  select toString;
-
-            //foreach (string actionText in actionsText)
-            //    sb.AppendLine(actionText);
-
-            var actions = from act in this.EnumerateActions()
+            var actionsByTable = from act in this.EnumerateActions()
                           group act by act.TableName into tableActions
                           orderby tableActions.Key
                           select new {
                               TableName = tableActions.Key,
-                              FieldActions = tableActions
-                                    .OrderBy(x => x.ToString())
-                                    .Select(x => x.ToString())
+                              TableActions = (from act in tableActions
+                                             let toString = act.ToString()
+                                             orderby toString
+                                             select toString).ToList<String>()
                           };

-            //foreach(var tableName in actions.
-            foreach (var aTable in actions)
-            {
-                sb.AppendLine(String.Format("# Actions for {0} table", aTable.TableName));
+            foreach (var tableActionsData in actionsByTable)
+            {
+                sb.AppendLine(String.Format("# Actions for {0} table", tableActionsData.TableName));

-                foreach (var act in aTable.FieldActions) sb.AppendLine(act);
+                foreach (var act in tableActionsData.TableActions)
+                    sb.AppendLine(act);

                 sb.AppendLine();
             }


Simplify GetAllAbbreviations using awesome LINQ extensions

--- UnitsNet/CustomCode/UnitSystem.cs
+++ UnitsNet/CustomCode/UnitSystem.cs
@@ -459,11 +459,7 @@

             if (_unitTypeToUnitValueToAbbrevs.TryGetValue(unitType, out unitValueToAbbrevs))
             {
-                foreach (var item in unitValueToAbbrevs)
-                {
-                    abbrevs.AddRange(item.Value);
-                }
-                return abbrevs.ToArray();
+                return unitValueToAbbrevs.Values.SelectMany(x => x).ToArray();
             }

             // Fall back to default culture


Comments; tweak resize icon

Comments; tweak resize icon

--- contractsWindow.cs
+++ contractsWindow.cs
@@ -593,10 +593,10 @@
 			bool failed = c.Container.Contract.ContractState == Contract.State.Active || c
 				.Container.Contract.ContractState == Contract.State.Cancelled || c.Container.Contract.ContractState == Contract.State.DeadlineExpired || c.Container.Contract.ContractState == Contract.State.Failed;

-			//Contract title buttons
-
+			//Add in space for the contract title buttons
 			GUILayout.Space(23 + size * 4);

+			//Draw inactive buttons if any popup window is open
 			if (!popup)
 			{
 				if (GUILayout.Button(contractTitle, cStyle, GUILayout.MaxWidth(225 + size * 30)))
@@ -607,6 +607,7 @@

 			r = GUILayoutUtility.GetLastRect();

+			//Only draw the rewards if they are visible in the window
 			if (WindowRect.width >= 270 + (size* 30))
 			{
 				if (r.yMin >= (scroll.y - 20) && r.yMax <= (scroll.y + WindowRect.height - (20 + size * 6)))
@@ -1205,7 +1206,7 @@
 				DMC_SkinsLibrary.SetCurrent("ContractUnitySkin");
 			}

-			//Contract config window button
+			//Toolbar options button
 			r.x = 188 + size * 28;
 			if (GUI.Button(r, new GUIContent(contractSkins.settingsIcon, "Toolbar Options")))
 			{
@@ -1220,7 +1221,7 @@

 		private void buildResizer(int id, int size)
 		{
-			Rect resizer = new Rect(WindowRect.width - 16 - size * 3, WindowRect.height - 25 - size * 3, 14 + size * 4, 22 + size * 4);
+			Rect resizer = new Rect(WindowRect.width - 25 - size * 3, WindowRect.height - 25 - size * 3, 22 + size * 4, 22 + size * 4);
 			GUI.Label(resizer, contractSkins.expandIcon, contractSkins.dragButton);
 			if (Event.current.type == EventType.mouseDown && Event.current.button == 0)
 			{


Remove TODO

Remove TODO

Remove TODO for using command-line arguments in Startup.

--- src/API/Startup.cs
+++ src/API/Startup.cs
@@ -37,15 +37,13 @@
             var builder = new ConfigurationBuilder()
                 .AddJsonFile("hosting.json")
                 .AddJsonFile("appsettings.json")
-                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
+                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
+                .AddEnvironmentVariables();

             if (env.IsDevelopment())
             {
                 builder.AddUserSecrets();
             }
-
-            // TODO Also use command-line arguments
-            builder.AddEnvironmentVariables();

             Configuration = builder.Build();
         }


context middleware comes after auth

context middleware comes after auth

--- src/Api/Startup.cs
+++ src/Api/Startup.cs
@@ -188,11 +188,11 @@
             // Add Cors
             app.UseCors("All");

+            // Add authentication to the request pipeline.
+            app.UseAuthentication();
+
             // Add current context
             app.UseMiddleware<CurrentContextMiddleware>();
-
-            // Add authentication to the request pipeline.
-            app.UseAuthentication();

             // Add MVC to the request pipeline.
             app.UseMvc();


ViewModel changed

ViewModel changed

--- ViewModels/MainWindowViewModel.cs
+++ ViewModels/MainWindowViewModel.cs
@@ -6,6 +6,7 @@
 using System.ComponentModel;
 using System.Windows.Controls;
 using System.Windows.Input;
+using Microsoft.Practices.Prism.Commands;

 namespace MediaPlayer
 {
@@ -57,33 +58,5 @@
         {
             //update ui
         }
-
-        // Main Media Element
-        private MediaElement _myMediaElement;
-
-        public MediaElement MyMediaElement
-        {
-            get { return _myMediaElement; }
-            set { this._myMediaElement = value; }
-        }
-
-        private ICommand _playCommand;
-
-        public ICommand PlayCommand
-        {
-            get { return _playCommand; }
-            set { this._playCommand = value; }
-        }
-
-        private void PlayMedia(object context)
-        {
-            this._myMediaElement.Play();
-        }
-
-        private bool CanPlayMedia(object context)
-        {
-            // verify if can play media
-            return true;
-        }
     }
 }


fix removing could accidentally clear the whole tree.

The path list in CondenseNodes in the C# implementation seems to be reverted in comparison to the original JS implementation.

--- src/RTree/RTree.cs
+++ src/RTree/RTree.cs
@@ -416,24 +416,26 @@

 		private void CondenseNodes(IList<RTreeNode<T>> path)
 		{
+            var count = path.Count;
+
 			// go through the path, removing empty nodes and updating bboxes
-			for (var i = path.Count - 1; i >= 0; i--)
-			{
-				if (path[i].Children.Count == 0)
-				{
-					if (i == 0)
-					{
-						Clear();
+			for (var i = 0; i < count; i++)
+			{
+                if (path[i].Children.Count == 0)
+				{
+                    if (i == count - 1)
+					{
+                        Clear();
 					}
 					else
 					{
-						var siblings = path[i - 1].Children;
-						siblings.Remove(path[i]);
-					}
+                        var siblings = path[i + 1].Children;
+                        siblings.Remove(path[i]);
+                    }
 				}
 				else
 				{
-					RefreshEnvelope(path[i]);
+                    RefreshEnvelope(path[i]);
 				}
 			}
 		}


Fix an issue that prevent creating directory shortcuts.

--- src/SilDev/Data.cs
+++ src/SilDev/Data.cs
@@ -5,7 +5,7 @@
 // ==============================================
 //
 // Filename: Data.cs
-// Version:  2017-05-18 14:53
+// Version:  2017-06-07 22:12
 //
 // Copyright (c) 2017, Si13n7 Developments (r)
 // All rights reserved.
@@ -95,7 +95,9 @@
             try
             {
                 var link = PathEx.Combine(!linkPath.EndsWithEx(".lnk") ? $"{linkPath}.lnk" : linkPath);
-                if (!Directory.Exists(Path.GetDirectoryName(link)) || !File.Exists(PathEx.Combine(targetPath)))
+                var name = Path.GetDirectoryName(link);
+                var path = PathEx.Combine(targetPath);
+                if (!Directory.Exists(name) || !PathEx.DirOrFileExists(path))
                     return false;
                 if (File.Exists(link))
                 {
@@ -103,13 +105,14 @@
                         return true;
                     File.Delete(link);
                 }
+                name = Path.GetDirectoryName(targetPath);
                 var shell = (IShellLink)new ShellLink();
                 if (!string.IsNullOrWhiteSpace(startArgs))
                     shell.SetArguments(startArgs);
                 shell.SetDescription(string.Empty);
                 shell.SetPath(targetPath);
                 shell.SetIconLocation(linkIcon ?? targetPath, 0);
-                shell.SetWorkingDirectory(Path.GetDirectoryName(targetPath));
+                shell.SetWorkingDirectory(name);
                 ((IPersistFile)shell).Save(link, false);
                 return File.Exists(link);
             }


StyleCop fixes to ObjectCache

StyleCop fixes to ObjectCache

--- src/ObjectCache.cs
+++ src/ObjectCache.cs
@@ -35,7 +35,7 @@
     /// Can be use for two purposes - to ensure there is only one instance of a given object,
     /// and to prevent the need to recreate objects that are expensive to create.
     /// </remarks>
-    internal class ObjectCache<K,V>
+    internal class ObjectCache<K, V>
     {
         private const int MostRecentListSize = 20;
         private const int PruneGap = 500;
@@ -54,7 +54,7 @@
         {
             get
             {
-                for(int i = 0; i < _recent.Count; ++i)
+                for (int i = 0; i < _recent.Count; ++i)
                 {
                     KeyValuePair<K, V> recentEntry = _recent[i];
                     if (recentEntry.Key.Equals(key))
@@ -72,6 +72,7 @@
                     {
                         MakeMostRecent(key, val);
                     }
+
                     return val;
                 }

@@ -101,7 +102,6 @@

         private void PruneEntries()
         {
-
             _nextPruneCount++;

             if (_nextPruneCount > PruneGap)
@@ -145,6 +145,5 @@

             _recent.Insert(0, new KeyValuePair<K, V>(key, val));
         }
-
     }
 }


implement simple analyze document command

--- src/Sir/Program.cs
+++ src/Sir/Program.cs
@@ -5,6 +5,7 @@
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Sir.Search;
+using Sir.VectorSpace;

 namespace Sir.Cmd
 {
@@ -172,5 +173,40 @@
             }
         }
     }
+
+    public class AnalyzeDocumentCommand : ICommand
+    {
+        public void Run(IDictionary<string, string> args, ILogger logger)
+        {
+            var dataDirectory = args["dataDirectory"];
+            var collection = args["collection"];
+            var documentId = long.Parse(args["documentId"]);
+            var select = new HashSet<string>(args["select"].Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
+            var collectionId = collection.ToHash();
+            var model = new BagOfCharsModel();
+
+            using (var sessionFactory = new SessionFactory(dataDirectory, logger))
+            using (var documents = new DocumentStreamSession(sessionFactory))
+            {
+                var doc = documents.ReadDoc((collectionId, documentId), select);
+
+                foreach (var key in select)
+                {
+                    var tokens = model.Tokenize(doc[key].ToString());
+                    var tree = new VectorNode();
+
+                    foreach (var token in tokens)
+                    {
+                        GraphBuilder.MergeOrAdd(tree, new VectorNode(token), model);
+                    }
+
+                    Console.WriteLine(key);
+                    Console.WriteLine(PathFinder.Visualize(tree));
+                    Console.WriteLine(string.Join('\n', tokens));
+                }
+
+            }
+        }
+    }
 }


Support args in dynamic event handlers

Support args in dynamic event handlers

--- src/TypeDefiner.cs
+++ src/TypeDefiner.cs
@@ -106,9 +106,57 @@
 			ConstructorBuilder constructorBuilder = handlerB.DefineConstructor (MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof (object), typeof (System.IntPtr) });
 			constructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

-			MethodBuilder invokeB = handlerB.DefineMethod ("Invoke", mattr, typeof (void), Type.EmptyTypes);
+			//MethodBuilder invokeB = handlerB.DefineMethod ("Invoke", mattr, typeof (void), Type.EmptyTypes);
+			MethodBuilder invokeB = DefineMethod (handlerB, "Invoke", mattr, declSignal.Arguments, true);
+
 			invokeB.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
 			return handlerB.CreateType ();
+		}
+
+		public static MethodBuilder DefineMethod (TypeBuilder typeB, string name, MethodAttributes mattr, Argument[] args, bool isSignal)
+		{
+			// TODO: Share this method for both signals and methods.
+			// TODO: Support out params.
+
+			//MethodBuilder mb = tb.DefineMethod (name, mattr, typeof(void), Type.EmptyTypes);
+
+			List<Type> parms = new List<Type> ();
+
+			if (args != null)
+				foreach (Argument arg in args) {
+					//if (arg.Direction == Introspection.ArgDirection.@in)
+						parms.Add (new Signature (arg.Type).ToType ());
+					//if (arg.Direction == Introspection.ArgDirection.@out)
+					//	parms.Add (new Signature (arg.Type).ToType ().MakeByRefType ());
+				}
+
+			Type retType = typeof (void);
+
+			/*
+			Signature outSig = Signature.Empty;
+			//this just takes the last out arg and uses is as the return type
+			if (declMethod.Arguments != null)
+				foreach (Argument arg in declMethod.Arguments)
+					if (arg.Direction == Introspection.ArgDirection.@out)
+						outSig = new Signature (arg.Type);
+
+			Type retType = outSig == Signature.Empty ? typeof (void) : outSig.ToType ();
+			*/
+			MethodBuilder mb = typeB.DefineMethod (name, mattr, retType, parms.ToArray ());
+
+			//define the parameter attributes and names
+			if (args != null) {
+				int argNum = 0;
+
+				foreach (Argument arg in args) {
+					//if (arg.Direction == Introspection.ArgDirection.@in)
+						mb.DefineParameter (++argNum, ParameterAttributes.In, arg.Name ?? ("arg" + argNum));
+					//if (arg.Direction == Introspection.ArgDirection.@out)
+					//	method_builder.DefineParameter (++argNum, ParameterAttributes.Out, arg.Name);
+				}
+			}
+
+			return mb;
 		}

 		public static void Define (TypeBuilder typeB, Interface iface)


Add configuration getting/setting

Add configuration getting/setting

--- src/Yio/Startup.cs
+++ src/Yio/Startup.cs
@@ -5,16 +5,30 @@
 using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Yio.Data.Constants;

 namespace Yio
 {
     public class Startup
     {
+        public Startup(IConfiguration configuration)
+        {
+            Configuration = configuration;
+
+            AppSettingsConstant.FileEndpoint = Configuration.GetSection("AppSettings").GetSection("FileEndpoint").Value;
+            AppSettingsConstant.FileStorage = Configuration.GetSection("AppSettings").GetSection("FileStorage").Value;
+        }
+
+        public IConfiguration Configuration { get; }
+
         // This method gets called by the runtime. Use this method to add services to the container.
         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
         public void ConfigureServices(IServiceCollection services)
         {
+            services.AddMvc();
+            services.AddOptions();
         }

         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.


Added INotifyPropertyChanged

Added INotifyPropertyChanged

--- WPF.Binding/Test/TestViewModel.cs
+++ WPF.Binding/Test/TestViewModel.cs
@@ -1,6 +1,8 @@
 using System;
 using System.Collections.Generic;
+using System.ComponentModel;
 using System.Linq;
+using System.Runtime.CompilerServices;
 using System.Text;
 using System.Threading.Tasks;
 using PropertyChanged;
@@ -8,7 +10,7 @@
 namespace WPF.Binding.Test
 {
     [ImplementPropertyChanged]
-    public class TestViewModel
+    public class TestViewModel : INotifyPropertyChanged
     {
         public TestViewModel()
         {
@@ -23,5 +25,7 @@
         {
             get { return string.Format("{0} {1}", FirstName, LastName); }
         }
+
+        public event PropertyChangedEventHandler PropertyChanged;
     }
 }


Fix for empty file probelm in ZipFile

Fix for empty file probelm in ZipFile

--- src/Zip/ZipFile.cs
+++ src/Zip/ZipFile.cs
@@ -325,7 +325,7 @@
 		long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData)
 		{
 			long pos = endLocation - minimumBlockSize;
-			if (pos <= 0) {
+			if (pos < 0) {
 				return -1;
 			}


FixUp shotImageUri parsing

FixUp shotImageUri parsing

--- WTM.Crawler/Parsers/ShotParser.cs
+++ WTM.Crawler/Parsers/ShotParser.cs
@@ -211,7 +211,7 @@
                                                        .Select(s => s.InnerText)
                                                        .FirstOrDefault(w => w.Contains("var imageSrc"));

-            var urn = imageUrlSection.ExtractValue(new Regex("var imageSrc = '([a-z0-9/.]*)';", RegexOptions.IgnoreCase));
+            var urn = imageUrlSection.ExtractValue(new Regex("var imageSrc = '([a-z0-9/.:]*\\.jpg)'"));

             var uri = new Uri(WebClient.UriBase, urn);


Update ZipFile.cs

Update ZipFile.cs

Correct the zip specification version by only checking the lower bits.

--- src/Zip/ZipFile.cs
+++ src/Zip/ZipFile.cs
@@ -1023,7 +1023,7 @@
 					throw new ZipException(string.Format("Wrong local header signature @{0:X}", offsetOfFirstEntry + entry.Offset));
 				}

-				short extractVersion = ( short )ReadLEUshort();
+				short extractVersion = ( short )ReadLEUshort() & 0x00ff;
 				short localFlags = ( short )ReadLEUshort();
 				short compressionMethod = ( short )ReadLEUshort();
 				short fileTime = ( short )ReadLEUshort();