Revert "Disable media transport control for old streamer while transitioning."

This reverts commit d00a97b1aa5b00abd3af6061e62e6f87726f2e7a.

--- src/Neptunium/Media/StationMediaPlayerAudioCoordinator.cs
+++ src/Neptunium/Media/StationMediaPlayerAudioCoordinator.cs
@@ -90,13 +90,9 @@
                         return;
                     }

-                    CurrentStreamer.Player.CommandManager.IsEnabled = false; //disable the media transport controls for the current streamer.
-
                     streamer.Player.Play();
                     UseStreamerBase(streamer);
-
                     await Task.WhenAll(streamer.FadeVolumeUpToAsync(1.0), ((BasicMediaStreamer)CurrentStreamer).FadeVolumeDownToAsync(0.0));
-
                     await StopStreamingCurrentStreamerAsync();


Backed out changeset: 2e961eac34d1

Backed out changeset: 2e961eac34d1

Was breaking a unit test and didn't cause any overhead

--HG--
branch : 1.x

--- src/Orchard.Web/Core/Common/Handlers/CommonPartHandler.cs
+++ src/Orchard.Web/Core/Common/Handlers/CommonPartHandler.cs
@@ -9,7 +9,6 @@
 using Orchard.ContentManagement.Handlers;
 using Orchard.Security;
 using Orchard.Services;
-using Orchard.ContentManagement.MetaData.Models;

 namespace Orchard.Core.Common.Handlers {
     [UsedImplicitly]
@@ -64,12 +63,14 @@
         public Localizer T { get; set; }

         protected override void Activating(ActivatingContentContext context) {
-            if (ContentTypeWithACommonPart(context.Definition))
+            if (ContentTypeWithACommonPart(context.ContentType))
                 context.Builder.Weld<ContentPart<CommonPartVersionRecord>>();
         }

-        protected bool ContentTypeWithACommonPart(ContentTypeDefinition contentTypeDefinition) {
+        protected bool ContentTypeWithACommonPart(string typeName) {
             //Note: What about content type handlers which activate "CommonPart" in code?
+            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(typeName);
+
             if (contentTypeDefinition != null)
                 return contentTypeDefinition.Parts.Any(part => part.PartDefinition.Name == "CommonPart");


Sanitizing RoutableService

Sanitizing RoutableService

--HG--
branch : 1.x

--- src/Orchard.Web/Core/Routable/Services/RoutableService.cs
+++ src/Orchard.Web/Core/Routable/Services/RoutableService.cs
@@ -53,12 +53,12 @@

         public static string RemoveDiacritics(string slug) {
             string stFormD = slug.Normalize(NormalizationForm.FormD);
-            StringBuilder sb = new StringBuilder();
-
-            for (int ich = 0; ich < stFormD.Length; ich++) {
-                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
+            var sb = new StringBuilder();
+
+            foreach (char t in stFormD) {
+                UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(t);
                 if (uc != UnicodeCategory.NonSpacingMark) {
-                    sb.Append(stFormD[ich]);
+                    sb.Append(t);
                 }
             }

@@ -69,7 +69,7 @@
             if ((model.Slug != null && !string.IsNullOrEmpty(model.Slug.Trim())) || string.IsNullOrEmpty(model.Title))
                 return;

-            FillSlugContext slugContext = new FillSlugContext(model.Title);
+            var slugContext = new FillSlugContext(model.Title);

             foreach (ISlugEventHandler slugEventHandler in _slugEventHandlers) {
                 slugEventHandler.FillingSlugFromTitle(slugContext);
@@ -95,8 +95,17 @@
         }

         public string GenerateUniqueSlug(IRoutableAspect part, IEnumerable<string> existingPaths) {
-            if (existingPaths == null || !existingPaths.Contains(part.Path))
+
+            if (existingPaths == null) {
                 return part.Slug;
+            }
+
+            // materializing the enumeration
+            existingPaths = existingPaths.ToArray();
+
+            if(!existingPaths.Contains(part.Path)) {
+                return part.Slug;
+            }

             int? version = existingPaths.Select(s => GetSlugVersion(part.Path, s)).OrderBy(i => i).LastOrDefault();

@@ -117,8 +126,7 @@
                        : null;
         }

-        public IEnumerable<IRoutableAspect> GetSimilarPaths(string path)
-        {
+        public IEnumerable<IRoutableAspect> GetSimilarPaths(string path) {
           return
             _contentManager.Query<RoutePart, RoutePartRecord>()
                 .Where(routable => routable.Path != null && routable.Path.StartsWith(path, StringComparison.OrdinalIgnoreCase))
@@ -138,13 +146,13 @@
                 return true;

             part.Path = part.GetPathWithSlug(part.Slug);
-            var pathsLikeThis = GetSimilarPaths(part.Path);
+            var pathsLikeThis = GetSimilarPaths(part.Path).ToArray();

             // Don't include *this* part in the list
             // of slugs to consider for conflict detection
-            pathsLikeThis = pathsLikeThis.Where(p => p.ContentItem.Id != part.ContentItem.Id);
-
-            if (pathsLikeThis.Count() > 0) {
+            pathsLikeThis = pathsLikeThis.Where(p => p.ContentItem.Id != part.ContentItem.Id).ToArray();
+
+            if (pathsLikeThis.Any()) {
                 var originalSlug = part.Slug;
                 var newSlug = GenerateUniqueSlug(part, pathsLikeThis.Select(p => p.Path));
                 part.Path = part.GetPathWithSlug(newSlug);


inny sposób przekazywania obiektów do skryptu

--- DjToKey/Models/Action.cs
+++ DjToKey/Models/Action.cs
@@ -14,15 +14,12 @@

         public void Execute(int val, V8ScriptEngine eng)
         {
-            string command = Command.Trim();
-            command = command.Replace("{VAL}", val.ToString());
-            command = command.Replace("{VALD}", (val == 127)? "1" : "-1");
-
             eng.AddHostObject("Keyboard", Simulator.Input.Keyboard);
             eng.AddHostObject("Mouse", Simulator.Input.Mouse);
-            eng.AddHostObject("value", val);
+            eng.AddHostObject("val", val);
+            eng.AddHostObject("Value", new { Raw = val, Transformed = (val == 127)? 1 : -1 });

-            eng.Execute(command);
+            eng.Execute(this.Command);
         }
     }
 }


Do not send flight states for EVA

Do not send flight states for EVA

--- Client/Systems/VesselFlightStateSys/VesselFlightStateSystem.cs
+++ Client/Systems/VesselFlightStateSys/VesselFlightStateSystem.cs
@@ -31,7 +31,7 @@
             new ConcurrentDictionary<Guid, VesselFlightStateUpdate>();

         public bool FlightStateSystemReady
-            => Enabled && FlightGlobals.ActiveVessel != null && Time.timeSinceLevelLoad > 1f &&
+            => Enabled && FlightGlobals.ActiveVessel != null && Time.timeSinceLevelLoad > 3f &&
                FlightGlobals.ready && FlightGlobals.ActiveVessel.loaded &&
                FlightGlobals.ActiveVessel.state != Vessel.State.DEAD && !FlightGlobals.ActiveVessel.packed &&
                FlightGlobals.ActiveVessel.vesselType != VesselType.Flag;
@@ -101,10 +101,9 @@
         /// </summary>
         private void SendFlightState()
         {
-            if (Enabled)
-            {
-                if (FlightStateSystemReady)
-                    MessageSender.SendCurrentFlightState();
+            if (Enabled && FlightStateSystemReady && !FlightGlobals.ActiveVessel.isEVA)
+            {
+                MessageSender.SendCurrentFlightState();

                 ChangeRoutineExecutionInterval(RoutineExecution.Update, nameof(SendFlightState), VesselCommon.IsSomeoneSpectatingUs ? 30 : 1000);
             }
@@ -159,7 +158,7 @@
             if (Enabled && FlightStateSystemReady)
             {
                 var vesselsToAdd = FlightGlobals.VesselsLoaded
-                    .Where(v => !v.packed && !FlyByWireDictionary.Keys.Contains(v.id));
+                    .Where(v => !v.isEVA && !v.packed && !FlyByWireDictionary.Keys.Contains(v.id));

                 foreach (var vesselToAdd in vesselsToAdd)
                 {


Изменен тип и добавлен контроль параметра. Замена буфера на поток.

--- src/ScriptEngine.HostedScript/Library/GlobalBinaryData.cs
+++ src/ScriptEngine.HostedScript/Library/GlobalBinaryData.cs
@@ -122,21 +122,31 @@
         /// <param name="size">Размер одной части данных.</param>
         /// <returns>Массив объектов типа ДвоичныеДанные.</returns>
         [ContextMethod("РазделитьДвоичныеДанные")]
-        public ArrayImpl SplitBinaryData(BinaryDataContext data, int size)
-        {
-            // Сделано на int т.к. BinaryContext.Size имеет тип int;
+        public ArrayImpl SplitBinaryData(BinaryDataContext data, long size)
+        {
+            if (size <= 0 || size > Int32.MaxValue)
+                throw RuntimeException.InvalidNthArgumentValue(2);
+
             ArrayImpl array = new ArrayImpl();
+            long dataSize = data.Size();
+
+            if (dataSize < size)
+            {
+                array.Add(data);
+                return array;
+            }

             int readedBytes = 0;
-
-            while (readedBytes < data.Buffer.Length)
-            {
-                int bytesToRead = size;
-                if (bytesToRead > data.Buffer.Length - readedBytes)
-                    bytesToRead = data.Buffer.Length - readedBytes;
+            var dataStream = data.GetStream();
+
+            while (readedBytes < dataSize)
+            {
+                int bytesToRead = (int)size;
+                if (bytesToRead > dataSize - readedBytes)
+                    bytesToRead = (int)(dataSize - readedBytes);

                 byte[] buffer = new byte[bytesToRead];
-                Buffer.BlockCopy(data.Buffer, readedBytes, buffer, 0, bytesToRead);
+                dataStream.Read(buffer, 0, bytesToRead);
                 readedBytes += bytesToRead;
                 array.Add(new BinaryDataContext(buffer));
             }


Can't call Build() or Update() on a container builder twice.

--- src/ServiceStack/DependencyInjection/DependencyService.cs
+++ src/ServiceStack/DependencyInjection/DependencyService.cs
@@ -27,11 +27,13 @@
         // To make matters worse, the initial requests for these objects may occur in any order
         // (a.k.a. "The Principal of Maximum Surprise").

-        private readonly ContainerBuilder _containerBuilder;
+        private readonly object _lockObject;
+        private ContainerBuilder _containerBuilder;
         private IContainer _container;

         public DependencyService()
         {
+            _lockObject = new object();
             _containerBuilder = new ContainerBuilder();
         }

@@ -55,9 +57,17 @@

         public void UpdateRegistrations()
         {
-            if (_container != null)
+            lock (_lockObject)
             {
-                _containerBuilder.Update(_container);
+                if (_container != null)
+                {
+                    _containerBuilder.Update(_container);
+                }
+                else
+                {
+                    _container = _containerBuilder.Build();
+                }
+                _containerBuilder = new ContainerBuilder();
             }
         }

@@ -83,15 +93,9 @@
         {
             if (_container == null)
             {
-                lock (_containerBuilder)
-                {
-                    if (_container == null)
-                    {
-                        _container = _containerBuilder.Build();
-                    }
-                }
+                UpdateRegistrations();
             }
-            return new DependencyResolver(_container);
+            return new DependencyResolver(_container.BeginLifetimeScope());
         }

         public T TryResolve<T>()


Preserve same behavior.

Preserve same behavior.

--- src/ServiceStack/DependencyInjection/DependencyService.cs
+++ src/ServiceStack/DependencyInjection/DependencyService.cs
@@ -157,7 +157,7 @@
         {
             if (_container == null)
             {
-                throw new NotSupportedException("Cannot create nested lifetime scope when the root one isn't ready.");
+                UpdateRegistrations();
             }
             return new DependencyResolver(_container.BeginLifetimeScope(builder));
         }


Made properties settable

Made properties settable

--- src/Sharpkit.Learn/LinearModel/BayesianRidgeRegression.cs
+++ src/Sharpkit.Learn/LinearModel/BayesianRidgeRegression.cs
@@ -94,67 +94,67 @@
         /// <summary>
         /// Gets a value indicating whether the regressors X will be normalized before regression.
         /// </summary>
-        public bool Normalize { get; private set; }
+        public bool Normalize { get; set; }

         /// <summary>
         /// Gets a value indicating whether to compute the objective function at each step of the model.
         /// </summary>
-        public bool ComputeScore { get; private set; }
+        public bool ComputeScore { get; set; }

         /// <summary>
         /// Gets hyper-parameter : inverse scale parameter (rate parameter) for the
         /// Gamma distribution prior over the lambda parameter.
         /// </summary>
-        public double Lambda1 { get; private set; }
+        public double Lambda1 { get; set; }

         /// <summary>
         /// Gets hyper-parameter : inverse scale parameter (rate parameter) for the
         /// Gamma distribution prior over the lambda parameter.
         /// </summary>
-        public double Lambda2 { get; private set; }
+        public double Lambda2 { get; set; }

         /// <summary>
         /// Gets Hyper-parameter : shape parameter for the Gamma distribution prior
         /// over the alpha parameter.
         /// </summary>
-        public double Alpha1 { get; private set; }
+        public double Alpha1 { get; set; }

         /// <summary>
         /// Gets Hyper-parameter : inverse scale parameter (rate parameter) for the
         /// Gamma distribution prior over the alpha parameter.
         /// </summary>
-        public double Alpha2 { get; private set; }
+        public double Alpha2 { get; set; }

         /// <summary>
         /// Gets precision.
         /// </summary>
-        public double Tol { get; private set; }
+        public double Tol { get; set; }

         /// <summary>
         /// Gets maximum number of iterations.
         /// </summary>
-        public int NumIter { get; private set; }
+        public int NumIter { get; set; }

         /// <summary>
         /// Gets a value indicating whether verbose mode when fitting the model.
         /// </summary>
-        public bool Verbose { get; private set; }
+        public bool Verbose { get; set; }

         /// <summary>
         /// Gets estimated precision of the noise.
         /// </summary>
-        public double Alpha { get; private set; }
+        public double Alpha { get; set; }

         /// <summary>
         /// Gets estimated precisions of the weights.
         /// (nFeatures).
         /// </summary>
-        public double Lambda { get; private set; }
+        public double Lambda { get; set; }

         /// <summary>
         /// Gets value of the objective function (to be maximized), If computed.
         /// </summary>
-        public List<double> Scores { get; private set; }
+        public List<double> Scores { get; set; }

         /// <summary>
         /// Fit linear model.


added objectid to dataPortal_Update

added objectid to dataPortal_Update

--- CslaVSTemplates/Csla2.x/CSharp/CslaVSTemplates/EditableRoot.cs
+++ CslaVSTemplates/Csla2.x/CSharp/CslaVSTemplates/EditableRoot.cs
@@ -245,6 +245,7 @@
                     using (SqlCommand cm = cn.CreateCommand())
                     {
                         cm.CommandText = "usp$safeitemrootname$Update";
+                        cm.Parameters.AddWithValue("@$safeitemrootname$ID", _$safeitemrootname$Id);
                         DoInsertUpdate(cm);
                     }
                 }
@@ -253,7 +254,6 @@
         private void DoInsertUpdate(SqlCommand cm)
         {
             cm.CommandType = CommandType.StoredProcedure;
-            cm.Parameters.AddWithValue("@$safeitemrootname$ID", _$safeitemrootname$Id);
             //cm.Parameters.AddWithValue("@SpecialServicerFee", _SpecialServicerFee);
             //cm.Parameters.AddWithValue("@PrincipalRecoveryFee", _PrincipalRecoveryFee);
             //cm.Parameters.AddWithValue("@LiquidationFee", _LiquidationFee);


Use ReadHeadPosition rather than ReadAllBackwards when initializing AllStreamSubscription

--- src/SqlStreamStore/Subscriptions/AllStreamSubscription.cs
+++ src/SqlStreamStore/Subscriptions/AllStreamSubscription.cs
@@ -147,14 +147,12 @@

         private async Task Initialize()
         {
-            ReadAllPage eventsPage;
+            long headPosition;
             try
             {
                 // Get the last stream version and subscribe from there.
-                eventsPage = await _readonlyStreamStore.ReadAllBackwards(
-                    Position.End,
-                    1,
-                    _disposed.Token).ConfigureAwait(false);
+                headPosition = await _readonlyStreamStore.ReadHeadPosition(_disposed.Token)
+                    .ConfigureAwait(false);
             }
             catch (ObjectDisposedException)
             {
@@ -175,7 +173,7 @@

             // Only new Messages, i.e. the one after the current last one.
             // Edge case for empty store where Next position 0 (when FromPosition = 0)
-            _nextPosition = eventsPage.FromPosition == 0 ? 0 : eventsPage.FromPosition + 1;
+            _nextPosition = headPosition == 0 ? 0 : headPosition + 1;
         }

         private async Task<ReadAllPage> Pull()


Delete unnecessary struct initialization (#21482)

--- src/System.Private.CoreLib/src/System/DateTime.Windows.cs
+++ src/System.Private.CoreLib/src/System/DateTime.Windows.cs
@@ -72,7 +72,8 @@

         private static unsafe bool SystemSupportsLeapSeconds()
         {
-            Interop.NtDll.SYSTEM_LEAP_SECOND_INFORMATION slsi = new Interop.NtDll.SYSTEM_LEAP_SECOND_INFORMATION();
+            Interop.NtDll.SYSTEM_LEAP_SECOND_INFORMATION slsi;
+
             return Interop.NtDll.NtQuerySystemInformation(
                                     Interop.NtDll.SystemLeapSecondInformation,
                                     (void *) &slsi,


Use a different ServiceId in an attempt that deleting the reminders from the azure table will take a shorter time.

--- src/TesterInternal/TimerTests/ReminderTests_AzureTable.cs
+++ src/TesterInternal/TimerTests/ReminderTests_AzureTable.cs
@@ -26,7 +26,10 @@
             ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.AzureTable,
             DataConnectionString = StorageTestConstants.DataConnectionString,
             LivenessType = GlobalConfiguration.LivenessProviderType.MembershipTableGrain, // Seperate testing of Reminders storage from membership storage
-            SiloConfigFile = new FileInfo("OrleansConfigurationForTesting.xml"),
+            AdjustConfig = config =>
+            {
+                config.Globals.ServiceId = Guid.NewGuid();
+            },
         };

         public static TestingSiloHost CreateSiloHost()
@@ -42,8 +45,6 @@
             // so we must proxy the call through a grain.
             //var controlProxy = GrainClient.GrainFactory.GetGrain<IReminderTestGrain2>(-1);
             //controlProxy.EraseReminderTable().WaitWithThrow(VSOTestConstants.InitTimeout);
-
-            Assert.AreEqual(GlobalConfiguration.LivenessProviderType.MembershipTableGrain, this.HostedCluster.Primary.Silo.GlobalConfig.LivenessType, "LivenesType");
         }

         [TestCleanup]


Update CertificateManager.cs

Update CertificateManager.cs

--- src/Titanium.Web.Proxy/Certificates/CertificateManager.cs
+++ src/Titanium.Web.Proxy/Certificates/CertificateManager.cs
@@ -550,13 +550,6 @@
                 pendingCertificateCreationTaskLock.Release();
             }

-            // create certificate outside of lock to allow other threads a chance to see the pending task.
-            // precludes the possiblility of multiple threads simultaneously generating the same certificate,
-            // we tolerate the case of a duplicate sequential generation due to a race (should be rare)
-            // t1: await createCertificateTask
-            // t2: cachedCertificates.TryGetValue->false
-            // t1: pendingCertificateCreationTasks.Remove
-            // t2: pendingCertificateCreationTasks.TryGetValue->false
             var certificate = await createCertificateTask;

             if (createdTask)


Use the method available in all projects in the solution

--- src/Utilities/Compiler/Extensions/DiagnosticExtensions.cs
+++ src/Utilities/Compiler/Extensions/DiagnosticExtensions.cs
@@ -192,7 +192,7 @@
                 // Microsoft.CodeAnalysis version 3.3 - 3.7 exposes options through 'SyntaxTree.DiagnosticOptions'. This API is deprecated in 3.7.

                 var syntaxTreeOptionsProvider = s_compilationOptionsSyntaxTreeOptionsProviderProperty?.GetValue(compilation.Options);
-                var syntaxTreeOptionsProviderTryGetDiagnosticValueMethod = syntaxTreeOptionsProvider?.GetType().GetMethod("TryGetDiagnosticValue");
+                var syntaxTreeOptionsProviderTryGetDiagnosticValueMethod = syntaxTreeOptionsProvider?.GetType().GetRuntimeMethods().FirstOrDefault(m => m.Name == "TryGetDiagnosticValue");
                 if (syntaxTreeOptionsProviderTryGetDiagnosticValueMethod == null && s_syntaxTreeDiagnosticOptionsProperty == null)
                 {
                     return rule.DefaultSeverity;


StepWaveform.MaxDataSize定数を追加

StepWaveform.MaxDataSize定数を追加

--- ux/Waveform/StepWaveform.cs
+++ ux/Waveform/StepWaveform.cs
@@ -30,6 +30,11 @@
         /// 円周率 Math.PI を 0.5 倍し Single 型にキャストした定数値です。
         /// </summary>
         protected const float PI_2 = (float)(Math.PI * 0.5);
+
+        /// <summary>
+        /// データとして保持できるステップ数を表した定数値です。
+        /// </summary>
+        protected const int MaxDataSize = 65536;

         /// <summary>
         /// 波形生成に用いられる生データの配列です。


Cleanup

Cleanup

--- src/Certify.Providers/DNS/OVH/OvhClient.cs
+++ src/Certify.Providers/DNS/OVH/OvhClient.cs
@@ -1,124 +1,124 @@
-// This file is inspired by https://github.com/ovh/csharp-ovh/blob/master/csharp-ovh/Client.cs , which
-// has been adapted to Certify in order to reduce dependencies and remove features useless in our context
-// Original file is copyright OVH SAS :
-
-//Copyright(c) 2013-2016, OVH SAS.
-//All rights reserved.
-
-//Redistribution and use in source and binary forms, with or without
-//modification, are permitted provided that the following conditions are met:
-
-//  * Redistributions of source code must retain the above copyright
-//   notice, this list of conditions and the following disclaimer.
-
-// * Redistributions in binary form must reproduce the above copyright
-//   notice, this list of conditions and the following disclaimer in the
-//   documentation and/or other materials provided with the distribution.
-
-// * Neither the name of OVH SAS nor the
-//   names of its contributors may be used to endorse or promote products
-//   derived from this software without specific prior written permission.
-
-//THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY
-//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-//DISCLAIMED.IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY
-//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Specialized;
-using System.Linq;
-using System.Net;
-using System.Net.Cache;
-using System.Security.Cryptography;
-using System.Text;
+// This file is inspired by https://github.com/ovh/csharp-ovh/blob/master/csharp-ovh/Client.cs , which
+// has been adapted to Certify in order to reduce dependencies and remove features useless in our context
+// Original file is copyright OVH SAS :
+
+//Copyright(c) 2013-2016, OVH SAS.
+//All rights reserved.
+
+//Redistribution and use in source and binary forms, with or without
+//modification, are permitted provided that the following conditions are met:
+
+//  * Redistributions of source code must retain the above copyright
+//   notice, this list of conditions and the following disclaimer.
+
+// * Redistributions in binary form must reproduce the above copyright
+//   notice, this list of conditions and the following disclaimer in the
+//   documentation and/or other materials provided with the distribution.
+
+// * Neither the name of OVH SAS nor the
+//   names of its contributors may be used to endorse or promote products
+//   derived from this software without specific prior written permission.
+
+//THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY
+//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+//DISCLAIMED.IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY
+//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Linq;
+using System.Net;
+using System.Net.Cache;
+using System.Security.Cryptography;
+using System.Text;
 using System.Threading.Tasks;
-using Newtonsoft.Json;
-
-namespace Certify.Providers.DNS.OVH
-{
-
-    // See https://github.com/ovh/csharp-ovh
-    // This module provides a simple C# wrapper over the OVH REST API.
-    // It handles requesting credential, signing queries...
-    // - To get your API keys: https://eu.api.ovh.com/createApp/
-    // - To get started with API: https://api.ovh.com/g934.first_step_with_api
-
-    /// <summary>
-    /// Low level OVH Client. It abstracts all the authentication and request
-    /// signing logic along with some nice tools helping with key generation.
-    /// All low level request logic including signing and error handling takes place
-    /// in "Client.Call" function. Convenient wrappers
-    /// "Client.Get" "Client.Post", "Client.Put",
-    /// "Client.Delete" should be used instead. "Client.Post",
-    /// "Client.Put" both accept arbitrary list of keyword arguments
-    /// mapped to "data" param of "Client.Call".
-    /// Example usage:
-    ///     from ovh import Client, APIError
-    ///     REGION = 'ovh-eu'
-    ///     APP_KEY= "<application key>"
-    ///     APP_SECRET= "<application secret key>"
-    ///     CONSUMER_KEY= "<consumer key>>"
-    ///     client = Client(REGION, APP_KEY, APP_SECRET, CONSUMER_KEY)
-    ///     try:
-    ///         print client.get('/me')
-    ///     except APIError as e:
-    ///         print "Ooops, failed to get my info:", e.msg
-    /// </summary>
-    public class OvhClient
-    {
-        private static readonly Dictionary<string, string> _endpoints = new Dictionary<string, string>()
-            {
-                { "ovh-eu", "https://eu.api.ovh.com/1.0/"               },
-                { "ovh-ca", "https://ca.api.ovh.com/1.0/"               },
-                { "kimsufi-eu", "https://eu.api.kimsufi.com/1.0/"       },
-                { "kimsufi-ca", "https://ca.api.kimsufi.com/1.0/"       },
-                { "soyoustart-eu", "https://eu.api.soyoustart.com/1.0/" },
-                { "soyoustart-ca", "https://ca.api.soyoustart.com/1.0/" },
-                { "runabove-ca", "https://api.runabove.com/1.0/"        }
-            };
-
-        private const int _defaultTimeout = 180;
-        private readonly WebClient _webClient;
-
-        /// <summary>
-        /// API Endpoint that this <c>Client</c> targets
-        /// </summary>
-        public string Endpoint { get; set; }
-        /// <summary>
-        /// API application Key
-        /// </summary>
-        public string ApplicationKey { get; set; }
-        /// <summary>
-        /// API application secret
-        /// </summary>
-        public string ApplicationSecret { get; set; }
-        /// <summary>
-        /// Consumer key that can be either <see cref="RequestConsumerKey">generated</see> or passed to the <see cref="ConfigurationManager">configuration manager</see>>
-        /// </summary>
-        public string ConsumerKey { get; set; }
-        /// <summary>
-        /// HTTP operations timeout
-        /// </summary>
-        public int Timeout { get; set; }
-
-        private bool _isTimeDeltaInitialized;
-        private long _timeDelta;
-        /// <summary>
-        /// Request signatures are valid only for a short amount of time to mitigate
-        /// risk of attack replay scenarii which requires to use a common time
-        /// reference.This function queries endpoint's time and computes the delta.
-        /// This entrypoint does not require authentication.
-        /// This method is *lazy*. It will only load it once even though it is used
-        /// for each request.
-        /// </summary>
-        public async Task<long> GetTimeDelta()
+using Newtonsoft.Json;
+
+namespace Certify.Providers.DNS.OVH
+{
+
+    // See https://github.com/ovh/csharp-ovh
+    // This module provides a simple C# wrapper over the OVH REST API.
+    // It handles requesting credential, signing queries...
+    // - To get your API keys: https://eu.api.ovh.com/createApp/
+    // - To get started with API: https://api.ovh.com/g934.first_step_with_api
+
+    /// <summary>
+    /// Low level OVH Client. It abstracts all the authentication and request
+    /// signing logic along with some nice tools helping with key generation.
+    /// All low level request logic including signing and error handling takes place
+    /// in "Client.Call" function. Convenient wrappers
+    /// "Client.Get" "Client.Post", "Client.Put",
+    /// "Client.Delete" should be used instead. "Client.Post",
+    /// "Client.Put" both accept arbitrary list of keyword arguments
+    /// mapped to "data" param of "Client.Call".
+    /// Example usage:
+    ///     from ovh import Client, APIError
+    ///     REGION = 'ovh-eu'
+    ///     APP_KEY= "<application key>"
+    ///     APP_SECRET= "<application secret key>"
+    ///     CONSUMER_KEY= "<consumer key>>"
+    ///     client = Client(REGION, APP_KEY, APP_SECRET, CONSUMER_KEY)
+    ///     try:
+    ///         print client.get('/me')
+    ///     except APIError as e:
+    ///         print "Ooops, failed to get my info:", e.msg
+    /// </summary>
+    public class OvhClient
+    {
+        private static readonly Dictionary<string, string> _endpoints = new Dictionary<string, string>()
+            {
+                { "ovh-eu", "https://eu.api.ovh.com/1.0/"               },
+                { "ovh-ca", "https://ca.api.ovh.com/1.0/"               },
+                { "kimsufi-eu", "https://eu.api.kimsufi.com/1.0/"       },
+                { "kimsufi-ca", "https://ca.api.kimsufi.com/1.0/"       },
+                { "soyoustart-eu", "https://eu.api.soyoustart.com/1.0/" },
+                { "soyoustart-ca", "https://ca.api.soyoustart.com/1.0/" },
+                { "runabove-ca", "https://api.runabove.com/1.0/"        }
+            };
+
+        private const int _defaultTimeout = 180;
+        private readonly WebClient _webClient;
+
+        /// <summary>
+        /// API Endpoint that this <c>Client</c> targets
+        /// </summary>
+        public string Endpoint { get; set; }
+        /// <summary>
+        /// API application Key
+        /// </summary>
+        public string ApplicationKey { get; set; }
+        /// <summary>
+        /// API application secret
+        /// </summary>
+        public string ApplicationSecret { get; set; }
+        /// <summary>
+        /// Consumer key that can be either <see cref="RequestConsumerKey">generated</see> or passed to the <see cref="ConfigurationManager">configuration manager</see>>
+        /// </summary>
+        public string ConsumerKey { get; set; }
+        /// <summary>
+        /// HTTP operations timeout
+        /// </summary>
+        public int Timeout { get; set; }
+
+        private bool _isTimeDeltaInitialized;
+        private long _timeDelta;
+        /// <summary>
+        /// Request signatures are valid only for a short amount of time to mitigate
+        /// risk of attack replay scenarii which requires to use a common time
+        /// reference.This function queries endpoint's time and computes the delta.
+        /// This entrypoint does not require authentication.
+        /// This method is *lazy*. It will only load it once even though it is used
+        /// for each request.
+        /// </summary>
+        public async Task<long> GetTimeDelta()
         {

             if (!_isTimeDeltaInitialized)
@@ -128,379 +128,384 @@
             }
             return _timeDelta;

-        }
-
-        private OvhClient()
-        {
-
-            _webClient = new WebClient();
-            _webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
-        }
-
-        public static string GetAvailableEndpointsAsString()
-        {
-            return string.Join(", ", _endpoints.Keys);
-        }
-
-        /// <summary>
-        /// Creates a new Client. No credential check is done at this point.
-        /// The "application_key" identifies your application while
-        /// "application_secret" authenticates it. On the other hand, the
-        /// "consumer_key" uniquely identifies your application's end user without
-        /// requiring his personal password.
-        /// If any of "endpoint", "application_key", "application_secret"
-        /// or "consumer_key" is not provided, this client will attempt to locate
-        /// from them from environment, %USERPROFILE%/.ovh.cfg or current_dir/.ovh.cfg.
-        /// </summary>
-        /// <param name="endpoint">API endpoint to use. Valid values in "Endpoints"</param>
-        /// <param name="applicationKey">Application key as provided by OVH</param>
-        /// <param name="applicationSecret">Application secret key as provided by OVH</param>
-        /// <param name="consumerKey">User token as provided by OVH</param>
-        /// <param name="timeout">Connection timeout for each request</param>
-        public OvhClient(string endpointName, string applicationKey,
-            string applicationSecret, string consumerKey,
-            int timeout = _defaultTimeout) : this()
-        {
-
-            if (!_endpoints.ContainsKey(endpointName))
-            {
-                var errorMsg = $"{endpointName} is not a valid endpointName. EndpointName should be one of the following values : {GetAvailableEndpointsAsString()}";
-                throw new ArgumentException(errorMsg, nameof(endpointName));
-            }
-
-            Endpoint = _endpoints[endpointName];
-            _webClient.BaseAddress = Endpoint;
-
-            //ApplicationKey
-            if (string.IsNullOrWhiteSpace(applicationKey))
-                throw new ArgumentException("ApplicationKey is required.", nameof(applicationKey));
-
-
-            ApplicationKey = applicationKey;
-
-
-            //SecretKey
-            if (string.IsNullOrWhiteSpace(applicationSecret))
-                throw new ArgumentException("ApplicationSecret is required.", nameof(applicationSecret));
-
-            ApplicationSecret = applicationSecret;
-
-            //ConsumerKey
-            if (string.IsNullOrWhiteSpace(consumerKey))
-                throw new ArgumentException("ConsumerKey is required.", nameof(consumerKey));
-            ConsumerKey = consumerKey;
-
-
-            //Timeout
-            Timeout = timeout;
-        }
-
-        #region GET
-
-        /// <summary>
-        /// Append arguments to the target URL
-        /// </summary>
-        /// <param name="target">Target URL</param>
-        /// <param name="kwargs">Key value arguments to append</param>
-        /// <returns>Url suffixed with kwargs</returns>
-        private string PrepareGetTarget(string target, NameValueCollection kwargs)
-        {
-            if (kwargs != null)
-            {
-                target += kwargs.ToString();
-            }
-
-            return target;
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="kwargs">Arguments to append to URL</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Get(string target, NameValueCollection kwargs = null, bool needAuth = true)
-        {
-            target = PrepareGetTarget(target, kwargs);
-            return await Call("GET", target, null, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call with an expected return type
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="kwargs">Arguments to append to URL</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Get<T>(string target, NameValueCollection kwargs = null, bool needAuth = true)
-        {
-            target = PrepareGetTarget(target, kwargs);
-            return await Call<T>("GET", target, null, needAuth);
-        }
-
-        #endregion
-
-        #region POST
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Object to serialize and send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Post(string target, object data, bool needAuth = true)
-        {
-            return await Call("POST", target, JsonConvert.SerializeObject(data), needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Post(string target, string data, bool needAuth = true)
-        {
-            return await Call("POST", target, data, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Object to serialize and send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Post<T>(string target, object data, bool needAuth = true)
-        {
-            return await Call<T>("POST", target, JsonConvert.SerializeObject(data), needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Post<T>(string target, string data, bool needAuth = true)
-        {
-            return await Call<T>("POST", target, data, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <typeparam name="Y">Input type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net with Strongly typed object as input</returns>
-        public async Task<T> Post<T, Y>(string target, Y data, bool needAuth = true)
-            where Y : class
-        {
-            return await Call<T, Y>("POST", target, data, needAuth);
-        }
-        #endregion
-
-        #region PUT
-        /// <summary>
-        /// Issues a PUT call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Object to serialize and send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Put(string target, object data, bool needAuth = true)
-        {
-            return await Call("PUT", target, JsonConvert.SerializeObject(data), needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Put(string target, string data, bool needAuth = true)
-        {
-            return await Call("PUT", target, data, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Object to serialize and send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Put<T>(string target, object data, bool needAuth = true)
-        {
-            return await Call<T>("PUT", target, JsonConvert.SerializeObject(data), needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Put<T>(string target, string data, bool needAuth = true)
-        {
-            return await Call<T>("PUT", target, data, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a POST call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <typeparam name="Y">Input type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="data">Json data to send as body</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net with Strongly typed object as input</returns>
-        public async Task<T> Put<T, Y>(string target, Y data, bool needAuth = true)
-            where Y : class
-        {
-            return await Call<T, Y>("PUT", target, data, needAuth);
-        }
-        #endregion PUT
-
-        #region DELETE
-        /// <summary>
-        /// Issues a DELETE call
-        /// </summary>
-        /// <param name="target">API method to call</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>Raw API response</returns>
-        public async Task<string> Delete(string target, bool needAuth = true)
-        {
-            return await Call("DELETE", target, null, needAuth);
-        }
-
-        /// <summary>
-        /// Issues a DELETE call
-        /// </summary>
-        /// <typeparam name="T">Expected return type</typeparam>
-        /// <param name="target">API method to call</param>
-        /// <param name="needAuth">If true, send authentication headers</param>
-        /// <returns>API response deserialized to T by JSON.Net</returns>
-        public async Task<T> Delete<T>(string target, bool needAuth = true)
-        {
-            return await Call<T>("DELETE", target, null, needAuth);
-        }
-
-        #endregion
-
-
-        /// <summary>
-        /// Lowest level call helper. If "consumerKey" is not "null", inject
-        /// authentication headers and sign the request.
-        /// Request signature is a sha1 hash on following fields, joined by '+'
-        ///  - application_secret
-        ///  - consumer_key
-        ///  - METHOD
-        ///  - full request url
-        ///  - body
-        ///  - server current time (takes time delta into account)
-        /// </summary>
-        /// <param name="method">HTTP verb. Usualy one of GET, POST, PUT, DELETE</param>
-        /// <param name="path">api entrypoint to call, relative to endpoint base path</param>
-        /// <param name="data">any json serializable data to send as request's body</param>
-        /// <param name="needAuth">if False, bypass signature</param>
-        /// <exception cref="HttpException">When underlying request failed for network reason</exception>
-        /// <exception cref="InvalidResponseException">when API response could not be decoded</exception>
-        private async Task<string> Call(string method, string path, string data = null, bool needAuth = true)
-        {
-            method = method.ToUpper();
-            if (path.StartsWith("/"))
-            {
-                path = path.Substring(1);
-            }
-            var target = Endpoint + path;
-            var headers = new WebHeaderCollection();
-            headers.Add("X-Ovh-Application", ApplicationKey);
-
-            if (data != null)
-            {
-                headers.Add("Content-type", "application/json");
-            }
-
-            if (needAuth)
-            {
-                if (ApplicationSecret == null)
-                {
-                    throw new InvalidOperationException("Application secret is missing.");
-                }
-                if (ConsumerKey == null)
-                {
-                    throw new InvalidOperationException("ConsumerKey is missing.");
-                }
-
-                var currentServerTimestamp = GetCurrentUnixTimestamp() + await GetTimeDelta();
-
-                var sha1Hasher = new SHA1Managed();
-                var toSign =
-                    string.Join("+", ApplicationSecret, ConsumerKey, method,
-                        target, data, currentServerTimestamp);
-                var binaryHash = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(toSign));
-                var signature = string.Join("",
-                    binaryHash.Select(x => x.ToString("X2"))).ToLower();
-
-                headers.Add("X-Ovh-Consumer", ConsumerKey);
-                headers.Add("X-Ovh-Timestamp", currentServerTimestamp.ToString());
-                headers.Add("X-Ovh-Signature", "$1$" + signature);
-            }
-
-            var response = "";
-
-            //NOTE: would be better to reuse some headers
-            _webClient.Headers = headers;
-            if (method != "GET")
-            {
-                response = await _webClient.UploadStringTaskAsync(path, method, data ?? "");
-            }
-            else
-            {
-                response = await _webClient.DownloadStringTaskAsync(path);
-            }
-            return response;
-        }
-
-        private async Task<T> Call<T>(string method, string path, string data = null, bool needAuth = true)
-        {
-            return JsonConvert.DeserializeObject<T>(await Call(method, path, data, needAuth));
-        }
-
-        private async Task<T> Call<T, Y>(string method, string path, Y data = null, bool needAuth = true)
-            where Y : class
-        {
-            return JsonConvert.DeserializeObject<T>(await Call(method, path, JsonConvert.SerializeObject(data), needAuth));
-        }
-
-
-        private async Task<long> ComputeTimeDelta()
-        {
-            var serverUnixTimestamp = await Get<long>("/auth/time", null, false);
-            var currentUnixTimestamp = GetCurrentUnixTimestamp();
-            return serverUnixTimestamp - currentUnixTimestamp;
-        }
-
-        private long GetCurrentUnixTimestamp()
-        {
-            return (long)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
-        }
-    }
-
-}
+        }
+
+        private OvhClient()
+        {
+
+            _webClient = new WebClient();
+            _webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
+        }
+
+        public static string GetAvailableEndpointsAsString()
+        {
+            return string.Join(", ", _endpoints.Keys);
+        }
+
+        /// <summary>
+        /// Creates a new Client. No credential check is done at this point.
+        /// The "application_key" identifies your application while
+        /// "application_secret" authenticates it. On the other hand, the
+        /// "consumer_key" uniquely identifies your application's end user without
+        /// requiring his personal password.
+        /// If any of "endpoint", "application_key", "application_secret"
+        /// or "consumer_key" is not provided, this client will attempt to locate
+        /// from them from environment, %USERPROFILE%/.ovh.cfg or current_dir/.ovh.cfg.
+        /// </summary>
+        /// <param name="endpoint">API endpoint to use. Valid values in "Endpoints"</param>
+        /// <param name="applicationKey">Application key as provided by OVH</param>
+        /// <param name="applicationSecret">Application secret key as provided by OVH</param>
+        /// <param name="consumerKey">User token as provided by OVH</param>
+        /// <param name="timeout">Connection timeout for each request</param>
+        public OvhClient(string endpointName, string applicationKey,
+            string applicationSecret, string consumerKey,
+            int timeout = _defaultTimeout) : this()
+        {
+
+            if (!_endpoints.ContainsKey(endpointName))
+            {
+                var errorMsg = $"{endpointName} is not a valid endpointName. EndpointName should be one of the following values : {GetAvailableEndpointsAsString()}";
+                throw new ArgumentException(errorMsg, nameof(endpointName));
+            }
+
+            Endpoint = _endpoints[endpointName];
+            _webClient.BaseAddress = Endpoint;
+
+            //ApplicationKey
+            if (string.IsNullOrWhiteSpace(applicationKey))
+            {
+                throw new ArgumentException("ApplicationKey is required.", nameof(applicationKey));
+            }
+
+            ApplicationKey = applicationKey;
+
+            //SecretKey
+            if (string.IsNullOrWhiteSpace(applicationSecret))
+            {
+                throw new ArgumentException("ApplicationSecret is required.", nameof(applicationSecret));
+            }
+
+            ApplicationSecret = applicationSecret;
+
+            //ConsumerKey
+            if (string.IsNullOrWhiteSpace(consumerKey))
+            {
+                throw new ArgumentException("ConsumerKey is required.", nameof(consumerKey));
+            }
+
+            ConsumerKey = consumerKey;
+
+            //Timeout
+            Timeout = timeout;
+        }
+
+        #region GET
+
+        /// <summary>
+        /// Append arguments to the target URL
+        /// </summary>
+        /// <param name="target">Target URL</param>
+        /// <param name="kwargs">Key value arguments to append</param>
+        /// <returns>Url suffixed with kwargs</returns>
+        private string PrepareGetTarget(string target, NameValueCollection kwargs)
+        {
+            if (kwargs != null)
+            {
+                target += kwargs.ToString();
+            }
+
+            return target;
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="kwargs">Arguments to append to URL</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Get(string target, NameValueCollection kwargs = null, bool needAuth = true)
+        {
+            target = PrepareGetTarget(target, kwargs);
+            return await Call("GET", target, null, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call with an expected return type
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="kwargs">Arguments to append to URL</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Get<T>(string target, NameValueCollection kwargs = null, bool needAuth = true)
+        {
+            target = PrepareGetTarget(target, kwargs);
+            return await Call<T>("GET", target, null, needAuth);
+        }
+
+        #endregion
+
+        #region POST
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Object to serialize and send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Post(string target, object data, bool needAuth = true)
+        {
+            return await Call("POST", target, JsonConvert.SerializeObject(data), needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Post(string target, string data, bool needAuth = true)
+        {
+            return await Call("POST", target, data, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Object to serialize and send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Post<T>(string target, object data, bool needAuth = true)
+        {
+            return await Call<T>("POST", target, JsonConvert.SerializeObject(data), needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Post<T>(string target, string data, bool needAuth = true)
+        {
+            return await Call<T>("POST", target, data, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <typeparam name="Y">Input type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net with Strongly typed object as input</returns>
+        public async Task<T> Post<T, Y>(string target, Y data, bool needAuth = true)
+            where Y : class
+        {
+            return await Call<T, Y>("POST", target, data, needAuth);
+        }
+        #endregion
+
+        #region PUT
+        /// <summary>
+        /// Issues a PUT call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Object to serialize and send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Put(string target, object data, bool needAuth = true)
+        {
+            return await Call("PUT", target, JsonConvert.SerializeObject(data), needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Put(string target, string data, bool needAuth = true)
+        {
+            return await Call("PUT", target, data, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Object to serialize and send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Put<T>(string target, object data, bool needAuth = true)
+        {
+            return await Call<T>("PUT", target, JsonConvert.SerializeObject(data), needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Put<T>(string target, string data, bool needAuth = true)
+        {
+            return await Call<T>("PUT", target, data, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a POST call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <typeparam name="Y">Input type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="data">Json data to send as body</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net with Strongly typed object as input</returns>
+        public async Task<T> Put<T, Y>(string target, Y data, bool needAuth = true)
+            where Y : class
+        {
+            return await Call<T, Y>("PUT", target, data, needAuth);
+        }
+        #endregion PUT
+
+        #region DELETE
+        /// <summary>
+        /// Issues a DELETE call
+        /// </summary>
+        /// <param name="target">API method to call</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>Raw API response</returns>
+        public async Task<string> Delete(string target, bool needAuth = true)
+        {
+            return await Call("DELETE", target, null, needAuth);
+        }
+
+        /// <summary>
+        /// Issues a DELETE call
+        /// </summary>
+        /// <typeparam name="T">Expected return type</typeparam>
+        /// <param name="target">API method to call</param>
+        /// <param name="needAuth">If true, send authentication headers</param>
+        /// <returns>API response deserialized to T by JSON.Net</returns>
+        public async Task<T> Delete<T>(string target, bool needAuth = true)
+        {
+            return await Call<T>("DELETE", target, null, needAuth);
+        }
+
+        #endregion
+
+
+        /// <summary>
+        /// Lowest level call helper. If "consumerKey" is not "null", inject
+        /// authentication headers and sign the request.
+        /// Request signature is a sha1 hash on following fields, joined by '+'
+        ///  - application_secret
+        ///  - consumer_key
+        ///  - METHOD
+        ///  - full request url
+        ///  - body
+        ///  - server current time (takes time delta into account)
+        /// </summary>
+        /// <param name="method">HTTP verb. Usualy one of GET, POST, PUT, DELETE</param>
+        /// <param name="path">api entrypoint to call, relative to endpoint base path</param>
+        /// <param name="data">any json serializable data to send as request's body</param>
+        /// <param name="needAuth">if False, bypass signature</param>
+        /// <exception cref="HttpException">When underlying request failed for network reason</exception>
+        /// <exception cref="InvalidResponseException">when API response could not be decoded</exception>
+        private async Task<string> Call(string method, string path, string data = null, bool needAuth = true)
+        {
+            method = method.ToUpper();
+            if (path.StartsWith("/"))
+            {
+                path = path.Substring(1);
+            }
+            var target = Endpoint + path;
+            var headers = new WebHeaderCollection();
+            headers.Add("X-Ovh-Application", ApplicationKey);
+
+            if (data != null)
+            {
+                headers.Add("Content-type", "application/json");
+            }
+
+            if (needAuth)
+            {
+                if (ApplicationSecret == null)
+                {
+                    throw new InvalidOperationException("Application secret is missing.");
+                }
+
+                if (ConsumerKey == null)
+                {
+                    throw new InvalidOperationException("ConsumerKey is missing.");
+                }
+
+                var currentServerTimestamp = GetCurrentUnixTimestamp() + await GetTimeDelta();
+
+                var sha1Hasher = new SHA1Managed();
+                var toSign =
+                    string.Join("+", ApplicationSecret, ConsumerKey, method,
+                        target, data, currentServerTimestamp);
+                var binaryHash = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(toSign));
+                var signature = string.Join("",
+                    binaryHash.Select(x => x.ToString("X2"))).ToLower();
+
+                headers.Add("X-Ovh-Consumer", ConsumerKey);
+                headers.Add("X-Ovh-Timestamp", currentServerTimestamp.ToString());
+                headers.Add("X-Ovh-Signature", "$1$" + signature);
+            }
+
+            var response = "";
+
+            //NOTE: would be better to reuse some headers
+            _webClient.Headers = headers;
+            if (method != "GET")
+            {
+                response = await _webClient.UploadStringTaskAsync(path, method, data ?? "");
+            }
+            else
+            {
+                response = await _webClient.DownloadStringTaskAsync(path);
+            }
+            return response;
+        }
+
+        private async Task<T> Call<T>(string method, string path, string data = null, bool needAuth = true)
+        {
+            return JsonConvert.DeserializeObject<T>(await Call(method, path, data, needAuth));
+        }
+
+        private async Task<T> Call<T, Y>(string method, string path, Y data = null, bool needAuth = true)
+            where Y : class
+        {
+            return JsonConvert.DeserializeObject<T>(await Call(method, path, JsonConvert.SerializeObject(data), needAuth));
+        }
+
+
+        private async Task<long> ComputeTimeDelta()
+        {
+            var serverUnixTimestamp = await Get<long>("/auth/time", null, false);
+            var currentUnixTimestamp = GetCurrentUnixTimestamp();
+            return serverUnixTimestamp - currentUnixTimestamp;
+        }
+
+        private long GetCurrentUnixTimestamp()
+        {
+            return (long)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
+        }
+    }
+
+}


Some commented nonsense

Some commented nonsense

--- KitchenSink.Lib/AutoCache.cs
+++ KitchenSink.Lib/AutoCache.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Concurrent;
 using System.Linq;
+using System.Linq.Expressions;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Runtime.CompilerServices;
@@ -220,6 +221,29 @@
             return typeBuilder.CreateType();
         }

+        //public static object MultiParam(object wrapper, object key, int counter, string methodName)
+        //{
+        //    var wrapperType = wrapper.GetType();
+        //    var innerField = wrapperType.GetField("_inner");
+        //    var inner = innerField.GetValue(wrapper);
+        //    var innerType = inner.GetType();
+        //    var cacheField = wrapperType.GetField("_cache" + counter);
+        //    var cache = cacheField.GetValue(wrapper);
+        //    var cacheType = cache.GetType();
+        //    var keyType = cacheType.GetGenericArguments()[0];
+        //    var valueType = cacheType.GetGenericArguments()[1];
+        //    var funcType = typeof(Func<,>).MakeGenericType(keyType, valueType);
+        //    var getOrAdd = cacheType.GetMethod("GetOrAdd", ArrayOf(keyType, funcType));
+        //    var keyParam = Expression.Parameter(keyType);
+        //    var funcParam = Expression.Parameter(funcType);
+        //    var argTypes = keyType.GetGenericArguments();
+        //    var innerMethod = innerType.GetMethod(methodName, argTypes);
+        //    var body = Expression.Call(innerMethod, ArrayOf(inner).Concat(args)); // TODO: Expression.Call(inner, innerMethod, key.Item1, key.Item2)
+        //    var lambda = Expression.Lambda(body, keyParam, funcParam);
+        //    var func = lambda.Compile();
+        //    return getOrAdd.Invoke(cache, ArrayOf(key, func));
+        //}
+
         private static CustomAttributeBuilder MakeCompilerGeneratedAttribute() =>
             new CustomAttributeBuilder(
                 typeof(CompilerGeneratedAttribute)


Added a log statement

Added a log statement

--- LA-6-ReturnSubtitles/run.csx
+++ LA-6-ReturnSubtitles/run.csx
@@ -67,6 +67,8 @@
     dynamic data = JsonConvert.DeserializeObject(jsonContent);

     log.Info(jsonContent);
+
+    log.Info($"asset id : {data.assetId}");

     if (data.assetId == null)
     {


Removed unnecessary Full Trust assertion.

--- src/Jails/Isolators/AppDomain/InvocationTarget.cs
+++ src/Jails/Isolators/AppDomain/InvocationTarget.cs
@@ -1,8 +1,6 @@
 using System;
-using System.IO;
 using System.Linq;
 using System.Reflection;
-using System.Security.Permissions;

 namespace Jails.Isolators.AppDomain
 {
@@ -19,7 +17,6 @@
             _target = new Lazy<object>(LoadTarget);
         }

-        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
         private object LoadTarget()
         {
             var type = (from asm in System.AppDomain.CurrentDomain.GetAssemblies()


Fix PInvokeTransitionFrame size for ARMEL (#4577)

Signed-off-by: Petr Bred <240e5f80fc72498dce662d23121702ab806c37e1@gmail.com>

--- src/JitInterface/src/CorInfoImpl.cs
+++ src/JitInterface/src/CorInfoImpl.cs
@@ -2336,8 +2336,11 @@
                 //      No need to save other preserved regs because of the JIT ensures that there are
                 //      no live GC references in callee saved registers around the PInvoke callsite.
                 int size = 5 * this.PointerSize;
-                if (_compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.ARM)
+
+                if (_compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.ARM ||
+                    _compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.ARMEL)
                     size += this.PointerSize; // m_ChainPointer
+
                 return (uint)size;
             }
         }


test suite: implemented repeat group

test suite: implemented repeat group

--- experimental/Slabs.Experimental.Console/TestSuiteBuilder.cs
+++ experimental/Slabs.Experimental.Console/TestSuiteBuilder.cs
@@ -78,9 +78,12 @@
 			_testGroups = new List<TestGroupBuilder>();
 		}

-		public TestSuiteBuilder Add(TestGroupBuilder testGroup)
+		public TestSuiteBuilder Add(TestGroupBuilder testGroup, int repeat = 1)
 		{
-			_testGroups.Add(testGroup);
+			if (repeat <= 1)
+				_testGroups.Add(testGroup);
+			else
+				_testGroups.AddRange(Enumerable.Repeat(testGroup, repeat));
 			return this;
 		}

@@ -89,6 +92,7 @@
 			var testGroups = _testGroups.SelectMany(x => x.Build()).ToList();
 			return new TestSuite(_serviceProvider, _loggerFactory, _name, testGroups);
 		}
+
 	}

 	// ReSharper disable once ClassNeverInstantiated.Global


Un-refactor GetOrCreateFooByGuid functions

Now that we need two different types of factories, one with an owner and
one without, the generic GetOrCreateCmObjectByGuid function was becoming
more complex than it's actually worth. Removing it and turning the four
"helper" functions into real factory functions has actually removed a
total of six lines of code -- a good clue that we were getting too
clever for our own good here.

--- src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs
+++ src/LfMerge/Actions/UpdateFdoFromMongoDbAction.cs
@@ -221,42 +221,36 @@
 			return fdoSense;
 		}

-		private TObject GetOrCreateCmObjectByGuid<TObject, TOwner>(Guid guid, TOwner owner, IRepository<TObject> repo, Func<TObject> factoryFuncNoOwner, Func<Guid, TOwner, TObject> factoryFuncWithOwner)
-			where TObject : ICmObject
-		{
-			TObject cmObject;
-			if (repo.TryGetObject(guid, out cmObject))
-			{
-				return cmObject;
-			}
-			else
-			{
-				if (owner == null)
-					cmObject = factoryFuncNoOwner();
-				else
-					cmObject = factoryFuncWithOwner(guid, owner);
-				return cmObject;
-			}
-		}
-
 		private ILexEntry GetOrCreateEntryByGuid(Guid guid)
 		{
-			return GetOrCreateCmObjectByGuid<ILexEntry, ICmObject>(guid, null, entryRepo, entryFactory.Create, null);
+			ILexEntry result;
+			if (!entryRepo.TryGetObject(guid, out result))
+				result = entryFactory.Create();
+			return result;
 		}

 		private ILexExampleSentence GetOrCreateExampleByGuid(Guid guid, ILexSense owner)
 		{
-			return GetOrCreateCmObjectByGuid<ILexExampleSentence, ILexSense>(guid, owner, exampleRepo, null, exampleFactory.Create);
+			ILexExampleSentence result;
+			if (!exampleRepo.TryGetObject(guid, out result))
+				result = exampleFactory.Create(guid, owner);
+			return result;
 		}

 		private ICmPicture GetOrCreatePictureByGuid(Guid guid)
 		{
-			return GetOrCreateCmObjectByGuid<ICmPicture, ICmObject>(guid, null, pictureRepo, pictureFactory.Create, null);
+			ICmPicture result;
+			if (!pictureRepo.TryGetObject(guid, out result))
+				result = pictureFactory.Create();
+			return result;
 		}

 		private ILexSense GetOrCreateSenseByGuid(Guid guid, ILexEntry owner)
 		{
-			return GetOrCreateCmObjectByGuid<ILexSense, ILexEntry>(guid, owner, senseRepo, null, senseFactory.Create);
+			ILexSense result;
+			if (!senseRepo.TryGetObject(guid, out result))
+				result = senseFactory.Create(guid, owner);
+			return result;
 		}

 		protected override ActionNames NextActionName


Fixed calling of static methods.

Fixed calling of static methods.

--- Lib/Compiler/MemberAccess.cs
+++ Lib/Compiler/MemberAccess.cs
@@ -135,7 +135,7 @@
                     throw new CompilerException("Cannot field the field '" + fieldName + "' in the object");
                 }
                 result = new Entry { type = Entry.Type.Method, value = methodInfo };
-                return true;
+                return !isStatic;
             }
         }


Build fix.

Build fix.

--- backend/src/Squidex.Domain.Apps.Entities/Contents/DomainObject/OperationContext.cs
+++ backend/src/Squidex.Domain.Apps.Entities/Contents/DomainObject/OperationContext.cs
@@ -9,7 +9,7 @@
 using System.Collections.Generic;
 using System.Security.Claims;
 using System.Threading.Tasks;
-using GraphQL.Utilities;
+using Microsoft.Extensions.DependencyInjection;
 using Squidex.Domain.Apps.Core.Schemas;
 using Squidex.Domain.Apps.Entities.Apps;
 using Squidex.Domain.Apps.Entities.Contents.Commands;
@@ -80,7 +80,7 @@
             };
         }

-        public T Resolve<T>()
+        public T Resolve<T>() where T : notnull
         {
             return serviceProvider.GetRequiredService<T>();
         }


Error throwing

Error throwing

--- src/OpenProtocolInterpreter/MIDs/MIDIdentifier.cs
+++ src/OpenProtocolInterpreter/MIDs/MIDIdentifier.cs
@@ -84,12 +84,19 @@
             int mid = int.Parse(package.Substring(4, 4));

             var func = this.messageInterpreterTemplates.FirstOrDefault(x => x.Key(mid));
+            if (func.Equals(default(KeyValuePair<Func<int, bool>, Func<string, MID>>)))
+                throw new NotImplementedException($"MID {mid} was not implemented, please register it on MidIntepreter constructor!");
+
             return func.Value(package);
         }

         public ExpectedMid IdentifyMid<ExpectedMid>(string package) where ExpectedMid : MID
         {
-            return (ExpectedMid)this.IdentifyMid(package);
+            MID mid = this.IdentifyMid(package);
+            if (mid.GetType().Equals(typeof(ExpectedMid)))
+                return (ExpectedMid)mid;
+
+            throw new InvalidCastException($"Package is MID {mid.GetType().Name}, cannot be casted to {typeof(ExpectedMid).Name}");
         }

         private bool isKeepAliveMessage(int mid) { return (mid == 9999); }


fix whitespace

fix whitespace

--- src/ConsoleMenu/Properties/AssemblyInfo.cs
+++ src/ConsoleMenu/Properties/AssemblyInfo.cs
@@ -9,7 +9,7 @@
 [assembly: AssemblyDescription ("Console menus are easy to build, complex menus are supported, and using them is simple and quick")]
 [assembly: AssemblyConfiguration ("")]
 [assembly: AssemblyCompany ("Sebastian Heuchler")]
-[assembly: AssemblyProduct ("ConsoleMenu")]
+[assembly: AssemblyProduct ("ConsoleMenu")]
 [assembly: AssemblyCopyright ("Copyright © 2015-18 Sebastian Heuchler")]
 [assembly: AssemblyTrademark ("")]
 [assembly: AssemblyCulture ("")]


Removing custom window flash workaround

Removing custom window flash workaround

This is achieved by NOT setting the owner for a glow window and by always adding SWP.NOACTIVATE on window position changes

--- src/ControlzEx/Controls/GlowWindow.xaml.cs
+++ src/ControlzEx/Controls/GlowWindow.xaml.cs
@@ -1,7 +1,8 @@
-#pragma warning disable 618
+#pragma warning disable 618
 namespace ControlzEx.Controls
 {
     using System;
+    using System.Diagnostics;
     using System.Runtime.InteropServices;
     using System.Windows;
     using System.Windows.Controls;
@@ -15,6 +16,7 @@
     using ControlzEx.Behaviors;
     using JetBrains.Annotations;

+    [DebuggerDisplay("{" + nameof(Title) + "}")]
     partial class GlowWindow
     {
         private readonly Func<Point, RECT, HT> getHitTestValue;
@@ -67,7 +69,8 @@
             this.Title = $"GlowWindow_{direction}";
             this.Name = this.Title;

-            this.Owner = owner;
+            // We must not set the owner of this window. Otherwise things like preventing window activation won't work correctly.
+            //this.Owner = owner;
             this.owner = owner;

             this.IsGlowing = true;
@@ -278,11 +281,13 @@
             var ws = NativeMethods.GetWindowStyle(this.windowHandle);
             var wsex = NativeMethods.GetWindowStyleEx(this.windowHandle);

+            ws &= ~WS.CAPTION; // We don't need a title bar
+            ws &= ~WS.SYSMENU; // We don't need a system context menu
             ws |= WS.POPUP;

             wsex &= ~WS_EX.APPWINDOW;
             wsex |= WS_EX.TOOLWINDOW;
-            wsex |= WS_EX.NOACTIVATE;
+            wsex |= WS_EX.NOACTIVATE; // We don't want our this window to be activated

             if (this.owner.ResizeMode == ResizeMode.NoResize || this.owner.ResizeMode == ResizeMode.CanMinimize)
             {
@@ -439,17 +444,16 @@
                     }
                     break;

+                case WM.WINDOWPOSCHANGED:
+                case WM.WINDOWPOSCHANGING:
+                    var wp = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
+                    wp.flags |= SWP.NOACTIVATE; // We always have to add SWP.NOACTIVATE to prevent accidental activation of this window
+                    Marshal.StructureToPtr(wp, lParam, true);
+                    break;
+
                 case WM.ACTIVATE:
-                    if (wParam.ToInt32() != 0
-                        && this.IsOwnerHandleValid())
-                    {
-                        handled = true;
-                        // We have to activate the owner async. Otherwise the active window on the taskbar is wrong.
-                        this.InvokeAsyncIfCanUpdateCore(DispatcherPriority.Send, () => NativeMethods.SetActiveWindow(this.ownerWindowHandle));
-                        // Flash window to mimic behavior of dialog activation for modal dialogs
-                        FlashWindowEx(this.ownerWindowHandle);
-                    }
-                    break;
+                    handled = true;
+                    return IntPtr.Zero;

                 case WM.MOUSEACTIVATE:
                     handled = true;
@@ -467,6 +471,7 @@
                 case WM.NCMBUTTONDBLCLK:
                 case WM.NCXBUTTONDOWN:
                 case WM.NCXBUTTONDBLCLK:
+                    handled = true;
                     if (this.IsOwnerHandleValid())
                     {
                         // WA_CLICKACTIVE = 2
@@ -530,20 +535,6 @@
             {
                 NativeMethods.SetWindowPos(this.windowHandle, this.ownerWindowHandle, 0, 0, 0, 0, SWP.NOMOVE | SWP.NOSIZE | SWP.NOACTIVATE);
             }
-
-            // The values used should be exactly the same as those being used by windows itself when flashing a modal dialog
-            bool FlashWindowEx(IntPtr hWnd)
-            {
-                var fInfo = new NativeMethods.FLASHWINFO();
-
-                fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
-                fInfo.hwnd = hWnd;
-                fInfo.dwFlags = NativeMethods.FlashWindowFlag.FLASHW_CAPTION;
-                fInfo.uCount = 8;
-                fInfo.dwTimeout = 50;
-
-                return NativeMethods.FlashWindowEx(ref fInfo);
-            }
         }

         private void InvokeIfCanUpdateCore([NotNull] Action invokeAction)


Disabled test-case which causes issues on Azure DevOps (and AppVeyor)

--- src/Dapplo.Windows.Tests/ClipboardTests.cs
+++ src/Dapplo.Windows.Tests/ClipboardTests.cs
@@ -126,7 +126,7 @@
         /// <summary>
         ///     Test monitoring the clipboard
         /// </summary>
-        [WpfFact]
+        //[WpfFact]
         public async Task TestClipboardMonitor_Text()
         {
             const string testString = "Dapplo.Windows.Tests.ClipboardTests";


Add extra tracing code

Add extra tracing code

It seems there's a bug in the GetMethodAddressForType method. This extra code should break if it's the emitted content that's wrong..

--- source/Cosmos.IL2CPU/VTablesImpl.cs
+++ source/Cosmos.IL2CPU/VTablesImpl.cs
@@ -113,9 +113,32 @@

 		public static int GetMethodAddressForType(int aType, int aMethodIndex) {
             	do {
+            		if (mTypes[aType].MethodIndexes == null) {
+							Console.Write("Type ");
+					        WriteNumber((uint)aType, 32);
+					        Console.WriteLine(", MethodIndexes is null!");
+					        while(true) ;
+					}
 					for (int i = 0; i < mTypes[aType].MethodIndexes.Length; i++) {
+						if (mTypes[aType].MethodAddresses == null) {
+							Console.Write("Type ");
+					        WriteNumber((uint)aType, 32);
+					        Console.WriteLine(", MethodAddresses is null!");
+					        while(true) ;
+						}
 						if (mTypes[aType].MethodIndexes[i] == aMethodIndex) {
-							return mTypes[aType].MethodAddresses[i];
+							var xResult = mTypes[aType].MethodAddresses[i];
+							if (xResult < 1048576) // if pointer is under 1MB, some issue exists!
+							{
+								Console.Write("Type ");
+						        WriteNumber((uint)aType, 32);
+						        Console.Write(", MethodIndex = ");
+						        WriteNumber((uint)aMethodIndex, 32);
+						        Console.WriteLine("");
+						        Console.WriteLine("Method found, but address invalid!");
+						        while(true) ;
+							}
+							return xResult;
 						}
 					}
                     if (aType == mTypes[aType].BaseTypeIdentifier)
@@ -147,4 +170,4 @@
 		[FieldOffset(12)]
 		public int[] MethodAddresses;
 	}
-}+}


Remove old, now-unused testing code from FwProject

--- src/LfMerge/FieldWorks/FwProject.cs
+++ src/LfMerge/FieldWorks/FwProject.cs
@@ -109,69 +109,6 @@

 			return fdoCache;
 		}
-
-		private void DelMe() {
-			Console.WriteLine("Starting UpdateFdoFromMongoDb");
-			// TODO: Get connection string from config, not hardcoded
-			string HardcodedMongoConnectionString = "mongodb://languageforge.local/scriptureforge";
-			string HardcodedProjectCode = "thai_food";
-			string HardcodedDatabasePrefix = "sf_"; // TODO: Is there a better way to get the prefix?
-			//string DatabaseName = "sf_" + HardcodedProjectCode;
-			var client = new MongoClient(HardcodedMongoConnectionString);
-			var sf = client.GetDatabase("scriptureforge");
-			var projects = sf.GetCollection<BsonDocument>("projects");
-			var F = Builders<BsonDocument>.Filter; // Make the next line shorter to read
-			var filter = F.Eq("appName", "lexicon") & F.Eq("projectCode", HardcodedProjectCode);
-			var project = projects.Find(filter).Limit(1).FirstOrDefaultAsync().Result; // Filter on server
-			//var project = projects.Find(doc => doc["appName"] == "lexicon" && doc["projectCode"] == HardcodedProjectCode)
-			//	.Limit(1).ToListAsync().Result.FirstOrDefault(); // Filter on client
-			if (project != null)
-			{
-				Console.WriteLine("Project \"{0}\" has code {1}", project["projectName"], project["projectCode"]);
-				var config = project["config"];
-				var fields = config["entry"]["fieldOrder"] as BsonArray;
-				foreach (var field in fields)
-					Console.WriteLine("  and has field: {0}", field);
-				string dbName = HardcodedDatabasePrefix + project["projectCode"];
-				var db = client.GetDatabase(dbName);
-				var collection = db.GetCollection<BsonDocument>("lexicon");
-				var bar = collection.Find(_ => true).ToListAsync().Result; // Without the Result, we would have to use await
-				foreach (var item in bar)
-				{
-					// To do this properly, we should get the inputSystems from the config["entry"]["fields"]["lexeme"] list
-					// For now, we hardcode the two th-fonipa and th writing system names
-					string th_fonipa;
-					try {
-						th_fonipa = item["lexeme"]["th-fonipa"]["value"].AsString;
-						Console.WriteLine("Item: {0}", th_fonipa);
-					}
-					catch(KeyNotFoundException) {
-						Console.WriteLine("No fonipa for {0}", item["lexeme"]["th"]["value"]);
-					}
-				}
-
-			}
-			Console.WriteLine("Stopping UpdateFdoFromMongoDb");
-
-			return;
-		}
-
-		private static IEnumerable<string> GetListOfMongoDatabases(MongoClient client)
-		{
-			IAsyncCursor<BsonDocument> foo = client.ListDatabasesAsync().Result;
-			List<BsonDocument> l = foo.ToListAsync().Result;
-			IEnumerable<string> result = l.Select(doc => doc["name"].AsString);
-			return result;
-		}
-
-		private static IEnumerable<string> GetListOfCollections(IMongoDatabase db)
-		{
-			IAsyncCursor<BsonDocument> foo = db.ListCollectionsAsync().Result;
-			List<BsonDocument> l = foo.ToListAsync().Result;
-			IEnumerable<string> result = l.Select(doc => doc["name"].AsString);
-			return result;
-		}
-
 	}
 }


Fix Now messages sent from a server without clients are recycled

--- Lidgren.Network/NetServer.cs
+++ Lidgren.Network/NetServer.cs
@@ -25,8 +25,11 @@
 		public void SendToAll(NetOutgoingMessage msg, NetDeliveryMethod method)
 		{
 			var all = this.Connections;
-			if (all.Count <= 0)
+			if (all.Count <= 0) {
+				if (msg.m_isSent == false)
+					Recycle(msg);
 				return;
+			}

 			SendMessage(msg, all, method, 0);
 		}
@@ -41,8 +44,11 @@
 		public void SendToAll(NetOutgoingMessage msg, NetConnection except, NetDeliveryMethod method, int sequenceChannel)
 		{
 			var all = this.Connections;
-			if (all.Count <= 0)
+			if (all.Count <= 0) {
+				if (msg.m_isSent == false)
+					Recycle(msg);
 				return;
+			}

 			if (except == null)
 			{


Update MichaelRidland.cs

Update MichaelRidland.cs

--- src/Firehose.Web/Authors/MichaelRidland.cs
+++ src/Firehose.Web/Authors/MichaelRidland.cs
@@ -14,7 +14,7 @@

         public string EmailAddress => "michael@xam-consulting.com";

-        public string ShortBioOrTagLine => "director of an Xamarin consultancy";
+        public string ShortBioOrTagLine => "";

         public Uri WebSite => new Uri("http://www.michaelridland.com");

@@ -29,4 +29,4 @@
         public string GitHubHandle => string.Empty;
         public GeoPosition Position => new GeoPosition(-33.8688200, 151.2092960);
     }
-}+}


Should fix build

Should fix build

--- src/NLog.AirBrake/AirBrakeTarget.cs
+++ src/NLog.AirBrake/AirBrakeTarget.cs
@@ -39,7 +39,7 @@
     /// <param name="logEvent">Logging event to be written out.</param>
     protected override void Write(LogEventInfo logEvent)
     {
-        var notice = (logEvent.Exception != null) ? SharpbrakeClient.BuildNotice(logEvent.Exception) : SharpbrakeClient.BuildNotice(logEvent.ToAirBrakeError());
+        var notice = (logEvent.Exception != null) ? SharpbrakeClient.BuildNotice(logEvent.Exception) : SharpbrakeClient.BuildNotice(ExtensionHolder.ToAirBrakeError(logEvent));
         // Override the notice message so we have the full exception
         // message, including the messages of the inner exceptions.
         // Also, include the log message, if it is set.


Untabified

Untabified

--- src/FluentMigrator.Runner/VersionLoader.cs
+++ src/FluentMigrator.Runner/VersionLoader.cs
@@ -143,9 +143,9 @@
         {
             var expression = new DeleteDataExpression { TableName = VersionTableMetaData.TableName, SchemaName = VersionTableMetaData.SchemaName };
             expression.Rows.Add(new DeletionDataDefinition
-									{
-										new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version)
-									});
+                                    {
+                                        new KeyValuePair<string, object>(VersionTableMetaData.ColumnName, version)
+                                    });
             expression.ExecuteWith(Processor);
         }
     }


WIP #58 - Add transaction so that service actually does something

--- Tests/Agiil.Web.TestBuild/Controllers/AddUserController.cs
+++ Tests/Agiil.Web.TestBuild/Controllers/AddUserController.cs
@@ -3,6 +3,7 @@
 using Agiil.Auth;
 using Agiil.Domain.Auth;
 using Agiil.Web.Models;
+using CSF.Data;

 namespace Agiil.Web.Controllers
 {
@@ -12,6 +13,7 @@
     readonly IUserCreator userCreator;
     readonly IGetsUserByUsername userQuery;
     readonly IUserPasswordUpdater passwordChanger;
+    readonly ITransactionCreator transactionCreator;

     public IHttpActionResult Post(CreateUserModel model)
     {
@@ -20,25 +22,34 @@

       bool exists;

-      var existingUser = userQuery.Get(model.username);
-      if(existingUser == null)
+      using(var tran = transactionCreator.BeginTransaction())
       {
-        userCreator.Add(model.username, model.password);
-        exists = false;
+        var existingUser = userQuery.Get(model.username);
+
+        if(existingUser == null)
+        {
+          userCreator.Add(model.username, model.password);
+          exists = false;
+        }
+        else
+        {
+          passwordChanger.ChangePassword(existingUser, model.password);
+          exists = true;
+        }
+
+        tran.Commit();
       }
-      else
-      {
-        passwordChanger.ChangePassword(existingUser, model.password);
-        exists = true;
-      }
-
+
       return Ok(exists? $"The existing user '{model.username}' was updated" : $"The user '{model.username}' was created");
     }

     public AddUserController(IUserCreator userCreator,
                              IGetsUserByUsername userQuery,
-                             IUserPasswordUpdater passwordChanger)
+                             IUserPasswordUpdater passwordChanger,
+                             ITransactionCreator transactionCreator)
     {
+      if(transactionCreator == null)
+        throw new ArgumentNullException(nameof(transactionCreator));
       if(passwordChanger == null)
         throw new ArgumentNullException(nameof(passwordChanger));
       if(userQuery == null)
@@ -49,6 +60,7 @@
       this.userCreator = userCreator;
       this.passwordChanger = passwordChanger;
       this.userQuery = userQuery;
+      this.transactionCreator = transactionCreator;
     }
   }
 }


price not set

price not set

--- src/Nethereum.Contracts/Function.cs
+++ src/Nethereum.Contracts/Function.cs
@@ -105,7 +105,7 @@
            HexBigInteger value, params object[] functionInput)
         {
             var encodedInput = GetData(functionInput);
-            return base.CreateTransactionInput(encodedInput, from, gas, value);
+            return base.CreateTransactionInput(encodedInput, from, gas, gasPrice, value);
         }


Comments Update in TestRunner Config

Comments Update in TestRunner Config

Fixed some spelling mistakes and added some comments for un-documented
lines

--- Tests/Cosmos.TestRunner.Core/DefaultEngineConfiguration.cs
+++ Tests/Cosmos.TestRunner.Core/DefaultEngineConfiguration.cs
@@ -12,24 +12,28 @@
                 throw new ArgumentNullException("engine");
             }

+            // Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then
+            // that kernel will be marked as a failiure and terminated
             engine.AllowedSecondsInKernel = 1800;

-            // If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are ran.
+            // If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run.
             engine.RunTargets.Add(RunTargetEnum.Bochs);

-            // if you're working on the compiler (or other lower parts), you can choose to run the compiler in process
-            // 1 thing to keep in mind though, is that this only works with 1 kernel at a time!
+            // If you're working on the compiler (or other lower parts), you can choose to run the compiler in process
+            // one thing to keep in mind though, is that this only works with 1 kernel at a time!
             //engine.RunIL2CPUInProcess = true;
+
             engine.EnableStackCorruptionChecks = false;
             //engine.RunWithGDB = true;

+            // Select kernels to be tested by adding them to the engine
             //engine.AddKernel(typeof(Cosmos.Compiler.Tests.Bcl.Kernel).Assembly.Location);
             //engine.AddKernel(typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel).Assembly.Location);
             //engine.AddKernel(typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel).Assembly.Location);
             //engine.AddKernel(typeof(SimpleStructsAndArraysTest.Kernel).Assembly.Location);
             //engine.AddKernel(typeof(VGACompilerCrash.Kernel).Assembly.Location);

-            // known bugs, therefor disabled for now:
+            // Known bugs, therefore disabled for now:
             //engine.AddKernel(typeof(BoxingTests.Kernel).Assembly.Location);

             // Experimental stuff:


portable package support

portable package support

--- src/FullBuild/Commands/Packages+Install.cs
+++ src/FullBuild/Commands/Packages+Install.cs
@@ -68,9 +68,9 @@
             GenerateTargetsForProject(pkg);
         }

-        private static XElement Generatewhen(IEnumerable<string> foldersToTry, string fxVersion, DirectoryInfo libDir)
-        {
-            foreach (var folderToTry in foldersToTry)
+        private static XElement GenerateWhen(IEnumerable<string> fxFolderNamesToTry, string fxVersion, DirectoryInfo libDir)
+        {
+            foreach (var folderToTry in fxFolderNamesToTry)
             {
                 var fxLibs = libDir.GetDirectory(folderToTry);
                 if (fxLibs.Exists)
@@ -86,6 +86,30 @@
             return null;
         }

+        private static XElement GeneratePortableWhen(IEnumerable<string> fxFolderNamesToTry, string fxVersion, DirectoryInfo libDir)
+        {
+            const string portablePrefix = "portable-";
+            foreach (var folderToTry in fxFolderNamesToTry)
+            {
+                var portableDirs = libDir.GetDirectories(portablePrefix + "*");
+                foreach (var portableDir in portableDirs)
+                {
+                    var portableDirName = portableDir.Name;
+                    var supportedFrameworks = portableDirName.Substring(portablePrefix.Length).Split('+');
+                    if (supportedFrameworks.Any(x => x.InvariantEquals(folderToTry)))
+                    {
+                        var condition = String.Format("'$(TargetFrameworkVersion)' == '{0}'", fxVersion);
+                        var when = new XElement(XmlHelpers.NsMsBuild + "When",
+                                                new XAttribute("Condition", condition),
+                                                GenerateItemGroup(portableDir));
+                        return when;
+                    }
+                }
+            }
+
+            return null;
+        }
+
         private static void GenerateTargetsForProject(Package package)
         {
             var pkgsDir = WellKnownFolders.GetPackageDirectory();
@@ -104,19 +128,42 @@
                     var fxVersion = FrameworkVersion.CompatibilityOrder[i];

                     XElement when = null;
+
+                    // first try to find a standard framework version
                     for (var j = i; j >= 0; --j)
                     {
                         var substituteVersion = FrameworkVersion.CompatibilityOrder[j];
-                        var foldersToTry = FrameworkVersion.FxVersion2Folder[substituteVersion];
-
-                        when = Generatewhen(foldersToTry, fxVersion, libDir);
+                        var fxFolderNamesToTry = FrameworkVersion.FxVersion2Folder[substituteVersion];
+
+                        when = GenerateWhen(fxFolderNamesToTry, fxVersion, libDir);
                         if (null != when)
                         {
                             break;
                         }
                     }

-                    when = when ?? Generatewhen(new[] {""}, fxVersion, libDir);
+                    // if nothing found then try to find a portable version
+                    if (null == when)
+                    {
+                        for (var j = i; j >= 0; --j)
+                        {
+                            var substituteVersion = FrameworkVersion.CompatibilityOrder[j];
+                            var fxFolderNamesToTry = FrameworkVersion.FxVersion2Folder[substituteVersion];
+
+                            when = GeneratePortableWhen(fxFolderNamesToTry, fxVersion, libDir);
+                            if (null != when)
+                            {
+                                break;
+                            }
+                        }
+                    }
+
+                    // nothing found then use default version
+                    if (null == when)
+                    {
+                        when = GenerateWhen(new[] {""}, fxVersion, libDir);
+                    }
+
                     whens.Add(when);
                 }
             }


Fixed issue with routed home index action not working correctly on start up

--- src/SFA.DAS.EAS.Web/Controllers/HomeController.cs
+++ src/SFA.DAS.EAS.Web/Controllers/HomeController.cs
@@ -24,7 +24,9 @@
             _configuration = configuration;
         }

+        [Route("~/")]
         [Route]
+        [Route("Index")]
         public async Task<ActionResult> Index()
         {
             var userId = OwinWrapper.GetClaimValue("sub");
@@ -160,14 +162,14 @@
                 TempData["virtualPageUrl"] = @"/user-changed-email";
                 TempData["virtualPageTitle"] = @"User Action - Changed Email";

-	            await OwinWrapper.UpdateClaims();
-
-	            var userRef = OwinWrapper.GetClaimValue("sub");
-	            var email = OwinWrapper.GetClaimValue("email");
-	            var firstName = OwinWrapper.GetClaimValue(DasClaimTypes.GivenName);
-	            var lastName = OwinWrapper.GetClaimValue(DasClaimTypes.FamilyName);
-
-	            await _homeOrchestrator.SaveUpdatedIdentityAttributes(userRef,email,firstName,lastName);
+                await OwinWrapper.UpdateClaims();
+
+                var userRef = OwinWrapper.GetClaimValue("sub");
+                var email = OwinWrapper.GetClaimValue("email");
+                var firstName = OwinWrapper.GetClaimValue(DasClaimTypes.GivenName);
+                var lastName = OwinWrapper.GetClaimValue(DasClaimTypes.FamilyName);
+
+                await _homeOrchestrator.SaveUpdatedIdentityAttributes(userRef, email, firstName, lastName);
             }
             return RedirectToAction("Index");
         }