fix unhandle exception over duplex protocol

--- SignalGo.Server/ServiceManager/Providers/BaseProvider.cs
+++ SignalGo.Server/ServiceManager/Providers/BaseProvider.cs
@@ -390,12 +390,17 @@
                             }
                             catch (Exception ex)
                             {
-                                if (serverBase.ErrorHandlingFunction != null)
-                                    result = serverBase.ErrorHandlingFunction(ex, serviceType, method, client);
                                 exception = ex;
                                 serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase CallMethod: {methodName}");
-                                callback.IsException = true;
-                                callback.Data = ServerSerializationHelper.SerializeObject(ex.ToString(), serverBase, isEnabledReferenceResolver: isEnabledReferenceResolver, isEnabledReferenceResolverForArray: isEnabledReferenceResolverForArray);
+                                if (serverBase.ErrorHandlingFunction != null)
+                                {
+                                    callback.Data = ServerSerializationHelper.SerializeObject(serverBase.ErrorHandlingFunction(ex, serviceType, method, client));
+                                }
+                                else
+                                {
+                                    callback.Data = ServerSerializationHelper.SerializeObject(ex.ToString(), serverBase, isEnabledReferenceResolver: isEnabledReferenceResolver, isEnabledReferenceResolverForArray: isEnabledReferenceResolverForArray);
+                                    callback.IsException = true;
+                                }
                             }
                         }
                     }
@@ -404,13 +409,15 @@
                 {
                     exception = ex;
                     serverBase.AutoLogger.LogError(ex, $"{client.IPAddress} {client.ClientId} ServerBase CallMethod 2: {methodName} serviceName: {serviceName}");
-                    callback.IsException = true;
                     if (serverBase.ErrorHandlingFunction != null)
                     {
                         callback.Data = ServerSerializationHelper.SerializeObject(serverBase.ErrorHandlingFunction(ex, serviceType, method, client));
                     }
                     else
+                    {
+                        callback.IsException = true;
                         callback.Data = ServerSerializationHelper.SerializeObject(ex.ToString(), serverBase);
+                    }
                 }
                 finally
                 {


Web application property values wet with the helper were never actually set.

--- Source/GSoft.Dynamite/Configuration/PropertyBagHelper.cs
+++ Source/GSoft.Dynamite/Configuration/PropertyBagHelper.cs
@@ -145,6 +145,7 @@
         {
             var webApplication = SPWebApplication.Lookup(webApplicationUrl);
             this.Set(webApplication.Properties, null, propertyBagValues, webApplicationUrl.AbsoluteUri);
+            webApplication.Update();
         }
         #endregion Web Application scope


UseWebSockets early

UseWebSockets early

--- Source/GraphQLTemplate/Source/GraphQLTemplate/Startup.cs
+++ Source/GraphQLTemplate/Source/GraphQLTemplate/Startup.cs
@@ -108,6 +108,9 @@
                 .UseIf(
                     this.webHostEnvironment.IsDevelopment(),
                     x => x.UseDeveloperExceptionPage())
+#if Subscriptions
+                .UseWebSockets()
+#endif
                 .UseRouting()
 #if CORS
                 .UseCors(CorsPolicyName.AllowAny)
@@ -133,12 +136,7 @@
                         builder.MapHealthChecks("/status/self", new HealthCheckOptions() { Predicate = _ => false });
 #endif
 #endif
-#if Subscriptions
-                    })
-                .UseWebSockets();
-#else
                     });
-#endif

     }
 }


Update PixelBandGetter.cs

Update PixelBandGetter.cs

--- src/RasterIO/PixelBandGetter.cs
+++ src/RasterIO/PixelBandGetter.cs
@@ -1,41 +1,30 @@
-// Copyright 2010 Green Code LLC
-// All rights reserved.
-//
-// The copyright holders license this file under the New (3-clause) BSD
-// License (the "License").  You may not use this file except in
-// compliance with the License.  A copy of the License is available at
-//
-//   http://www.opensource.org/licenses/BSD-3-Clause
-//
-// and is included in the NOTICE.txt file distributed with this work.
-//
-// Contributors:
+// Contributors:
 //   James Domingo, Green Code LLC

 using Landis.SpatialModeling;
-using System;
-
-namespace Landis.RasterIO
-{
-    /// <summary>
-    /// Accessor for getting a particular pixel band as another data type.
-    /// </summary>
-    public class PixelBandGetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandGetter<TRasterBand>
-        where TPixelBand : struct
-        where TRasterBand : struct
-    {
-        private Converter<TPixelBand, TRasterBand> converter;
-
-        public PixelBandGetter(PixelBand                          pixelBand,
-                               Converter<TPixelBand, TRasterBand> converter)
-            : base(pixelBand)
-        {
-            this.converter = converter;
-        }
-
-        public TRasterBand GetValue()
-        {
-            return converter(pixelBand.Value);
-        }
-    }
-}
+using System;
+
+namespace Landis.RasterIO
+{
+    /// <summary>
+    /// Accessor for getting a particular pixel band as another data type.
+    /// </summary>
+    public class PixelBandGetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandGetter<TRasterBand>
+        where TPixelBand : struct
+        where TRasterBand : struct
+    {
+        private Converter<TPixelBand, TRasterBand> converter;
+
+        public PixelBandGetter(PixelBand                          pixelBand,
+                               Converter<TPixelBand, TRasterBand> converter)
+            : base(pixelBand)
+        {
+            this.converter = converter;
+        }
+
+        public TRasterBand GetValue()
+        {
+            return converter(pixelBand.Value);
+        }
+    }
+}


Fix style warnings

Fix style warnings

--- Source/Serilog.Exceptions/Core/ExceptionPropertiesBag.cs
+++ Source/Serilog.Exceptions/Core/ExceptionPropertiesBag.cs
@@ -59,10 +59,13 @@
             this.AddPairToProperties(key, value);
         }

+        /// <inheritdoc />
+        public bool ContainsProperty(string key) => this.properties.ContainsKey(key);
+
         private void AddPairToProperties(string key, object? value)
         {
 #if NET5_0
-            int i = 0;
+            var i = 0;
             while (!this.properties.TryAdd(key, value) && i < 5)
             {
                 key += "$";
@@ -82,7 +85,6 @@
         /// </summary>
         private string MakeSureKeyIsUnique(string key)
         {
-
             var i = 0;
             while (this.properties.ContainsKey(key) && i < 5)
             {
@@ -92,8 +94,5 @@

             return key;
         }
-
-        /// <inheritdoc />
-        public bool ContainsProperty(string key) => this.properties.ContainsKey(key);
     }
 }


Update PixelBandSetter.cs

Update PixelBandSetter.cs

--- src/RasterIO/PixelBandSetter.cs
+++ src/RasterIO/PixelBandSetter.cs
@@ -1,41 +1,30 @@
-// Copyright 2010 Green Code LLC
-// All rights reserved.
-//
-// The copyright holders license this file under the New (3-clause) BSD
-// License (the "License").  You may not use this file except in
-// compliance with the License.  A copy of the License is available at
-//
-//   http://www.opensource.org/licenses/BSD-3-Clause
-//
-// and is included in the NOTICE.txt file distributed with this work.
-//
-// Contributors:
+// Contributors:
 //   James Domingo, Green Code LLC

 using Landis.SpatialModeling;
-using System;
-
-namespace Landis.RasterIO
-{
-    /// <summary>
-    /// Accessor for setting a particular pixel band with another data type.
-    /// </summary>
-    public class PixelBandSetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandSetter<TRasterBand>
-        where TPixelBand : struct
-        where TRasterBand : struct
-    {
-        private Converter<TRasterBand, TPixelBand> converter;  // TRasterBand -> TPixelBand
-
-        public PixelBandSetter(PixelBand                          pixelBand,
-                               Converter<TRasterBand, TPixelBand> converter)
-            : base(pixelBand)
-        {
-            this.converter = converter;
-        }
-
-        public void SetValue(TRasterBand newValue)
-        {
-            pixelBand.Value = converter(newValue);
-        }
-    }
-}
+using System;
+
+namespace Landis.RasterIO
+{
+    /// <summary>
+    /// Accessor for setting a particular pixel band with another data type.
+    /// </summary>
+    public class PixelBandSetter<TPixelBand, TRasterBand> : PixelBandAccessor<TPixelBand>, IPixelBandSetter<TRasterBand>
+        where TPixelBand : struct
+        where TRasterBand : struct
+    {
+        private Converter<TRasterBand, TPixelBand> converter;  // TRasterBand -> TPixelBand
+
+        public PixelBandSetter(PixelBand                          pixelBand,
+                               Converter<TRasterBand, TPixelBand> converter)
+            : base(pixelBand)
+        {
+            this.converter = converter;
+        }
+
+        public void SetValue(TRasterBand newValue)
+        {
+            pixelBand.Value = converter(newValue);
+        }
+    }
+}


Significantly simplified the AutoInjectionTaskMergeDetail logic

--- Sources/Bijectiv/Factory/AutoInjectionTaskMergeDetail.cs
+++ Sources/Bijectiv/Factory/AutoInjectionTaskMergeDetail.cs
@@ -38,8 +38,39 @@
     /// <summary>
     /// The <see cref="IMerge"/> specific <see cref="AutoInjectionTask"/> implementation detail.
     /// </summary>
-    public class AutoInjectionTaskMergeDetail : AutoInjectionTaskTransformDetail
+    public class AutoInjectionTaskMergeDetail : AutoInjectionTaskDetail
     {
+        /// <summary>
+        /// An expression that performs a merge from a <see cref="IInjectionContext"/>.
+        /// </summary>
+        private static readonly Expression MergeExpression = ((Expression<Func<IMergeResult>>)(
+            () =>
+                Placeholder.Of<IInjectionContext>("context")
+                    .InjectionStore.Resolve<IMerge>(
+                        Placeholder.Of<Type>("sourceMemberType"),
+                        Placeholder.Of<Type>("targetMemberType")).Merge(
+                            Placeholder.Of<object>("sourceMember"),
+                            Placeholder.Of<object>("targetMember"),
+                            Placeholder.Of<IInjectionContext>("context")))).Body;
+
+        /// <summary>
+        /// A <see cref="IMergeResult.Target"/> variable.
+        /// </summary>
+        private static readonly ParameterExpression ResultVariable = Expression.Variable(typeof(IMergeResult));
+
+        /// <summary>
+        /// An expression that accesses <see cref="IMergeResult.Target"/>.
+        /// </summary>
+        private static readonly Expression ResultTargetExpression = ((Expression<Func<object>>)(
+            () => Placeholder.Of<IMergeResult>("result").Target)).Body;
+
+        /// <summary>
+        /// An expression that decides whether <see cref="IMergeResult.Action"/> is
+        /// <see cref="PostMergeAction.Replace"/>.
+        /// </summary>
+        private static readonly Expression IsReplaceActionExpression = ((Expression<Func<bool>>)(
+            () => Placeholder.Of<IMergeResult>("result").Action == PostMergeAction.Replace)).Body;
+
         /// <summary>
         /// Creates the member mapping <see cref="Expression"/>.
         /// </summary>
@@ -61,122 +92,101 @@
             MemberInfo targetMember)
         {
             /* Creates an expression that is equivalent to:
-             *
-             * if (target.Member == null)
-             * {
-             *     target.Member = transform(source.Member)
-             * }
-             * else
-             * {
-             *      var merge = store.Resolve<IMerge>(source.Member.Type, target.Member.Type)
-             *      if (merge == null)
-             *      {
-             *          target.Member = transform(source.Member)
-             *      }
-             *      else
-             *      {
-             *          var result = merge(source.Member, target.Member)
-             *          if (result.Action == Replace)
-             *          {
-             *              target.Member = result.Target
-             *          }
-             *      }
-             * }
+             *
+             *  var merge = store.Resolve<IMerge>(source.Member.Type, target.Member.Type)
+             *  var result = merge(source.Member, target.Member)
+             *  if (result.Action == Replace)
+             *  {
+             *      target.Member = result.Target
+             *  }
              */

+            var replaceTargetExpression = Expression.Assign(
+                targetMember.GetAccessExpression(scaffold.Target),
+                Expression.Convert(ResultTargetExpression, targetMember.GetReturnType()));
+
+            Expression template = Expression.Block(
+                new[] { ResultVariable },
+                Expression.Assign(ResultVariable, MergeExpression),
+                Expression.IfThen(IsReplaceActionExpression, replaceTargetExpression));
+
+            return ReplacePlaceholders(scaffold, sourceMember, targetMember, template);
+        }
+
+        /// <summary>
+        /// Replaces the placeholders in a template expression.
+        /// </summary>
+        /// <param name="scaffold">
+        /// The scaffold on which the injection is being built.
+        /// </param>
+        /// <param name="sourceMember">
+        /// The source member.
+        /// </param>
+        /// <param name="targetMember">
+        /// The target member.
+        /// </param>
+        /// <param name="template">
+        /// The template expression.
+        /// </param>
+        /// <returns>
+        /// The merge <see cref="Expression"/> with their placeholders replaced.
+        /// </returns>
+        private static Expression ReplacePlaceholders(
+            InjectionScaffold scaffold,
+            MemberInfo sourceMember,
+            MemberInfo targetMember,
+            Expression template)
+        {
             var sourceMemberType = sourceMember.GetReturnType();
             var targetMemberType = targetMember.GetReturnType();
-
-            var sourceMemberTypeExpression = SourceMemberTypeExpression(sourceMemberType);
-            var targetMemberTypeExpression = TargetMemberTypeExpression(targetMemberType);
-            var resolveExpression = ResolveExpression();
-            var isMergeNullExpression = IsMergeNullExpression();
-
-            Expression<Func<IMergeResult>> performMergeExpression = () =>
-                Placeholder.Of<IMerge>("merge").Merge(
-                    Placeholder.Of<object>("sourceMember"),
-                    Placeholder.Of<object>("targetMember"),
-                    Placeholder.Of<IInjectionContext>("context"));
-
-            Expression<Func<bool>> isTargetMemberNull = () => Placeholder.Of<object>("targetMember") == null;
-
-            var mergeVariable = Expression.Variable(typeof(IMerge));
-            var assignMerge = Expression.Assign(mergeVariable, resolveExpression.Body);
-
-            var resultVariable = Expression.Variable(typeof(IMergeResult));
-            var assignMergeResult = Expression.Assign(resultVariable, performMergeExpression.Body);
-
-            Expression<Func<bool>> isReplaceTargetExpression = () =>
-                Placeholder.Of<IMergeResult>("result").Action == PostMergeAction.Replace;
-
-            Expression<Func<object>> resultTargetExpression = () => Placeholder.Of<IMergeResult>("result").Target;
-
-            var conditionalReplaceTargetExpression = Expression.IfThen(
-                isReplaceTargetExpression.Body,
-                Expression.Assign(targetMember.GetAccessExpression(scaffold.Target), Expression.Convert(resultTargetExpression.Body, targetMemberType)));
-
-            var transformExpression = base.CreateExpression(scaffold, sourceMember, targetMember);
-
-            var postMergeExpression = Expression.Block(
-                new[] { resultVariable },
-                assignMergeResult,
-                Expression.IfThen(isReplaceTargetExpression.Body, conditionalReplaceTargetExpression));
-
-            var mergeExpression = Expression.Block(
-                new[] { mergeVariable },
-                new Expression[] { assignMerge, Expression.IfThenElse(isMergeNullExpression.Body, transformExpression, postMergeExpression) });
-
+            var sourceMemberTypeExpression = CreateSourceMemberTypeExpression(sourceMemberType);
+            var targetMemberTypeExpression = CreateTargetMemberTypeExpression(targetMemberType);
             var sourceMemberExpression = Expression.Convert(sourceMember.GetAccessExpression(scaffold.Source), typeof(object));
             var targetMemberExpression = Expression.Convert(targetMember.GetAccessExpression(scaffold.Target), typeof(object));

-            Expression expression = Expression.IfThenElse(
-                isTargetMemberNull.Body,
-                transformExpression,
-                mergeExpression);
+            template = new PlaceholderExpressionVisitor("context", scaffold.InjectionContext).Visit(template);
+            template = new PlaceholderExpressionVisitor("sourceMember", sourceMemberExpression).Visit(template);
+            template = new PlaceholderExpressionVisitor("targetMember", targetMemberExpression).Visit(template);
+            template = new PlaceholderExpressionVisitor("targetMemberType", targetMemberTypeExpression).Visit(template);
+            template = new PlaceholderExpressionVisitor("sourceMemberType", sourceMemberTypeExpression).Visit(template);
+            template = new PlaceholderExpressionVisitor("result", ResultVariable).Visit(template);

-            expression = new PlaceholderExpressionVisitor("context", scaffold.InjectionContext).Visit(expression);
-            expression = new PlaceholderExpressionVisitor("sourceMember", sourceMemberExpression).Visit(expression);
-            expression = new PlaceholderExpressionVisitor("targetMember", targetMemberExpression).Visit(expression);
-            expression = new PlaceholderExpressionVisitor("targetMemberType", targetMemberTypeExpression.Body).Visit(expression);
-            expression = new PlaceholderExpressionVisitor("sourceMemberType", sourceMemberTypeExpression.Body).Visit(expression);
-            expression = new PlaceholderExpressionVisitor("merge", mergeVariable).Visit(expression);
-            return new PlaceholderExpressionVisitor("result", resultVariable).Visit(expression);
+            return template;
         }

-        private static Expression<Func<bool>> IsMergeNullExpression()
+        /// <summary>
+        /// Creates an <see cref="Expression"/> that provides the target member <see cref="Type"/>.
+        /// </summary>
+        /// <param name="type">
+        /// The target member type.
+        /// </param>
+        /// <returns>
+        /// An <see cref="Expression"/> that provides the target member <see cref="Type"/>.
+        /// </returns>
+        private static Expression CreateTargetMemberTypeExpression(Type type)
         {
-            Expression<Func<bool>> isMergeNull = () => Placeholder.Of<IMerge>("merge") == null;
-            return isMergeNull;
+            return ((type.IsValueType || type.IsSealed)
+                ? (Expression<Func<Type>>)(() => type)
+                : (() => Placeholder.Of<object>("targetMember").GetType())).Body;
         }

-        private static Expression<Func<IMerge>> ResolveExpression()
+        /// <summary>
+        /// Creates an <see cref="Expression"/> that provides the source member <see cref="Type"/>.
+        /// </summary>
+        /// <param name="type">
+        /// The source member type.
+        /// </param>
+        /// <returns>
+        /// An <see cref="Expression"/> that provides the source member <see cref="Type"/>.
+        /// </returns>
+        private static Expression CreateSourceMemberTypeExpression(Type type)
         {
-            Expression<Func<IMerge>> resolveExpression =
-                () =>
-                Placeholder.Of<IInjectionContext>("context")
-                    .InjectionStore.Resolve<IMerge>(
-                        Placeholder.Of<Type>("sourceMemberType"),
-                        Placeholder.Of<Type>("targetMemberType"));
-            return resolveExpression;
-        }
-
-        private static Expression<Func<Type>> TargetMemberTypeExpression(Type targetMemberType)
-        {
-            var targetMemberTypeExpression = (targetMemberType.IsValueType || targetMemberType.IsSealed)
-                                                 ? (Expression<Func<Type>>)(() => targetMemberType)
-                                                 : (() => Placeholder.Of<object>("targetMember").GetType());
-            return targetMemberTypeExpression;
-        }
-
-        private static Expression<Func<Type>> SourceMemberTypeExpression(Type sourceMemberType)
-        {
-            var sourceMemberTypeExpression = (sourceMemberType.IsValueType || sourceMemberType.IsSealed)
-                                                 ? (Expression<Func<Type>>)(() => sourceMemberType)
-                                                 : (() =>
-                                                    (Placeholder.Of<object>("sourceMember") == null
-                                                         ? sourceMemberType
-                                                         : Placeholder.Of<object>("sourceMember").GetType()));
-            return sourceMemberTypeExpression;
+            return ((type.IsValueType || type.IsSealed)
+                ? (Expression<Func<Type>>)(() => type)
+                : (() =>
+                    (Placeholder.Of<object>("sourceMember") == null
+                        ? type
+                        : Placeholder.Of<object>("sourceMember").GetType()))).Body;
         }
     }
 }


Inform sourcemap generator when a new line is added to minified file.

--- src/Smidge.Nuglify/NuglifyJs.cs
+++ src/Smidge.Nuglify/NuglifyJs.cs
@@ -91,6 +91,12 @@

             if (nuglifyJsCodeSettings.SourceMapType != SourceMapType.None)
             {
+                if (codeSettings.SymbolsMap != null)
+                {
+                    // tell the source map we have added a new line to the output (fixes offsets).
+                    codeSettings.SymbolsMap.NewLineInsertedInOutput();
+                }
+
                 AddSourceMapAppenderToContextAsync(fileProcessContext.BundleContext, nuglifyJsCodeSettings.SourceMapType);
             }


Removed shortcut case which should never occur.

--- src/SqlLocalDb/SqlLocalDbApi.cs
+++ src/SqlLocalDb/SqlLocalDbApi.cs
@@ -485,12 +485,6 @@
                 throw GetLocalDbError(hr, Logger.TraceEvent.GetInstanceNames);
             }

-            if (count == 0)
-            {
-                // Shortcut, no instances
-                return new string[0];
-            }
-
             // Allocate enough memory to receive the instance name array
             int nameLength = MaxInstanceNameLength;
             IntPtr ptrNames = Marshal.AllocHGlobal(nameLength * count);


Refactor Add Integers Operation to use GetValues and CloneWithValues

--- Src/TensorSharp/Operations/AddIntegerIntegerOperation.cs
+++ Src/TensorSharp/Operations/AddIntegerIntegerOperation.cs
@@ -9,12 +9,17 @@
     {
         public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
         {
-            Tensor<int> result = new Tensor<int>();
+            int[] values1 = tensor1.GetValues();
+            int l = values1.Length;

-            result.SetValue(tensor1.GetValue() + tensor2.GetValue());
+            int[] values2 = tensor2.GetValues();

-            return result;
-            return result;
+            int[] newvalues = new int[l];
+
+            for (int k = 0; k < l; k++)
+                newvalues[k] = values1[k] + values2[k];
+
+            return tensor1.CloneWithNewValues(newvalues);
         }
     }
 }


Fix if statement that was incorrect

Fix if statement that was incorrect

--- TESS/Controllers/Contracts/CustomerContractController.cs
+++ TESS/Controllers/Contracts/CustomerContractController.cs
@@ -2083,7 +2083,7 @@
                 String value = Request.Form["id"];
                 view_Contract co = new view_Contract("Contract_id='" + value + "'");
                 //a.Select("Article_number = " + value);
-                if (co.Status == "Makulerad")
+                if (co.Status == "Makulerat")
                     co.Delete("Contract_id='" + value + "'");
                 else
                     return "-1";


Adds a loopback check to ensure we only write to the Project Collection that is configured in the AggregatorConfig.xml. Without this, the Aggregator would try to update unrelated workitems in other collections by ID. **SCARY**

--- TFSAggregator/TfsSpecific/WorkItemChangedEventHandler.cs
+++ TFSAggregator/TfsSpecific/WorkItemChangedEventHandler.cs
@@ -13,6 +13,8 @@

 namespace TFSAggregator.TfsSpecific
 {
+    using Microsoft.TeamFoundation.Client;
+
     /// <summary>
     /// The class that subscribes to server side events on the TFS server.
     /// We're only interested in WorkItemChanged events, so we'll filter that out before calling our main logic.
@@ -38,6 +40,13 @@
         public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs,
                                                     out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
         {
+            //Abort for non-configured ProjectCollection:
+            //Abort early if there is a context mismatch
+            if (ShouldAbort(requestContext, new Uri(TFSAggregatorSettings.TFSUri)))
+            {
+                return EventNotificationStatus.ActionPermitted;
+            }
+
             var result = new ProcessingResult();
             try
             {
@@ -65,6 +74,16 @@
             return result.NotificationStatus;
         }

+        private bool ShouldAbort(TeamFoundationRequestContext requestContext, Uri configuredUri)
+        {
+            TeamFoundationLocationService service = requestContext.GetService<TeamFoundationLocationService>();
+            Uri selfReferenceUri = service.GetSelfReferenceUri(requestContext, service.GetDefaultAccessMapping(requestContext));
+            MiscHelpers.LogMessage("Self reference uri = " + selfReferenceUri, false);
+            MiscHelpers.LogMessage("Configured uri = " + configuredUri, false);
+            var collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(selfReferenceUri);
+            return !collection.Uri.AbsoluteUri.Equals(configuredUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase);
+        }
+
         public string Name
         {
             get { return "TFSAggregator"; }


Re-factoring duplicate number checks for saving a template so that it is more performance-friendly

--- Trifolia.Web/Controllers/API/TemplateEditorController.cs
+++ Trifolia.Web/Controllers/API/TemplateEditorController.cs
@@ -432,13 +432,16 @@
                 // Create/update constraints
                 this.SaveConstraints(tdb, template, model.Constraints);

+                var allNumbers = (from t in tdb.Templates
+                                  join tc in tdb.TemplateConstraints on t.Id equals tc.TemplateId
+                                  where t.OwningImplementationGuideId == template.OwningImplementationGuideId
+                                  select new { tc.Id, tc.Number });
                 var duplicateNumbers = (from tcc in template.ChildConstraints
-                                        join tc in tdb.TemplateConstraints on tcc.Number equals tc.Number
-                                        join t in tdb.Templates on tc.TemplateId equals t.Id
-                                        where tcc.Id != tc.Id && t.OwningImplementationGuideId == template.OwningImplementationGuideId
-                                        select tcc.Number).ToList();
-
-                if (duplicateNumbers.Count > 0)
+                                        join an in allNumbers on tcc.Number equals an.Number
+                                        where tcc.Id != an.Id
+                                        select tcc.Number);
+
+                if (duplicateNumbers.Count() > 0)
                 {
                     response.Error = string.Format("The following constraints have duplicate numbers: {0}", string.Join(", ", duplicateNumbers));
                 }


Add ZenMode property

Add ZenMode property

--- TwitchPlaysAssembly/Src/Helpers/TwitchPlaysProperties.cs
+++ TwitchPlaysAssembly/Src/Helpers/TwitchPlaysProperties.cs
@@ -3,6 +3,7 @@
 	public TwitchPlaysProperties()
 	{
 		AddProperty("TimeMode", new Property(() => OtherModes.TimedModeOn, x => { OtherModes.TimedModeOn = (bool)x; }));
+		AddProperty("ZenMode", new Property(() => OtherModes.ZenModeOn, x => OtherModes.ZenModeOn = (bool) x));
 		AddProperty("TimeModeTimeLimit", new Property(() => TwitchPlaySettings.data.TimeModeStartingTime, SetTimeModeTimeLimit));
 		AddProperty("ircConnectionSendMessage", new Property(null, x => IRCConnection.Instance.SendMessage((string)x)));
 		AddProperty("Reward", new Property(() => TwitchPlaySettings.GetRewardBonus(), x => TwitchPlaySettings.SetRewardBonus((int) x)));


新增註解

新增註解

新增註解

--- UartOscilloscopeTests/CSharpFiles/DataProcessingTests.cs
+++ UartOscilloscopeTests/CSharpFiles/DataProcessingTests.cs
@@ -21,6 +21,9 @@
 			String2CharArrayTestPart1();                                        //	呼叫String2CharArrayTestPart1方法

 		}                                                                       //	結束String2CharArrayTest方法
+		/// <summary>
+		/// String2CharArrayTestPart1以靜態字串於測試String2CharArray方法，能否順利完成字串至字元陣列轉換
+		/// </summary>
 		[TestMethod()]
 		public void String2CharArrayTestPart1()                                 //	String2CharArrayTestPart1方法
 		{                                                                       //	進入String2CharArrayTestPart1方法


added try catch

added try catch

--- VS/CSHARP/asm-dude-vsix/CodeFolding/CodeFoldingTagger.cs
+++ VS/CSHARP/asm-dude-vsix/CodeFolding/CodeFoldingTagger.cs
@@ -257,33 +257,39 @@
         /// </summary>
         private (int StartPosFolding, int StartPosDescription) Is_Start_Masm_Keyword(string lineContent, int lineNumber)
         {
-            ITextSnapshotLine line = this._buffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber);
-            IEnumerable<IMappingTagSpan<AsmTokenTag>> tags = this._aggregator.GetTags(line.Extent);
-            foreach (IMappingTagSpan<AsmTokenTag> asmTokenSpan in tags)
-            {
-                if (asmTokenSpan.Tag.Type == AsmTokenType.Directive)
-                {
-                    string tokenStr = asmTokenSpan.Span.GetSpans(this._buffer)[0].GetText().ToUpper();
-                    //AsmDudeToolsStatic.Output_INFO("CodeFoldingTagger:IsStartMasmKeyword: tokenStr=" + tokenStr);
-                    switch (tokenStr)
+            try
+            {
+                ITextSnapshotLine line = this._buffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber);
+                IEnumerable<IMappingTagSpan<AsmTokenTag>> tags = this._aggregator.GetTags(line.Extent);
+                foreach (IMappingTagSpan<AsmTokenTag> asmTokenSpan in tags)
+                {
+                    if (asmTokenSpan.Tag.Type == AsmTokenType.Directive)
                     {
-                        case "SEGMENT":
-                        case "MACRO":
-                        case "STRUCT":
-                        case ".IF":
-                        case ".WHILE":
-                        case "PROC":
-                            {
-                                return (lineContent.Length, lineContent.Length);
-                            }
-                        case "EXTERN":
-                        case "EXTRN": // no start region on a line with EXTERN keyword
-                            {
-                                return (-1, -1);
-                            }
-                        default: break;
+                        string tokenStr = asmTokenSpan.Span.GetSpans(this._buffer)[0].GetText().ToUpper();
+                        //AsmDudeToolsStatic.Output_INFO("CodeFoldingTagger:IsStartMasmKeyword: tokenStr=" + tokenStr);
+                        switch (tokenStr)
+                        {
+                            case "SEGMENT":
+                            case "MACRO":
+                            case "STRUCT":
+                            case ".IF":
+                            case ".WHILE":
+                            case "PROC":
+                                {
+                                    return (lineContent.Length, lineContent.Length);
+                                }
+                            case "EXTERN":
+                            case "EXTRN": // no start region on a line with EXTERN keyword
+                                {
+                                    return (-1, -1);
+                                }
+                            default: break;
+                        }
                     }
                 }
+            } catch (Exception e)
+            {
+                AsmDudeToolsStatic.Output_ERROR(string.Format("{0}:Is_Start_Masm_Keyword; e={1}", ToString(), e.ToString()));
             }
             return (-1, -1);
         }


Test fix attempt. #60

Test fix attempt. #60

- Ignore test that is likely causing issues

--- VaraniumSharp.Tests/Concurrency/StaTaskSchedulerTests.cs
+++ VaraniumSharp.Tests/Concurrency/StaTaskSchedulerTests.cs
@@ -63,7 +63,7 @@
             sut.Threads.Should().Be(expectedThreads);
         }

-        [Fact(Skip = "Runner issue")]
+        [Fact]
         public void RunningTaskSynchronouslyWillCorrectlySwitchToStaThread()
         {
             // arrange
@@ -93,7 +93,7 @@
             act.Should().Throw<ArgumentOutOfRangeException>();
         }

-        [Fact]
+        [Fact(Skip = "Runner issue")]
         public void TasksAreCorrectlyQueued()
         {
             // arrange


Handled special case on Repeat when count equals 1.

--- WmcSoft.Core/Collections/Generic/EnumerableExtensions.cs
+++ WmcSoft.Core/Collections/Generic/EnumerableExtensions.cs
@@ -823,16 +823,22 @@
         /// <param name="source">The enumerator</param>
         /// <param name="count">The number of time to repeat the sequence</param>
         /// <param name="collate">Collate the items</param>
-        /// <returns>The list with the repeated sequence</returns>
+        /// <returns>The list with the repeated sequence.</returns>
         public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int count, bool collate = true) {
             if (source == null) throw new ArgumentNullException(nameof(source));
             if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));

-            if (count == 0)
+            switch (count) {
+            case 0:
                 return Enumerable.Empty<T>();
-            if (collate)
-                return new CollateRepeat<T>(source, count).AsCollection();
-            return new GroupedRepeat<T>(source, count).AsCollection();
+            case 1:
+                return source;
+            default:
+                // most optimized implementation tries to cast as ICollection<T>, not IReadOnlyCollection, to get the count of items.
+                return collate
+                    ? new CollateRepeat<T>(source, count).AsCollection()
+                    : new GroupedRepeat<T>(source, count).AsCollection();
+            }
         }

         #endregion


Fix wrong type usage in ObjectDescriptor

--- YamlDotNet/Serialization/Descriptors/ObjectDescriptor.cs
+++ YamlDotNet/Serialization/Descriptors/ObjectDescriptor.cs
@@ -143,6 +143,8 @@

 		private bool PrepareMember(MemberDescriptorBase member)
 		{
+			var memberType = member.Type;
+
 			// If the member has a set, this is a conventional assign method
 			if (member.HasSet)
 			{
@@ -151,7 +153,7 @@
 			else
 			{
 				// Else we cannot only assign its content if it is a class
-				member.SerializeMemberMode = type.IsClass ? SerializeMemberMode.Content : SerializeMemberMode.Never;
+				member.SerializeMemberMode = memberType.IsClass ? SerializeMemberMode.Content : SerializeMemberMode.Never;
 			}

 			var attributeRegistry = Settings.AttributeRegistry;
@@ -166,19 +168,19 @@
 				if (!member.HasSet)
 				{
 					if (memberAttribute.SerializeMethod == SerializeMemberMode.Assign ||
-						(type.IsValueType && member.SerializeMemberMode == SerializeMemberMode.Content))
-						throw new ArgumentException("{0} {1} is not writeable by {2}.".DoFormat(type.FullName, member.Name, memberAttribute.SerializeMethod.ToString()));
+						(memberType.IsValueType && member.SerializeMemberMode == SerializeMemberMode.Content))
+						throw new ArgumentException("{0} {1} is not writeable by {2}.".DoFormat(memberType.FullName, member.Name, memberAttribute.SerializeMethod.ToString()));
 				}
 				member.SerializeMemberMode = memberAttribute.SerializeMethod;
 			}

 			if (member.SerializeMemberMode == SerializeMemberMode.Binary)
 			{
-				if (!type.IsArray)
+				if (!memberType.IsArray)
 					throw new InvalidOperationException("{0} {1} of {2} is not an array. Can not be serialized as binary."
-															.DoFormat(type.FullName, member.Name, type.FullName));
-				if (!type.GetElementType().IsPureValueType())
-					throw new InvalidOperationException("{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary.".DoFormat(type.GetElementType(), type.FullName, member.Name, type.FullName));
+															.DoFormat(memberType.FullName, member.Name, type.FullName));
+				if (!memberType.GetElementType().IsPureValueType())
+					throw new InvalidOperationException("{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary.".DoFormat(memberType.GetElementType(), memberType.FullName, member.Name, type.FullName));
 			}

 			// ShouldSerialize
@@ -186,7 +188,7 @@
 			//      ShouldSerializeSomeProperty => call it
 			//      DefaultValueAttribute(default) => compare to it
 			//      otherwise => true
-			var shouldSerialize = type.GetMethod("ShouldSerialize" + member.Name, BindingFlags.Instance | BindingFlags.NonPublic);
+			var shouldSerialize = type.GetMethod("ShouldSerialize" + member.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
 			if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null)
 				member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray);

@@ -196,8 +198,8 @@
 			{
 				object defaultValue = defaultValueAttribute.Value;
 				Type defaultType = defaultValue == null ? null : defaultValue.GetType();
-				if (defaultType.IsNumeric() && defaultType != type)
-					defaultValue = type.CastToNumericType(defaultValue);
+				if (defaultType.IsNumeric() && defaultType != memberType)
+					defaultValue = memberType.CastToNumericType(defaultValue);
 				member.ShouldSerialize = obj => !TypeExtensions.AreEqual(defaultValue, member.Get(obj));
 			}


Improved R2LDanmaku cache

Improved R2LDanmaku cache

--- src/WPFDanmakuLib/WPFDanmaku.cs
+++ src/WPFDanmakuLib/WPFDanmaku.cs
@@ -82,18 +82,42 @@
             mCache_R2LPropertyPath = new PropertyPath("(Canvas.Left)");
         }

+        /// <summary>
+        /// Draw a right to left danmaku on binded canvas
+        /// </summary>
+        /// <param name="Content">Danmaku content</param>
+        /// <param name="Style">Override default danmaku style if needed</param>
+        /// <returns></returns>
         public string DrawDanmaku_R2L(string Content, BaseDanmaku Style = null) {
             SolidColorBrush _FillBrush;
             Duration _duration;
+            DropShadowEffect _ShadowEffect;
             if (Style == null || Style == mDefaultDanmakuStyle) {
                 Style = mDefaultDanmakuStyle;
                 _FillBrush = mCache_SolidColorBrush;
+                _ShadowEffect = mCache_ShadowEffect;
                 _duration = mCache_Duration;
             } else {
-                // replace cache
-                _FillBrush = new SolidColorBrush(Color.FromRgb(Style.ColorR, Style.ColorG, Style.ColorB));
-                _duration = new Duration(TimeSpan.FromMilliseconds(Style.Duration));
+                if (Style.Duration != mDefaultDanmakuStyle.Duration) {
+                    _duration = new Duration(TimeSpan.FromMilliseconds(Style.Duration));
+                } else {
+                    _duration = mCache_Duration;
+                }
+
+                if (Style.ColorR != mDefaultDanmakuStyle.ColorR || Style.ColorG != mDefaultDanmakuStyle.ColorG || Style.ColorB != mDefaultDanmakuStyle.ColorB) {
+                    _FillBrush = new SolidColorBrush(Color.FromRgb(Style.ColorR, Style.ColorG, Style.ColorB));
+                    _ShadowEffect = mCache_ShadowEffect;
+                    if ((Style.ColorR + Style.ColorG + Style.ColorB + 1) / 3 >= 255 / 2) {
+                        _ShadowEffect.Color = Color.FromRgb(0, 0, 0);
+                    } else {
+                        _ShadowEffect.Color = Color.FromRgb(255, 255, 255);
+                    }
+                } else {
+                    _ShadowEffect = mCache_ShadowEffect;
+                    _FillBrush = mCache_SolidColorBrush;
+                }
             }
+
             OutlinedTextBlock _thisDanmaku = new OutlinedTextBlock();
             _thisDanmaku.Name = "uni_" + Utils.getRandomString(5);

@@ -107,7 +131,7 @@
             _thisDanmaku.FontWeight = FontWeights.Bold;

             if (Style.Shadow) {
-                _thisDanmaku.Effect = mCache_ShadowEffect;
+                _thisDanmaku.Effect = _ShadowEffect;
             }

             // Animation


Added missing namespaces

Added missing namespaces

--- src/WpfMath/TexFormulaParser.cs
+++ src/WpfMath/TexFormulaParser.cs
@@ -7,6 +7,8 @@
 using System.Windows.Media;
 using WpfMath.Atoms;
 using WpfMath.Exceptions;
+using System.Text;
+using System.Text.RegularExpressions;

 namespace WpfMath
 {
@@ -274,6 +276,55 @@
             return value.Segment(start, position - start - 1);
         }

+        private string ReadGroup(string str,char leftchar,char rightchar,int startPosition)
+        {
+            StringBuilder sb = new StringBuilder();
+            if (startPosition==str.Length)
+            {
+                throw new TexParseException("illegal end!");
+            }
+            int deepness = 0;bool groupfound = false;
+            var start = startPosition;
+            if (str[start]==leftchar)
+            {
+                start++;
+                while (start < str.Length && groupfound == false)
+                {
+                    if (str[start] == leftchar)
+                    {
+                        deepness++;
+                        sb.Append(leftchar);
+                    }
+                    else if (str[start] == rightchar)
+                    {
+                        if (deepness == 0)
+                        {
+                            groupfound = true;
+                        }
+                        else
+                        {
+                            deepness--;
+                            sb.Append(rightchar);
+                        }
+                    }
+                    else
+                    {
+                        sb.Append(str[start]);
+                    }
+                    start++;
+                }
+            }
+
+            if (groupfound)
+            {
+                return sb.ToString();
+            }
+            else
+            {
+                throw new TexParseException("missing->>" + rightchar);
+            }
+        }
+
         private TexFormula ReadScript(TexFormula formula, SourceSpan value, ref int position)
         {
             SkipWhiteSpace(value, ref position);


C# 7.0 cleanup.

C# 7.0 cleanup.

--- src/DoConfiguration.cs
+++ src/DoConfiguration.cs
@@ -12,20 +12,26 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.

-using System;
-
-using Serilog.Core;
-using Serilog.Events;
-
 namespace Serilog.Enricher.WhenDo
 {
+    #region Using
+
+    using System;
+
+    using Serilog.Core;
+    using Serilog.Events;
+
+    #endregion
+
     public class DoConfiguration
     {
         readonly Func<Action<LogEvent, ILogEventPropertyFactory>, LoggerConfiguration> _doEnrich;

         readonly Func<Func<LogEvent, bool>, LoggerConfiguration> _doFilter;

-        public DoConfiguration(Func<Action<LogEvent, ILogEventPropertyFactory>, LoggerConfiguration> doEnrich, Func<Func<LogEvent, bool>, LoggerConfiguration> doFilter)
+        public DoConfiguration(
+            Func<Action<LogEvent, ILogEventPropertyFactory>, LoggerConfiguration> doEnrich,
+            Func<Func<LogEvent, bool>, LoggerConfiguration> doFilter)
         {
             _doEnrich = doEnrich;
             _doFilter = doFilter;
@@ -33,63 +39,92 @@

         public LoggerConfiguration RemovePropertyIfPresent(params string[] properties)
         {
-            Func<string[], Action<LogEvent, ILogEventPropertyFactory>> action = (p) => (e, f) =>
+            Action<LogEvent, ILogEventPropertyFactory> OuterAction(string[] p)
+            {
+                void InnerAction(LogEvent e, ILogEventPropertyFactory f)
                 {
                     foreach (var prop in p)
                     {
                         e.RemovePropertyIfPresent(prop);
                     }
-                };
+                }

-            return _doEnrich(action(properties));
+                return InnerAction;
+            }
+
+            return _doEnrich(OuterAction(properties));
         }

         public LoggerConfiguration SendTo(ILogger sendToLogger)
         {
             if (sendToLogger == null) throw new ArgumentNullException(nameof(sendToLogger));

-            Func<ILogger, Func<LogEvent, bool>> action = (l) => (e) =>
+            Func<LogEvent, bool> OuterFunc(ILogger l)
             {
-                // write event to other logger
-                l.Write(e);
+                bool InnerFunc(LogEvent e)
+                {
+                    // write event to other logger
+                    l.Write(e);

-                // log event to this logger as well
-                return true;
-            };
+                    // log event to this logger as well
+                    return true;
+                }

-            return _doFilter(action(sendToLogger));
+                return InnerFunc;
+            }
+
+            return _doFilter(OuterFunc(sendToLogger));
         }

         public LoggerConfiguration PipeTo(ILogger pipeToLogger)
         {
             if (pipeToLogger == null) throw new ArgumentNullException(nameof(pipeToLogger));

-            Func<ILogger, Func<LogEvent, bool>> action = (l) => (e) =>
+            Func<LogEvent, bool> OuterFunc(ILogger l)
             {
-                // write event to other logger
-                l.Write(e);
+                bool InnerFunc(LogEvent e)
+                {
+                    // write event to other logger
+                    l.Write(e);

-                // do not log event to this logger (disable event)
-                return false;
-            };
+                    // do not log event to this logger (disable event)
+                    return false;
+                }

-            return _doFilter(action(pipeToLogger));
+                return InnerFunc;
+            }
+
+            return _doFilter(OuterFunc(pipeToLogger));
         }

         public LoggerConfiguration AddPropertyIfAbsent(string name, object value, bool destructureObject = false)
         {
-            Func<string, object, bool, Action<LogEvent, ILogEventPropertyFactory>> action = (n, v, d) => (e, f) =>
-                { e.AddPropertyIfAbsent(f.CreateProperty(n, v, d)); };
+            Action<LogEvent, ILogEventPropertyFactory> OuterAction(string n, object v, bool d)
+            {
+                void InnerAction(LogEvent e, ILogEventPropertyFactory f)
+                {
+                    e.AddPropertyIfAbsent(f.CreateProperty(n, v, d));
+                }

-            return _doEnrich(action(name, value, destructureObject));
+                return InnerAction;
+            }
+
+            return _doEnrich(OuterAction(name, value, destructureObject));
         }

         public LoggerConfiguration AddOrUpdateProperty(string name, object value, bool destructureObject = false)
         {
-            Func<string, object, bool, Action<LogEvent, ILogEventPropertyFactory>> action = (n, v, d) => (e, f) =>
-                { e.AddOrUpdateProperty(f.CreateProperty(n, v, d)); };
+            Action<LogEvent, ILogEventPropertyFactory> OuterAction(string n, object v, bool d)
+            {
+                void InnerAction(LogEvent e, ILogEventPropertyFactory f)
+                {
+                    e.AddOrUpdateProperty(f.CreateProperty(n, v, d));
+                }

-            return _doEnrich(action(name, value, destructureObject));
+                return InnerAction;
+            }
+
+            return _doEnrich(OuterAction(name, value, destructureObject));
         }
     }
 }


Use correct corlib version when importing references

--- src/DotNet/Importer.cs
+++ src/DotNet/Importer.cs
@@ -421,7 +421,11 @@
 			var pkt = asmName.GetPublicKeyToken();
 			if (pkt == null || pkt.Length == 0)
 				pkt = null;
-			return module.UpdateRowId(new AssemblyRefUser(asmName.Name, asmName.Version, PublicKeyBase.CreatePublicKeyToken(pkt), asmName.CultureInfo.Name));
+
+			AssemblyRef assemblyRef = new AssemblyRefUser(asmName.Name, asmName.Version, PublicKeyBase.CreatePublicKeyToken(pkt), asmName.CultureInfo.Name);
+			if (assemblyRef.IsCorLib())
+				return module.CorLibTypes.AssemblyRef;
+			return module.UpdateRowId(assemblyRef);
 		}

 		/// <summary>
@@ -770,6 +774,9 @@
 		IResolutionScope CreateScopeReference(IAssembly defAsm, ModuleDef defMod) {
 			if (defAsm == null)
 				return null;
+			if (defAsm.IsCorLib())
+				return defMod.CorLibTypes.AssemblyRef;
+
 			var modAsm = module.Assembly;
 			if (defMod != null && defAsm != null && modAsm != null) {
 				if (UTF8String.CaseInsensitiveEquals(modAsm.Name, defAsm.Name)) {


add primary user synchronization to interactive database seeder

--- abremir.AllMyBricks.DatabaseSeeder/InteractiveConsole.cs
+++ abremir.AllMyBricks.DatabaseSeeder/InteractiveConsole.cs
@@ -1,13 +1,18 @@
-using abremir.AllMyBricks.DatabaseSeeder.Configuration;
+using abremir.AllMyBricks.Data.Enumerations;
+using abremir.AllMyBricks.Data.Interfaces;
+using abremir.AllMyBricks.DatabaseSeeder.Configuration;
 using abremir.AllMyBricks.DatabaseSeeder.Services;
 using abremir.AllMyBricks.DataSynchronizer.Events.SetSynchronizationService;
 using abremir.AllMyBricks.DataSynchronizer.Events.SetSynchronizer;
 using abremir.AllMyBricks.DataSynchronizer.Events.SubthemeSynchronizer;
 using abremir.AllMyBricks.DataSynchronizer.Events.ThemeSynchronizer;
+using abremir.AllMyBricks.DataSynchronizer.Events.UserSynchronizationService;
+using abremir.AllMyBricks.DataSynchronizer.Events.UserSynchronizer;
 using abremir.AllMyBricks.DataSynchronizer.Interfaces;
 using Easy.MessageHub;
 using System;
 using System.Diagnostics;
+using System.Linq;
 using Terminal.Gui;

 namespace abremir.AllMyBricks.DatabaseSeeder
@@ -15,6 +20,7 @@
     public static class InteractiveConsole
     {
         private static FrameView SetsSynchronizationProgressFrame;
+        private static FrameView PrimaryUsersSynchronizationProgressFrame;
         private static bool CanExit = true;

         public static void Run()
@@ -52,6 +58,25 @@
             SetsSynchronizationProgressFrame.Add(totalUpdatedSubthemesLabel);
             SetsSynchronizationProgressFrame.Add(totalUpdatedSetsLabel);

+            PrimaryUsersSynchronizationProgressFrame = new FrameView(new Rect(10, 1, 99, topLevel.Frame.Height - 4), "Primary Users Synchronization Progress...");
+
+            var userCountLabel = new Label(4, 3, "".PadRight(70));
+
+            var userLabel = new Label(4, 5, "".PadRight(70));
+            var userProgress = new ProgressBar(new Rect(4, 6, 88, 1));
+
+            var syncTypeLabel = new Label(4, 8, "".PadRight(70));
+
+            var syncLabel = new Label(4, 10, "".PadRight(70));
+            var syncProgress = new ProgressBar(new Rect(4, 11, 88, 1));
+
+            PrimaryUsersSynchronizationProgressFrame.Add(userCountLabel);
+            PrimaryUsersSynchronizationProgressFrame.Add(userLabel);
+            PrimaryUsersSynchronizationProgressFrame.Add(userProgress);
+            PrimaryUsersSynchronizationProgressFrame.Add(syncTypeLabel);
+            PrimaryUsersSynchronizationProgressFrame.Add(syncLabel);
+            PrimaryUsersSynchronizationProgressFrame.Add(syncProgress);
+
             var themeCount = 0f;
             var themeIndex = 0f;
             var subthemeCount = 0f;
@@ -62,6 +87,11 @@
             var totalUpdatedSubthemes = 0f;
             var totalUpdatedSets = 0f;

+            var userCount = 0f;
+            var userIndex = 0f;
+            var syncCount = 0f;
+            var syncIndex = 0f;
+
             var messageHub = IoC.IoCContainer.GetInstance<IMessageHub>();

             Stopwatch stopwatch = null;
@@ -317,7 +347,112 @@

                 Application.Run(dialog);
             });
-
+            messageHub.Subscribe<UserSynchronizationServiceStart>(_ =>
+            {
+                PrimaryUsersSynchronizationProgressFrame.Clear();
+
+                Application.MainLoop.Invoke(PrimaryUsersSynchronizationProgressFrame.ChildNeedsDisplay);
+
+                stopwatch = Stopwatch.StartNew();
+            });
+            messageHub.Subscribe<UsersAcquired>(message =>
+            {
+                userCountLabel.Text = $"Found {message.Count} users to process";
+                userCount = message.Count;
+                userIndex = 0f;
+                userProgress.Fraction = 0f;
+
+                Application.MainLoop.Invoke(userCountLabel.ChildNeedsDisplay);
+                Application.MainLoop.Invoke(userProgress.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<UserSynchronizerStart>(message =>
+            {
+                userLabel.Text = $"Processing user {message.Username}";
+                userIndex++;
+                userProgress.Fraction = userIndex / userCount;
+
+                Application.MainLoop.Invoke(userLabel.ChildNeedsDisplay);
+                Application.MainLoop.Invoke(userProgress.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<AllMyBricksToBricksetStart>(_ =>
+            {
+                syncTypeLabel.Text = "Updating brickset.com with updated owned and wanted sets since previous sync";
+
+                Application.MainLoop.Invoke(syncTypeLabel.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<AllMyBricksToBricksetAcquiringSetsEnd>(message =>
+            {
+                syncLabel.Text = $"Uploading data of {message.Count} sets to brickset.com...";
+                syncCount = message.Count;
+                syncIndex = 0f;
+                syncProgress.Fraction = 0f;
+
+                Application.MainLoop.Invoke(syncLabel.ChildNeedsDisplay);
+                Application.MainLoop.Invoke(syncProgress.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<BricksetToAllMyBricksStart>(_ =>
+            {
+                syncTypeLabel.Text = "Downloading from brickset.com all owned and wanted sets missing in AllMyBricks";
+
+                Application.MainLoop.Invoke(syncTypeLabel.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<BricksetToAllMyBricksAcquiringSetsEnd>(message =>
+            {
+                syncLabel.Text = $"Adding {message.Count} sets to AllMyBricks";
+                syncCount = message.Count;
+                syncIndex = 0f;
+                syncProgress.Fraction = 0f;
+
+                Application.MainLoop.Invoke(syncLabel.ChildNeedsDisplay);
+                Application.MainLoop.Invoke(syncProgress.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<UserSynchronizerSynchronizingSetStart>(_ =>
+            {
+                syncIndex++;
+                syncProgress.Fraction = syncIndex / syncCount;
+
+                Application.MainLoop.Invoke(syncProgress.ChildNeedsDisplay);
+            });
+            messageHub.Subscribe<UserSynchronizationServiceEnd>(_ =>
+            {
+                userCountLabel.Text = string.Empty;
+                userProgress.Fraction = 0f;
+                userLabel.Text = string.Empty;
+                syncTypeLabel.Text = string.Empty;
+                syncLabel.Text = string.Empty;
+                syncProgress.Fraction = 0f;
+                userCount = 0f;
+                userIndex = 0f;
+                syncIndex = 0f;
+                syncCount = 0f;
+
+                stopwatch.Stop();
+
+                PrimaryUsersSynchronizationProgressFrame.Clear();
+
+                Application.MainLoop.Invoke(PrimaryUsersSynchronizationProgressFrame.ChildNeedsDisplay);
+
+                var dialog = new Dialog("Primary Users Synchronization finished", 50, 8, new Button("Ok")
+                {
+                    Clicked = () =>
+                    {
+                        topLevelWindow.Remove(PrimaryUsersSynchronizationProgressFrame);
+
+                        CanExit = true;
+
+                        Application.RequestStop();
+                    }
+                });
+
+                var totalTimeLabel = new Label($"Primary users synchronized in {stopwatch.Elapsed.ToString(@"hh\:mm\:ss")}")
+                {
+                    X = Pos.Center(),
+                    Y = 1
+                };
+                dialog.Add(totalTimeLabel);
+
+                Application.Run(dialog);
+            });

             AddMenuBar(topLevel, topLevelWindow);

@@ -328,6 +463,8 @@
             AddUncompressDatabaseFileButton(topLevelWindow);

             AddCompactDatabaseButton(topLevelWindow);
+
+            AddPrimaryUsersList(topLevelWindow);

             Application.Run();
         }
@@ -372,6 +509,30 @@
                                 Application.MainLoop.AddTimeout(TimeSpan.FromMilliseconds(500), _ => true);

                                 IoC.IoCContainer.GetInstance<ISetSynchronizationService>().SynchronizeAllSets();
+                            }
+                        }),
+                        new MenuItem("_Primary Users' Sets", "", () =>
+                        {
+                            if (CanExit)
+                            {
+                                CanExit = false;
+
+                                var userRepository = IoC.IoCContainer.GetInstance<IBricksetUserRepository>();
+
+                                foreach (var primaryUser in Settings.BricksetPrimaryUsers)
+                                {
+                                    if (userRepository.Get(primaryUser.Key) == null)
+                                    {
+                                        userRepository.Add(BricksetUserTypeEnum.Primary, primaryUser.Key);
+                                    }
+                                }
+
+                                window.Add(PrimaryUsersSynchronizationProgressFrame);
+
+                                // HACK: since there is a bug in Application.MainLoop.Invoke(...) this is needed to force the UI to refresh!
+                                Application.MainLoop.AddTimeout(TimeSpan.FromMilliseconds(500), _ => true);
+
+                                IoC.IoCContainer.GetInstance<IUserSynchronizationService>().SynchronizeBricksetPrimaryUsersSets();
                             }
                         })
                     })
@@ -540,5 +701,133 @@
                 );
             }
         }
+
+        private static void AddPrimaryUsersList(Window window)
+        {
+            var userRepository = IoC.IoCContainer.GetInstance<IBricksetUserRepository>();
+
+            var primaryUsersLabel = new Label(3, 10, "Primary Users");
+
+            var primaryUsersList = new ListView(new Rect(3, 11, 50, 14), Settings.BricksetPrimaryUsers.Select(keyValuePair => $"{keyValuePair.Key}/{keyValuePair.Value}").ToList());
+            primaryUsersList.ColorScheme = Colors.Dialog;
+            primaryUsersList.SelectedItem = 0;
+
+            var deletePrimaryUserButton = new Button("Delete primary user")
+            {
+                X = 3,
+                Y = 25,
+                Clicked = () =>
+                {
+                    var primaryUsers = Settings.BricksetPrimaryUsers;
+                    var selectedUser = primaryUsers.Skip(primaryUsersList.SelectedItem).Take(1).First();
+
+                    var dialog = new Dialog(
+                        "Delete primary user",
+                        50,
+                        8,
+                        new Button("Ok", false)
+                        {
+                            Clicked = () =>
+                            {
+                                primaryUsers.Remove(selectedUser.Key);
+                                Settings.BricksetPrimaryUsers = primaryUsers;
+
+                                primaryUsersList.SetSource(primaryUsers.Select(keyValuePair => $"{keyValuePair.Key}/{keyValuePair.Value}").ToList());
+
+                                Application.RequestStop();
+                            }
+                        },
+                        new Button("Cancel", false)
+                        {
+                            Clicked = Application.RequestStop
+                        });
+
+                    dialog.Add(
+                        new Label($"Do you want to delete primary user {selectedUser.Key}?")
+                        {
+                            Y = 1
+                        }
+                    );
+
+                    Application.Run(dialog);
+                }
+            };
+
+            primaryUsersList.SelectedChanged += () =>
+            {
+                if (primaryUsersList.SelectedItem == -1)
+                {
+                    window.Remove(deletePrimaryUserButton);
+                }
+                else
+                {
+                    window.Add(deletePrimaryUserButton);
+                }
+            };
+
+            var addPrimaryUserButton = new Button("Add primary user")
+            {
+                X = 33,
+                Y = 25,
+                Clicked = () =>
+                {
+                    var primaryUserUsername = new TextField(string.Empty)
+                    {
+                        Y = 2
+                    };
+                    var primaryUserUserHash = new TextField(string.Empty)
+                    {
+                        Y = 4
+                    };
+
+                    var dialog = new Dialog(
+                        "Add primary user",
+                        50,
+                        11,
+                        new Button("Ok", false)
+                        {
+                            Clicked = () =>
+                            {
+                                var username = primaryUserUsername.Text.ToString();
+                                var userHash = primaryUserUserHash.Text.ToString();
+
+                                var primaryUsers = Settings.BricksetPrimaryUsers;
+                                primaryUsers.Add(username, userHash);
+                                Settings.BricksetPrimaryUsers = primaryUsers;
+
+                                primaryUsersList.SetSource(primaryUsers.Select(keyValuePair => $"{keyValuePair.Key}/{keyValuePair.Value}").ToList());
+
+                                Application.RequestStop();
+                            }
+                        },
+                        new Button("Cancel", false)
+                        {
+                            Clicked = Application.RequestStop
+                        });
+
+                    dialog.Add(
+                        new Label("Username:")
+                        {
+                            Y = 1
+                        },
+                        primaryUserUsername,
+                        new Label("User hash:")
+                        {
+                            Y = 3
+                        },
+                        primaryUserUserHash
+                    );
+
+                    Application.Run(dialog);
+                }
+            };
+
+            window.Add(
+                primaryUsersLabel,
+                primaryUsersList,
+                deletePrimaryUserButton,
+                addPrimaryUserButton
+            );
+        }
     }
 }


Unspecified tags

Unspecified tags

--- AgilefantTimes/API/Agilefant/UserPerformed.cs
+++ AgilefantTimes/API/Agilefant/UserPerformed.cs
@@ -53,53 +53,83 @@
             PerformedTasks["pair"] = 0.0;
             PerformedTasks["chore"] = 0.0;
             PerformedTasks["fix"] = 0.0;
+            PerformedTasks["unspecified"] = 0.0;
             foreach (var task in tasks)
             {
                 var desc = task.Description?.ToLower() ?? "";
                 var time = task.MinutesSpent/60.0;

+                var tagged = false;
+
                 if (desc.Contains("#test "))
+                {
                     PerformedTasks["test"] = time + PerformedTasks["test"];
+                    tagged = true;
+                }

                 if (desc.Contains("#testmanual"))
+                {
                     PerformedTasks["testmanual"] = time + PerformedTasks["testmanual"];
+                    tagged = true;
+                }

                 if (desc.Contains("#testmanual"))
+                {
                     PerformedTasks["testmanual"] = time + PerformedTasks["testmanual"];
+                    tagged = true;
+                }

                 if (desc.Contains("#implement"))
+                {
                     PerformedTasks["implement"] = time + PerformedTasks["implement"];
+                    tagged = true;
+                }

                 if (desc.Contains("#refactor"))
+                {
                     PerformedTasks["refactor"] = time + PerformedTasks["refactor"];
+                    tagged = true;
+                }

                 if (desc.Contains("#document"))
+                {
                     PerformedTasks["document"] = time + PerformedTasks["document"];
+                    tagged = true;
+                }

                 if (desc.Contains("#chore"))
+                {
                     PerformedTasks["chore"] = time + PerformedTasks["chore"];
+                    tagged = true;
+                }

                 if (desc.Contains("#fix"))
+                {
                     PerformedTasks["fix"] = time + PerformedTasks["fix"];
+                    tagged = true;
+                }

-                if (desc.Contains("#pair"))
+                if (!tagged)
                 {
-                    PerformedTasks["pair"] = time + PerformedTasks["pair"];
-                    var ind = desc.IndexOf("#pair[", StringComparison.Ordinal);
-                    if (ind < 0) continue;
-                    ind += 6;
-                    var end = desc.IndexOf("]", ind, StringComparison.Ordinal);
-                    var pairs = desc.Substring(ind, end - ind).Split(',');
-                    foreach (var pair in pairs)
+                    PerformedTasks["unspecified"] = time + PerformedTasks["unspecified"];
+                }
+
+                if (!desc.Contains("#pair")) continue;
+                PerformedTasks["pair"] = time + PerformedTasks["pair"];
+                var ind = desc.IndexOf("#pair[", StringComparison.Ordinal);
+                if (ind < 0) continue;
+                ind += 6;
+                var end = desc.IndexOf("]", ind, StringComparison.Ordinal);
+                var pairs = desc.Substring(ind, end - ind).Split(',');
+                foreach (var pair in pairs)
+                {
+                    var p = pair.Trim();
+                    if (p == userCode)
                     {
-                        var p = pair.Trim();
-                        if (p == userCode)
-                        {
-                            continue;
-                        }
-                        var curr = time + (ProgrammedWithHours.ContainsKey(p) ? ProgrammedWithHours[p] : 0);
-                        ProgrammedWithHours[p] = curr;
+                        continue;
                     }
+                    var curr = time + (ProgrammedWithHours.ContainsKey(p) ? ProgrammedWithHours[p] : 0);
+                    ProgrammedWithHours[p] = curr;
                 }
             }


CP-13690 : Add the default URL for auto update of managementagent().msi

--- src/xenguestlib/AutoUpdate.cs
+++ src/xenguestlib/AutoUpdate.cs
@@ -46,7 +46,7 @@
 {
     public class FeatureAutoUpdate : Feature, IRefresh
     {
-        const string MSI_URL = "http://127.0.0.1/";
+        const string MSI_URL = "http://updates.vmd.citrix.com/XenServer/WinGuestAgent/Latest/";
         static volatile Thread autoUpdateThread = null;
         static object threadlock = new object();
         static bool stopping = false;
@@ -184,9 +184,9 @@
                 {
                     string msiName;
                     if (Win32Impl.is64BitOS() && (!Win32Impl.isWOW64()))
-                        msiName = "citrixguestagentx64.msi";
+                        msiName = "managementagentx64.msi";
                     else
-                        msiName = "citrixguestagentx86.msi";
+                        msiName = "managementagentx86.msi";

                     string msiURL = downloadURL + msiName;


function 1.3 done

function 1.3 done

--- functions/funktions-1/funktio-3/Program.cs
+++ functions/funktions-1/funktio-3/Program.cs
@@ -6,7 +6,38 @@
     {
         static void Main(string[] args)
         {
-            Console.WriteLine("Hello World!");
+            Console.OutputEncoding = System.Text.Encoding.UTF8;
+            int retNumber = numberFromRange(1, 50);
+            Console.WriteLine($"Syöttämäsi luku {retNumber} on sallittu");
+            Console.ReadKey();
+
+        }
+        static int NumberFromRange(int lowerBound, int upperBound)
+        {
+            bool isNumber;
+            int input = 0;
+            int ret = 0;
+
+            do
+            {
+                Console.Write("Syötä numero väliltä 1-50: ");
+                isNumber = int.TryParse(Console.ReadLine(), out input);
+
+
+                if (input >= lowerBound && input <= upperBound)
+                {
+                    ret = input;
+                    break;
+                }
+                else
+                {
+
+                    isNumber = false;
+                }
+            }
+            while (isNumber == false);
+
+            return ret;
         }
     }
 }


Response.End example

Response.End example

--- ApiExamples/CSharp/ApiExamples/ExMailMerge.cs
+++ ApiExamples/CSharp/ApiExamples/ExMailMerge.cs
@@ -41,7 +41,12 @@
                 new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });

             // Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
-            Assert.That(() => doc.Save(Response, "Artifacts/MailMerge.ExecuteArray.doc", ContentDisposition.Inline, null), Throws.TypeOf<ArgumentNullException>()); //Thrown because HttpResponse is null in the test.
+            Assert.That(() => doc.Save(Response, "Artifacts/MailMerge.ExecuteArray.doc", ContentDisposition.Inline, null),
+                Throws.TypeOf<ArgumentNullException>()); //Thrown because HttpResponse is null in the test.
+
+            // The response will need to be closed manually to make sure that no superfluous content is added to the document after saving
+            Assert.That(() => Response.End(),
+                Throws.TypeOf<NullReferenceException>());
             //ExEnd
         }
 #endif


Optimized Sieve

Optimized Sieve

--- ReverseWords/ErastotenesSieve/Sieve.cs
+++ ReverseWords/ErastotenesSieve/Sieve.cs
@@ -9,18 +9,14 @@
         internal List<int> Run(int numberOfItems)
         {
             List<int> list = Enumerable.Range(0,numberOfItems).ToList();
-            List<int> primes = new List<int>();
-            primes.Add(0);
-            primes.Add(1);
             int current = 2;
             do
             {
-                primes.Add(current);
-                list = list.Where(x => x == 0 || x == current || x % current != 0).ToList();
+                list = list.Where(x => x == 0 || x == current || x%current != 0).ToList();
                 current = list.SkipWhile(x => x < current).Skip(1).Take(1).SingleOrDefault();
-            } while (current != 0);
+            } while (current < Math.Sqrt(numberOfItems));

-            return primes;
+            return list;
         }

         public int GetMaxPrime(int numberOfItems) {


remove volatile keyword. SQLite's threadsafety is a lot less clear than I thought.

--- SQLitePCL.pretty/DatabaseConnection.cs
+++ SQLitePCL.pretty/DatabaseConnection.cs
@@ -472,7 +472,7 @@
         private readonly sqlite3 db;
         private readonly IEnumerable<IStatement> statements;

-        private volatile bool disposed = false;
+        private bool disposed = false;

         internal SQLiteDatabaseConnection(sqlite3 db)
         {


Refactored DOM attribute name

Refactored DOM attribute name

--- Samples/ViewModels/DOMNodeViewModel.cs
+++ Samples/ViewModels/DOMNodeViewModel.cs
@@ -107,7 +107,7 @@
                 typeName = FindName(type);

                 var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty)
-                    .Where(m => m.GetCustomAttributes(typeof(DOMAttribute), false).Length > 0)
+                    .Where(m => m.GetCustomAttributes(typeof(DomNameAttribute), false).Length > 0)
                     .OrderBy(m => m.Name);

                 foreach (var property in properties)
@@ -145,12 +145,12 @@

         String FindName(MemberInfo member)
         {
-            var objs = member.GetCustomAttributes(typeof(DOMAttribute), true);
+            var objs = member.GetCustomAttributes(typeof(DomNameAttribute), true);

             if (objs.Length == 0)
                 return member.Name;

-            return ((DOMAttribute)objs[0]).OfficialName;
+            return ((DomNameAttribute)objs[0]).OfficialName;
         }
     }
 }


Fix onchange called too much

Fix onchange called too much

--- Scripts/GameApi/LiteNetLibSyncField.cs
+++ Scripts/GameApi/LiteNetLibSyncField.cs
@@ -58,7 +58,8 @@
             CanSetElement = typeof(INetSerializableWithElement).IsAssignableFrom(GetFieldType());
             if (CanSetElement)
                 NetSerializableWithElementInstance = (INetSerializableWithElement)Activator.CreateInstance(GetFieldType());
-            OnChange(true);
+            if (IsServer)
+                OnChange(true);
         }

         internal void NetworkUpdate(float time)


Fix for HttpClient bug in mono closes #119

--- SendGrid/SendGridMail/Transport/Web.cs
+++ SendGrid/SendGridMail/Transport/Web.cs
@@ -55,8 +55,6 @@
 		public void Deliver(ISendGrid message)
 		{
             var client = new HttpClient();
-
-            client.BaseAddress = new Uri("https://" + BaseUrl);
 		    client.Timeout = _timeout;

             var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
@@ -65,7 +63,7 @@
 			var content = new MultipartFormDataContent();
 			AttachFormParams(message, content);
 			AttachFiles(message, content);
-			var response = client.PostAsync(Endpoint + ".xml", content).Result;
+			var response = client.PostAsync("https://" + BaseUrl + Endpoint + ".xml", content).Result;
 			CheckForErrors(response);
 		}

@@ -76,17 +74,16 @@
 		public async Task DeliverAsync(ISendGrid message)
 		{
 		    var client = new HttpClient();
-
-		    client.BaseAddress = new Uri("https://" + BaseUrl);
 		    client.Timeout = _timeout;

             var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
-            client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");
+
+			client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");

 			var content = new MultipartFormDataContent();
 			AttachFormParams(message, content);
 			AttachFiles(message, content);
-			var response = await client.PostAsync(Endpoint + ".xml", content);
+			var response = await client.PostAsync("https://" + BaseUrl + Endpoint + ".xml", content);
 			await CheckForErrorsAsync(response);
 		}


Fix chat messages crash the server.

Fix chat messages crash the server.

--- Server/Message/Reader/ChatMsgReader.cs
+++ Server/Message/Reader/ChatMsgReader.cs
@@ -31,7 +31,8 @@
                     ChatSystemReceiver.HandleLeaveMessage(client, (ChatLeaveMsgData)message);
                     break;
                 case ChatMessageType.ChannelMessage:
-                    ChatSystemReceiver.HandleChannelMessage(client, (ChatChannelMsgData)message);
+                    //TODO: Is the fix from message to data correct?  If so, do any of the other cases need to change?  This fix was done as a quick fix to stop the message error because message is a ChatCliMsg but data is a ChatChannelMsgData.
+                    ChatSystemReceiver.HandleChannelMessage(client, (ChatChannelMsgData)data);
                     break;
                 case ChatMessageType.PrivateMessage:
                     ChatSystemReceiver.HandlePrivateMessage(client, (ChatPrivateMsgData)message);


Fix normalizing a vector results in a zero vector

--- SharpMath/Geometry/VectorExtensions.cs
+++ SharpMath/Geometry/VectorExtensions.cs
@@ -1,10 +1,15 @@
-namespace SharpMath.Geometry
+using SharpMath.Geometry.Exceptions;
+
+namespace SharpMath.Geometry
 {
     public static class VectorExtensions
     {
         public static T Negate<T>(this Vector vector) where T : Vector, new()
         {
             var resultVector = new T();
+            if (vector.Dimension != resultVector.Dimension)
+                throw new DimensionException("The dimensions of the vectors do not equal each other.");
+
             for (uint i = 0; i < vector.Dimension; ++i)
                 resultVector[i] = -vector[i];
             return resultVector;
@@ -17,8 +22,11 @@
         public static T Normalize<T>(this Vector vector) where T : Vector, new()
         {
             var resultVector = new T();
+            if (vector.Dimension != resultVector.Dimension)
+                throw new DimensionException("The dimensions of the vectors do not equal each other.");
+
             for (uint i = 0; i < vector.Dimension; ++i)
-                resultVector[i] /= vector.Magnitude;
+                resultVector[i] = vector[i] / vector.Magnitude;
             return resultVector;
         }
     }


test case showing where two columns are filled and the third only has one option so it's easy to complete

--- SodukoTests/SolveKnownPuzzleFixture.cs
+++ SodukoTests/SolveKnownPuzzleFixture.cs
@@ -13,8 +13,10 @@
     {
         static readonly int? _ = null;

-        [Test, TestCaseSource("OnePossibleAnswerCases")]
-        public void SolveWhereOnePossibleAnswer(int?[,] puzzle, int expectedX, int expectedY, int cellValue)
+        [Test]
+        [TestCaseSource("OnePossibleAnswerCases")]
+        [TestCaseSource("ThirdRemainingColumnAnswerCases")]
+        public void SolveCell(int?[,] puzzle, int expectedX, int expectedY, int cellValue)
         {
             //Arrange
             var model = new BoardViewModel();
@@ -27,6 +29,32 @@
             Assert.AreEqual(cellValue, model.Cells[expectedX][expectedY].Number);
         }

+        #region Test Case Sources
+        static object[] ThirdRemainingColumnAnswerCases =
+        {
+            new object[] { new int?[9,9] {
+                {1, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, 1, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, 2, _, _, _, _, _, _},
+                {_, _, 3, _, _, _, _, _, _}
+            }, 6, 2, 1 },
+            new object[] { new int?[9,9] {
+                {_, _, _, _, _, _, _, _, 1},
+                {_, _, _, _, _, 1, _, _, _},
+                {2, _, 3, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _},
+                {_, _, _, _, _, _, _, _, _}
+            }, 2, 1, 1 }
+        };
         static object[] OnePossibleAnswerCases =
         {
             new object[] { new int?[9,9] {
@@ -42,18 +70,18 @@
             }, 0, 0, 1 },
             new object[] { new int?[9,9] {
                 {_, _, _, _, _, _, _, _, _},
-                {2, _, _, _, _, _, _, _, _},
-                {3, _, _, _, _, _, _, _, _},
-                {4, _, _, _, _, _, _, _, _},
-                {5, _, _, _, _, _, _, _, _},
-                {6, _, _, _, _, _, _, _, _},
-                {7, _, _, _, _, _, _, _, _},
-                {8, _, _, _, _, _, _, _, _},
-                {9, _, _, _, _, _, _, _, _}
-            }, 0, 0, 1 },
+                {_, 2, _, _, _, _, _, _, _},
+                {_, 3, _, _, _, _, _, _, _},
+                {_, 4, _, _, _, _, _, _, _},
+                {_, 5, _, _, _, _, _, _, _},
+                {_, 6, _, _, _, _, _, _, _},
+                {_, 7, _, _, _, _, _, _, _},
+                {_, 8, _, _, _, _, _, _, _},
+                {_, 9, _, _, _, _, _, _, _}
+            }, 0, 1, 1 },
             new object[] { new int?[9,9] {
-                {_, 2, 3, _, _, _, _, _, _},
-                {4, 5, 6, _, _, _, _, _, _},
+                {1, 2, 3, _, _, _, _, _, _},
+                {4, _, 6, _, _, _, _, _, _},
                 {7, 8, 9, _, _, _, _, _, _},
                 {_, _, _, _, _, _, _, _, _},
                 {_, _, _, _, _, _, _, _, _},
@@ -61,7 +89,7 @@
                 {_, _, _, _, _, _, _, _, _},
                 {_, _, _, _, _, _, _, _, _},
                 {_, _, _, _, _, _, _, _, _}
-            }, 0, 0, 1 },
+            }, 1, 1, 5 },
             new object[] { new int?[9,9] {
                 {_, _, _, _, _, _, _, _, _},
                 {_, _, _, _, _, _, _, _, _},
@@ -85,6 +113,7 @@
                 {_, _, _, _, _, _, _, _, _}
             }, 0, 0, 1 }*/
         };
+        #endregion

     }
 }


:hammer: :fire: re-factored ActivitiesGetter due to potential for subtle bug

--- SonghayCore/Models/ActivitiesGetter.cs
+++ SonghayCore/Models/ActivitiesGetter.cs
@@ -12,14 +12,6 @@
     public abstract class ActivitiesGetter
     {
         /// <summary>
-        /// Initializes a new instance of the <see cref="ActivitiesGetter"/> class.
-        /// </summary>
-        public ActivitiesGetter()
-        {
-            this.SetupActivities();
-        }
-
-        /// <summary>
         /// Initializes a new instance of the <see cref="ActivitiesGetter" /> class.
         /// </summary>
         /// <param name="args">The arguments.</param>
@@ -27,7 +19,6 @@
         {
             this._defaultActivityName = ToActivityName(args);
             this.Args = new ProgramArgs(ToActivityArgs(args));
-            this.SetupActivities();
         }

         /// <summary>
@@ -58,12 +49,12 @@
         }

         /// <summary>
-        /// Called when the storage and lazy instantiation
-        /// of <see cref="IActivity"/> types needs to be stated.
+        /// Loads the activities.
         /// </summary>
         /// <param name="activities">The activities.</param>
-        protected virtual void OnSetupActivities(Dictionary<string, Lazy<IActivity>> activities)
+        public virtual void LoadActivities(Dictionary<string, Lazy<IActivity>> activities)
         {
+            this._activities = activities;
         }

         static string[] ToActivityArgs(string[] args)
@@ -78,12 +69,6 @@
             return args.First();
         }

-        void SetupActivities()
-        {
-            this._activities = new Dictionary<string, Lazy<IActivity>>();
-            this.OnSetupActivities(this._activities);
-        }
-
         Dictionary<string, Lazy<IActivity>> _activities;
         string _defaultActivityName;
     }


#1738 MethodCaller CreateInstance methods require dependency injection

--- Source/Csla/Reflection/MethodCaller.cs
+++ Source/Csla/Reflection/MethodCaller.cs
@@ -12,6 +12,7 @@
 using Csla.Properties;
 using System.Globalization;
 using System.Threading.Tasks;
+using Microsoft.Extensions.DependencyInjection;

 namespace Csla.Reflection
 {
@@ -190,10 +191,7 @@
     /// <param name="objectType">Type of object to create.</param>
     public static object CreateInstance(Type objectType)
     {
-      var ctor = GetCachedConstructor(objectType);
-      if (ctor == null)
-        throw new NotImplementedException(objectType.Name + " " + Resources.DefaultConstructor + Resources.MethodNotImplemented);
-      return ctor.Invoke();
+      return ActivatorUtilities.CreateInstance(ApplicationContext.ScopedServiceProvider, objectType);
     }

     /// <summary>
@@ -203,7 +201,7 @@
     /// <param name="parameters">Parameters for constructor</param>
     public static object CreateInstance(Type objectType, params object[] parameters)
     {
-      return Activator.CreateInstance(objectType, parameters);
+      return ActivatorUtilities.CreateInstance(ApplicationContext.ScopedServiceProvider, objectType, parameters);
     }

     /// <summary>
@@ -217,7 +215,7 @@
     {
       var genericType = type.GetGenericTypeDefinition();
       var gt = genericType.MakeGenericType(paramTypes);
-      return Activator.CreateInstance(gt);
+      return CreateInstance(gt);
     }

     #endregion


Make the path logic consistent across environments.

--- Source/Slinqy.Test.Functional/Setup.cs
+++ Source/Slinqy.Test.Functional/Setup.cs
@@ -83,11 +83,16 @@

             const string ScreenshotDirectoryName = "Screenshots";

-            if (!Directory.Exists(ScreenshotDirectoryName))
-                Directory.CreateDirectory(ScreenshotDirectoryName);
+            var screenshotsPath = Path.Combine(
+                Environment.CurrentDirectory,
+                ScreenshotDirectoryName
+            );
+
+            if (!Directory.Exists(screenshotsPath))
+                Directory.CreateDirectory(screenshotsPath);

             var screenshotPath = Path.Combine(
-                ScreenshotDirectoryName,
+                screenshotsPath,
                 failedTestName + " - Failure.png"
             );


Enabled AtomEventsOnAzure to enumerate all indexes

There's no unit test coverage of the implementation, because unit testing
when a Persistent Fixture is involved, is too brittle. I have, however,
manually tested that the feature works.

--- AtomEventStore.AzureBlob/AtomEventsOnAzure.cs
+++ AtomEventStore.AzureBlob/AtomEventsOnAzure.cs
@@ -9,7 +9,7 @@

 namespace Grean.AtomEventStore.AzureBlob
 {
-    public class AtomEventsOnAzure : IAtomEventStorage
+    public class AtomEventsOnAzure : IAtomEventStorage, IEnumerable<UuidIri>
     {
         private readonly CloudBlobContainer container;

@@ -52,5 +52,30 @@
         {
             return this.container.GetBlockBlobReference(href.ToString() + ".xml");
         }
+
+        public IEnumerator<UuidIri> GetEnumerator()
+        {
+            return this.container
+                .ListBlobs()
+                .OfType<CloudBlobDirectory>()
+                .Select(d => d.Uri.Segments.Last())
+                .Select(s => s.Trim('/'))
+                .Select(TryParseGuid)
+                .Where(t => t.Item1)
+                .Select(t => (UuidIri)t.Item2)
+                .GetEnumerator();
+        }
+
+        private static Tuple<bool, Guid> TryParseGuid(string candidate)
+        {
+            Guid id;
+            var success = Guid.TryParse(candidate, out id);
+            return new Tuple<bool, Guid>(success, id);
+        }
+
+        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+        {
+            return this.GetEnumerator();
+        }
     }
 }


"Get" extension method broadened to type IEnumerable<KeyValuePair<TKey, TValue>>, so that both IDictionary and IReadOnlyDictionary types are captured.

--- Sources/MayBee/EnumerableExtensions.cs
+++ Sources/MayBee/EnumerableExtensions.cs
@@ -109,12 +109,29 @@
         /// Looks up a key and returns the associated value wrapped in an <see cref="IMaybe{T}"/>,
         /// or an empty <see cref="IMaybe{T}"/> if the key doesn't exist.
         /// </summary>
-        public static Maybe<TValue> Get<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key)
+        public static Maybe<TValue> Get<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, TKey key)
         {
-            TValue value;
-            var exists = source.TryGetValue(key, out value);
+            var dict = source as IDictionary<TKey, TValue>;

-            return exists ? Maybe.Is(value) : Maybe.Empty<TValue>();
-        }
+            if (dict != null)
+            {
+                TValue value;
+                var exists = dict.TryGetValue(key, out value);
+
+                return exists ? Maybe.Is(value) : Maybe.Empty<TValue>();
+            }
+
+            var readOnlyDict = source as IReadOnlyDictionary<TKey, TValue>;
+
+            if (readOnlyDict != null)
+            {
+                TValue value;
+                var exists = readOnlyDict.TryGetValue(key, out value);
+
+                return exists ? Maybe.Is(value) : Maybe.Empty<TValue>();
+            }
+
+            return source.FirstAsMaybe(p => p.Key.Equals(key)).Select(p => p.Value);
+        }
     }
 }


Added information about the logged in user to the footer

--- AzureAdMvcExample/Views/Shared/_Layout.cshtml
+++ AzureAdMvcExample/Views/Shared/_Layout.cshtml
@@ -1,4 +1,6 @@
-<!DOCTYPE html>
+@using System.Security.Claims
+@using ClaimTypes = System.IdentityModel.Claims.ClaimTypes
+<!DOCTYPE html>

     <meta charset="utf-8" />
@@ -31,6 +33,17 @@

         @RenderBody()
+
+

+            @if (User.Identity.IsAuthenticated)
+            {
+                @:Logged in as @(ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName).Value) @(ClaimsPrincipal.Current.FindFirst(ClaimTypes.Surname).Value).
+            }
+            else
+            {
+                @:Not logged in
+            }
+

     @Scripts.Render("~/bundles/jquery")
     @Scripts.Render("~/bundles/bootstrap")


BV-841 tried to get rows' cells' values without having to resort to a who other package. Commenting code out for now until I figure it out

--- BroadvineOnboard/App_Code/ExcelSpreadSheet.cs
+++ BroadvineOnboard/App_Code/ExcelSpreadSheet.cs
@@ -41,16 +41,45 @@
         {
             //get
             //{
-            //    //if (columns == null) columns = Rows.Skip(0).First().ToArray().Select(x => x.Value.ToString());
-            //    //return columns;
+            //    if (columns == null)
+            //    {
+            //        TODO: Figure Out how to get this code to work :/
+            //        //columns = RowsNoHeader.Skip(6).First().ToArray().Select(x => x.Value.ToString());
+            //        //columns = RowsNoHeader.Skip(RowStart).First().ToArray().Select(x => x.Value.ToString());
+            //        var row = RowsNoHeader.Skip(6).First();

+            //        List<string> cols = new List<string>();
+            //        foreach (var cell in row.ToArray())
+            //        {
+            //            cols.Add(cell.Value.ToString());
+            //        }
+            //    }

+            //    return columns;
             //}

             get
             {
-                if (columns == null) columns = ReadExcelFileSAX(excelFileName);    // SAX
+                if (columns == null)
+                {
+                    columns = ReadExcelFileSAX(excelFileName);    // SAX
+                }
+
                 return columns;
+            }
+        }
+
+        private IQueryable<LinqToExcel.RowNoHeader> rowsNoHeader;
+        public IQueryable<LinqToExcel.RowNoHeader> RowsNoHeader
+        {
+            get
+            {
+                if (rowsNoHeader == null)
+                {
+                    rowsNoHeader = from d in excel.WorksheetNoHeader(this.SelectedWorksheet) select d;
+                }
+
+                return rowsNoHeader;
             }
         }

@@ -59,7 +88,11 @@
         {
             get
             {
-                if (rows == null) rows = from d in excel.Worksheet(this.SelectedWorksheet) select d;
+                if (rows == null)
+                {
+                    rows = from d in excel.Worksheet(this.SelectedWorksheet) select d;
+                }
+
                 return rows;
             }
         }


Patch to Spatial.Net for TopDocs.totalHits and TopDocs.scoreDocs

git-svn-id: 6c68d65edd5507bf6b37474e0d155329cbeeff2a@890209 13f79535-47bb-0310-9956-ffa450edef68

--- C#/contrib/Spatial.Net/Tests/TestCartesian.cs
+++ C#/contrib/Spatial.Net/Tests/TestCartesian.cs
@@ -143,8 +143,8 @@
 			// Perform the search, using the term query, the distance filter, and the
 			// distance sort
 			TopDocs hits = _searcher.Search(tq, dq.Filter, 1000, sort);
-			int results = hits.TotalHits;
-			ScoreDoc[] scoreDocs = hits.ScoreDocs;
+			int results = hits.totalHits;
+			ScoreDoc[] scoreDocs = hits.scoreDocs;

 			// Get a list of distances
 			Dictionary<int, Double> distances = dq.DistanceFilter.Distances;


update

update

--- CSharpGL/0Foundations/OpenGLAPI/OpenGL.2.0.cs
+++ CSharpGL/0Foundations/OpenGLAPI/OpenGL.2.0.cs
@@ -16,7 +16,7 @@
         ///// <param name="modeAlpha"></param>
         //public delegate void glBlendEquationSeparate(uint modeRGB, uint modeAlpha);
         /// <summary>
-        ///
+        /// Select buffers that are written to.
         /// </summary>
         /// <param name="n"></param>
         /// <param name="bufs"></param>


Filter teradps.io exports by areaid and dps

--- CasualMeter.Common/TeraDpsApi/DataExporter.cs
+++ CasualMeter.Common/TeraDpsApi/DataExporter.cs
@@ -158,6 +158,25 @@
                 Task.Run(() => ExcelExport.ExcelSave(teradpsData, teraData));
             }
             if (string.IsNullOrEmpty(SettingsHelper.Instance.Settings.TeraDpsToken) || string.IsNullOrEmpty(SettingsHelper.Instance.Settings.TeraDpsUser) || !SettingsHelper.Instance.Settings.SiteExport) return;
+            /*
+              Validation, without that, the server cpu will be burning \o
+            */
+            var areaId = int.Parse(teradpsData.areaId);
+            if (
+                areaId != 886 &&
+                areaId != 467 &&
+                areaId != 767 &&
+                areaId != 768 &&
+                areaId != 468
+                )
+            {
+                return;
+            }
+
+            if (int.Parse(teradpsData.partyDps) < 2000000)
+            {
+                return;
+            }
             string json = JsonConvert.SerializeObject(teradpsData, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
             Task.Run(() => Send(entity, json, 3));
         }


Make HierarchyNode.AddChild virtual

Make HierarchyNode.AddChild virtual

--- Common/Product/SharedProject/HierarchyNode.cs
+++ Common/Product/SharedProject/HierarchyNode.cs
@@ -1732,7 +1732,7 @@
         /// AddChild - add a node, sorted in the right location.
         /// </summary>
         /// <param name="node">The node to add.</param>
-        public void AddChild(HierarchyNode node) {
+        public virtual void AddChild(HierarchyNode node) {
             Utilities.ArgumentNotNull("node", node);

             Debug.Assert(ProjectMgr.ItemIdMap[node.hierarchyId] == null || ProjectMgr.ItemIdMap[node.hierarchyId] == node);


Manually cut NodejsProjectNode -> NodeJsFolderNode reference link

--- Common/Product/SharedProject/HierarchyNode.cs
+++ Common/Product/SharedProject/HierarchyNode.cs
@@ -1564,6 +1564,10 @@
         /// </summary>
         /// <param name="disposing">Is the Dispose called by some internal member, or it is called by from GC.</param>
         protected virtual void Dispose(bool disposing) {
+            firstChild = null;
+            lastChild = null;
+            nextSibling = null;
+            itemNode = null;
         }

         /// <summary>


Update PostLogHelpHandler.cs

Update PostLogHelpHandler.cs

--- CompatBot/EventHandlers/PostLogHelpHandler.cs
+++ CompatBot/EventHandlers/PostLogHelpHandler.cs
@@ -13,7 +13,7 @@
     internal static class PostLogHelpHandler
     {
         private const RegexOptions DefaultOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture;
-        private static readonly Regex UploadLogMention = new Regex(@"\b((?<vulkan>(vul[ck][ae]n(-?1)?))|(?<help>(post|upload|send|give)(ing)?\s+((a|the|rpcs3('s)?|your|you're|ur|my|full)\s+)*\blogs?))\b", DefaultOptions);
+        private static readonly Regex UploadLogMention = new Regex(@"\b((?<vulkan>(vul[ck][ae]n(-?1)?))|(?<help>(post|upload|send|give)(ing)?\s+((a|the|rpcs3('s)?|your|you're|ur|my|full|game)\s+)*\blogs?))\b", DefaultOptions);
         private static readonly SemaphoreSlim TheDoor = new SemaphoreSlim(1, 1);
         private static readonly TimeSpan ThrottlingThreshold = TimeSpan.FromSeconds(5);
         private static readonly Dictionary<string, Explanation> DefaultExplanation = new Dictionary<string, Explanation>