Use ReferenceEquals for clarity

Use ReferenceEquals for clarity

--- src/Workspaces/Core/Portable/Utilities/Documentation/XmlDocumentationProvider.cs
+++ src/Workspaces/Core/Portable/Utilities/Documentation/XmlDocumentationProvider.cs
@@ -189,7 +189,7 @@
             public override bool Equals(object obj)
             {
                 // Only one instance is expected to exist, so reference equality is fine.
-                return this == obj;
+                return ReferenceEquals(this, obj);
             }

             public override int GetHashCode()


Fixed offset in parentheses handling.

Fixed offset in parentheses handling.

--- Scripting/Parser/Construct/ParseExpression.cs
+++ Scripting/Parser/Construct/ParseExpression.cs
@@ -1459,7 +1459,7 @@
                     parts[last] is string && ((string)parts[last]).Length == 1 && ((string)parts[last])[0] == ParenClose))
                     return;

-                for (int i = 1; i < last; i++)
+                for (int i = 0; i < last; i++)
                 {
                     string check = parts[i] as string;


prepare for release

prepare for release

prepare for release

--- src/ADAL.Common/CommonAssemblyInfo.cs
+++ src/ADAL.Common/CommonAssemblyInfo.cs
@@ -37,7 +37,7 @@
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyMetadata("Serviceable", "True")]

-[assembly: AssemblyVersion("3.11.0.0")]
+[assembly: AssemblyVersion("3.12.0.0")]

 // On official build, attribute AssemblyInformationalVersionAttribute is added as well
 // with its value equal to the hash of the last commit to the git branch.


Refactor day 2's solution

Refactor day 2's solution

Improve code readability.
Fix typo.

--- src/AdventOfCode2015/Puzzles/Day02.cs
+++ src/AdventOfCode2015/Puzzles/Day02.cs
@@ -40,13 +40,10 @@
         /// </returns>
         internal static Tuple<int, int> GetTotalWrappingPaperAreaAndRibbonLength(IEnumerable<string> dimensions)
         {
-            // Read in the dimensions of the presents from the specified input file
-            List<Present> presents = new List<Present>();
-
-            foreach (string line in dimensions)
-            {
-                presents.Add(Present.Parse(line));
-            }
+            // Parse the dimensions of the presents
+            var presents = dimensions
+                .Select(Present.Parse)
+                .ToList();

             // Determine the total area of wrapping paper required and the amount of ribbon
             int totalArea = presents.Sum(GetWrappingPaperArea);
@@ -79,10 +76,18 @@
         /// <returns>The length of ribbon, in feet, required to wrap the present.</returns>
         private static int GetRibbonLength(Present present)
         {
-            int smallestPerimiter = new[] { (present.Length + present.Width) * 2, (present.Width + present.Height) * 2, (present.Height + present.Length) * 2 }.Min();
+            var perimetersOfSides = new[]
+            {
+                (present.Length + present.Width) * 2,
+                (present.Width + present.Height) * 2,
+                (present.Height + present.Length) * 2,
+            };
+
+            int smallestPerimeter = perimetersOfSides.Min();
+
             int lengthForBow = present.Height * present.Length * present.Width;

-            return smallestPerimiter + lengthForBow;
+            return smallestPerimeter + lengthForBow;
         }

         /// <summary>
@@ -92,8 +97,19 @@
         /// <returns>The area of wrapping paper, in square feet, required to wrap the present.</returns>
         private static int GetWrappingPaperArea(Present present)
         {
-            int surfaceArea = (2 * present.Length * present.Width) + (2 * present.Width * present.Height) + (2 * present.Height * present.Length);
-            int extra = new[] { present.Length * present.Width, present.Width * present.Height, present.Height * present.Length }.Min();
+            int surfaceArea =
+                (2 * present.Length * present.Width) +
+                (2 * present.Width * present.Height) +
+                (2 * present.Height * present.Length);
+
+            var areasOfSides = new[]
+            {
+                present.Length * present.Width,
+                present.Width * present.Height,
+                present.Height * present.Length,
+            };
+
+            int extra = areasOfSides.Min();

             return surfaceArea + extra;
         }


Output namespaces

Output namespaces

--- src/ApiApprover/PublicApiGenerator.cs
+++ src/ApiApprover/PublicApiGenerator.cs
@@ -43,12 +43,14 @@
                 foreach (var publicType in publicTypes)
                 {
                     var writer = new StringWriter();
+                    var @namespace = new CodeNamespace(publicType.Namespace);
                     var genClass = CreateClassDeclaration(publicType);
                     foreach (var memberInfo in publicType.GetMembers().Where(m => !IsDotNetTypeMember(m)).OrderBy(m => m.Name))
                     {
                         AddMemberToClassDefinition(genClass, memberInfo);
                     }
-                    provider.GenerateCodeFromType(genClass, writer, cgo);
+                    @namespace.Types.Add(genClass);
+                    provider.GenerateCodeFromNamespace(@namespace, writer, cgo);
                     var gennedClass = GenerateClassCode(writer);
                     publicApiBuilder.AppendLine(gennedClass);
                 }


Removed heartbeatinterval setting.

Removed heartbeatinterval setting.

--- SignalR/Configuration/ConfigurationManager.cs
+++ SignalR/Configuration/ConfigurationManager.cs
@@ -7,18 +7,10 @@
         public ConfigurationManager()
         {
             ReconnectionTimeout = TimeSpan.FromSeconds(110);
-            HeartBeatInterval = TimeSpan.FromSeconds(10);
             DisconnectTimeout = TimeSpan.FromSeconds(20);
         }

         public TimeSpan ReconnectionTimeout
-        {
-            get;
-            set;
-        }
-
-
-        public TimeSpan HeartBeatInterval
         {
             get;
             set;


Reformat.

Reformat.

--- src/Avalonia.Base/AvaloniaProperty.cs
+++ src/Avalonia.Base/AvaloniaProperty.cs
@@ -459,37 +459,6 @@
             return GetMetadataWithOverrides(type);
         }

-        private PropertyMetadata GetMetadataWithOverrides(Type type)
-        {
-            if (type is null)
-            {
-                throw new ArgumentNullException(nameof(type));
-            }
-
-            if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
-            {
-                return result;
-            }
-
-            Type currentType = type;
-
-            while (currentType != null)
-            {
-                if (_metadata.TryGetValue(currentType, out result))
-                {
-                    _metadataCache[type] = result;
-
-                    return result;
-                }
-
-                currentType = currentType.GetTypeInfo().BaseType;
-            }
-
-            _metadataCache[type] = _defaultMetadata;
-
-            return _defaultMetadata;
-        }
-
         /// <summary>
         /// Checks whether the <paramref name="value"/> is valid for the property.
         /// </summary>
@@ -554,6 +523,37 @@
             _metadataCache.Clear();

             _hasMetadataOverrides = true;
+        }
+
+        private PropertyMetadata GetMetadataWithOverrides(Type type)
+        {
+            if (type is null)
+            {
+                throw new ArgumentNullException(nameof(type));
+            }
+
+            if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
+            {
+                return result;
+            }
+
+            Type currentType = type;
+
+            while (currentType != null)
+            {
+                if (_metadata.TryGetValue(currentType, out result))
+                {
+                    _metadataCache[type] = result;
+
+                    return result;
+                }
+
+                currentType = currentType.GetTypeInfo().BaseType;
+            }
+
+            _metadataCache[type] = _defaultMetadata;
+
+            return _defaultMetadata;
         }

         [DebuggerHidden]


Adds Error to the RtmStartResponse model.

--- SlackBotRedux.Core.Models/RtmStartResponse.cs
+++ SlackBotRedux.Core.Models/RtmStartResponse.cs
@@ -9,6 +9,14 @@
     public class RtmStartResponse
     {
         public bool Ok { get; set; }
+
+        public enum ErrorType
+        {
+            NotAuthed,
+            InvalidAuth,
+            AccountInactive
+        }
+        public ErrorType Error { get; set; }

         /// <summary>
         /// The WebSocket Message Server URL; connecting to this URL will initiate a Real Time Messaging session. These URLs are only valid for 30 seconds.


Fixed returns value; Issue 4883

Fixed returns value; Issue 4883

--- src/Avalonia.Controls/ItemsControl.cs
+++ src/Avalonia.Controls/ItemsControl.cs
@@ -169,7 +169,7 @@
         /// </summary>
         /// <param name="items">The collection.</param>
         /// <param name="index">The index.</param>
-        /// <returns>The index of the item or -1 if the item was not found.</returns>
+        /// <returns>The item at the given index or null if the index is out of bounds.</returns>
         protected static object ElementAt(IEnumerable items, int index)
         {
             if (index != -1 && index < items.Count())


pass key modifiers to focus

pass key modifiers to focus

--- src/Avalonia.Controls/ItemsControl.cs
+++ src/Avalonia.Controls/ItemsControl.cs
@@ -295,7 +295,7 @@

                         if (next != null)
                         {
-                            focus.Focus(next, NavigationMethod.Directional);
+                            focus.Focus(next, NavigationMethod.Directional, e.KeyModifiers);
                             e.Handled = true;
                         }


TSI-1308 Cleaned up ResolveRichText TBB and allow it to run in a Page Template too, so it can be used to pre-process Page metadata (TSI-2163)

--- Sdl.Web.Tridion.Templates/Templates/ResolveRichText.cs
+++ Sdl.Web.Tridion.Templates/Templates/ResolveRichText.cs
@@ -15,9 +15,7 @@
 namespace Sdl.Web.Tridion.Templates
 {
     /// <summary>
-    /// Resolves rich text fields from the package output.
-    /// Replacing img tags that point to a YouTube video with a youtube tag,
-    /// so these can be resolved correctly by the web application.
+    /// Pre-processes Rich Text fields so they contain sufficient information for Rich Text Processing in the Web Application.
     /// </summary>
     [TcmTemplateTitle("Resolve Rich Text")]
     [TcmTemplateParameterSchema("resource:Sdl.Web.Tridion.Resources.ResolveRichTextParameters.xsd")]
@@ -27,201 +25,105 @@
         private const string FileNameAttribute = "data-multimediaFileName";
         private const string FileSizeAttribute = "data-multimediaFileSize";
         private const string MimeTypeAttribute = "data-multimediaMimeType";
-        private const string LinkPattern = @"xlink:href=\\""(tcm\:\d+\-\d+)\\""";
-        private const string XhtmlPattern = " xmlns=\\\"http://www.w3.org/1999/xhtml\\\"";
+        private const string TcmXLinkPattern = @"xlink:href=\\""(tcm\:\d+\-\d+)\\""";
+        private const string XhtmlNamespaceDeclaration = " xmlns=\\\"http://www.w3.org/1999/xhtml\\\"";

-        private List<string> _metaFieldNames = new List<string>();
+        private List<string> _dataFieldNames;

         public override void Transform(Engine engine, Package package)
         {
             Initialize(engine, package);
-            Component comp = GetComponent();
-            if (IsPageTemplate() || comp == null)
-            {
-                Logger.Error("No Component found (is this a Page Template?)");
-                return;
-            }
+
             Item outputItem = package.GetByName(Package.OutputName);
             if (outputItem == null)
             {
-                Logger.Error("No Output package item found (is this TBB placed at the end?)");
+                Logger.Error("No Output item found in package. Ensure this TBB is executed at the end of the modular templating pipeline.");
                 return;
             }
-            _metaFieldNames = (package.GetValue("multimediaLinkAttributes") ?? String.Empty).Split(',').Select(s => s.Trim()).ToList();

-            // resolve rich text fields
+            string multimediaLinkAttributesParam = package.GetValue("multimediaLinkAttributes") ?? string.Empty;
+            Logger.Debug("Using multimediaLinkAttributes: " + multimediaLinkAttributesParam);
+            _dataFieldNames = multimediaLinkAttributesParam.Split(',').Select(s => s.Trim()).ToList();
+
             string output = outputItem.GetAsString();
-            package.Remove(outputItem);
-            if (output.StartsWith("<"))
-            {
-                Logger.Debug("Content is XML");
-                //XML - only for backwards compatibility
-                package.PushItem(Package.OutputName, package.CreateXmlDocumentItem(ContentType.Xml, ResolveXmlContent(output)));
-            }
-            else
-            {
-                Logger.Debug("Content is JSON");
-                //JSON
-                package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Text, ResolveJsonContent(output)));
-            }
+            package.Remove(outputItem);
+            package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Text, PreProcessRichTextContent(output)));
         }

-        private string ResolveJsonContent(string content)
+        private string PreProcessRichTextContent(string content)
         {
-            //remove XHTML namespace
-            content = content.Replace(XhtmlPattern, String.Empty);
+            // Strip off XHTML namespace declarations
+            content = content.Replace(XhtmlNamespaceDeclaration, string.Empty);

-            //add data attributes to component links
-            content = Regex.Replace(content, LinkPattern, delegate(Match match)
-            {
-                Logger.Debug("Found RTF link match: " + match.Value);
-                string compId = match.Groups[1].Value;
-                string replaced = match.Value;
-                Component comp = (Component)Engine.GetObject(compId);
+            // Add data attributes to MM component links
+            content = Regex.Replace(
+                content,
+                TcmXLinkPattern,
+                match =>
+                {
+                    string originalLink = match.Value;
+                    string linkedItemId = match.Groups[1].Value;
+                    Component linkedComponent = Engine.GetObject(linkedItemId) as Component;

-                // add attributes for model mapping
-                if (comp != null && comp.BinaryContent != null)
-                {
-                    // set attributes for multimedia component
-                    string attributes = String.Empty;
-                    StringBuilder attributesBuilder = new StringBuilder();
-                    attributesBuilder.AppendFormat(" {0}=\"{1}\"", SchemaUriAttribute, comp.Schema.Id);
-                    attributesBuilder.AppendFormat(" {0}=\"{1}\"", FileNameAttribute, comp.BinaryContent.Filename);
-                    attributesBuilder.AppendFormat(" {0}=\"{1}\"", FileSizeAttribute, comp.BinaryContent.Size);
-                    attributesBuilder.AppendFormat(" {0}=\"{1}\"", MimeTypeAttribute, comp.BinaryContent.MultimediaType.MimeType);
-
-                    // resolve metadata into additional data-attributes
-                    if (comp.Metadata != null)
+                    if (linkedComponent == null || linkedComponent.BinaryContent == null)
                     {
-                        ItemFields fields = new ItemFields(comp.Metadata, comp.MetadataSchema);
-                        attributesBuilder.Append(ProcessFields(fields));
+                        // Linked item is not a MM Component.
+                        return originalLink;
                     }

-                    // encode and strip first and last character (quotes added by encode)
-                    if (attributesBuilder.Length > 0)
+                    Logger.Debug("Found Multimedia Component Link in Rich Text: " + linkedComponent.ToString());
+
+                    StringBuilder dataAttributesBuilder = new StringBuilder();
+                    BinaryContent binaryContent = linkedComponent.BinaryContent;
+                    dataAttributesBuilder.AppendFormat(" {0}=\"{1}\"", SchemaUriAttribute, linkedComponent.Schema.Id);
+                    dataAttributesBuilder.AppendFormat(" {0}=\"{1}\"", FileNameAttribute, binaryContent.Filename);
+                    dataAttributesBuilder.AppendFormat(" {0}=\"{1}\"", FileSizeAttribute, binaryContent.Size);
+                    dataAttributesBuilder.AppendFormat(" {0}=\"{1}\"", MimeTypeAttribute, binaryContent.MultimediaType.MimeType);
+
+                    if (linkedComponent.Metadata != null)
                     {
-                        attributes = JsonEncode(attributesBuilder.ToString()).Substring(1);
-                        attributes = attributes.Substring(0, attributes.Length - 1);
+                        ItemFields metadataFields = new ItemFields(linkedComponent.Metadata, linkedComponent.MetadataSchema);
+                        ExtractDataAttributes(metadataFields, dataAttributesBuilder);
                     }
-                    replaced = replaced + attributes;
+
+                    string dataAttributes;
+                    if (dataAttributesBuilder.Length > 0)
+                    {
+                        // encode and strip first and last character (quotes added by encode)
+                        dataAttributes = JsonEncode(dataAttributesBuilder.ToString()).Substring(1);
+                        dataAttributes = dataAttributes.Substring(0, dataAttributes.Length - 1);
+                        Logger.Debug("Added data attributes: " + dataAttributes);
+                    }
+                    else
+                    {
+                        dataAttributes = string.Empty;
+                    }
+
+                    return originalLink + dataAttributes;
                 }
-                return replaced;
-            });
+                );
+
             return content;
         }

-        private string ProcessFields(ItemFields fields)
+        private void ExtractDataAttributes(ItemFields fields, StringBuilder dataAttributesBuilder)
         {
-            StringBuilder attributesBuilder = new StringBuilder();
-            if (fields!=null)
+            if (fields == null)
             {
-                Logger.Debug(String.Join(", ", _metaFieldNames));
-                foreach (string fieldname in _metaFieldNames)
-                {
-                    Logger.Debug("Processing field: " + fieldname);
-                    if (fields.Contains(fieldname))
-                    {
-                        string attribute = String.Format(" data-{0}=\"{1}\"", fieldname, System.Net.WebUtility.HtmlEncode(fields.GetSingleFieldValue(fieldname)));
-                        Logger.Debug("Attribute:" + attribute);
-                        // TODO: XML encode the value
-                        attributesBuilder.Append(attribute);
-                    }
-                }
+                return;
+            }

-                foreach (ItemField field in fields)
-                {
-                    if (field is EmbeddedSchemaField)
-                    {
-                        attributesBuilder.Append(ProcessFields(((EmbeddedSchemaField)field).Value));
-                    }
-                }
+            foreach (string fieldname in _dataFieldNames.Where(fn => fields.Contains(fn)))
+            {
+                string dataAttribute = string.Format(" data-{0}=\"{1}\"", fieldname, System.Net.WebUtility.HtmlEncode(fields.GetSingleFieldValue(fieldname)));
+                dataAttributesBuilder.Append(dataAttribute);
             }
-            Logger.Debug("attributes:" + attributesBuilder);
-            return attributesBuilder.ToString();
-        }

-        private XmlDocument ResolveXmlContent(string content)
-        {
-            XmlDocument doc = new XmlDocument();
-            doc.LoadXml(content);
-            XmlNodeList fields = doc.SelectNodes("//Field[@FieldType='Xhtml']/Values/string");
-            foreach (XmlElement field in fields)
+            // Flatten embedded fields
+            foreach (EmbeddedSchemaField embeddedSchemaField in fields.OfType<EmbeddedSchemaField>())
             {
-                field.InnerXml = ResolveXhtml(field.InnerXml);
+                ExtractDataAttributes(embeddedSchemaField.Value, dataAttributesBuilder);
             }
-            return doc;
-        }
-
-        private string ResolveXhtml(string input)
-        {
-            XmlDocument xhtml = new XmlDocument();
-            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xhtml.NameTable);
-            nsmgr.AddNamespace(Constants.XlinkPrefix, Constants.XlinkNamespace);
-            xhtml.LoadXml(String.Format("<root>{0}</root>", UnEscape(input)));
-
-            // locate linked components
-            foreach (XmlElement link in xhtml.SelectNodes("//*[@xlink:href[starts-with(string(.),'tcm:')]]", nsmgr))
-            {
-                string uri = link.Attributes["xlink:href"].IfNotNull(attr => attr.Value);
-                //string title = img.Attributes["xlink:title"].IfNotNull(attr => attr.Value);
-                //string src = img.Attributes["src"].IfNotNull(attr => attr.Value);
-                if (!string.IsNullOrEmpty(uri))
-                {
-                    Component comp = (Component)Engine.GetObject(uri);
-
-                    // resolve multimedia component
-                    if (comp != null && comp.BinaryContent != null)
-                    {
-                        // set attributes for multimedia component
-                        link.SetAttribute(SchemaUriAttribute, comp.Schema.Id);
-                        link.SetAttribute(FileNameAttribute, comp.BinaryContent.Filename);
-                        link.SetAttribute(FileSizeAttribute, comp.BinaryContent.Size.ToString(CultureInfo.InvariantCulture));
-                        link.SetAttribute(MimeTypeAttribute, comp.BinaryContent.MultimediaType.MimeType);
-
-                        // resolve metadata into additional data-attributes
-                        if (comp.Metadata != null)
-                        {
-                            ItemFields fields = new ItemFields(comp.Metadata, comp.MetadataSchema);
-                            ProcessFields(fields, link);
-                        }
-                    }
-                }
-            }
-            return Escape(xhtml.DocumentElement.InnerXml);
-        }
-
-        private void ProcessFields(ItemFields fields, XmlElement link)
-        {
-            if (fields != null)
-            {
-                foreach (string fieldname in _metaFieldNames)
-                {
-                    if (fields.Contains(fieldname))
-                    {
-                        link.SetAttribute("data-" + fieldname, fields.GetSingleFieldValue(fieldname));
-                    }
-                }
-
-                foreach (ItemField field in fields)
-                {
-                    if (field is EmbeddedSchemaField)
-                    {
-                        ProcessFields(((EmbeddedSchemaField)field).Value, link);
-                    }
-                }
-            }
-        }
-
-        private static string UnEscape(string input)
-        {
-            return input.Replace("<", "<").Replace(">", ">");
-        }
-
-        private static string Escape(string input)
-        {
-            // escape angle brackets and remove xhtml namespace
-            string xmlns = String.Format(" {0}=\"{1}\"", Constants.XhtmlPrefix, Constants.XhtmlNamespace);
-            return input.Replace("<", "<").Replace(">", ">").Replace(xmlns, String.Empty);
         }
     }
 }


updating doc comment on EnumUtil.Parse<T>()

--- Flamtap/Flamtap/Extensions/EnumUtil.cs
+++ Flamtap/Flamtap/Extensions/EnumUtil.cs
@@ -5,7 +5,7 @@
     public static class EnumUtil
     {
         /// <summary>
-        /// Parses a string value to it's equivalent enum value.
+        /// Parses a string value to it's equivalent enum value. Case insensitive.
         /// </summary>
         /// <typeparam name="T">The enum type.</typeparam>
         /// <returns> The enum value with specified name.</returns>


New contract orbit renderer

New contract orbit renderer

--- Source/Parameters/DMSpecificOrbitParameter.cs
+++ Source/Parameters/DMSpecificOrbitParameter.cs
@@ -72,17 +72,7 @@

 		private void setupOrbit()
 		{
-			orbitDriver = new OrbitDriver();
-			orbitDriver.orbit = new Orbit();
-			orbitDriver.orbit.referenceBody = body;
-			orbitDriver.orbit.inclination = inc;
-			orbitDriver.orbit.eccentricity = ecc;
-			orbitDriver.orbit.argumentOfPeriapsis = aop;
-			orbitDriver.orbit.semiMajorAxis = sma;
-			orbitDriver.orbit.LAN = lan;
-			orbitDriver.orbit.meanAnomalyAtEpoch = mae;
-			orbitDriver.orbit.epoch = epo;
-			orbitDriver.orbit.Init();
+			orbitRenderer = ContractOrbitRenderer.Setup(Root, new Orbit(inc, ecc, sma, lan, aop, mae, epo, body));

 			orbitLoaded = true;
 		}
@@ -104,11 +94,14 @@
 			if (!orbitLoaded)
 				return;

-			if (orbitDriver.orbit == null)
-			{
-				this.SetIncomplete();
+			if (orbitRenderer == null)
 				return;
-			}
+
+			if (orbitRenderer.driver == null)
+				return;
+
+			if (orbitRenderer.driver.orbit == null)
+				return;

 			if (root == null)
 			{
@@ -123,7 +116,7 @@
 				if (v == null)
 					continue;

-				if (VesselUtilities.VesselAtOrbit(orbitDriver.orbit, deviationWindow, v))
+				if (VesselUtilities.VesselAtOrbit(orbitRenderer.driver.orbit, deviationWindow, v))
 				{
 					this.SetComplete();
 					return;
@@ -183,7 +176,7 @@
 		{
 			try
 			{
-				double d = orbitDriver.orbit.inclination;
+				double d = orbitRenderer.driver.orbit.inclination;
 				orbitTested = true;
 				DMUtils.DebugLog("Orbit Checks Out...");
 				return true;


add AddWithoutDupplicateAsync

add AddWithoutDupplicateAsync

--- SignalGo.Shared/Models/ConcurrentBlockingCollection.cs
+++ SignalGo.Shared/Models/ConcurrentBlockingCollection.cs
@@ -36,6 +36,33 @@
                 if (_IsCanceled)
                     return;
                 await _addLock.WaitAsync();
+                _items.Add(item);
+                //Console.WriteLine("added" + item);
+                if (_taskCompletionSource.Task.Status == TaskStatus.WaitingForActivation)
+                {
+                    CompleteTask();
+                }
+                else
+                {
+                    //Console.WriteLine("wrong status 2 : " + _taskCompletionSource.Task.Status);
+                }
+            }
+            finally
+            {
+                _addLock.Release();
+            }
+        }
+#endif
+#if (!NET35 && !NET40)
+        public async Task AddWithoutDupplicateAsync(T item)
+        {
+            try
+            {
+                if (_IsCanceled)
+                    return;
+                await _addLock.WaitAsync();
+                if (_items.Contains(item))
+                    return;
                 _items.Add(item);
                 //Console.WriteLine("added" + item);
                 if (_taskCompletionSource.Task.Status == TaskStatus.WaitingForActivation)


Incremented build number

Incremented build number

--- Source/ScreenFrame/Properties/AssemblyInfo.cs
+++ Source/ScreenFrame/Properties/AssemblyInfo.cs
@@ -32,5 +32,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.3.6.0")]
-[assembly: AssemblyFileVersion("1.3.6.0")]
+[assembly: AssemblyVersion("1.3.8.0")]
+[assembly: AssemblyFileVersion("1.3.8.0")]


bug fixed

bug fixed

--- src/CatLib.Framework/Routing/Route.cs
+++ src/CatLib.Framework/Routing/Route.cs
@@ -390,7 +390,7 @@
         /// <param name="context">上下文</param>
         private void ControllerCall(Request request, Response response, object context)
         {
-            container.Call(context, action.Func, request, response);
+            container.Call(context, action.Func);
         }

         /// <summary>


Small refactoring of stripe

Small refactoring of stripe

--- Source/TeaCommerce.PaymentProviders/Stripe.cs
+++ Source/TeaCommerce.PaymentProviders/Stripe.cs
@@ -147,15 +147,13 @@
           // A web hook request so update existing order
           StripeCharge charge = Mapper<StripeCharge>.MapFromJson( stripeEvent.Data.Object.ToString() );

-          if (stripeEvent.Type.StartsWith("charge."))
-          {
-              var state = GetPaymentState(charge);
-              if (order.TransactionInformation.PaymentState != state)
-              {
-                  order.TransactionInformation.TransactionId = charge.Id;
-                  order.TransactionInformation.PaymentState = state;
-                  order.Save();
-              }
+          if ( stripeEvent.Type.StartsWith( "charge." ) ) {
+            PaymentState paymentState = GetPaymentState( charge );
+            if ( order.TransactionInformation.PaymentState != paymentState ) {
+              order.TransactionInformation.TransactionId = charge.Id;
+              order.TransactionInformation.PaymentState = paymentState;
+              order.Save();
+            }
           }
         }
       } catch ( Exception exp ) {


Selection improvement.

Selection improvement.

--- SmartNextOcurrence/SmartNextOcurrence/NextOcurrence.cs
+++ SmartNextOcurrence/SmartNextOcurrence/NextOcurrence.cs
@@ -18,6 +18,60 @@

 namespace SmartNextOcurrence
 {
+    public class Selection
+    {
+        private readonly IWpfTextView _view;
+        private readonly Tuple<ITrackingPoint, ITrackingPoint> _selection;
+        private int _start;
+        private int _end;
+        private int _lastPosition;
+
+        public int Start { get { return _start; } }
+
+        public int End { get { return _end; } }
+
+        public Selection(Tuple<ITrackingPoint, ITrackingPoint> selection, IWpfTextView view)
+        {
+            _selection = selection;
+            _view = view;
+            _start = _selection.Item1.GetPosition(_view.TextSnapshot);
+            _end = _selection.Item2.GetPosition(_view.TextSnapshot);
+            _lastPosition = _end;
+        }
+
+        public void Move(int position)
+        {
+            if (_lastPosition > position)
+            {
+                if (position > _start)
+                {
+                    _end = position;
+                }
+                else if (position < _start)
+                {
+                    _start = position;
+                }
+            }
+            else if (_lastPosition < position)
+            {
+                if (position > _start && _end > _lastPosition)
+                {
+                    _start = position;
+                }
+                else if (position > _start)
+                {
+                    _end = position;
+                }
+                else if (position < _start)
+                {
+                    _start = position;
+                }
+            }
+
+            _lastPosition = position;
+        }
+    }
+
     internal sealed class NextOcurrence
     {
         private readonly IOleCommandTarget _nextTarget; // Usado para propagar os eventos nos demais locais onde conter um cursor
@@ -25,6 +79,7 @@
         private readonly IWpfTextView _view;
         private List<ITrackingPoint> _trackPointList = new List<ITrackingPoint>();
         private List<Tuple<ITrackingPoint, ITrackingPoint>> _selectedTrackPointList = new List<Tuple<ITrackingPoint, ITrackingPoint>>();
+        private List<Selection> _selectionList = new List<Selection>();
         private int _lastIndex = 0;

         public bool Editing { get; set; } = false;
@@ -121,10 +176,21 @@
         {
             _layer.RemoveAllAdornments();

+            //// Draw the selections
+            //foreach (var item in _selectedTrackPointList)
+            //{
+            //    DrawSingleSelection(item);
+            //}
+
             // Draw the selections
-            foreach (var item in _selectedTrackPointList)
-            {
-                DrawSingleSelection(item);
+            foreach (var item in _selectionList)
+            {
+                DrawSingleSelection(
+                    new Tuple<ITrackingPoint, ITrackingPoint>
+                    (
+                        _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, item.Start), PointTrackingMode.Positive),
+                        _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, item.End), PointTrackingMode.Positive)
+                    ));
             }

             // Draw the cursors
@@ -241,6 +307,14 @@
                             )
                         );

+                        _selectionList.Add(new Selection(
+                            new Tuple<ITrackingPoint, ITrackingPoint>
+                            (
+                                _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, match.Index), PointTrackingMode.Positive),
+                                _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, match.Index + match.Length), PointTrackingMode.Positive)
+                            ),
+                            _view));
+
                         RedrawScreen();
                     }
                 }
@@ -263,23 +337,28 @@
             {
                 ITrackingPoint cursorPos = _trackPointList[i];

-                int start = (cursorPos.GetPosition(_view.TextSnapshot) == 0) ? 0 : (cursorPos.GetPosition(_view.TextSnapshot) - 1);
-                int end = cursorPos.GetPosition(_view.TextSnapshot);
+                int newCursorPosition = (_trackPointList[i].GetPosition(_view.TextSnapshot) == 0) ? 0 : (_trackPointList[i].GetPosition(_view.TextSnapshot) - 1);
+
+                _trackPointList[i] = _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, newCursorPosition), PointTrackingMode.Positive);

                 // Pega o item da seleção mas este item tem o mesmo índice do item de tracking point
                 Tuple<ITrackingPoint, ITrackingPoint> selectedItem = _selectedTrackPointList[i];
+
+                int start = cursorPos.GetPosition(_view.TextSnapshot) < selectedItem.Item1.GetPosition(_view.TextSnapshot) ? ((cursorPos.GetPosition(_view.TextSnapshot) == 0) ? 0 : (cursorPos.GetPosition(_view.TextSnapshot))) : selectedItem.Item1.GetPosition(_view.TextSnapshot);
+                int end = cursorPos.GetPosition(_view.TextSnapshot) > selectedItem.Item1.GetPosition(_view.TextSnapshot) ? cursorPos.GetPosition(_view.TextSnapshot) - 1 : cursorPos.GetPosition(_view.TextSnapshot) + 1;
+
+                //int start = (cursorPos.GetPosition(_view.TextSnapshot) == 0) ? 0 : (cursorPos.GetPosition(_view.TextSnapshot) - 1);
+                //int end = cursorPos.GetPosition(_view.TextSnapshot);

                 // Crio uma tupla mas atualizo apenas o início da seleção, o final da seleção permanece o mesmo
                 _selectedTrackPointList[i] =
                     new Tuple<ITrackingPoint, ITrackingPoint>
                     (
                         _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, start), PointTrackingMode.Positive),
-                        selectedItem.Item2
+                        _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, end), PointTrackingMode.Positive)
                     );

-                int newCursorPosition = (_trackPointList[i].GetPosition(_view.TextSnapshot) == 0) ? 0 : (_trackPointList[i].GetPosition(_view.TextSnapshot) - 1);
-
-                _trackPointList[i] = _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, newCursorPosition), PointTrackingMode.Positive);
+                _selectionList[i].Move(newCursorPosition);
             }

             Selecting = true;
@@ -319,6 +398,8 @@
                 int newCursorPosition = ((cursorPos.GetPosition(_view.TextSnapshot) + 1) > textLength) ? textLength : (cursorPos.GetPosition(_view.TextSnapshot) + 1);

                 _trackPointList[i] = _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, newCursorPosition), PointTrackingMode.Positive);
+
+                _selectionList[i].Move(newCursorPosition);
             }

             Selecting = true;
@@ -373,6 +454,8 @@
                         _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, startPosition), PointTrackingMode.Positive),
                         _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, endPosition), PointTrackingMode.Positive)
                     );
+
+                _selectionList[i].Move(newCursorPosition);
             }

             Selecting = true;
@@ -428,6 +511,8 @@
                         _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, startPosition), PointTrackingMode.Positive),
                         _view.TextSnapshot.CreateTrackingPoint(new SnapshotPoint(_view.TextSnapshot, endPosition), PointTrackingMode.Positive)
                     );
+
+                _selectionList[i].Move(newCursorPosition);
             }

             Selecting = true;
@@ -573,6 +658,7 @@
         {
             Selecting = false;
             _selectedTrackPointList.Clear();
+            _selectionList.Clear();
             _view.Caret.IsHidden = false;
             _view.Selection.IsActive = true;
             //_layer.RemoveMatchingAdornments();


refs #166

refs #166

Parameter name was niet juist, en er was 1 missing.

git-svn-id: 0ffdc289f568b1e7493e560395a00d06174c8a92@753 99b415e2-69d1-4072-8d93-0ed3a15484ab

--- Solution/Chiro.Gap.ServiceContracts/IGroepenService.cs
+++ Solution/Chiro.Gap.ServiceContracts/IGroepenService.cs
@@ -140,8 +140,9 @@
         /// <summary>
         /// Voegt een categorie toe aan de groep
         /// </summary>
-        /// <param name="cnaam">De naam van de nieuwe categorie</param>
         /// <param name="groepID">De groep waaraan het wordt toegevoegd</param>
+        /// <param name="naam">De naam van de nieuwe categorie</param>
+        /// <param name="code">code voor de nieuwe categorie</param>
         /// <returns>De ID van de aangemaakte categorie</returns>
         [OperationContract]
         int CategorieToevoegen(int groepID, String naam, String code);


update assembly version

update assembly version

--- src/Compat/Properties/AssemblyInfo.cs
+++ src/Compat/Properties/AssemblyInfo.cs
@@ -29,8 +29,8 @@
 //      Build Number
 //      Revision
 //
-// You can specify all the values or you can default the Build and Revision Numbers
+// You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("0.1.*")]
+[assembly: AssemblyFileVersion("0.1.0.0")]


Fixes #593.  Toepassing start weer als je GAV bent van precies 1 groep.

git-svn-id: 0ffdc289f568b1e7493e560395a00d06174c8a92@1260 99b415e2-69d1-4072-8d93-0ed3a15484ab

--- Solution/Chiro.Gap.WebApp/Controllers/GavController.cs
+++ Solution/Chiro.Gap.WebApp/Controllers/GavController.cs
@@ -9,6 +9,7 @@
 using System.Web.Mvc;

 using Chiro.Cdf.ServiceHelper;
+using Chiro.Gap.Domain;
 using Chiro.Gap.ServiceContracts;
 using Chiro.Gap.ServiceContracts.DataContracts;

@@ -33,7 +34,7 @@
 			if (groepInfos.Count() == 1)
 			{
 				// Redirect naar personenlijst van gevraagde groep;
-				r = RedirectToAction("List", new { Controller = "Personen", groepID = groepInfos.First().ID, page = 1 });
+				r = RedirectToAction("Index", new { Controller = "Personen", groepID = groepInfos.First().ID});
 			}
 			else
 			{


Fixed a bug in VBArrayDescriptor.GenerateBinaryImage() method caused due to incorrect use of startIndex parameter being passed in.

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

--- Source/Libraries/GSF.Core/Interop/VBArrayDescriptor.cs
+++ Source/Libraries/GSF.Core/Interop/VBArrayDescriptor.cs
@@ -133,8 +133,8 @@

             for (int i = 0; i < m_arrayDimensionDescriptors.Count; i++)
             {
-                Buffer.BlockCopy(BitConverter.GetBytes(m_arrayDimensionDescriptors[i].Length), 0, buffer, (i * DimensionDescriptor.BinaryLength) + 2, 4);
-                Buffer.BlockCopy(BitConverter.GetBytes(m_arrayDimensionDescriptors[i].LowerBound), 0, buffer, (i * DimensionDescriptor.BinaryLength) + 6, 4);
+                Buffer.BlockCopy(BitConverter.GetBytes(m_arrayDimensionDescriptors[i].Length), 0, buffer, startIndex + (i * DimensionDescriptor.BinaryLength) + 2, 4);
+                Buffer.BlockCopy(BitConverter.GetBytes(m_arrayDimensionDescriptors[i].LowerBound), 0, buffer, startIndex + (i * DimensionDescriptor.BinaryLength) + 6, 4);
             }

             return length;


GSF.InstallerActions: Updated CompanyInfoAction to better handle possible null exceptions.

--- Source/Libraries/GSF.InstallerActions/CustomActions.cs
+++ Source/Libraries/GSF.InstallerActions/CustomActions.cs
@@ -278,6 +278,10 @@
         [CustomAction]
         public static ActionResult CompanyInfoAction(Session session)
         {
+            const string DefaultCompanyName = "Grid Protection Alliance";
+            const string DefaultCompanyAcronym = "GPA";
+            const string DefaultSystemName = " ";
+
             Logger logger = new Logger(session);

             logger.Log("Begin CompanyInfoAction");
@@ -311,22 +315,22 @@
                 {
                     // Search for existing CompanyName settings and update their values
                     foreach (XElement companyNameElement in systemSettings.Elements("add").Where(element => element.Attributes("name").Any(nameAttribute => string.Compare(nameAttribute.Value, "CompanyName", StringComparison.OrdinalIgnoreCase) == 0)))
-                        companyNameElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "COMPANYNAME"));
+                        companyNameElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "COMPANYNAME") ?? DefaultCompanyName);

                     // Search for existing CompanyAcronym settings and update their values
                     foreach (XElement companyAcronymElement in systemSettings.Elements("add").Where(element => element.Attributes("name").Any(nameAttribute => string.Compare(nameAttribute.Value, "CompanyAcronym", StringComparison.OrdinalIgnoreCase) == 0)))
-                        companyAcronymElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "COMPANYACRONYM"));
+                        companyAcronymElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "COMPANYACRONYM") ?? DefaultCompanyAcronym);

                     // Search for existing SystemName settings and update their values
                     foreach (XElement systemNameElement in systemSettings.Elements("add").Where(element => element.Attributes("name").Any(nameAttribute => string.Compare(nameAttribute.Value, "SystemName", StringComparison.OrdinalIgnoreCase) == 0)))
-                        systemNameElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "SYSTEMNAME"));
+                        systemNameElement.Attributes("value").ToList().ForEach(valueAttribute => valueAttribute.Value = GetPropertyValue(session, "SYSTEMNAME") ?? DefaultSystemName);

                     // Add CompanyName setting if no such setting exists
                     if (!systemSettings.Elements("add").Any(element => element.Attributes("name").Any(nameAttribute => string.Compare(nameAttribute.Value, "CompanyName", StringComparison.OrdinalIgnoreCase) == 0)))
                     {
                         systemSettings.Add(new XElement("add",
                             new XAttribute("name", "CompanyName"),
-                            new XAttribute("value", GetPropertyValue(session, "COMPANYNAME")),
+                            new XAttribute("value", GetPropertyValue(session, "COMPANYNAME") ?? DefaultCompanyName),
                             new XAttribute("description", $"The name of the company who owns this instance of the {serviceName}."),
                             new XAttribute("encrypted", "false")
                         ));
@@ -337,7 +341,7 @@
                     {
                         systemSettings.Add(new XElement("add",
                             new XAttribute("name", "CompanyAcronym"),
-                            new XAttribute("value", GetPropertyValue(session, "COMPANYACRONYM")),
+                            new XAttribute("value", GetPropertyValue(session, "COMPANYACRONYM") ?? DefaultCompanyAcronym),
                             new XAttribute("description", $"The acronym representing the company who owns this instance of the {serviceName}."),
                             new XAttribute("encrypted", "false")
                         ));
@@ -348,7 +352,7 @@
                     {
                         systemSettings.Add(new XElement("add",
                             new XAttribute("name", "SystemName"),
-                            new XAttribute("value", GetPropertyValue(session, "SYSTEMNAME")),
+                            new XAttribute("value", GetPropertyValue(session, "SYSTEMNAME") ?? DefaultSystemName),
                             new XAttribute("description", $"Name of system for this instance of the {serviceName} that will be prefixed to system level tags, when defined. Value should follow tag naming conventions, e.g., no spaces and all upper case."),
                             new XAttribute("encrypted", "false")
                         ));


EditableTextBox: IsEditing fix

EditableTextBox: IsEditing fix

--- Source/PropertyTools.Wpf/Controls/EditableTextBlock.cs
+++ Source/PropertyTools.Wpf/Controls/EditableTextBlock.cs
@@ -139,8 +139,9 @@
             {
                 be.UpdateSource();
             }
-
+            this.internalIsEditingChange = true;
             this.IsEditing = false;
+            this.internalIsEditingChange = false;
             var p = this.Parent as Panel;
             p.Children.Remove(this.textBox);
             this.textBox = null;
@@ -151,11 +152,18 @@
             }
         }

+        private bool internalIsEditingChange;
+
         /// <summary>
         /// Handles changes in IsEditing.
         /// </summary>
         private void IsEditingChanged()
         {
+            if (this.internalIsEditingChange)
+            {
+                return;
+            }
+
             if (this.IsEditing)
             {
                 this.BeginEdit();


Adds unit test Get_SlinqyQueueDoesNotExistInCollection_IsReturned and refactors how its parent class handles instantiating the client.

--- Source/Slinqy.Core.Test.Unit/SlinqyQueueClientTests.cs
+++ Source/Slinqy.Core.Test.Unit/SlinqyQueueClientTests.cs
@@ -10,7 +10,17 @@
     /// </summary>
     public class SlinqyQueueClientTests
     {
+        private readonly SlinqyQueueClient client;
         private readonly IPhysicalQueueService fakePhysicalQueueService = A.Fake<IPhysicalQueueService>();
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="SlinqyQueueClientTests"/> class.
+        /// </summary>
+        public
+        SlinqyQueueClientTests()
+        {
+            this.client = new SlinqyQueueClient(this.fakePhysicalQueueService);
+        }

         /// <summary>
         /// Verifies the constructor checks for null values.
@@ -34,10 +44,10 @@
         CreateAsync_QueueNameValid_CreateDelegateInvoked()
         {
             // Arrange
-            var client = new SlinqyQueueClient(this.fakePhysicalQueueService);
+            const string queueName = "test";

             // Act
-            await client.CreateAsync("test");
+            await this.client.CreateAsync(queueName);

             // Assert
             A.CallTo(() =>
@@ -57,13 +67,29 @@
             // Arrange
             string queueName = null;

-            var client = new SlinqyQueueClient(
-                this.fakePhysicalQueueService
-            );
+            // Act
+            Func<Task<SlinqyQueue>> action = async () => await this.client.CreateAsync(queueName);
+
+            // Assert
+            await Assert.ThrowsAsync<ArgumentNullException>(action);
+        }
+
+        /// <summary>
+        /// Verifies that a SlinqyQueue instance is added and returned when one doesn't already exist.
+        /// </summary>
+        [Fact]
+        public
+        void
+        Get_SlinqyQueueDoesNotExistInCollection_IsReturned()
+        {
+            // Arrange
+            const string queueName = "test";

             // Act
+            var actualQueueName = this.client.Get(queueName).Name;
+
             // Assert
-            await Assert.ThrowsAsync<ArgumentNullException>(async () => await client.CreateAsync(queueName));
+            Assert.Equal(queueName, actualQueueName);
         }
     }
-}
+}


[Toolkit.Graphics] Fix issue #286. SpriteBatch was not working with multiple instance.

--- Source/Toolkit/SharpDX.Toolkit.Graphics/SpriteBatch.cs
+++ Source/Toolkit/SharpDX.Toolkit.Graphics/SpriteBatch.cs
@@ -107,7 +107,7 @@
         private readonly EffectPass spriteEffectPass;
         private readonly Direct3D11.Texture2D tempTexture2D = new Direct3D11.Texture2D(IntPtr.Zero);
         private readonly TextureComparer textureComparer = new TextureComparer();
-        private readonly Buffer<VertexPositionColorTexture> vertexBuffer;
+        private readonly ResourceContext resourceContext;
         private readonly VertexInputLayout vertexInputLayout;
         private BlendState blendState;

@@ -128,7 +128,6 @@
         private Texture2D[] spriteTextures;

         private Matrix transformMatrix;
-        private int vertexBufferPosition;

         private static readonly short[] indices;

@@ -166,8 +165,7 @@
             effectSampler = spriteEffect.Parameters["TextureSampler"];

             // Creates the vertex buffer (shared by within a device context).
-            vertexBuffer = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerContext, "SpriteBatch.VertexBuffer", () => Buffer.Vertex.New<VertexPositionColorTexture>(GraphicsDevice, MaxVertexCount, ResourceUsage.Dynamic));
-            vertexBufferPosition = 0;
+            resourceContext = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerContext, "SpriteBatch.VertexBuffer", () => new ResourceContext(GraphicsDevice));

             // Creates the vertex input layout (we don't need to cache them as they are already cached).
             vertexInputLayout = VertexInputLayout.New(VertexBufferLayout.New<VertexPositionColorTexture>(0));
@@ -729,7 +727,7 @@

         private void DrawBatchPerTexture(Texture2D texture, SpriteInfo[] sprites, int offset, int count)
         {
-            var nativeShaderResourceViewPointer = ((ShaderResourceView) texture).NativePointer;
+            var nativeShaderResourceViewPointer = ((ShaderResourceView)texture).NativePointer;

             if (customEffect != null)
             {
@@ -772,19 +770,16 @@
             float deltaY = 1f/(texture.Height);
             while (count > 0)
             {
-                var noOverwrite = SetDataOptions.NoOverwrite;
-
                 // How many sprites do we want to draw?
                 int batchSize = count;

                 // How many sprites does the D3D vertex buffer have room for?
-                int remainingSpace = MaxBatchSize - vertexBufferPosition;
+                int remainingSpace = MaxBatchSize - resourceContext.VertexBufferPosition;
                 if (batchSize > remainingSpace)
                 {
                     if (remainingSpace < MinBatchSize)
                     {
-                        vertexBufferPosition = 0;
-                        noOverwrite = SetDataOptions.Discard;
+                        resourceContext.VertexBufferPosition = 0;
                         batchSize = (count < MaxBatchSize) ? count : MaxBatchSize;
                     }
                     else
@@ -794,8 +789,11 @@
                 }

                 // Sets the data directly to the buffer in memory
-                int offsetInBytes = vertexBufferPosition* VerticesPerSprite * Utilities.SizeOf<VertexPositionColorTexture>();
-                vertexBuffer.SetDynamicData(GraphicsDevice, ptr =>
+                int offsetInBytes = resourceContext.VertexBufferPosition * VerticesPerSprite * Utilities.SizeOf<VertexPositionColorTexture>();
+
+                var noOverwrite = resourceContext.VertexBufferPosition == 0 ? SetDataOptions.Discard : SetDataOptions.NoOverwrite;
+
+                resourceContext.VertexBuffer.SetDynamicData(GraphicsDevice, ptr =>
                                                                 {
                                                                     var texturePtr = (VertexPositionColorTexture*) ptr;
                                                                     for (int i = 0; i < batchSize; i++)
@@ -803,12 +801,12 @@
                                                                 }, offsetInBytes, noOverwrite);

                 // Draw from the specified index
-                int startIndex = vertexBufferPosition * IndicesPerSprite;
+                int startIndex = resourceContext.VertexBufferPosition * IndicesPerSprite;
                 int indexCount = batchSize * IndicesPerSprite;
                 GraphicsDevice.DrawIndexed(PrimitiveType.TriangleList, indexCount, startIndex);

                 // Update position, offset and remaining count
-                vertexBufferPosition += batchSize;
+                resourceContext.VertexBufferPosition += batchSize;
                 offset += batchSize;
                 count -= batchSize;
             }
@@ -884,10 +882,16 @@
             GraphicsDevice.SetVertexInputLayout(vertexInputLayout);

             // VertexBuffer
-            GraphicsDevice.SetVertexBuffer(vertexBuffer);
+            GraphicsDevice.SetVertexBuffer(resourceContext.VertexBuffer);

             // Index buffer
             GraphicsDevice.SetIndexBuffer(indexBuffer, false);
+
+            // If this is a deferred D3D context, reset position so the first Map call will use D3D11_MAP_WRITE_DISCARD.
+            if (GraphicsDevice.IsDeferred)
+            {
+                resourceContext.VertexBufferPosition = 0;
+            }
         }

         #region Nested type: BackToFrontComparer
@@ -959,5 +963,21 @@
         }

         #endregion
+
+
+        /// <summary>
+        /// Use a ResourceContext per GraphicsDevice (DeviceContext)
+        /// </summary>
+        private class ResourceContext : Component
+        {
+            public readonly Buffer<VertexPositionColorTexture> VertexBuffer;
+
+            public int VertexBufferPosition;
+
+            public ResourceContext(GraphicsDevice device)
+            {
+                VertexBuffer = ToDispose(Buffer.Vertex.New<VertexPositionColorTexture>(device, MaxVertexCount, ResourceUsage.Dynamic));
+            }
+        }
     }
 }


[Toolkit.Graphics] Fix issue #362. One method of SpriteBatch.Draw was not using SpriteEffects parameter (flip horizontal/vertical)

--- Source/Toolkit/SharpDX.Toolkit.Graphics/SpriteBatch.cs
+++ Source/Toolkit/SharpDX.Toolkit.Graphics/SpriteBatch.cs
@@ -314,7 +314,7 @@
         public void Draw(ShaderResourceView texture, DrawingRectangle destinationRectangle, DrawingRectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth)
         {
             var destination = new DrawingRectangleF(destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height);
-            DrawSprite(texture, ref destination, false, ref sourceRectangle, color, rotation, ref vector2Zero, SpriteEffects.None, layerDepth);
+            DrawSprite(texture, ref destination, false, ref sourceRectangle, color, rotation, ref origin, effects, layerDepth);
         }

         /// <summary>


[add]サブライム数判定メソッドの追加

[add]サブライム数判定メソッドの追加

--- Src/LoveWholeNumber/LoveWholeNumber/Class1.cs
+++ Src/LoveWholeNumber/LoveWholeNumber/Class1.cs
@@ -498,6 +498,25 @@
         }

         /// <summary>
+        /// サブライム数判定
+        /// </summary>
+        /// <param name="n">判定したい自然数</param>
+        /// <returns>サブライム数ならtrue でないならfalse</returns>
+        public static bool IsSublimeNumber(int n)
+        {
+            if (n < 1)
+                return false;
+
+            int count = DivisorFunction(n, 0);
+            int sum = DivisorFunction(n, 1);
+
+            if (IsPerfectNumber(count) && IsPerfectNumber(sum) && count != sum)
+                return true;
+
+            return false;
+        }
+
+        /// <summary>
         /// 最大公約数の取得
         /// </summary>
         /// <param name="m">整数m</param>


Refactoring and cleanup of new Assembly dir helper

--- Src/Simple.Data.Mysql/MysqlConnectorHelper.cs
+++ Src/Simple.Data.Mysql/MysqlConnectorHelper.cs
@@ -20,6 +20,12 @@
             }
         }

+        private static string GetAssemblyDirectory()
+        {
+            var codeBaseUri = new UriBuilder(Assembly.GetAssembly(typeof(MysqlConnectorHelper)).CodeBase);
+            return Path.GetDirectoryName(Uri.UnescapeDataString(codeBaseUri.Path));
+        }
+
         public static IDbConnection CreateConnection(string connectionString)
         {
             var connection = DbFactory.CreateConnection();
@@ -35,27 +41,15 @@
             adapter.SelectCommand = command;
             return adapter;
         }
-
-
+
         private static DbProviderFactory GetDbFactory()
         {
-			if (string.IsNullOrEmpty(AssemblyDirectory)) throw new ArgumentException("Unrecognised assemblyFile.");
-
-			var mysqlAssembly = Assembly.LoadFrom(Path.Combine(AssemblyDirectory, "MySql.Data.dll"));
+            var mysqlAssembly = Assembly.LoadFrom(Path.Combine(GetAssemblyDirectory(), "MySql.Data.dll"));

             var mysqlDbFactoryType = mysqlAssembly.GetType("MySql.Data.MySqlClient.MySqlClientFactory");
             return (DbProviderFactory)Activator.CreateInstance(mysqlDbFactoryType);
         }

-		private static string AssemblyDirectory
-		{
-			get
-			{
-				string codeBase = Assembly.GetAssembly(typeof(MysqlConnectorHelper)).CodeBase;
-				UriBuilder uri = new UriBuilder(codeBase);
-				string path = Uri.UnescapeDataString(uri.Path);
-				return Path.GetDirectoryName(path);
-			}
-		}
+
     }
 }


[storekit] fix bug #12726 by adding a null check

but i think the underlying problem is app store setup or provisioning
profiles

--- StoreKit/NonConsumables/NonConsumableViewController.cs
+++ StoreKit/NonConsumables/NonConsumableViewController.cs
@@ -122,39 +122,47 @@
 				var NSgreyscaleProductId = new NSString(greyscaleProductId);
 				var NSsepiaProductId = new NSString(sepiaProductId);

-				// we only update the button with a price if the user hasn't already purchased it
-				if (!greyscalePurchased && info.ContainsKey(NSgreyscaleProductId)) {
-					pricesLoaded = true;
-
-					var product = (SKProduct) info.ObjectForKey(NSgreyscaleProductId);
-
-					Console.WriteLine("Product id: " + product.ProductIdentifier);
-					Console.WriteLine("Product title: " + product.LocalizedTitle);
-					Console.WriteLine("Product description: " + product.LocalizedDescription);
-					Console.WriteLine("Product price: " + product.Price);
-					Console.WriteLine("Product l10n price: " + product.LocalizedPrice());
-
-					greyscaleButton.Enabled = true;
-					greyscaleTitle.Text = product.LocalizedTitle;
-					greyscaleDescription.Text = product.LocalizedDescription;
-					greyscaleButton.SetTitle("Buy " + product.LocalizedPrice(), UIControlState.Normal);
-				}
-				// we only update the button with a price if the user hasn't already purchased it
-				if (!sepiaPurchased && info.ContainsKey(NSsepiaProductId)) {
-					pricesLoaded = true;
-
-					var product = (SKProduct) info.ObjectForKey(NSsepiaProductId);
-
-					Console.WriteLine("Product id: " + product.ProductIdentifier);
-					Console.WriteLine("Product title: " + product.LocalizedTitle);
-					Console.WriteLine("Product description: " + product.LocalizedDescription);
-					Console.WriteLine("Product price: " + product.Price);
-					Console.WriteLine("Product l10n price: " + product.LocalizedPrice());
-
-					sepiaButton.Enabled = true;
-					sepiaTitle.Text = product.LocalizedTitle;
-					sepiaDescription.Text = product.LocalizedDescription;
-					sepiaButton.SetTitle("Buy " + product.LocalizedPrice(), UIControlState.Normal);
+				if (info == null) {
+					// if info is null, probably NO valid prices returned, therefore it doesn't exist at all
+					greyscaleDescription.Text = "check iTunes connect setup";
+					sepiaDescription.Text = "check iTunes connect setup";
+					greyscaleButton.SetTitle("invalid product id", UIControlState.Disabled);
+					sepiaButton.SetTitle("invalid product id", UIControlState.Disabled);
+				} else {
+					// we only update the button with a price if the user hasn't already purchased it
+					if (!greyscalePurchased && info.ContainsKey(NSgreyscaleProductId)) {
+						pricesLoaded = true;
+
+						var product = (SKProduct) info.ObjectForKey(NSgreyscaleProductId);
+
+						Console.WriteLine("Product id: " + product.ProductIdentifier);
+						Console.WriteLine("Product title: " + product.LocalizedTitle);
+						Console.WriteLine("Product description: " + product.LocalizedDescription);
+						Console.WriteLine("Product price: " + product.Price);
+						Console.WriteLine("Product l10n price: " + product.LocalizedPrice());
+
+						greyscaleButton.Enabled = true;
+						greyscaleTitle.Text = product.LocalizedTitle;
+						greyscaleDescription.Text = product.LocalizedDescription;
+						greyscaleButton.SetTitle("Buy " + product.LocalizedPrice(), UIControlState.Normal);
+					}
+					// we only update the button with a price if the user hasn't already purchased it
+					if (!sepiaPurchased && info.ContainsKey(NSsepiaProductId)) {
+						pricesLoaded = true;
+
+						var product = (SKProduct) info.ObjectForKey(NSsepiaProductId);
+
+						Console.WriteLine("Product id: " + product.ProductIdentifier);
+						Console.WriteLine("Product title: " + product.LocalizedTitle);
+						Console.WriteLine("Product description: " + product.LocalizedDescription);
+						Console.WriteLine("Product price: " + product.Price);
+						Console.WriteLine("Product l10n price: " + product.LocalizedPrice());
+
+						sepiaButton.Enabled = true;
+						sepiaTitle.Text = product.LocalizedTitle;
+						sepiaDescription.Text = product.LocalizedDescription;
+						sepiaButton.SetTitle("Buy " + product.LocalizedPrice(), UIControlState.Normal);
+					}
 				}
 			});


a few more helpers

a few more helpers

--- StackExchange.Profiling/ClientTimingHelper.cs
+++ StackExchange.Profiling/ClientTimingHelper.cs
@@ -42,12 +42,28 @@
         }

         /// <summary>
-        /// To be used inline in razor pages
+        /// To be used inline in razor pages - times a script be sure to call InitClientTimings first
         /// </summary>
-        public static IHtmlString TimeScript(this WebPageBase page, string name, Func<object, HelperResult> stuff)
+        public static IHtmlString TimeScript(this WebPageBase page, string name, Func<object, HelperResult> html)
         {
-            var result = stuff(null).ToHtmlString();
+            var result = html(null).ToHtmlString();
             return new HtmlString(TimeScript(name, result));
+        }
+
+        /// <summary>
+        /// To be used inline in razor pages - times a script be sure to call InitClientTimings first
+        /// </summary>
+        public static IHtmlString TimeScript(this WebPageBase page, string name, IHtmlString html)
+        {
+            return new HtmlString(TimeScript(name, html.ToHtmlString()));
+        }
+
+        /// <summary>
+        /// To be used inline in razor pages - times a script be sure to call InitClientTimings first
+        /// </summary>
+        public static IHtmlString TimeScript(this WebPageBase page, string name, string html)
+        {
+            return new HtmlString(TimeScript(name, html));
         }
     }
 }


Add support for creating unparented nodes in the graph.

--- StructuredXmlEditor/View/CustomControls/Graph/Graph.cs
+++ StructuredXmlEditor/View/CustomControls/Graph/Graph.cs
@@ -1,4 +1,5 @@
 using StructuredXmlEditor.Data;
+using StructuredXmlEditor.Definition;
 using System;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
@@ -357,6 +358,67 @@
 		}

 		//--------------------------------------------------------------------------
+		protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
+		{
+			var pos = e.GetPosition(this);
+
+			ContextMenu menu = new ContextMenu();
+
+			var create = menu.AddItem("Create");
+			var validTypes = new HashSet<GraphNodeDefinition>();
+			foreach (var node in Nodes)
+			{
+				foreach (var data in node.Datas)
+				{
+					if (data is GraphNodeDataLink)
+					{
+						var link = data as GraphNodeDataLink;
+						var def = link.GraphReferenceItem.Definition as GraphReferenceDefinition;
+						foreach (var d in def.Definitions.Values)
+						{
+							validTypes.Add(d);
+						}
+					}
+				}
+			}
+
+			foreach (var def in validTypes.OrderBy(d => d.Name))
+			{
+				create.AddItem(def.Name, () =>
+				{
+					var grid = Nodes.First().GraphNodeItem.Grid;
+					var undo = grid.RootItems[0].UndoRedo;
+
+					GraphNodeItem item = null;
+
+					using (undo.DisableUndoScope())
+					{
+						item = def.CreateData(undo) as GraphNodeItem;
+
+						item.Grid = Nodes.First().GraphNodeItem.Grid;
+						item.X = pos.X;
+						item.Y = pos.Y;
+					}
+
+					undo.ApplyDoUndo(
+						delegate
+						{
+							grid.GraphNodeItems.Add(item);
+						},
+						delegate
+						{
+							grid.GraphNodeItems.Remove(item);
+						},
+						"Create " + item.Name);
+				});
+			}
+
+			menu.IsOpen = true;
+
+			base.OnMouseRightButtonDown(e);
+		}
+
+		//--------------------------------------------------------------------------
 		private Rect GetRectOfObject(GraphNode node)
 		{
 			Rect rectangleBounds = new Rect();


Hooks now support regular expressions

Hooks now support regular expressions

--- System.Net.EmbeddedHttp/EmbeddedHttpServer.cs
+++ System.Net.EmbeddedHttp/EmbeddedHttpServer.cs
@@ -6,6 +6,7 @@
 using System.Text.RegularExpressions;
 using System.Threading;
 using System.Web;
+using System.Text.RegularExpressions;

 namespace System.Net.EmbeddedHttp
 {
@@ -204,6 +205,21 @@
         }

         /// <summary>
+        /// Hook matcher function
+        /// </summary>
+        /// <param name="hooks">Hooks to text. Can contain regular expressions</param>
+        /// <param name="text">text to match</param>
+        /// <returns>ture if text matches to any of the hooks, false if text doesn't mach any hooks</returns>
+        private bool MathesHook(string[] hooks, string text)
+        {
+            foreach (var i in hooks)
+            {
+                if (Regex.IsMatch(text, i)) return true;
+            }
+            return false;
+        }
+
+        /// <summary>
         /// Starts the server
         /// </summary>
         public void Start()
@@ -215,6 +231,7 @@
             ProcessAppPackages();
             _listener.Start();
             _log.Info("Server started.", "Prefix", _listener.Prefixes.First());
+            //threaded serve function
             ThreadPool.QueueUserWorkItem((o) =>
             {
                 try
@@ -228,7 +245,9 @@
                             {
                                 var file = GetFileName(ctx.Request.RawUrl);
                                 if (string.IsNullOrEmpty(file)) file = "index.html";
-                                var handler = (from i in _handlers where i.Hooks.Contains(file) select i).FirstOrDefault();
+
+
+                                var handler = (from i in _handlers where MathesHook(i.Hooks, file) select i).FirstOrDefault();

                                 if (handler != null)
                                 {
@@ -273,7 +292,7 @@
                             catch (Exception ex)
                             {
                                 _log.Error("Error handling request", ctx.Request.RawUrl, ex.Message);
-                                HandleError(ctx, 501, ex);
+                                HandleError(ctx, 500, ex);
                             }
                             finally
                             {


Added a convention for naming view models to the service.

--- System.Windows.Documents.Reporting/ReportingService.cs
+++ System.Windows.Documents.Reporting/ReportingService.cs
@@ -53,9 +53,18 @@
         private IReadOnlyIocContainer iocContainer;

         /// <summary>
-        /// Contains all cached types of the assembly of a view that has been created.
+        /// Contains all cached types of the assembly. The types are used when activating a view model convention-based.
         /// </summary>
         private Type[] assemblyTypes = null;
+
+        #endregion
+
+        #region Public Properties
+
+        /// <summary>
+        /// Gets or sets the naming convention for view models. The function gets the name of the document type and returns the name of the corresponding view model. This function is used for convention-based view model activation. The default implementation adds "ViewModel" to the name of the document.
+        /// </summary>
+        public Func<string, string> ViewModelNamingConvention { get; set; } = documentName => string.Concat(documentName, "ViewModel");

         #endregion

@@ -334,7 +343,7 @@
             {
                 try
                 {
-                    // Creates the view model via dependency injection
+                    // Lets the IOC container instantiate the view model, so that all dependencies can be injected
                     viewModel = this.iocContainer.GetInstance(viewModelType).Inject(parameters);
                 }
                 catch (Exception e)
@@ -347,7 +356,7 @@
             T document;
             try
             {
-                // Lets the kernel instantiate the document, so that all dependencies can be injected
+                // Lets the IOC container instantiate the document, so that all dependencies can be injected
                 document = this.iocContainer.GetInstance<T>();
             }
             catch (Exception e)
@@ -401,14 +410,5 @@
         }

         #endregion
-
-        #region Public Properties
-
-        /// <summary>
-        /// Gets or sets the naming convention for view models. The function gets the name of the document type and returns the name of the corresponding view model. This function is used for convention-based view model activation. The default implementation adds "ViewModel" to the name of the document.
-        /// </summary>
-        public Func<string, string> ViewModelNamingConvention { get; set; } = documentName => string.Concat(documentName, "ViewModel");
-
-        #endregion
     }
 }