Consider UndoBuffer state on load

Consider UndoBuffer state on load

- Issue MatterHackers/MCCentral#4023
Undo history is lost on ReloadAll

--- PartPreviewWindow/ViewControls3D.cs
+++ PartPreviewWindow/ViewControls3D.cs
@@ -210,6 +210,9 @@
 				redoButton.Enabled = undoBuffer.RedoCount > 0;
 			};

+			undoButton.Enabled = undoBuffer.UndoCount > 0;
+			redoButton.Enabled = undoBuffer.RedoCount > 0;
+
 			var buttonGroupA = new ObservableCollection<GuiWidget>();

 			if (UserSettings.Instance.IsTouchScreen)


Restore key up/down functionality for layer view, use new pattern

--- PartPreviewWindow/ViewGcodeBasic.cs
+++ PartPreviewWindow/ViewGcodeBasic.cs
@@ -29,6 +29,7 @@

 using System;
 using System.IO;
+using System.Linq;
 using MatterHackers.Agg;
 using MatterHackers.Agg.UI;
 using MatterHackers.GCodeVisualizer;
@@ -94,6 +95,8 @@

 		private BedConfig bedPlate;

+		private SystemWindow parentSystemWindow;
+
 		public ViewGcodeBasic(Vector3 viewerVolume, Vector2 bedCenter, BedShape bedShape, WindowMode windowMode, ViewControls3D viewControls3D, ThemeConfig theme, MeshViewerWidget externalMeshViewer)
 		{
 			this.externalMeshViewer = externalMeshViewer;
@@ -138,9 +141,38 @@
 			ApplicationController.Instance.AdvancedControlsPanelReloading.RegisterEvent((s, e) => printer.BedPlate.GCodeRenderer?.Clear3DGCode(), ref unregisterEvents);
 		}

+		public override void OnLoad(EventArgs args)
+		{
+			// Find and hook the parent system window KeyDown event
+			if (this.Parents<SystemWindow>().FirstOrDefault() is SystemWindow systemWindow)
+			{
+				systemWindow.KeyDown += Parent_KeyDown;
+				parentSystemWindow = systemWindow;
+			}
+
+			base.OnLoad(args);
+		}
+
+		private void Parent_KeyDown(object sender, KeyEventArgs keyEvent)
+		{
+			if (this.Visible)
+			{
+				switch(keyEvent.KeyCode)
+				{
+					case Keys.Up:
+						bedPlate.ActiveLayerIndex += 1;
+						break;
+					case Keys.Down:
+						bedPlate.ActiveLayerIndex -= 1;
+						break;
+				}
+			}
+		}
+
 		private void ActiveLayer_Changed(object sender, EventArgs e)
 		{
-			if (bedPlate.ActiveLayerIndex != (int)(selectLayerSlider.Value + .5))
+			if (selectLayerSlider != null
+				&& bedPlate.ActiveLayerIndex != (int)(selectLayerSlider.Value + .5))
 			{
 				selectLayerSlider.Value = bedPlate.ActiveLayerIndex;
 			}
@@ -421,10 +453,9 @@
 			popupContainer.AddChild(showRetractions);

-			// put in a show speed checkbox
+			// Speeds checkbox
 			var showSpeeds = new CheckBox("Speeds".Localize(), textColor: textColor);
 			showSpeeds.Checked = options.RenderSpeeds;
-			//showSpeeds.Checked = gradient.Visible;
 			showSpeeds.CheckedStateChanged += (sender, e) =>
 			{
 				gradientWidget.Visible = showSpeeds.Checked;
@@ -433,7 +464,7 @@

 			popupContainer.AddChild(showSpeeds);

-			// put in a simulate extrusion checkbox
+			// Extrusion checkbox
 			var simulateExtrusion = new CheckBox("Extrusion".Localize(), textColor: textColor);
 			simulateExtrusion.Checked = options.SimulateExtrusion;
 			simulateExtrusion.CheckedStateChanged += (sender, e) =>
@@ -442,21 +473,20 @@
 			};
 			popupContainer.AddChild(simulateExtrusion);

-			// put in a render extrusion transparent checkbox
+			// Transparent checkbox
 			var transparentExtrusion = new CheckBox("Transparent".Localize(), textColor: textColor)
 			{
 				Checked = options.TransparentExtrusion,
 				Margin = new BorderDouble(5, 0, 0, 0),
 				HAnchor = HAnchor.ParentLeft,
 			};
-
 			transparentExtrusion.CheckedStateChanged += (sender, e) =>
 			{
 				options.TransparentExtrusion = transparentExtrusion.Checked;
 			};
 			popupContainer.AddChild(transparentExtrusion);

-			// put in a simulate extrusion checkbox
+			// Extrusion checkbox
 			if (ActiveSliceSettings.Instance.GetValue<int>(SettingsKey.extruder_count) > 1)
 			{
 				CheckBox hideExtruderOffsets = new CheckBox("Hide Offsets", textColor: textColor);
@@ -468,7 +498,7 @@
 				popupContainer.AddChild(hideExtruderOffsets);
 			}

-			// Put in the sync to print checkbox
+			// Sync To Print checkbox
 			if (windowMode == WindowMode.Embeded)
 			{
 				var syncToPrint = new CheckBox("Sync To Print".Localize(), textColor: textColor);
@@ -769,6 +799,12 @@
 		{
 			unregisterEvents?.Invoke(this, null);

+			// Find and unhook the parent system window KeyDown event
+			if (parentSystemWindow != null)
+			{
+				parentSystemWindow.KeyDown -= Parent_KeyDown;
+			}
+
 			if (externalMeshViewer != null)
 			{
 				externalMeshViewer.TrackballTumbleWidget.DrawGlContent -= TrackballTumbleWidget_DrawGlContent;


Move things into ListViewHelper class

Move things into ListViewHelper class

--- Pingo/MainWindow/MainWindow.xaml.cs
+++ Pingo/MainWindow/MainWindow.xaml.cs
@@ -1,6 +1,5 @@
 using Pingo.Classes;
 using System;
-using System.Collections.Generic;
 using System.ComponentModel;
 using System.Linq;
 using System.Threading;
@@ -22,19 +21,12 @@
         protected Timers timers = new Timers();
         protected IO io;
         protected ProgressBarUpdater progressBarUpdater;
+        protected ListViewHelper listViewHelper;

         //Locks
         object globalLock = new object();
         object threadLock = new object();

-        GridViewColumnHeader lastHeaderClicked = null;
-        ListSortDirection lastDirection = ListSortDirection.Ascending;
-        SortDescription sd = new SortDescription();
-
-        List<int> selectedIndices = new List<int>();
-
-        ICollectionView dataView;
-
         //Constructor
         public MainWindow()
         {
@@ -49,6 +41,8 @@
             //Initialize objects
             io = new IO(hostList);
             timers = new Timers(this);
+            listViewHelper = new ListViewHelper(this, hostList);
+            progressBarUpdater = new ProgressBarUpdater(progressBar, this);

             //Focus and highlight textbox
             txtInput.Focus();
@@ -56,22 +50,6 @@

             //Set ListView source
             lsvOutput.ItemsSource = hostList.GetHostsAsDataTable().DefaultView;
-
-            progressBarUpdater = new ProgressBarUpdater(progressBar, this);
-        }
-
-        private void UpdateSelectedIndices()
-        {
-            selectedIndices.Clear();
-
-            for (int i = 0; i < lsvOutput.SelectedItems.Count; i++)
-            {
-                dataView.SortDescriptions.Clear();
-                selectedIndices.Add(lsvOutput.Items.IndexOf(lsvOutput.SelectedItems[i]));
-
-                if (sd.PropertyName != null)
-                    dataView.SortDescriptions.Add(sd);
-            }
         }

         //Header click event
@@ -87,30 +65,30 @@
             {
                 string header = headerClicked.Column.Header as string;

-                if (headerClicked != this.lastHeaderClicked)
+                if (headerClicked != listViewHelper.LastHeaderClicked)
                 {
                     direction = ListSortDirection.Ascending;
-                    Sort(header, direction);
+                    listViewHelper.Sort(header, direction);
                 }
                 else
                 {
-                    if (this.lastDirection == ListSortDirection.Ascending)
+                    if (listViewHelper.LastSortDirection == ListSortDirection.Ascending)
                     {
                         direction = ListSortDirection.Descending;
-                        Sort(header, direction);
+                        listViewHelper.Sort(header, direction);
                     }
                     else
                     {
                         headerClicked.Column.HeaderTemplate = null;
                         direction = ListSortDirection.Ascending;
                         headerClicked = null;
-                        lastHeaderClicked = null;
-
-                        dataView = CollectionViewSource.GetDefaultView(hostList.GetHostsAsDataTable().DefaultView);
-                        dataView.SortDescriptions.Clear();
-                        dataView.Refresh();
-
-                        sd = new SortDescription();
+                        listViewHelper.LastHeaderClicked = null;
+
+                        listViewHelper.View = CollectionViewSource.GetDefaultView(hostList.GetHostsAsDataTable().DefaultView);
+                        listViewHelper.View.SortDescriptions.Clear();
+                        listViewHelper.View.Refresh();
+
+                        listViewHelper.CurrentSort = new SortDescription();
                     }
                 }

@@ -129,30 +107,14 @@
                 }

                 //Remove arrow from previously sorted header
-                if (this.lastHeaderClicked != null && this.lastHeaderClicked != headerClicked)
-                {
-                    this.lastHeaderClicked.Column.HeaderTemplate = null;
-                }
-
-                this.lastHeaderClicked = headerClicked;
-                this.lastDirection = direction;
-            }
-        }
-
-        //Sort code
-        private void Sort(string sortBy, ListSortDirection direction)
-        {
-            dataView = CollectionViewSource.GetDefaultView(hostList.GetHostsAsDataTable().DefaultView);
-
-            sortBy = sortBy.TrimStart();
-
-            if (sortBy == "Last Updated")
-                sortBy = "Timestamp";
-
-            dataView.SortDescriptions.Clear();
-            sd = new SortDescription(sortBy, direction);
-            dataView.SortDescriptions.Add(sd);
-            dataView.Refresh();
+                if (listViewHelper.LastHeaderClicked != null && listViewHelper.LastHeaderClicked != headerClicked)
+                {
+                    listViewHelper.LastHeaderClicked.Column.HeaderTemplate = null;
+                }
+
+                listViewHelper.LastHeaderClicked = headerClicked;
+                listViewHelper.LastSortDirection = direction;
+            }
         }

         private void btnEnter_Click(object sender, RoutedEventArgs e)
@@ -283,8 +245,8 @@
                                 lock (threadLock)
                                 {
                                     //Remove Sort
-                                    dataView = CollectionViewSource.GetDefaultView(hostList.GetHostsAsDataTable().DefaultView);
-                                    dataView.SortDescriptions.Clear();
+                                    listViewHelper.View = CollectionViewSource.GetDefaultView(hostList.GetHostsAsDataTable().DefaultView);
+                                    listViewHelper.View.SortDescriptions.Clear();

                                     this.Dispatcher.BeginInvoke(new Action(() =>
                                     {
@@ -319,11 +281,11 @@
                                     this.Dispatcher.BeginInvoke(new Action(() =>
                                     {
                                         //Remove sort arrow
-                                        if (lastHeaderClicked != null)
-                                            lastHeaderClicked.Column.HeaderTemplate = null;
-
-                                        lastHeaderClicked = null;
-                                        lastDirection = ListSortDirection.Ascending;
+                                        if (listViewHelper.LastHeaderClicked != null)
+                                            listViewHelper.LastHeaderClicked.Column.HeaderTemplate = null;
+
+                                        listViewHelper.LastHeaderClicked = null;
+                                        listViewHelper.LastSortDirection = ListSortDirection.Ascending;

                                         this.Title = "Pingo - Idle";

@@ -454,7 +416,7 @@
                                 {
                                     this.Dispatcher.BeginInvoke(new Action(() =>
                                     {
-                                        UpdateSelectedIndices();
+                                        listViewHelper.UpdateSelectedIndices();

                                         this.Title = "Pingo - Working";
                                         progressBar.Value = 0;
@@ -464,16 +426,16 @@

                                     double progress = 1.0;

-                                    Parallel.For(0, selectedIndices.Count(), i =>
+                                    Parallel.For(0, listViewHelper.GetSelectedIndices().Count(), i =>
                                         {
                                             progressBar.Dispatcher.BeginInvoke(new Action(() =>
                                             {
-                                                progressBarUpdater.UpdateProgressBar(progress, double.Parse(selectedIndices.Count().ToString()));
+                                                progressBarUpdater.UpdateProgressBar(progress, double.Parse(listViewHelper.GetSelectedIndices().Count().ToString()));
                                             }));

                                             progress++;

-                                            hostList.GetHostsAsList()[selectedIndices[i]].Ping();
+                                            hostList.GetHostsAsList()[listViewHelper.GetSelectedIndices()[i]].Ping();
                                         });

                                     progressBar.Dispatcher.BeginInvoke(
@@ -483,11 +445,11 @@

                                                 hostList.UpdateData();

-                                                if (sd.PropertyName != null)
+                                                if (listViewHelper.CurrentSort.PropertyName != null)
                                                 {
-                                                    dataView.SortDescriptions.Clear();
-                                                    dataView.SortDescriptions.Add(sd);
-                                                    dataView.Refresh();
+                                                    listViewHelper.View.SortDescriptions.Clear();
+                                                    listViewHelper.View.SortDescriptions.Add(listViewHelper.CurrentSort);
+                                                    listViewHelper.View.Refresh();
                                                 }
                                             }));
                                 }
@@ -523,23 +485,23 @@
                                 {
                                     lsvOutput.Dispatcher.BeginInvoke(new Action(() =>
                                     {
-                                        UpdateSelectedIndices();
-                                        dataView.SortDescriptions.Clear();
+                                        listViewHelper.UpdateSelectedIndices();
+                                        listViewHelper.View.SortDescriptions.Clear();
                                     }));

                                     this.Dispatcher.BeginInvoke(new Action(() =>
                                     {
-                                        selectedIndices.Sort();
-
-                                        for (int i = 0; i < selectedIndices.Count(); i++)
-                                        {
-                                            hostList.GetHostsAsList().RemoveAt(selectedIndices[i] - i);
+                                        listViewHelper.GetSelectedIndices().Sort();
+
+                                        for (int i = 0; i < listViewHelper.GetSelectedIndices().Count(); i++)
+                                        {
+                                            hostList.GetHostsAsList().RemoveAt(listViewHelper.GetSelectedIndices()[i] - i);
                                         }

                                         hostList.UpdateData();
-                                        if (sd.PropertyName != null)
-                                            dataView.SortDescriptions.Add(sd);
-                                        dataView.Refresh();
+                                        if (listViewHelper.CurrentSort.PropertyName != null)
+                                            listViewHelper.View.SortDescriptions.Add(listViewHelper.CurrentSort);
+                                        listViewHelper.View.Refresh();
                                     }));
                                 }
                             }
@@ -578,11 +540,11 @@
                                         hostList.UpdateData();

                                         //Remove sort arrow
-                                        if (lastHeaderClicked != null)
-                                            lastHeaderClicked.Column.HeaderTemplate = null;
-
-                                        lastHeaderClicked = null;
-                                        lastDirection = ListSortDirection.Ascending;
+                                        if (listViewHelper.LastHeaderClicked != null)
+                                            listViewHelper.LastHeaderClicked.Column.HeaderTemplate = null;
+
+                                        listViewHelper.LastHeaderClicked = null;
+                                        listViewHelper.LastSortDirection = ListSortDirection.Ascending;
                                     }));
                             }
                             catch (Exception ex)
@@ -698,11 +660,11 @@
             {
                 try
                 {
-                    dataView.SortDescriptions.Clear();
+                    listViewHelper.View.SortDescriptions.Clear();
                     string copy = hostList.GetHostsAsList()[lsvOutput.Items.IndexOf(lsvOutput.SelectedItems[0])].ToString()[0];
                     Clipboard.SetText(copy);
-                    if (sd.PropertyName != null)
-                        dataView.SortDescriptions.Add(sd);
+                    if (listViewHelper.CurrentSort.PropertyName != null)
+                        listViewHelper.View.SortDescriptions.Add(listViewHelper.CurrentSort);
                     MessageBox.Show("Hostname " + copy + " copied to clipboard", null, MessageBoxButton.OK, MessageBoxImage.Information);
                 }
                 catch (Exception ex)


Cache GetIdentifier.

Cache GetIdentifier.

--- ExRam.Gremlinq.Core/Models/GraphElementPropertyModel.cs
+++ ExRam.Gremlinq.Core/Models/GraphElementPropertyModel.cs
@@ -1,7 +1,9 @@
 using System;
+using System.Collections.Concurrent;
 using System.Collections.Immutable;
 using System.Linq;
 using System.Reflection;
+using System.Runtime.CompilerServices;
 using ExRam.Gremlinq.Core.Extensions;
 using LanguageExt;

@@ -31,6 +33,8 @@

         public static readonly IGraphElementPropertyModel Default = new DefaultGraphElementPropertyModel();

+        private static readonly ConditionalWeakTable<IGraphElementPropertyModel, ConcurrentDictionary<MemberInfo, object>> IdentifierDict = new ConditionalWeakTable<IGraphElementPropertyModel, ConcurrentDictionary<MemberInfo, object>>();
+
         public static IGraphElementPropertyModel ConfigureNames(this IGraphElementPropertyModel model, Func<MemberInfo, string, string> overrideTransformation)
         {
             return model.ConfigureMetadata(_ => _.ConfigureNames(overrideTransformation));
@@ -55,44 +59,51 @@

         internal static object GetIdentifier(this IGraphElementPropertyModel model, MemberInfo member)
         {
-            if (member.DeclaringType.IsInterface)
-            {
-                var interfaceGetter = ((PropertyInfo)member).GetMethod;
+            return IdentifierDict
+                .GetOrCreateValue(model)
+                .GetOrAdd(
+                    member,
+                    closureMember =>
+                    {
+                        if (closureMember.DeclaringType != null && closureMember.DeclaringType.IsInterface)
+                        {
+                            var interfaceGetter = ((PropertyInfo)closureMember).GetMethod;

-                var implementingGetter = model.Metadata.Keys
-                    .Select(x => x.DeclaringType)
-                    .Distinct()
-                    .Where(declaringType => member.DeclaringType.IsAssignableFrom(declaringType))
-                    .Select(declaringType =>
-                    {
-                        var interfaceMap = declaringType
-                            .GetInterfaceMap(member.DeclaringType);
+                            var implementingGetter = model.Metadata.Keys
+                                .Select(x => x.DeclaringType)
+                                .Distinct()
+                                .Where(declaringType => closureMember.DeclaringType.IsAssignableFrom(declaringType))
+                                .Select(declaringType =>
+                                {
+                                    var interfaceMap = declaringType
+                                        .GetInterfaceMap(closureMember.DeclaringType);

-                        var index = Array.IndexOf(
-                            interfaceMap.InterfaceMethods,
-                            interfaceGetter);
+                                    var index = Array.IndexOf(
+                                        interfaceMap.InterfaceMethods,
+                                        interfaceGetter);

-                        return interfaceMap.TargetMethods[index];
-                    })
-                    .ToArray();
+                                    return interfaceMap.TargetMethods[index];
+                                })
+                                .ToArray();

-                var identifiers = model.Metadata.Keys
-                    .Where(m => member.DeclaringType.IsAssignableFrom(m.DeclaringType))
-                    .OfType<PropertyInfo>()
-                    .Where(p => implementingGetter.Contains(p.GetMethod, MemberInfoEqualityComparer.Instance))
-                    .Select(model.GetIdentifier)
-                    .Distinct()
-                    .ToArray();
+                            var identifiers = model.Metadata.Keys
+                                .Where(m => closureMember.DeclaringType.IsAssignableFrom(m.DeclaringType))
+                                .OfType<PropertyInfo>()
+                                .Where(p => implementingGetter.Contains(p.GetMethod, MemberInfoEqualityComparer.Instance))
+                                .Select(model.GetIdentifier)
+                                .Distinct()
+                                .ToArray();

-                if (identifiers.Length != 1)
-                    throw new InvalidOperationException("Contradicting identifiers.");
+                            if (identifiers.Length != 1)
+                                throw new InvalidOperationException("Contradicting identifiers.");

-                return identifiers[0];
-            }
-
-            return model.GetIdentifier(model.Metadata
-                .TryGetValue(member)
-                .IfNone(new PropertyMetadata(member.Name)));
+                            return identifiers[0];
+                        }
+
+                        return model.GetIdentifier(model.Metadata
+                            .TryGetValue(closureMember)
+                            .IfNone(new PropertyMetadata(closureMember.Name)));
+                    });
         }

         internal static object GetIdentifier(this IGraphElementPropertyModel model, PropertyMetadata metadata)


Added sample for picking Symbol from FeatureDataRow

git-tfs-id: [https://tfs.codeplex.com/tfs/TFS01]$/SharpMap/Trunk;C66374

--- ExampleCodeSnippets/Theming.cs
+++ ExampleCodeSnippets/Theming.cs
@@ -1,4 +1,3 @@
-
 namespace ExampleCodeSnippets
 {
     public class SymbolRotationTheming
@@ -69,6 +68,78 @@
         }
     }

+    public class SymbolFromFeatureDataRowTheming
+    {
+        /// <summary>
+        /// Name of the column, which contains the rotation angle in degrees [0, 360]
+        /// </summary>
+        public System.String SymbolColumn { get; set; }
+
+        /// <summary>
+        /// Default vector style from which parts are to be modified
+        /// </summary>
+        public SharpMap.Styles.VectorStyle DefaultStyle { get; set; }
+
+        /// <summary>
+        /// Creates an instance of this class
+        /// </summary>
+        /// <param name="symbolColumn">Name of the column, which contains the symbol</param>
+        public SymbolFromFeatureDataRowTheming(System.String symbolColumn)
+            : this(symbolColumn, new SharpMap.Styles.VectorStyle())
+        {
+        }
+
+        /// <summary>
+        /// Creates an instance of this class
+        /// </summary>
+        /// <param name="styleRotationColumn">Name of the column, which contains the symbol</param>
+        /// <param name="defaultStyle">Default vector style from which parts are to be modified</param>
+        public SymbolFromFeatureDataRowTheming(System.String styleRotationColumn, SharpMap.Styles.VectorStyle defaultStyle)
+        {
+            SymbolColumn = styleRotationColumn;
+            DefaultStyle = defaultStyle;
+        }
+
+        private static SharpMap.Styles.VectorStyle CloneStyle(SharpMap.Styles.VectorStyle styleToClone)
+        {
+            SharpMap.Styles.VectorStyle style =
+                new SharpMap.Styles.VectorStyle
+                {
+                    Enabled = styleToClone.Enabled,
+                    MinVisible = styleToClone.MinVisible,
+                    MaxVisible = styleToClone.MaxVisible,
+                    Line = styleToClone.Line.Clone() as System.Drawing.Pen,
+                    Fill = styleToClone.Fill.Clone() as System.Drawing.Brush,
+                    Outline = styleToClone.Outline.Clone() as System.Drawing.Pen,
+                    EnableOutline = styleToClone.EnableOutline,
+                    Symbol = styleToClone.Symbol.Clone() as System.Drawing.Bitmap,
+                    SymbolOffset = styleToClone.SymbolOffset,
+                    SymbolRotation = styleToClone.SymbolRotation,
+                    SymbolScale = styleToClone.SymbolScale
+                };
+
+            return style;
+        }
+
+        public SharpMap.Styles.VectorStyle GetRotatedSymol(SharpMap.Data.FeatureDataRow row)
+        {
+            if (!System.String.IsNullOrEmpty(SymbolColumn))
+                try
+                {
+                    SharpMap.Styles.VectorStyle dataStyle = CloneStyle(DefaultStyle);
+                    if (!row.IsNull(SymbolColumn))
+                    {
+                        dataStyle.Symbol = new System.Drawing.Bitmap(
+                            new System.IO.MemoryStream((byte[]) row[SymbolColumn]));
+                    }
+                    return dataStyle;
+                }
+                catch { }
+
+            return null;
+        }
+    }
+
     [NUnit.Framework.TestFixture]
     public class SymbolRotationThemingTest
     {
@@ -122,4 +193,96 @@
         }
     }

+    [NUnit.Framework.TestFixture]
+    public class SymbolFromFeatureDataRowTest
+    {
+        private static readonly System.Random _randomNumberGenerator = new System.Random();
+        static System.Double[] GetRandomOrdinates(System.Int32 size, System.Double min, System.Double max)
+        {
+            System.Double[] arr = new System.Double[size];
+            System.Double width = max - min;
+            for (System.Int32 i = 0; i < size; i++)
+            {
+                System.Double randomValue = _randomNumberGenerator.NextDouble();
+                arr[i] = min + randomValue * width;
+            }
+            return arr;
+        }
+
+        [NUnit.Framework.Test]
+        public void TestSymbolSelectionTheming()
+        {
+            //Create a map
+            SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(720, 360));
+
+            //Create some random sample data
+            CreatingData cd = new CreatingData();
+            SharpMap.Data.FeatureDataTable fdt =
+                cd.CreatePointFeatureDataTableFromArrays(GetRandomOrdinates(80, -180, 180),
+                                                         GetRandomOrdinates(80, -90, 90), null);
+
+            //Add rotation column and fill with random rotation values
+            fdt.Columns.Add("Symbol", typeof(System.Byte[]));
+            foreach (SharpMap.Data.FeatureDataRow row in fdt.Rows)
+                row["Symbol"] = RandomSymbol((int)System.Math.Floor(_randomNumberGenerator.NextDouble() * 360d));
+
+
+            //Create layer and datasource
+            SharpMap.Layers.VectorLayer vl = new SharpMap.Layers.VectorLayer("Points", new SharpMap.Data.Providers.GeometryFeatureProvider(fdt));
+
+            //Create default style
+            SharpMap.Styles.VectorStyle defaultStyle = new SharpMap.Styles.VectorStyle();
+            defaultStyle.Symbol = new System.Drawing.Bitmap(@"..\..\..\DemoWinForm\Resources\flag.png");
+            defaultStyle.SymbolScale = 0.5f;
+
+            //Create theming class and apply to layer
+            SymbolFromFeatureDataRowTheming srt = new SymbolFromFeatureDataRowTheming("Symbol", defaultStyle);
+            vl.Theme = new SharpMap.Rendering.Thematics.CustomTheme(srt.GetRotatedSymol);
+
+            map.Layers.Add(vl);
+            map.ZoomToExtents();
+            System.Drawing.Image mapImage = map.GetMap();
+            mapImage.Save("SymbolFromFDR.bmp");
+        }
+
+        private byte[] RandomSymbol(int number)
+        {
+            number = number%360;
+            string text ="";
+            System.Drawing.Brush brush = null;
+            if (number < 60)
+                return null;
+            if (number < 120)
+            {
+                text = "<120";
+                brush = System.Drawing.Brushes.DarkGreen;
+            }
+            else if(number < 240)
+            {
+                text = number.ToString();
+                brush = System.Drawing.Brushes.Orange;
+            }
+            else
+            {
+                text = ">240";
+                brush = System.Drawing.Brushes.Red;
+            }
+
+            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(120, 60);
+            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
+            System.Drawing.RectangleF size = new System.Drawing.RectangleF(0f, 0f, 120f, 60f);
+            g.FillRectangle(System.Drawing.Brushes.White, size);
+            var sf = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoWrap)
+                         {Alignment = System.Drawing.StringAlignment.Center};
+
+            g.DrawString(text, new System.Drawing.Font("Arial", 24), brush, size, sf);
+            g.Flush();
+            g.Dispose();
+            var ms = new System.IO.MemoryStream();
+            bmp.MakeTransparent(System.Drawing.Color.White);
+            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
+            return ms.ToArray();
+        }
+    }
+
 }


Add ResolveByName attribute to TargetControl property

--- src/Avalonia.Xaml.Interactions/Custom/ShowOnDoubleTappedBehavior.cs
+++ src/Avalonia.Xaml.Interactions/Custom/ShowOnDoubleTappedBehavior.cs
@@ -19,6 +19,7 @@
     /// <summary>
     /// Gets or sets the target control. This is a avalonia property.
     /// </summary>
+    [ResolveByName]
     public Control? TargetControl
     {
         get => GetValue(TargetControlProperty);


Update PBU-Main-Future.cs

Update PBU-Main-Future.cs

--- ProcessBlockUtil/PBU-Main-Future.cs
+++ ProcessBlockUtil/PBU-Main-Future.cs
@@ -22,6 +22,7 @@
 using System.ServiceProcess;
 using System.Threading;
 using System.Collections;
+using System.Text;

 namespace ACProcessBlockUtil
 {
@@ -55,7 +56,7 @@

 	    if(File.Exists(userProfile + "\\ACRules.txt")){
 		    ar = new ArrayList<String>();
-		    sr = new SteamReader(userProfile + "\\ACRules.txt");
+		    sr = new SteamReader(userProfile + "\\ACRules.txt", new ASCIIEncoding());
 		    while(true){
 			    String tempLine = sr.ReadLine();
 			    if(tempLine == null){


Delete old commented code

Delete old commented code

--- src/Elasticsearch.Net/Serialization/ElasticsearchNetJsonStrategy.cs
+++ src/Elasticsearch.Net/Serialization/ElasticsearchNetJsonStrategy.cs
@@ -1,126 +0,0 @@
-//using System;
-//using System.Collections.Generic;
-//using System.Globalization;
-//using System.Linq;
-//using System.Reflection;
-//
-//namespace Elasticsearch.Net
-//{
-//	internal class ElasticsearchNetJsonStrategy : PocoJsonSerializerStrategy
-//	{
-//		public override bool TrySerializeNonPrimitiveObject(object input, out object output)
-//		{
-//			if (!(input is Exception))
-//				return base.TrySerializeNonPrimitiveObject(input, out output);
-//
-//			var e = input as Exception;
-//			var exceptionsJson = FlattenExceptions(e).ToList();
-//			var array = new JsonArray(exceptionsJson.Count);
-//			array.AddRange(exceptionsJson);
-//			output = array;
-//			return true;
-//		}
-//
-//		private IEnumerable<JsonObject> FlattenExceptions(Exception e)
-//		{
-//			var depth = 0;
-//			var maxExceptions = 20;
-//			do
-//			{
-//				var o = ToExceptionJsonObject(e, depth);
-//				depth++;
-//				yield return o;
-//
-//				e = e.InnerException;
-//			} while (depth < maxExceptions && e != null);
-//		}
-//
-//		private JsonObject ToExceptionJsonObject(Exception e, int depth)
-//		{
-//			var o = new JsonObject();
-//			var helpUrl = e.HelpLink;
-//			var stackTrace = e.StackTrace;
-//			var remoteStackTrace = string.Empty;
-//			var remoteStackIndex = string.Empty;
-//			var exceptionMethod = string.Empty;
-//			var hresult = e.HResult;
-//			var source = e.Source;
-//			var className = string.Empty;
-//
-//			o.Add("Depth", depth);
-//			o.Add("ClassName", className);
-//			o.Add("Message", e.Message);
-//			o.Add("Source", source);
-//			o.Add("StackTraceString", stackTrace);
-//			o.Add("RemoteStackTraceString", remoteStackTrace);
-//			o.Add("RemoteStackIndex", remoteStackIndex);
-//			o.Add("HResult", hresult);
-//			o.Add("HelpURL", helpUrl);
-//			//TODO Find out how to get exceptionMethod again
-//			WriteStructuredExceptionMethod(o, exceptionMethod);
-//			return o;
-//		}
-//
-//		private static void WriteStructuredExceptionMethod(JsonObject o, string exceptionMethodString)
-//		{
-//			if (string.IsNullOrWhiteSpace(exceptionMethodString)) return;
-//
-//			var args = exceptionMethodString.Split('\0', '\n');
-//
-//			if (args.Length != 5) return;
-//
-//			var memberType = int.Parse(args[0], CultureInfo.InvariantCulture);
-//			var name = args[1];
-//			var assemblyName = args[2];
-//			var className = args[3];
-//			var signature = args[4];
-//			var an = new AssemblyName(assemblyName);
-//			var exceptionMethod = new JsonObject();
-//
-//			exceptionMethod.Add("Name", name);
-//			exceptionMethod.Add("AssemblyName", an.Name);
-//			exceptionMethod.Add("AssemblyVersion", an.Version.ToString());
-//			exceptionMethod.Add("AssemblyCulture", an.CultureName);
-//			exceptionMethod.Add("ClassName", className);
-//			exceptionMethod.Add("Signature", signature);
-//			exceptionMethod.Add("MemberType", memberType);
-//			o.Add("ExceptionMethod", exceptionMethod);
-//		}
-//
-//		public override object DeserializeObject(object value, Type type)
-//		{
-//			if (type == typeof(DynamicBody))
-//			{
-//				var dict = base.DeserializeObject(value, typeof(IDictionary<string, object>)) as IDictionary<string, object>;
-//				return dict == null ? null : DynamicBody.Create(dict);
-//			}
-//			if (type == typeof(ServerError))
-//			{
-//				var dict = base.DeserializeObject(value, typeof(IDictionary<string, object>)) as IDictionary<string, object>;
-//				return ServerError.Create(dict, this);
-//			}
-//			if (type == typeof(ShardFailure))
-//			{
-//				var dict = base.DeserializeObject(value, typeof(IDictionary<string, object>)) as IDictionary<string, object>;
-//				return ShardFailure.CreateShardFailure(dict, this);
-//			}
-//			if (type == typeof(Error))
-//			{
-//				if (value is string s)
-//					return new Error { Reason = s };
-//
-//				var dict = base.DeserializeObject(value, typeof(IDictionary<string, object>)) as IDictionary<string, object>;
-//				return Error.CreateError(dict, this);
-//			}
-//			if (type == typeof(ErrorCause))
-//			{
-//				if (value is string s)
-//					return new ErrorCause { Reason = s };
-//
-//				var dict = base.DeserializeObject(value, typeof(IDictionary<string, object>)) as IDictionary<string, object>;
-//				return ErrorCause.CreateErrorCause(dict, this);
-//			}
-//			return base.DeserializeObject(value, type);
-//		}
-//	}
-//}


Delete DependencyInjectionSetup.cs

Delete DependencyInjectionSetup.cs

--- src/Equinox.Services.API/Configurations/DependencyInjectionSetup.cs
+++ src/Equinox.Services.API/Configurations/DependencyInjectionSetup.cs
@@ -1,16 +0,0 @@
-using System;
-using Equinox.Infra.CrossCutting.IoC;
-using Microsoft.Extensions.DependencyInjection;
-
-namespace Equinox.Services.Api.Configurations
-{
-    public static class DependencyInjectionSetup
-    {
-        public static void AddDependencyInjectionSetup(this IServiceCollection services)
-        {
-            if (services == null) throw new ArgumentNullException(nameof(services));
-
-            NativeInjectorBootStrapper.RegisterServices(services);
-        }
-    }
-}


Fix HttpClientHelpers url escape data string

--- src/GeekLearning.Test.Integration/Helpers/Http/HttpClientHelpers.cs
+++ src/GeekLearning.Test.Integration/Helpers/Http/HttpClientHelpers.cs
@@ -26,7 +26,7 @@
             {
                 Content = new FormUrlEncodedContent(contentData)
             };
-
+
             CookiesHelper.CopyCookiesFromResponse(requestMsg, responseMsg);

             return await httpClient.SendAsync(requestMsg);
@@ -61,7 +61,7 @@
                             jValue?.ToString("o", CultureInfo.InvariantCulture) :
                             jValue?.ToString(CultureInfo.InvariantCulture);

-            return new Dictionary<string, string> { { token.Path, Uri.EscapeDataString(value ?? string.Empty) } };
+            return new Dictionary<string, string> { { token.Path, value } };
         }
     }
-}+}


Add test 'Can_replace_extension'

Add test 'Can_replace_extension'

--- test/InfoCarrier.Core.FunctionalTests/InfoCarrierDbContextOptionsBuilderExtensionsTest.cs
+++ test/InfoCarrier.Core.FunctionalTests/InfoCarrierDbContextOptionsBuilderExtensionsTest.cs
@@ -23,5 +23,21 @@

             Assert.Equal("DummyDatabase", extension.InfoCarrierBackend.ServerUrl);
         }
+
+        [Fact]
+        public void Can_replace_extension()
+        {
+            IInfoCarrierBackend backend = InfoCarrierTestHelpers.CreateDummyBackend(typeof(DbContext));
+            var optionsBuilder = new DbContextOptionsBuilder();
+
+            optionsBuilder.UseInfoCarrierBackend(backend);
+            var extension1 = optionsBuilder.Options.Extensions.OfType<InfoCarrierOptionsExtension>().Single();
+
+            optionsBuilder.UseInfoCarrierBackend(backend);
+            var extension2 = optionsBuilder.Options.Extensions.OfType<InfoCarrierOptionsExtension>().Single();
+
+            Assert.NotSame(extension1, extension2);
+            Assert.Same(extension1.InfoCarrierBackend, extension2.InfoCarrierBackend);
+        }
     }
 }


Removed unused function from QtProject.cs

--- Qt4VS2003/QtProjectLib/QtProject.cs
+++ Qt4VS2003/QtProjectLib/QtProject.cs
@@ -696,15 +696,6 @@
             return true;
         }

-		public void AddUic4BuildStep(string fileName)
-		{
-
-            VCFile file = (VCFile)((IVCCollection)vcPro.Files).Item(fileName);
-
-            if (file != null)
-				AddUic4BuildStep(file);
-		}
-
         /// <summary>
         /// This function adds a uic4 build step to a given file.
         /// </summary>
@@ -2519,7 +2510,7 @@
             {
                 if (file.Name.EndsWith(".ui") && !IsUic3File(file))
                 {
-                    AddUic4BuildStep(file.FullPath);
+                    AddUic4BuildStep(file);
                     Messages.PaneMessage(dte, "Update uic step for " + file.Name + ".");
                     ++updatedFiles;
                 }


fixed update submodule again

fixed update submodule again

--- FlubuCore/Context/FluentInterface/GitFluentInterface.cs
+++ FlubuCore/Context/FluentInterface/GitFluentInterface.cs
@@ -49,7 +49,7 @@

         public GitSubmoduleTask InitSubmodules()
         {
-            return Submodule().Init().Recursive();
+            return Submodule().Update().Init().Recursive();
         }

         public GitSubmoduleTask PullSubmodules()


Updated AssemblyInfo

Updated AssemblyInfo

--- RearGate/Properties/AssemblyInfo.cs
+++ RearGate/Properties/AssemblyInfo.cs
@@ -1,16 +1,19 @@
 using System.Reflection;
-using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;

 // General Information about an assembly is controlled through the following
 // set of attributes. Change these attribute values to modify the information
 // associated with an assembly.
 [assembly: AssemblyTitle("RearGate")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
+[assembly: AssemblyDescription("A tool to autolaunch patches from USB")]
+#if DEBUG
+[assembly: AssemblyConfiguration("Debug")]
+#else
+[assembly: AssemblyConfiguration("Release")]
+#endif
+[assembly: AssemblyCompany("Svetomech")]
 [assembly: AssemblyProduct("RearGate")]
-[assembly: AssemblyCopyright("Copyright ©  2017")]
+[assembly: AssemblyCopyright("Copyright © Svetomech TheRainwildsKeeper 2017")]
 [assembly: AssemblyTrademark("")]
 [assembly: AssemblyCulture("")]


ExcludeUnusedStylesInExcelToHTML

ExcludeUnusedStylesInExcelToHTML

--- Examples/CSharp/RunExamples.cs
+++ Examples/CSharp/RunExamples.cs
@@ -108,33 +108,8 @@
                 Console.WriteLine(ex.Message);
             }

-            int iii = 0;
-
-            //_CellsHelper.IndexToName.Run();
-            //_CellsHelper.MergeFiles.Run();
-            //_CellsHelper.NameToIndex.Run();
-            //_CellsHelper.NumberOfSignificantDigits.Run();
-            //_CellsHelper.UsingCustomImplementationFactoryToCreateCustomImplementationOfMemoryStream.Run();
-
-            //UsingSparklines.Run();
-            //Applying3DFormat.Run();
-            //ChangeChartSizeAndPosition.Run();
-            //ChartRendering.Run();
-            //ChartToPdf.Run();
-            //HandleAutomaticUnitsOfChartAxisLikeMicrosoftExcel.Run();
-            //HowToCreateChart.Run();
-            //ReadManipulateExcel2016Charts.Run();
-            //SetShapeTypeOfDataLabelsOfChart.Run();
-            //SettingCategoryData.Run();
-            //SettingChartsData.Run();
-            SetValuesFormatCodeOfChartSeries.Run();
-
-            Console.Write("Press key...");
-            Console.ReadKey();
-            return;

             // Uncomment the one you want to try out
-
             //Aspose.Cells for .NET v18.2
             //WorkbookSettings.ControlExternalResourcesUsingWorkbookSetting_StreamProvider.Run();
             //_Workbook.FilterDefinedNamesWhileLoadingWorkbook.Run();
@@ -460,6 +435,32 @@
             //SettingSharedFormula.Run();

+            //int iii = 0;
+
+            //_CellsHelper.IndexToName.Run();
+            //_CellsHelper.MergeFiles.Run();
+            //_CellsHelper.NameToIndex.Run();
+            //_CellsHelper.NumberOfSignificantDigits.Run();
+            //_CellsHelper.UsingCustomImplementationFactoryToCreateCustomImplementationOfMemoryStream.Run();
+
+            //UsingSparklines.Run();
+            //Applying3DFormat.Run();
+            //ChangeChartSizeAndPosition.Run();
+            //ChartRendering.Run();
+            //ChartToPdf.Run();
+            //HandleAutomaticUnitsOfChartAxisLikeMicrosoftExcel.Run();
+            //HowToCreateChart.Run();
+            //ReadManipulateExcel2016Charts.Run();
+            //SetShapeTypeOfDataLabelsOfChart.Run();
+            //SettingCategoryData.Run();
+            //SettingChartsData.Run();
+            //SetValuesFormatCodeOfChartSeries.Run();
+
+            //Console.Write("Press key...");
+            //Console.ReadKey();
+            //return;
+
+
             //// CopyShapesBetweenWorksheets
             //// =====================================================
             // CopyChart.Run();


Fix ring glow lookup being incorrect

Fix ring glow lookup being incorrect

--- osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/GlowPiece.cs
+++ osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/GlowPiece.cs
@@ -25,7 +25,7 @@
             {
                 Anchor = Anchor.Centre,
                 Origin = Anchor.Centre,
-                Texture = textures.Get("ring-glow"),
+                Texture = textures.Get("Gameplay/osu/ring-glow"),
                 Blending = BlendingParameters.Additive,
                 Alpha = 0.5f
             };


Fix incorrect blank lines

Fix incorrect blank lines

--- osu.Game.Tests/Beatmaps/Formats/LegacyBeatmapDecoderTest.cs
+++ osu.Game.Tests/Beatmaps/Formats/LegacyBeatmapDecoderTest.cs
@@ -707,7 +707,6 @@
                 Assert.That(third.ControlPoints[5].Type.Value, Is.EqualTo(null));
                 Assert.That(third.ControlPoints[6].Position.Value, Is.EqualTo(new Vector2(480, 0)));
                 Assert.That(third.ControlPoints[6].Type.Value, Is.EqualTo(null));
-
             }
         }
     }


Chooser earlier items in song select tests to avoid potentially not having enough

--- osu.Game.Tests/Visual/SongSelect/TestScenePlaySongSelect.cs
+++ osu.Game.Tests/Visual/SongSelect/TestScenePlaySongSelect.cs
@@ -488,8 +488,9 @@
             AddStep("select beatmap externally", () =>
             {
                 target = manager.GetAllUsableBeatmapSets()
-                                .Where(b => b.Beatmaps.Any(bi => bi.RulesetID == targetRuleset))
-                                .ElementAt(5).Beatmaps.First(bi => bi.RulesetID == targetRuleset);
+                                .First(b => b.Beatmaps.Any(bi => bi.RulesetID == targetRuleset))
+                                .Beatmaps
+                                .First(bi => bi.RulesetID == targetRuleset);

                 Beatmap.Value = manager.GetWorkingBeatmap(target);
             });
@@ -534,8 +535,10 @@

             AddStep("select beatmap externally", () =>
             {
-                target = manager.GetAllUsableBeatmapSets().Where(b => b.Beatmaps.Any(bi => bi.RulesetID == 1))
-                                .ElementAt(5).Beatmaps.First();
+                target = manager
+                         .GetAllUsableBeatmapSets()
+                         .First(b => b.Beatmaps.Any(bi => bi.RulesetID == 1))
+                         .Beatmaps.First();

                 Beatmap.Value = manager.GetWorkingBeatmap(target);
             });


Fix typo in VersionNavigation class name (#5044)

Fix typo in VersionNavigation class name

--- osu.Game/Online/API/Requests/Responses/APIChangelogBuild.cs
+++ osu.Game/Online/API/Requests/Responses/APIChangelogBuild.cs
@@ -31,9 +31,9 @@
         public List<APIChangelogEntry> ChangelogEntries { get; set; }

         [JsonProperty("versions")]
-        public VersionNatigation Versions { get; set; }
+        public VersionNavigation Versions { get; set; }

-        public class VersionNatigation
+        public class VersionNavigation
         {
             [JsonProperty("next")]
             public APIChangelogBuild Next { get; set; }


Remove whitespace

Remove whitespace

--- osu.Game/Screens/OnlinePlay/Components/RoomLocalUserInfo.cs
+++ osu.Game/Screens/OnlinePlay/Components/RoomLocalUserInfo.cs
@@ -56,7 +56,6 @@
                     attemptDisplay.Text += $" ({remaining} remaining)";
                 }
             }
-
             else
             {
                 attemptDisplay.Text = string.Empty;


Change number of cells. ( 9 => 7 )

Change number of cells. ( 9 => 7 )

--- XamarinLifeGameXAML/Logic/CellUtils.cs
+++ XamarinLifeGameXAML/Logic/CellUtils.cs
@@ -22,7 +22,7 @@
             return Tuple.Create(x, y);
         }

-        public static int CellSize => 9;
+        public static int CellSize => 7;

         public static int ArraySize => CellSize * CellSize;
     }


CP-16921: Update XenCenter bindings

CP-16921: Update XenCenter bindings

Reverted the changes to the XenObjectDownloader class

Signed-off-by: Mihaela Stoica <be95049f8e30d921fc7e2579c00c48bd84c40606@citrix.com>

--- XenModel/XenAPI/XenObjectDownloader.cs
+++ XenModel/XenAPI/XenObjectDownloader.cs
@@ -589,26 +589,5 @@
             foreach (KeyValuePair<XenRef<VGPU_type>, VGPU_type> entry in records)
                 changes.Add(new ObjectChange(typeof(VGPU_type), entry.Key.opaque_ref, entry.Value));
         }
-
-        private static void Download_PVS_farm(Session session, List<ObjectChange> changes)
-        {
-            Dictionary<XenRef<PVS_farm>, PVS_farm> records = PVS_farm.get_all_records(session);
-            foreach (KeyValuePair<XenRef<PVS_farm>, PVS_farm> entry in records)
-                changes.Add(new ObjectChange(typeof(PVS_farm), entry.Key.opaque_ref, entry.Value));
-        }
-
-        private static void Download_PVS_server(Session session, List<ObjectChange> changes)
-        {
-            Dictionary<XenRef<PVS_server>, PVS_server> records = PVS_server.get_all_records(session);
-            foreach (KeyValuePair<XenRef<PVS_server>, PVS_server> entry in records)
-                changes.Add(new ObjectChange(typeof(PVS_server), entry.Key.opaque_ref, entry.Value));
-        }
-
-        private static void Download_PVS_proxy(Session session, List<ObjectChange> changes)
-        {
-            Dictionary<XenRef<PVS_proxy>, PVS_proxy> records = PVS_proxy.get_all_records(session);
-            foreach (KeyValuePair<XenRef<PVS_proxy>, PVS_proxy> entry in records)
-                changes.Add(new ObjectChange(typeof(PVS_proxy), entry.Key.opaque_ref, entry.Value));
-        }
     }
 }


Make sure we have a good selected item

Make sure we have a good selected item

--- PartPreviewWindow/View3D/Gui3D/MoveInZControl.cs
+++ PartPreviewWindow/View3D/Gui3D/MoveInZControl.cs
@@ -46,8 +46,7 @@
 {
 	public class MoveInZControl : InteractionVolume
 	{
-		public IObject3D SelectedItemOnMouseMove;
-		public IObject3D SelectedItemOnMouseDown;
+		public IObject3D ActiveSelectedItem;
 		protected PlaneShape hitPlane;
 		protected Vector3 initialHitPosition;
 		protected Mesh upArrowMesh;
@@ -68,9 +67,9 @@
 			{
 				ForceHide = () =>
 				{
+					var selectedItem = InteractionContext.Scene.SelectedItem;
 					// if the selection changes
-					if (InteractionContext.Scene.SelectedItem != SelectedItemOnMouseDown
-						&& InteractionContext.Scene.SelectedItem != SelectedItemOnMouseMove)
+					if (selectedItem != ActiveSelectedItem)
 					{
 						return true;
 					}
@@ -187,14 +186,15 @@

 		public override void OnMouseDown(MouseEvent3DArgs mouseEvent3D)
 		{
-			if (mouseEvent3D.info != null && InteractionContext.Scene.HasSelection)
+			var selectedItem = InteractionContext.Scene.SelectedItem;
+
+			if (mouseEvent3D.info != null
+				&& selectedItem != null)
 			{
 				HadClickOnControl = true;
-				SelectedItemOnMouseDown = InteractionContext.Scene.SelectedItem;
+				ActiveSelectedItem = selectedItem;

 				zHeightDisplayInfo.Visible = true;
-
-				var selectedItem = InteractionContext.Scene.SelectedItem;

 				double distanceToHit = Vector3.Dot(mouseEvent3D.info.HitPosition, mouseEvent3D.MouseRay.directionNormal);
 				hitPlane = new PlaneShape(mouseEvent3D.MouseRay.directionNormal, distanceToHit, null);
@@ -209,7 +209,8 @@

 		public override void OnMouseMove(MouseEvent3DArgs mouseEvent3D)
 		{
-			SelectedItemOnMouseMove = InteractionContext.Scene.SelectedItem;
+			var selectedItem = InteractionContext.Scene.SelectedItem;
+			ActiveSelectedItem = selectedItem;
 			if (MouseOver)
 			{
 				zHeightDisplayInfo.Visible = true;
@@ -223,10 +224,9 @@
 			{
 				IntersectInfo info = hitPlane.GetClosestIntersection(mouseEvent3D.MouseRay);

-				if (info != null && InteractionContext.Scene.HasSelection)
-				{
-					var selectedItem = InteractionContext.Scene.SelectedItem;
-
+				if (info != null
+					&& selectedItem != null)
+				{
 					var delta = info.HitPosition.Z - initialHitPosition.Z;

 					double newZPosition = mouseDownSelectedBounds.minXYZ.Z + delta;
@@ -288,13 +288,13 @@

 		private void InteractionLayer_AfterDraw(object sender, DrawEventArgs drawEvent)
 		{
-			if (InteractionContext.Scene.HasSelection
+			var selectedItem = InteractionContext.Scene.SelectedItem;
+
+			if (selectedItem != null
 				&& lines.Count > 2)
 			{
 				if (zHeightDisplayInfo.Visible)
 				{
-					var selectedItem = InteractionContext.Scene.SelectedItem;
-
 					for (int i = 0; i < lines.Count; i += 2)
 					{
 						// draw the measure line


Improved file format support - entries can contain multiple strings, and up to 5 strings will now be loaded (needed for the Status Names DATs).

--- PlayOnline.FFXI/IThings/DMSGStringTableEntry2.cs
+++ PlayOnline.FFXI/IThings/DMSGStringTableEntry2.cs
@@ -17,7 +17,26 @@
     }

     public override string ToString() {
-      return this.Text_;
+    string Text = String.Empty;
+      if (this.String1_ != null)
+	Text += this.String1_;
+      if (this.String2_ != null) {
+	Text += " / ";
+	Text += this.String2_;
+	if (this.String3_ != null) {
+	  Text += " / ";
+	  Text += this.String3_;
+	  if (this.String4_ != null) {
+	    Text += " / ";
+	    Text += this.String4_;
+	    if (this.String5_ != null) {
+	      Text += " / ";
+	      Text += this.String5_;
+	    }
+	  }
+	}
+      }
+      return Text;
     }

     public override List<PropertyPages.IThing> GetPropertyPages() {
@@ -30,7 +49,13 @@
       get {
 	return new List<string>(new string[] {
 	  "index",
-	  "text",
+	  "string-1",
+	  "string-2",
+	  "string-3",
+	  "string-4",
+	  "string-5",
+	  // 5 is an arbitrary limit; so far I've only seen tables with 1 or 2 strings per entry
+	  "string-count"
 	});
       }
     }
@@ -42,13 +67,23 @@
     #region Data Fields

     private uint?  Index_;
-    private string Text_;
+    private string String1_;
+    private string String2_;
+    private string String3_;
+    private string String4_;
+    private string String5_;
+    private uint?  StringCount_;

     #endregion

     public override void Clear() {
-      this.Index_ = null;
-      this.Text_  = null;
+      this.Index_       = null;
+      this.String1_     = null;
+      this.String2_     = null;
+      this.String3_     = null;
+      this.String4_     = null;
+      this.String5_     = null;
+      this.StringCount_ = null;
     }

     #endregion
@@ -57,32 +92,52 @@

     public override bool HasField(string Field) {
       switch (Field) {
-	case "index": return this.Index_.HasValue;
-	case "text":  return (this.Text_ != null);
-	default:      return false;
+	case "index":        return this.Index_.HasValue;
+	case "string-1":     return (this.String1_ != null);
+	case "string-2":     return (this.String2_ != null);
+	case "string-3":     return (this.String3_ != null);
+	case "string-4":     return (this.String4_ != null);
+	case "string-5":     return (this.String5_ != null);
+	case "string-count": return this.StringCount_.HasValue;
+	default:             return false;
       }
     }

     public override string GetFieldText(string Field) {
       switch (Field) {
-	case "index": return (!this.Index_.HasValue ? String.Empty : String.Format("{0:00000}", this.Index_.Value));
-	case "text":  return this.Text_;
-	default:      return null;
+	case "index":        return (!this.Index_.HasValue ? String.Empty : String.Format("{0:00000}", this.Index_.Value));
+	case "string-1":     return ((this.String1_ == null) ? String.Empty : this.String1_);
+	case "string-2":     return ((this.String2_ == null) ? String.Empty : this.String2_);
+	case "string-3":     return ((this.String3_ == null) ? String.Empty : this.String3_);
+	case "string-4":     return ((this.String4_ == null) ? String.Empty : this.String4_);
+	case "string-5":     return ((this.String5_ == null) ? String.Empty : this.String5_);
+	case "string-count": return (!this.StringCount_.HasValue ? String.Empty : this.StringCount_.ToString());
+	default:             return null;
       }
     }

     public override object GetFieldValue(string Field) {
       switch (Field) {
-	case "index": return (!this.Index_.HasValue ? null : (object) this.Index_.Value);
-	case "text":  return this.Text_;
-	default:      return null;
+	case "index":        return (!this.Index_.HasValue ? null : (object) this.Index_.Value);
+	case "string-1":     return this.String1_;
+	case "string-2":     return this.String2_;
+	case "string-3":     return this.String3_;
+	case "string-4":     return this.String4_;
+	case "string-5":     return this.String5_;
+	case "string-count": return (!this.StringCount_.HasValue ? null : (object) this.StringCount_.Value);
+	default:             return null;
       }
     }

     protected override void LoadField(string Field, System.Xml.XmlElement Node) {
       switch (Field) {
-	case "index": this.Index_ = (uint) this.LoadUnsignedIntegerField(Node); break;
-	case "text":  this.Text_  =        this.LoadTextField           (Node); break;
+	case "index":        this.Index_       = (uint) this.LoadUnsignedIntegerField(Node); break;
+	case "string-1":     this.String1_     = this.LoadTextField(Node); break;
+	case "string-2":     this.String2_     = this.LoadTextField(Node); break;
+	case "string-3":     this.String3_     = this.LoadTextField(Node); break;
+	case "string-4":     this.String4_     = this.LoadTextField(Node); break;
+	case "string-5":     this.String5_     = this.LoadTextField(Node); break;
+	case "string-count": this.StringCount_ = (uint) this.LoadUnsignedIntegerField(Node); break;
       }
     }

@@ -99,17 +154,47 @@
       this.Index_ = Index;
       BR.BaseStream.Position = HeaderBytes + 0x8 * Index.Value;
       try {
-      uint Offset = ~BR.ReadUInt32() + 40;
-      uint Length = ~BR.ReadUInt32() - 40;
+      uint Offset = ~BR.ReadUInt32();
+      uint Length = ~BR.ReadUInt32();
 	if (Length < 0 || Offset + Length > DataBytes)
 	  return false;
 	BR.BaseStream.Position = HeaderBytes + EntryBytes + Offset;
-      byte[] TextBytes = BR.ReadBytes((int) Length);
-	for (uint i = 0; i < TextBytes.Length; ++i)
-	  TextBytes[i] ^= 0xff;
-	this.Text_ = E.GetString(TextBytes).TrimEnd('\0');
+	this.StringCount_ = ~BR.ReadUInt32();
+      uint[] StringOffsets = new uint[this.StringCount_.Value];
+      uint[] StringFlags   = new uint[this.StringCount_.Value];
+	for (uint i = 0; i < this.StringCount_.Value; ++i) {
+	  StringOffsets[i] = ~BR.ReadUInt32();
+	  StringFlags  [i] = ~BR.ReadUInt32();
+	  if (StringOffsets[i] < 0 || (StringFlags[i] != 0 && StringFlags[i] != 1))
+	    return false;
+	}
+	// Meaning of flags is unclear so far.
+	for (uint i = 0; i < this.StringCount_.Value; ++i) {
+	   // not sure why the offsets are based 28 bytes past the start of the entry, but they are
+	  BR.BaseStream.Position = HeaderBytes + EntryBytes + Offset + 28 + StringOffsets[i];
+	List<byte> TextBytes = new List<byte>();
+	  while (true) {
+	  byte[] FourBytes = BR.ReadBytes(4);
+	    FourBytes[0] ^= 0xff;
+	    FourBytes[1] ^= 0xff;
+	    FourBytes[2] ^= 0xff;
+	    FourBytes[3] ^= 0xff;
+	    TextBytes.AddRange(FourBytes);
+	    if (FourBytes[3] == 0)
+	      break;
+	  }
+	string Text = E.GetString(TextBytes.ToArray()).TrimEnd('\0');
+	  switch (i) {
+	    case 0: this.String1_ = Text; break;
+	    case 1: this.String2_ = Text; break;
+	    case 2: this.String3_ = Text; break;
+	    case 3: this.String4_ = Text; break;
+	    case 4: this.String5_ = Text; break;
+	  }
+	}
 	return true;
       } catch { }
+      this.Clear();
       return false;
     }


Implemented Delete method. It should e really implemented with try/catch.

git-svn-id: 16f658619b342a39b0afd2472f072a689916e5a2@362 6f2d7086-9719-0410-ba06-0b8292a297aa

--- Psycho/src/Core/Psycho.Core/Psycho.Data/Topic.cs
+++ Psycho/src/Core/Psycho.Core/Psycho.Data/Topic.cs
@@ -116,6 +116,8 @@

 		public void Delete ()
 		{
+			if (this.Parent != null)
+				this.Parent.SubtopicList.Remove(this);
 		}

 		public void ForEach (System.Action<Topic> action)


AJAX account lookup filters out inactive accounts now.

--- Purchasing.Web/Controllers/AccountsController.cs
+++ Purchasing.Web/Controllers/AccountsController.cs
@@ -23,13 +23,13 @@
         }

         /// <summary>
-        /// Ajax call to search for any kfs acount, match by id or name
+        /// Ajax call to search for any kfs account, match by id or name
         /// </summary>
         /// <param name="searchTerm"></param>
         /// <returns></returns>
         public JsonNetResult SearchKfsAccounts(string searchTerm)
         {
-            var results = Repository.OfType<Account>().Queryable.Where(a => a.Id.Contains(searchTerm) || a.Name.Contains(searchTerm)).Select(a => new { Id = a.Id, Name = a.Name }).ToList();
+            var results = Repository.OfType<Account>().Queryable.Where(a => a.IsActive && (a.Id.Contains(searchTerm) || a.Name.Contains(searchTerm))).Select(a => new { Id = a.Id, Name = a.Name }).ToList();
             return new JsonNetResult(results);
         }


FIX test causing lower Turtle parser coverage

--- RDFSharp.Test/Model/Serializers/RDFTurtleTest.cs
+++ RDFSharp.Test/Model/Serializers/RDFTurtleTest.cs
@@ -2090,7 +2090,7 @@
         {
             MemoryStream stream = new MemoryStream();
             using (StreamWriter writer = new StreamWriter(stream))
-                writer.WriteLine($"@prefix rdf");
+                writer.Write($"@prefix rdf");
             Assert.ThrowsException<RDFModelException>(() => RDFTurtle.Deserialize(new MemoryStream(stream.ToArray()), null));
         }


Allow reading binary files by multiple readers at the same time (#127)

--- ISOv4Plugin/Mappers/TimeLogMapper.cs
+++ ISOv4Plugin/Mappers/TimeLogMapper.cs
@@ -496,7 +496,7 @@
                 if (!File.Exists(fileName))
                     yield break;

-                using (var binaryReader = new System.IO.BinaryReader(File.Open(fileName, FileMode.Open)))
+                using (var binaryReader = new System.IO.BinaryReader(File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
                 {
                     while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
                     {


Small output enhancement

Small output enhancement

--- ITCC.HTTP/Server/ServerStatistics.cs
+++ ITCC.HTTP/Server/ServerStatistics.cs
@@ -45,6 +45,8 @@
         ///     In milliseconds
         /// </summary>
         private double _totalRequestTime;
+
+        private string _slowestRequest;

         private long _requestCount;

@@ -117,18 +119,19 @@

                 var methodKeys = methodDict.Keys.ToList();
                 methodKeys.Sort();
-                methodKeys.ForEach(m => builder.AppendLine($"\t\t{m, 10}: { methodDict[m]}"));
+                methodKeys.ForEach(m => builder.AppendLine($"\t\t{m, -10}: { methodDict[m]}"));
             });
             builder.AppendLine();

             if (_requestCount > 0)
             {
                 builder.AppendLine("Total performance statistics:");
-                builder.AppendLine($"\tRequest count:        {_requestCount, 10} ms");
+                builder.AppendLine($"\tRequest count:        {_requestCount}");
                 builder.AppendLine($"\tAverage request time: {_totalRequestTime / _requestCount, 10} ms");
                 builder.AppendLine($"\tMax     request time: {_maxRequestTime, 10} ms");
                 builder.AppendLine($"\tMin     request time: {_minRequestTime, 10} ms");
                 builder.AppendLine($"\tTotal   request time: {_totalRequestTime, 10} ms");
+                builder.AppendLine($"\tSlowest request:      {_slowestRequest}");
             }

@@ -140,7 +143,11 @@
             InitOrIncrement(_responseCodes, response.StatusCode);

             _minRequestTime = Math.Min(processingTime, _minRequestTime);
-            _maxRequestTime = Math.Min(processingTime, _maxRequestTime);
+            if (processingTime > _maxRequestTime)
+            {
+                _maxRequestTime = processingTime;
+                _slowestRequest = uri;
+            }
             _totalRequestTime += processingTime;
             _requestCount++;


Add debugger display attribute

Add debugger display attribute

--- InfluxDB.WriteOnly/InfluxDbClient.cs
+++ InfluxDB.WriteOnly/InfluxDbClient.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.IO;
 using System.Net;
 using System.Net.Http;
@@ -15,6 +16,7 @@
         Task WriteAsync(string dbName, IEnumerable<Point> points);
     }

+    [DebuggerDisplay("Endpoint = {" + nameof(endpoint) + "}")]
     public class InfluxDbClient : IInfluxDbClient
     {
         private readonly InfluxDbClientOptions options;


refactor: optimize

refactor: optimize

--- Jasily/Threading/Tasks/UniqueTask.cs
+++ Jasily/Threading/Tasks/UniqueTask.cs
@@ -8,9 +8,9 @@
     {
         private bool isCompleted;
         private T result;
-        private readonly Func<Task<T>> taskFunc;
+        private Func<Task<T>> taskFunc;
         private Task<T> task;
-        private readonly object syncRoot = new object();
+        private object syncRoot = new object();

         public UniqueTask([NotNull] Func<Task<T>> taskFunc)
         {
@@ -36,6 +36,12 @@

             this.result = await this.task;
             this.isCompleted = true;
+
+            // remove
+            this.task = null;
+            this.syncRoot = null;
+            this.taskFunc = null;
+
             return this.result;
         }
     }
@@ -43,9 +49,9 @@
     public sealed class UniqueTask
     {
         private bool isCompleted;
-        private readonly Func<Task> taskFunc;
+        private Func<Task> taskFunc;
         private Task task;
-        private readonly object syncRoot = new object();
+        private object syncRoot = new object();

         public UniqueTask([NotNull] Func<Task> taskFunc)
         {
@@ -71,6 +77,11 @@

             await this.task;
             this.isCompleted = true;
+
+            // remove
+            this.task = null;
+            this.syncRoot = null;
+            this.taskFunc = null;
         }
     }
 }


Last tweaks for Contract System (relates to #92)

--- KerbalAlarmClock/KerbalAlarmClock.cs
+++ KerbalAlarmClock/KerbalAlarmClock.cs
@@ -158,14 +158,6 @@
             APIAwake();
         }

-        Boolean blnContractsSystemReady = false;
-        void ContractsReady()
-        {
-            LogFormatted("Contracts System Ready");
-            UpdateContractDetails();
-            blnContractsSystemReady = true;
-        }
-
         internal override void Start()
         {
             LogFormatted_DebugOnly("Start function-Setting up ScenarioModule");
@@ -221,6 +213,17 @@
             DestroyAppLauncherButton();

             APIDestroy();
+        }
+
+        Boolean blnContractsSystemReady = false;
+        void ContractsReady()
+        {
+            LogFormatted("Contracts System Ready");
+            //update the list
+            UpdateContractDetails();
+
+            //set the flag to say we can start processing contracts
+            blnContractsSystemReady = true;
         }

         #region "Update Code"
@@ -1272,9 +1275,8 @@
 		{
 			if(lstContracts==null) return;

+            //check the ready flag
             if (!blnContractsSystemReady) return;
-
-            LogFormatted("Contracts Count {0}", lstContracts.Count);

 			//check for expired/dead contracts
 			if (settings.ContractExpireDelete)


Fixed bug in deserialization method

Fixed bug in deserialization method

--- KnightMoves.Hierarchical/TreeNode.cs
+++ KnightMoves.Hierarchical/TreeNode.cs
@@ -514,8 +514,11 @@
                 {
                     n.IsSerializable = false;
                     n.Root = root;
-                    n.Parent = nodeIndex.Single(p => p.Id.Equals(n.ParentId));
-                    nodeIndex.Add(n);
+                    n.Parent = nodeIndex.First(p => p.Id.Equals(n.ParentId));
+                    if (!nodeIndex.Contains(n))
+                    {
+                        nodeIndex.Add(n);
+                    }
                     return true;
                 });
             }


Sort test repo list

Sort test repo list

--- Kudu.TestHarness/TestRepositories.cs
+++ Kudu.TestHarness/TestRepositories.cs
@@ -11,22 +11,22 @@
     {
         private static TestRepositoryInfo[] _repoList = new TestRepositoryInfo[]
         {
+            new TestRepositoryInfo("git@github.com:KuduQAOrg/RepoWithPrivateSubModule.git",         "4820516"),
+            new TestRepositoryInfo("https://github.com/KuduApps/Bakery.git",                        "2f29dc6"),
+            new TestRepositoryInfo("https://github.com/KuduApps/ConditionalCompilation.git",        "a104578"),
+            new TestRepositoryInfo("https://github.com/KuduApps/CustomBuildScript.git",             "2c156bd"),
+            new TestRepositoryInfo("https://github.com/KuduApps/CustomDeploymentSettingsTest.git",  "66e15f2"),
+            new TestRepositoryInfo("https://github.com/KuduApps/HangProcess.git",                   "2e53ab6"),
+            new TestRepositoryInfo("https://github.com/KuduApps/HelloKudu.git",                     "2370e44"),
             new TestRepositoryInfo("https://github.com/KuduApps/HelloWorld.git",                    "1f3dfd8"),
-            new TestRepositoryInfo("https://github.com/KuduApps/HelloKudu.git",                     "2370e44"),
+            new TestRepositoryInfo("https://github.com/KuduApps/Mvc3Application_NoSolution.git",    "4e36ca3"),
+            new TestRepositoryInfo("https://github.com/KuduApps/Mvc3AppWithTestProject.git",        "5df86e3"),
+            new TestRepositoryInfo("https://github.com/KuduApps/NodeHelloWorldNoConfig.git",        "d8a15b6"),
+            new TestRepositoryInfo("https://github.com/KuduApps/NoDeployableProjects.git",          "e21eb82"),
+            new TestRepositoryInfo("https://github.com/KuduApps/NpmSite.git",                       "2b29b9d"),
             new TestRepositoryInfo("https://github.com/KuduApps/VersionPinnedNodeJsApp.git",        "9461da6"),
-            new TestRepositoryInfo("https://github.com/KuduApps/CustomDeploymentSettingsTest.git",  "66e15f2"),
-            new TestRepositoryInfo("https://github.com/KuduApps/Mvc3AppWithTestProject.git",        "5df86e3"),
-            new TestRepositoryInfo("https://github.com/KuduApps/CustomBuildScript.git",             "2c156bd"),
             new TestRepositoryInfo("https://github.com/KuduApps/WarningsAsErrors.git",              "51b6a48"),
-            new TestRepositoryInfo("https://github.com/KuduApps/Mvc3Application_NoSolution.git",    "4e36ca3"),
-            new TestRepositoryInfo("https://github.com/KuduApps/NoDeployableProjects.git",          "e21eb82"),
-            new TestRepositoryInfo("https://github.com/KuduApps/ConditionalCompilation.git",        "a104578"),
             new TestRepositoryInfo("https://github.com/KuduApps/waws.git",                          "7652a66"),
-            new TestRepositoryInfo("https://github.com/KuduApps/Bakery.git",                        "2f29dc6"),
-            new TestRepositoryInfo("https://github.com/KuduApps/NpmSite.git",                       "2b29b9d"),
-            new TestRepositoryInfo("https://github.com/KuduApps/NodeHelloWorldNoConfig.git",        "d8a15b6"),
-            new TestRepositoryInfo("git@github.com:KuduQAOrg/RepoWithPrivateSubModule.git",         "4820516"),
-            new TestRepositoryInfo("https://github.com/KuduApps/HangProcess.git",                   "2e53ab6"),
         };

         private static Dictionary<string, TestRepositoryInfo> _repos;


Fix mistakes in HybridDictionary<,>, use KeyComparer property

Fix mistakes in HybridDictionary<,>, use this.KeyComparer.Equals method instead
of default Object.Equals method.

--- Linx/Collections/HybridDictionary.cs
+++ Linx/Collections/HybridDictionary.cs
@@ -476,7 +476,7 @@
         {
             TKey key;
             return this.KeySelector == null
-                || this.KeySelector(index, this[key = this.Keys[index]]).Equals(key);
+                || this.KeyComparer.Equals(this.KeySelector(index, this[key = this.Keys[index]]), key);
         }

         public Boolean RemoveValue(TValue item)
@@ -552,7 +552,7 @@
                     : indexes.ZipWith(
                           keys,
                           values,
-                          (i_, k_, v_) => this.KeySelector(i_, v_).Equals(k_)
+                          (i_, k_, v_) => this.KeyComparer.Equals(this.KeySelector(i_, v_), k_)
                       ),
                 (i, k, v, c) => new Tuple(i, k, v, c)
             );
@@ -598,14 +598,14 @@
                         : indexes.ZipWith(
                               keys,
                               values,
-                              (i_, k_, v_) => this.KeySelector(i_, v_).Equals(k_)
+                              (i_, k_, v_) => this.KeyComparer.Equals(this.KeySelector(i_, v_), k_)
                           ),
                     (i, k, v, c) => new Tuple(i, k, v, c)
                 )
                 .ToList();
             foreach (Tuple e in elements)
             {
-                if (this.Keys[e.Index].Equals(e.Key))
+                if (this.KeyComparer.Equals(this.Keys[e.Index], e.Key))
                 {
                     this[e.Key] = e.Value;
                 }


Shared mode mutex is now global

Shared mode mutex is now global

--- LiteDB/Client/Shared/SharedEngine.cs
+++ LiteDB/Client/Shared/SharedEngine.cs
@@ -23,7 +23,7 @@

             try
             {
-                _mutex = new Mutex(false, name + ".Mutex");
+                _mutex = new Mutex(false, "Global\\" + name + ".Mutex");
             }
             catch(NotSupportedException ex)
             {


added site.css to bundles part of viewport fix

--- MPGTracker/App_Start/BundleConfig.cs
+++ MPGTracker/App_Start/BundleConfig.cs
@@ -25,7 +25,7 @@
             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                         "~/Scripts/modernizr-*"));

-            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css",  "~/Content/bootstrap-responsive.css", "~/Content/jquery-ui.css"));
+            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css",  "~/Content/bootstrap-responsive.css", "~/Content/jquery-ui.css", "~/Content/site.css"));

             bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                         "~/Content/themes/base/jquery.ui.core.css",


Run index creation as long running task

Run index creation as long running task

--- MatterControlLib/LuceneHelpSearch.cs
+++ MatterControlLib/LuceneHelpSearch.cs
@@ -1,7 +1,10 @@

+using System;
 using System.Collections.Generic;
 using System.IO.Compression;
 using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
 using Lucene.Net.Analysis.Standard;
 using Lucene.Net.Documents;
 using Lucene.Net.Index;
@@ -9,7 +12,9 @@
 using Lucene.Net.Search;
 using Lucene.Net.Store;
 using Lucene.Net.Util;
+using MatterHackers.Agg;
 using MatterHackers.Agg.Platform;
+using MatterHackers.Localizations;
 using MatterHackers.MatterControl;
 using MatterHackers.MatterControl.DataStorage;
 using MatterHackers.MatterControl.PartPreviewWindow;
@@ -40,7 +45,21 @@

 			writer = new IndexWriter(dir, indexConfig);

-			//IndexDocuments();
+			// If the index lacks a reasonable number of documents, rebuild it from the zip file
+			if (writer.MaxDoc < 10)
+			{
+				ApplicationController.Instance.Tasks.Execute(
+					"Preparing help index".Localize(),
+					null,
+					(progress, cancellationToken) =>
+					{
+						string relativePath = System.IO.Path.Combine("OemSettings", "help-docs.zip");
+
+						IndexZipFile(relativePath, progress, cancellationToken);
+
+						return Task.CompletedTask;
+					});
+			}
 		}

 		public LuceneHelpSearch()
@@ -58,7 +77,7 @@
 			}
 		}

-		private static void IndexDocuments()
+		private static void IndexZipFile(string filePath, IProgress<ProgressStatus> progress, CancellationToken cancellationToken)
 		{
 			Dictionary<string, HelpArticle> helpArticles;

@@ -66,10 +85,9 @@
 			writer.DeleteAll();

 			// Build index from help-docs.zip
-			using (var file = AggContext.StaticData.OpenStream(System.IO.Path.Combine("OemSettings", "help-docs.zip")))
+			using (var file = AggContext.StaticData.OpenStream(filePath))
 			using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
 			{
-
 				var tocEntry = zip.Entries.FirstOrDefault(e => e.FullName == "toc.json");

 				using (var docStream = tocEntry.Open())
@@ -85,8 +103,28 @@
 					ProcessHelpTree(rootHelpArticle, helpArticles);
 				}

+				var progressStatus = new ProgressStatus()
+				{
+					//Status = "",
+					Progress0To1 = 0
+				};
+
+				var count = zip.Entries.Count;
+				double i = 0;
+
 				foreach (var entry in zip.Entries)
 				{
+					progressStatus.Progress0To1 = i++ / count;
+					progress.Report(progressStatus);
+
+					// Observe and abort on cancellationToken signal
+					if (cancellationToken.IsCancellationRequested)
+					{
+						writer.DeleteAll();
+						writer.Commit();
+						return;
+					}
+
 					if (entry.FullName.ToLower().EndsWith(".md"))
 					{
 						using (var docStream = entry.Open())


implemented meetup delete api

implemented meetup delete api

--- MeetU/MeetU/API/MeetupsController.cs
+++ MeetU/MeetU/API/MeetupsController.cs
@@ -1,4 +1,5 @@
-using System.Data;
+using System;
+using System.Data;
 using System.Data.Entity;
 using System.Data.Entity.Infrastructure;
 using System.Linq;
@@ -7,6 +8,7 @@
 using System.Web.Http;
 using System.Web.Http.Description;
 using MeetU.Models;
+using Microsoft.AspNet.Identity;

 namespace MeetU.API
 {
@@ -141,11 +143,11 @@
                 .Where(m => m.IsCancelled == false)
                 .FirstOrDefaultAsync(x => x.Id == id);
             if (meetup == null)
-            {
                 return NotFound();
-            }
-
-            db.Meetups.Remove(meetup);
+            if(meetup.Sponsor != User.Identity.GetUserId())
+                return BadRequest();
+            meetup.IsCancelled = true;
+            meetup.CancelledAt = DateTime.Now;
             await db.SaveChangesAsync();

             return Ok(meetup);


Gray code

Gray code

--- LeetCode/remote/gray_code.cs
+++ LeetCode/remote/gray_code.cs
@@ -35,6 +35,36 @@
                    })
                .Select(x => Convert.ToInt32(x.ToString(), 2))
                .ToList();
+    }
+}
+
+//  Lol regression
+//  https://leetcode.com/submissions/detail/65770834/
+//
+//  Submission Details
+//  12 / 12 test cases passed.
+//      Status: Accepted
+//      Runtime: 429 ms
+//
+//          Submitted: 0 minutes ago
+public class Solution {
+    public IList<int> GrayCode(int n) {
+        if (n == 0) {
+            return new List<int> { 0 };
+        }
+
+        return Gray(n).Select(x => x.Take(n).Aggregate(0, (acc, y) => (acc << 1) | y)).ToList();
+    }
+
+    public IList<IList<int>> Gray(int n) {
+        if (n == 0) {
+            return new List<IList<int>> { new List<int> { 0 } };
+        }
+
+        var previous = Gray(n - 1);
+        return previous.Select(x => new List<int> { 0 }.Concat(x).ToList())
+               .Concat(previous.Reverse().Select(x => new List<int> { 1 }.Concat(x).ToList()))
+               .ToList<IList<int>>();
     }
 }


Green: Can delete with converter

Green: Can delete with converter

--- LazyStorage/InMemory/InMemoryRepositoryWithConverter.cs
+++ LazyStorage/InMemory/InMemoryRepositoryWithConverter.cs
@@ -52,8 +52,8 @@
         {
             var storableItem = m_Converter.GetStorableObject(item);

-            var obj = m_Repository.SingleOrDefault(x => x.Id == storableItem.Id);
-            m_Repository.Remove(obj);
+            var obj = m_Repository.Where(x => m_Converter.IsEqual(storableItem, item));
+            m_Repository.Remove(obj.First());
         }


Added more tests for DeleteRole and GetUsersInRole.

--- MongoDB.Web.Test/TestRoleProvider.cs
+++ MongoDB.Web.Test/TestRoleProvider.cs
@@ -192,7 +192,7 @@
         }

         [Test]
-        public void TestDeleteRoleWhenPopulated() {
+        public void TestDeleteRoleWhenPopulatedWithNoThrowOnPopulated() {
             var membershipConfig = new NameValueCollection(_membershipConfig);
             var roleConfig = new NameValueCollection(_roleConfig);

@@ -214,6 +214,30 @@
             roleProvider.DeleteRole("role1", false);
             Assert.IsFalse(roleProvider.RoleExists("role1"));
             Assert.Throws<ArgumentException>(() => roleProvider.IsUserInRole("user1", "role1"));
+        }
+
+        [Test]
+        public void TestDeleteRoleWhenPopulatedWithThrowOnPopulated() {
+            var membershipConfig = new NameValueCollection(_membershipConfig);
+            var roleConfig = new NameValueCollection(_roleConfig);
+
+            var membershipProvider = new MongoMembershipProvider();
+            membershipProvider.Initialize(DefaultMembershipName, membershipConfig);
+
+            var roleProvider = new MongoRoleProvider();
+            roleProvider.Initialize(DefaultRoleName, roleConfig);
+
+            MembershipCreateStatus status;
+            membershipProvider.CreateUser("user1", "123456", "test@test.com", null, null, true, null, out status);
+            membershipProvider.CreateUser("user2", "123456", "test@test.com", null, null, true, null, out status);
+
+            roleProvider.CreateRole("role1");
+            roleProvider.CreateRole("role2");
+
+            roleProvider.AddUsersToRoles(new[] { "user1", "user2" }, new[] { "role1", "role2" });
+
+
+            Assert.Throws<ProviderException>(() => roleProvider.DeleteRole("role1", true));
         }

         #endregion
@@ -350,6 +374,28 @@
             Assert.Contains("user2", userNames);
         }

+        [Test]
+        public void TestGetUsersInRoleWhenNoUsersInRole() {
+            var membershipConfig = new NameValueCollection(_membershipConfig);
+            var roleConfig = new NameValueCollection(_roleConfig);
+
+            var membershipProvider = new MongoMembershipProvider();
+            membershipProvider.Initialize(DefaultMembershipName, membershipConfig);
+
+            var roleProvider = new MongoRoleProvider();
+            roleProvider.Initialize(DefaultRoleName, roleConfig);
+
+            MembershipCreateStatus status;
+            membershipProvider.CreateUser("user1", "123456", "test@test.com", null, null, true, null, out status);
+            membershipProvider.CreateUser("user2", "123456", "test@test.com", null, null, true, null, out status);
+            membershipProvider.CreateUser("user3", "123456", "test@test.com", null, null, true, null, out status);
+
+            roleProvider.CreateRole("role1");
+
+            var userNames = roleProvider.GetUsersInRole("role1");
+            Assert.AreEqual(0, userNames.Length);
+        }
+
         #endregion

     }


Window menu

Window menu

--- Library/Software/WpfApplication/Ultimate/MainMenuBus.cs
+++ Library/Software/WpfApplication/Ultimate/MainMenuBus.cs
@@ -13,6 +13,7 @@
         {
             menu.AddCommand(TopMenuKey.File, "_File");
             menu.AddCommand(TopMenuKey.Option, "_Option");
+            menu.AddCommand(TopMenuKey.Window, "_Window");
             menu.AddCommand(TopMenuKey.Help, "_Help");

             menu.AddCommandChild(TopMenuKey.File, SubMenuKey.FileExit, "E_xit");
@@ -22,6 +23,12 @@
             Tooltip = "Provides information and files for you to seek help or report issues."};

             menu.AddCommand(seed);
+
+            menu.AddCommandChild(TopMenuKey.Window, SubMenuKey.SaveUserPlacement, "Save Placement");
+            menu.AddCommand(new MenuSeed<SubMenuKey>() { ParentKey = TopMenuKey.Window, Key = SubMenuKey.SaveAsPlacement,
+                Label = "Save Placement As...", DebugOnly = true });
+            menu.AddCommandChild(TopMenuKey.Window, SubMenuKey.ReadUserPlacement, "Restore Own Placement");
+            menu.AddCommandChild(TopMenuKey.Window, SubMenuKey.ReadDefaultPlacement, "Restore Default Placement");
         }

         protected override void HandleButton(ButtonMessage<SubMenuKey> m)


Fixed sometimes failing test to properly assert

--- src/MassTransit.AutomatonymousIntegration.Tests/EnterEvent_Specs.cs
+++ src/MassTransit.AutomatonymousIntegration.Tests/EnterEvent_Specs.cs
@@ -34,7 +34,7 @@
                 CorrelationId = sagaId
             });

-            Guid? saga = await _repository.ShouldContainSaga(x => x.CorrelationId == sagaId && Equals(x.CurrentState, _machine.Running), TestTimeout);
+            Guid? saga = await _repository.ShouldContainSaga(x => x.CorrelationId == sagaId && Equals(x.CurrentState, _machine.RunningFaster), TestTimeout);
             Assert.IsTrue(saga.HasValue);

             Assert.AreEqual(1, _repository[saga.Value].Instance.OnEnter);
@@ -101,10 +101,11 @@
                 {
                     Console.WriteLine("Running.Enter:Then");
                     context.Instance.OnEnter = context.Instance.Counter;
-                }));
+                }).TransitionTo(RunningFaster));
             }

             public State Running { get; private set; }
+            public State RunningFaster { get; private set; }
             public Event<Start> Started { get; private set; }
             public Event<Stop> Stopped { get; private set; }
         }


Update GenericModelBinder.BindModel to use correct overload of Activator.CreateInstance

--- src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs
+++ src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs
@@ -21,7 +21,7 @@
             Type binderType = ResolveBinderType(bindingContext.ModelType);
             if (binderType != null)
             {
-                var binder = _activator.CreateInstance<IModelBinder>();
+                var binder = (IModelBinder)_activator.CreateInstance(binderType);
                 return binder.BindModel(bindingContext);
             }


解决表体为空抛异常的问题

解决表体为空抛异常的问题

--- NPOIHelper/NPOI/Excel/ExcelHelper.cs
+++ NPOIHelper/NPOI/Excel/ExcelHelper.cs
@@ -124,7 +124,7 @@

                     if (!body.Any())
                     {
-                        throw new Exception("没有需要导出的数据");
+                        //throw new Exception("没有需要导出的数据");
                     }

                     //表头


Ignoring a test that fails of slow machines

--- Rhino.Etl.Tests/LoadTest/LoadTestJoinsFixture.cs
+++ Rhino.Etl.Tests/LoadTest/LoadTestJoinsFixture.cs
@@ -7,6 +7,7 @@
 	public class LoadTestJoinsFixture
 	{
 		[Test]
+        [Ignore("It depends too much of what the machine is doing and how powerful it is")]
 		public void CanDoLargeJoinsefficently()
 		{
 			Stopwatch stopwatch = Stopwatch.StartNew();


ApplicationInsightsSink updated to use ITelemetryInitializer instead of IContextInitializer

--- SLAB_AI/SLAB_AI/Sinks/ApplicationInsightsSink.cs
+++ SLAB_AI/SLAB_AI/Sinks/ApplicationInsightsSink.cs
@@ -28,8 +28,8 @@
         /// <exception cref="ArgumentNullException">Thrown if InstrumentationKey value is null.</exception>
         /// <exception cref="ArgumentException">Thrown if the InstrumentationKey is empty</exception>
         /// <param name="InstrumentationKey">The ID that determines the application component under which your data appears in Application Insights.</param>
-        /// <param name="contextInitializers">The (optional) Application Insights context initializers.</param>
-        public ApplicationInsightsSink(String InstrumentationKey, params IContextInitializer[] contextInitializers)
+        /// <param name="telemetryInitializers">The (optional) Application Insights telemetry initializers.</param>
+        public ApplicationInsightsSink(String InstrumentationKey, params ITelemetryInitializer[] telemetryInitializers)
         {
             telemetryClient = new TelemetryClient();
             if (InstrumentationKey == null)
@@ -44,11 +44,11 @@

             TelemetryConfiguration.Active.InstrumentationKey = InstrumentationKey;

-            if (contextInitializers != null)
+            if (telemetryInitializers != null)
             {
-                foreach (var contextInitializer in contextInitializers)
+                foreach (var telemetryInitializer in telemetryInitializers)
                 {
-                    TelemetryConfiguration.Active.ContextInitializers.Add(contextInitializer);
+                    TelemetryConfiguration.Active.TelemetryInitializers.Add(telemetryInitializer);
                 }
             }
         }


PAE-30: More security fixes

PAE-30: More security fixes

--- src/Modules/Manage/Dnn.PersonaBar.Roles/Services/RolesController.cs
+++ src/Modules/Manage/Dnn.PersonaBar.Roles/Services/RolesController.cs
@@ -96,6 +96,12 @@
                 else
                 {
                     var existingRole = RoleController.Instance.GetRoleById(PortalId, roleDto.Id);
+                    if (existingRole == null)
+                    {
+                        return Request.CreateErrorResponse(HttpStatusCode.NotFound,
+                            Localization.GetString("RoleNotFound", Components.Constants.LocalResourcesFile));
+                    }
+
                     if (existingRole.IsSystemRole)
                     {
                         if (role.Description != existingRole.Description)//In System roles only description can be updated.


Code cleanup for #1755

Code cleanup for #1755

--- src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs
+++ src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs
@@ -17,11 +17,10 @@
         /// Adds services required for OpenAPI 3.0 generation (change document settings to generate Swagger 2.0).
         /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
         /// <param name="configure">Configure the document.</param>
-        public static IServiceCollection AddOpenApiDocument(this IServiceCollection serviceCollection, Action<SwaggerDocumentSettings> configure = null)
+        public static IServiceCollection AddOpenApiDocument(this IServiceCollection serviceCollection, Action<SwaggerDocumentSettings> configure)
         {
-            return AddSwaggerDocument(serviceCollection, settings =>
+            return AddOpenApiDocument(serviceCollection, (settings, services) =>
             {
-                settings.SchemaType = SchemaType.OpenApi3;
                 configure?.Invoke(settings);
             });
         }
@@ -41,8 +40,7 @@
         /// Adds services required for Swagger 2.0 generation (change document settings to generate OpenAPI 3.0).
         /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
         /// <param name="configure">Configure the document.</param>
-        public static IServiceCollection AddSwaggerDocument(this IServiceCollection serviceCollection,
-            Action<SwaggerDocumentSettings> configure = null)
+        public static IServiceCollection AddSwaggerDocument(this IServiceCollection serviceCollection, Action<SwaggerDocumentSettings> configure)
         {
             return AddSwaggerDocument(serviceCollection, (settings, services) =>
             {
@@ -55,12 +53,12 @@
         /// <param name="configure">Configure the document.</param>
         public static IServiceCollection AddSwaggerDocument(this IServiceCollection serviceCollection, Action<SwaggerDocumentSettings, IServiceProvider> configure = null)
         {
-            serviceCollection.AddSingleton(s =>
+            serviceCollection.AddSingleton(services =>
             {
                 var settings = new SwaggerDocumentSettings();
                 settings.SchemaType = SchemaType.Swagger2;

-                configure?.Invoke(settings, s);
+                configure?.Invoke(settings, services);

                 if (settings.PostProcess != null)
                 {
@@ -68,12 +66,12 @@
                     settings.DocumentProcessors.Add(processor);
                 }

-                foreach (var documentProcessor in s.GetRequiredService<IEnumerable<IDocumentProcessor>>())
+                foreach (var documentProcessor in services.GetRequiredService<IEnumerable<IDocumentProcessor>>())
                 {
                     settings.DocumentProcessors.Add(documentProcessor);
                 }

-                foreach (var operationProcessor in s.GetRequiredService<IEnumerable<IOperationProcessor>>())
+                foreach (var operationProcessor in services.GetRequiredService<IEnumerable<IOperationProcessor>>())
                 {
                     settings.OperationProcessors.Add(operationProcessor);
                 }


No word wrap, and show scrollbars if necessary.

--- Sandra.UI.WF.Chess/MdiContainerForm.UIActions.cs
+++ Sandra.UI.WF.Chess/MdiContainerForm.UIActions.cs
@@ -106,6 +106,8 @@
                         Font = new Font("Consolas", 10),
                         Text = File.ReadAllText(Program.DefaultSettings.AbsoluteFilePath),
                         ReadOnly = true,
+                        WordWrap = false,
+                        ScrollBars = RichTextBoxScrollBars.Both,
                     };

                     settingsTextBox.BindActions(new UIActionBindings


fixed test expectations

fixed test expectations

--- src/Simple.OData.Client.UnitTests/Core/TypedDataAggregationTests.cs
+++ src/Simple.OData.Client.UnitTests/Core/TypedDataAggregationTests.cs
@@ -207,7 +207,7 @@
                     }));

             var commandText = await command.GetCommandTextAsync();
-            Assert.Equal("Products?$apply=filter%28Category%2FCategoryName%20in%20%28%27Beverage%27%2C%27Food%27%29%29%2Fgroupby%28%28Category%2FCategoryName%29%2Caggregate%28UnitPrice%20with%20average%20as%20AverageUnitPrice%29%29", commandText);
+            Assert.Equal("Products?$apply=filter%28%28Category%2FCategoryName%20in%20%28%27Beverage%27%2C%27Food%27%29%29%29%2Fgroupby%28%28Category%2FCategoryName%29%2Caggregate%28UnitPrice%20with%20average%20as%20AverageUnitPrice%29%29", commandText);
         }

         [Fact]


simplify use of application convention

simplify use of application convention

--- src/Swashbuckle.Swagger/Application/SwaggerApplicationConvention.cs
+++ src/Swashbuckle.Swagger/Application/SwaggerApplicationConvention.cs
@@ -1,6 +1,4 @@
-using System.Linq;
-using Microsoft.AspNet.Mvc;
-using Microsoft.AspNet.Mvc.ApplicationModels;
+using Microsoft.AspNet.Mvc.ApplicationModels;

 namespace Swashbuckle.Application
 {
@@ -8,41 +6,11 @@
     {
         public void Apply(ApplicationModel application)
         {
+            application.ApiExplorer.IsVisible = true;
             foreach (var controller in application.Controllers)
             {
-                ApplyControllerConvention(controller);
+                controller.ApiExplorer.GroupName = controller.ControllerName;
             }
-        }
-
-        private void ApplyControllerConvention(ControllerModel controller)
-        {
-            foreach (var action in controller.Actions)
-            {
-                if (ApiExplorerShouldIgnore(action))
-                {
-                    action.ApiExplorer.IsVisible = false;
-                }
-                else
-                {
-                    action.ApiExplorer.IsVisible = true;
-                    action.ApiExplorer.GroupName = controller.ControllerName;
-                }
-            }
-        }
-
-        private bool ApiExplorerShouldIgnore(ActionModel action)
-        {
-            var actionSettings = action.Attributes
-                .OfType<ApiExplorerSettingsAttribute>()
-                .FirstOrDefault();
-            if (actionSettings != null) return actionSettings.IgnoreApi;
-
-            var controllerSettings = action.Controller.Attributes
-                .OfType<ApiExplorerSettingsAttribute>()
-                .FirstOrDefault();
-            if (controllerSettings != null) return controllerSettings.IgnoreApi;
-
-            return false;
         }
     }
 }


improve memory

improve memory

--- LifegameGame/MinMaxPlayer.cs
+++ LifegameGame/MinMaxPlayer.cs
@@ -47,7 +47,7 @@
 		/// </summary>
 		/// <param name="p"></param>
 		/// <param name="isMin">minを求めるならtrue</param>
-		float EvalPosition(BoardInstance board, Point p, int depth, CellState side)
+		protected virtual float EvalPosition(BoardInstance board, Point p, int depth, CellState side)
 		{
 			EvalCount++;
 			Board.PlayingBoard = board;
@@ -70,22 +70,25 @@
 			}
 			else
 			{
-				List<float> scores = new List<float>();
-				foreach (var item in GetPlayablePoints())
+				return GetBestChild(next, depth, side);
+			}
+		}
+
+		protected virtual float GetBestChild(BoardInstance next, int depth, CellState side)
+		{
+			List<float> scores = new List<float>();
+			float current = (this.Side == side ? float.MinValue : float.MaxValue);
+			foreach (var item in GetPlayablePoints())
+			{
+				//var b = Board.VirtualPlay(Side, item);
+				//float score = Board.EvalScore();
+				float score = (EvalPosition(next, item, depth - 1, side == CellState.White ? CellState.Black : CellState.White));
+				if ((this.Side == side && score > current) || (this.Side != side && score < current))
 				{
-					//var b = Board.VirtualPlay(Side, item);
-					//float score = Board.EvalScore();
-					scores.Add(EvalPosition(next, item, depth - 1, side == CellState.White ? CellState.Black : CellState.White));
-				}
-				if (this.Side != side)
-				{
-					return scores.Min();
-				}
-				else
-				{
-					return scores.Max();
+					current = score;
 				}
 			}
+			return current;
 		}