Update PathGeometryConverter.cs

Update PathGeometryConverter.cs

--- src/Core2D/Modules/Renderer/SkiaSharp/PathGeometryConverter.cs
+++ src/Core2D/Modules/Renderer/SkiaSharp/PathGeometryConverter.cs
@@ -16,59 +16,89 @@

 public static class PathGeometryConverter
 {
-    public static void CreateFigure(this PathFigureViewModel pathFigure, SKPath path)
-    {
+    private static bool CreateFigure(this PathFigureViewModel figure, SKPath path)
+    {
+        if (figure.StartPoint is null)
+        {
+            return false;
+        }
+
         path.MoveTo(
-            (float)(pathFigure.StartPoint.X),
-            (float)(pathFigure.StartPoint.Y));
-
-        foreach (var segment in pathFigure.Segments)
-        {
-            if (segment is LineSegmentViewModel lineSegment)
+            (float)figure.StartPoint.X,
+            (float)figure.StartPoint.Y);
+
+        foreach (var segment in figure.Segments)
+        {
+            switch (segment)
             {
-                path.LineTo(
-                    (float)(lineSegment.Point.X),
-                    (float)(lineSegment.Point.Y));
+                case LineSegmentViewModel lineSegment:
+                {
+                    if (lineSegment.Point is null)
+                    {
+                        return false;
+                    }
+                    path.LineTo(
+                        (float)lineSegment.Point.X,
+                        (float)lineSegment.Point.Y);
+                    break;
+                }
+                case CubicBezierSegmentViewModel cubicBezierSegment:
+                {
+                    if (cubicBezierSegment.Point1 is null || cubicBezierSegment.Point2 is null || cubicBezierSegment.Point3 is null)
+                    {
+                        return false;
+                    }
+                    path.CubicTo(
+                        (float)cubicBezierSegment.Point1.X,
+                        (float)cubicBezierSegment.Point1.Y,
+                        (float)cubicBezierSegment.Point2.X,
+                        (float)cubicBezierSegment.Point2.Y,
+                        (float)cubicBezierSegment.Point3.X,
+                        (float)cubicBezierSegment.Point3.Y);
+                    break;
+                }
+                case QuadraticBezierSegmentViewModel quadraticBezierSegment:
+                {
+                    if (quadraticBezierSegment.Point1 is null || quadraticBezierSegment.Point2 is null)
+                    {
+                        return false;
+                    }
+                    path.QuadTo(
+                        (float)quadraticBezierSegment.Point1.X,
+                        (float)quadraticBezierSegment.Point1.Y,
+                        (float)quadraticBezierSegment.Point2.X,
+                        (float)quadraticBezierSegment.Point2.Y);
+                    break;
+                }
+                case ArcSegmentViewModel arcSegment:
+                {
+                    if (arcSegment.Point is null || arcSegment.Size is null)
+                    {
+                        return false;
+                    }
+                    path.ArcTo(
+                        (float)arcSegment.Size.Width,
+                        (float)arcSegment.Size.Height,
+                        (float)arcSegment.RotationAngle,
+                        arcSegment.IsLargeArc ? SKPathArcSize.Large : SKPathArcSize.Small,
+                        arcSegment.SweepDirection == SweepDirection.Clockwise
+                            ? SKPathDirection.Clockwise
+                            : SKPathDirection.CounterClockwise,
+                        (float)arcSegment.Point.X,
+                        (float)arcSegment.Point.Y);
+                    break;
+                }
+                default:
+                    throw new NotSupportedException("Not supported segment type: " + segment.GetType());
             }
-            else if (segment is QuadraticBezierSegmentViewModel quadraticBezierSegment)
-            {
-                path.QuadTo(
-                    (float)(quadraticBezierSegment.Point1.X),
-                    (float)(quadraticBezierSegment.Point1.Y),
-                    (float)(quadraticBezierSegment.Point2.X),
-                    (float)(quadraticBezierSegment.Point2.Y));
-            }
-            else if (segment is CubicBezierSegmentViewModel cubicBezierSegment)
-            {
-                path.CubicTo(
-                    (float)(cubicBezierSegment.Point1.X),
-                    (float)(cubicBezierSegment.Point1.Y),
-                    (float)(cubicBezierSegment.Point2.X),
-                    (float)(cubicBezierSegment.Point2.Y),
-                    (float)(cubicBezierSegment.Point3.X),
-                    (float)(cubicBezierSegment.Point3.Y));
-            }
-            else if (segment is ArcSegmentViewModel arcSegment)
-            {
-                path.ArcTo(
-                    (float)(arcSegment.Size.Width),
-                    (float)(arcSegment.Size.Height),
-                    (float)arcSegment.RotationAngle,
-                    arcSegment.IsLargeArc ? SKPathArcSize.Large : SKPathArcSize.Small,
-                    arcSegment.SweepDirection == SweepDirection.Clockwise ? SKPathDirection.Clockwise : SKPathDirection.CounterClockwise,
-                    (float)(arcSegment.Point.X),
-                    (float)(arcSegment.Point.Y));
-            }
-            else
-            {
-                throw new NotSupportedException("Not supported segment type: " + segment.GetType());
-            }
-        }
-
-        if (pathFigure.IsClosed)
+        }
+
+        if (figure.IsClosed)
         {
             path.Close();
         }
+
+        return true;
     }

     public static PathShapeViewModel ToPathGeometry(SKPath path, IViewModelFactory viewModelFactory)
@@ -82,7 +112,7 @@

         using var iterator = path.CreateRawIterator();
         var points = new SKPoint[4];
-        var pathVerb = SKPathVerb.Move;
+        SKPathVerb pathVerb;

         while ((pathVerb = iterator.Next(points)) != SKPathVerb.Done)
         {
@@ -93,33 +123,29 @@
                     context.BeginFigure(
                         viewModelFactory.CreatePointShape(points[0].X, points[0].Y),
                         false);
-                }
-                    break;
-
+                    break;
+                }
                 case SKPathVerb.Line:
                 {
                     context.LineTo(
                         viewModelFactory.CreatePointShape(points[1].X, points[1].Y));
-                }
-                    break;
-
+                    break;
+                }
                 case SKPathVerb.Cubic:
                 {
                     context.CubicBezierTo(
                         viewModelFactory.CreatePointShape(points[1].X, points[1].Y),
                         viewModelFactory.CreatePointShape(points[2].X, points[2].Y),
                         viewModelFactory.CreatePointShape(points[3].X, points[3].Y));
-                }
-                    break;
-
+                    break;
+                }
                 case SKPathVerb.Quad:
                 {
                     context.QuadraticBezierTo(
                         viewModelFactory.CreatePointShape(points[1].X, points[1].Y),
                         viewModelFactory.CreatePointShape(points[2].X, points[2].Y));
-                }
-                    break;
-
+                    break;
+                }
                 case SKPathVerb.Conic:
                 {
                     var quads = SKPath.ConvertConicToQuads(points[0], points[1], points[2], iterator.ConicWeight(), 1);
@@ -129,21 +155,20 @@
                     context.QuadraticBezierTo(
                         viewModelFactory.CreatePointShape(quads[3].X, quads[3].Y),
                         viewModelFactory.CreatePointShape(quads[4].X, quads[4].Y));
-                }
-                    break;
-
+                    break;
+                }
                 case SKPathVerb.Close:
                 {
                     context.SetClosedState(true);
-                }
-                    break;
+                    break;
+                }
             }
         }

         return geometry;
     }

-    public static SKPath ToSKPath(this IEnumerable<BaseShapeViewModel> shapes)
+    public static SKPath? ToSKPath(this IEnumerable<BaseShapeViewModel> shapes)
     {
         var path = new SKPath
         {
@@ -156,122 +181,162 @@
             {
                 case LineShapeViewModel lineShape:
                 {
+                    if (lineShape.Start is null || lineShape.End is null)
+                    {
+                        return null;
+                    }
                     if (previous is null || previous != lineShape.Start)
                     {
                         path.MoveTo(
-                            (float)(lineShape.Start.X),
-                            (float)(lineShape.Start.Y));
+                            (float)lineShape.Start.X,
+                            (float)lineShape.Start.Y);
                     }
                     path.LineTo(
-                        (float)(lineShape.End.X),
-                        (float)(lineShape.End.Y));
+                        (float)lineShape.End.X,
+                        (float)lineShape.End.Y);
                     previous = lineShape.End;
-                }
-                    break;
-
+                    break;
+                }
                 case RectangleShapeViewModel rectangleShape:
                 {
+                    if (rectangleShape.TopLeft is null || rectangleShape.BottomRight is null)
+                    {
+                        return null;
+                    }
                     path.AddRect(
-                        SkiaSharpDrawUtil.CreateRect(rectangleShape.TopLeft, rectangleShape.BottomRight),
-                        SKPathDirection.Clockwise);
-                }
-                    break;
-
+                        SkiaSharpDrawUtil.CreateRect(rectangleShape.TopLeft, rectangleShape.BottomRight));
+                    break;
+                }
                 case EllipseShapeViewModel ellipseShape:
                 {
+                    if (ellipseShape.TopLeft is null || ellipseShape.BottomRight is null)
+                    {
+                        return null;
+                    }
                     path.AddOval(
-                        SkiaSharpDrawUtil.CreateRect(ellipseShape.TopLeft, ellipseShape.BottomRight),
-                        SKPathDirection.Clockwise);
-                }
-                    break;
-
+                        SkiaSharpDrawUtil.CreateRect(ellipseShape.TopLeft, ellipseShape.BottomRight));
+                    break;
+                }
                 case ArcShapeViewModel arcShape:
                 {
+                    if (arcShape.Point1 is null
+                        || arcShape.Point2 is null
+                        || arcShape.Point3 is null
+                        || arcShape.Point4 is null)
+                    {
+                        return null;
+                    }
                     var a = new GdiArc(
                         Point2.FromXY(arcShape.Point1.X, arcShape.Point1.Y),
                         Point2.FromXY(arcShape.Point2.X, arcShape.Point2.Y),
                         Point2.FromXY(arcShape.Point3.X, arcShape.Point3.Y),
                         Point2.FromXY(arcShape.Point4.X, arcShape.Point4.Y));
                     var rect = new SKRect(
-                        (float)(a.X),
-                        (float)(a.Y),
+                        (float)a.X,
+                        (float)a.Y,
                         (float)(a.X + a.Width),
                         (float)(a.Y + a.Height));
                     path.AddArc(rect, (float)a.StartAngle, (float)a.SweepAngle);
-                }
-                    break;
-
+                    break;
+                }
                 case CubicBezierShapeViewModel cubicBezierShape:
                 {
+                    if (cubicBezierShape.Point1 is null
+                        || cubicBezierShape.Point2 is null
+                        || cubicBezierShape.Point3 is null
+                        || cubicBezierShape.Point4 is null)
+                    {
+                        return null;
+                    }
                     if (previous is null || previous != cubicBezierShape.Point1)
                     {
                         path.MoveTo(
-                            (float)(cubicBezierShape.Point1.X),
-                            (float)(cubicBezierShape.Point1.Y));
+                            (float)cubicBezierShape.Point1.X,
+                            (float)cubicBezierShape.Point1.Y);
                     }
                     path.CubicTo(
-                        (float)(cubicBezierShape.Point2.X),
-                        (float)(cubicBezierShape.Point2.Y),
-                        (float)(cubicBezierShape.Point3.X),
-                        (float)(cubicBezierShape.Point3.Y),
-                        (float)(cubicBezierShape.Point4.X),
-                        (float)(cubicBezierShape.Point4.Y));
+                        (float)cubicBezierShape.Point2.X,
+                        (float)cubicBezierShape.Point2.Y,
+                        (float)cubicBezierShape.Point3.X,
+                        (float)cubicBezierShape.Point3.Y,
+                        (float)cubicBezierShape.Point4.X,
+                        (float)cubicBezierShape.Point4.Y);
                     previous = cubicBezierShape.Point4;
-                }
-                    break;
-
+                    break;
+                }
                 case QuadraticBezierShapeViewModel quadraticBezierShape:
                 {
+                    if (quadraticBezierShape.Point1 is null
+                        || quadraticBezierShape.Point2 is null
+                        || quadraticBezierShape.Point3 is null)
+                    {
+                        return null;
+                    }
                     if (previous is null || previous != quadraticBezierShape.Point1)
                     {
                         path.MoveTo(
-                            (float)(quadraticBezierShape.Point1.X),
-                            (float)(quadraticBezierShape.Point1.Y));
+                            (float)quadraticBezierShape.Point1.X,
+                            (float)quadraticBezierShape.Point1.Y);
                     }
                     path.QuadTo(
-                        (float)(quadraticBezierShape.Point2.X),
-                        (float)(quadraticBezierShape.Point2.Y),
-                        (float)(quadraticBezierShape.Point3.X),
-                        (float)(quadraticBezierShape.Point3.Y));
+                        (float)quadraticBezierShape.Point2.X,
+                        (float)quadraticBezierShape.Point2.Y,
+                        (float)quadraticBezierShape.Point3.X,
+                        (float)quadraticBezierShape.Point3.Y);
                     previous = quadraticBezierShape.Point3;
-                }
-                    break;
-
+                    break;
+                }
                 case TextShapeViewModel textShape:
                 {
+                    if (textShape.TopLeft is null || textShape.BottomRight is null)
+                    {
+                        return null;
+                    }
                     var resultPath = ToSKPath(textShape);
                     if (resultPath is { } && !resultPath.IsEmpty)
                     {
-                        path.AddPath(resultPath, SKPathAddMode.Append);
-                    }
-                }
-                    break;
-
+                        path.AddPath(resultPath);
+                    }
+                    break;
+                }
                 case PathShapeViewModel pathShape:
                 {
                     var resultPath = ToSKPath(pathShape);
-                    if (resultPath is { } && !resultPath.IsEmpty)
-                    {
-                        path.AddPath(resultPath, SKPathAddMode.Append);
-                    }
-                }
-                    break;
-
+                    if (resultPath is { })
+                    {
+                        if (!resultPath.IsEmpty)
+                        {
+                            path.AddPath(resultPath);
+                        }
+                    }
+                    else
+                    {
+                        return null;
+                    }
+                    break;
+                }
                 case GroupShapeViewModel groupShape:
                 {
                     var resultPath = ToSKPath(groupShape.Shapes);
-                    if (resultPath is { } && !resultPath.IsEmpty)
-                    {
-                        path.AddPath(resultPath, SKPathAddMode.Append);
-                    }
-                }
-                    break;
+                    if (resultPath is { })
+                    {
+                        if (!resultPath.IsEmpty)
+                        {
+                            path.AddPath(resultPath);
+                        }
+                    }
+                    else
+                    {
+                        return null;
+                    }
+                    break;
+                }
             }
         }
         return path;
     }

-    public static SKPath ToSKPath(this BaseShapeViewModel shape)
+    public static SKPath? ToSKPath(this BaseShapeViewModel shape)
     {
         return shape switch
         {
@@ -289,140 +354,181 @@
         };
     }

-    public static SKPath ToSKPath(this LineShapeViewModel line)
-    {
+    public static SKPath? ToSKPath(this LineShapeViewModel lineShape)
+    {
+        if (lineShape.Start is null || lineShape.End is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.MoveTo(
-            (float)(line.Start.X),
-            (float)(line.Start.Y));
+            (float)lineShape.Start.X,
+            (float)lineShape.Start.Y);
         path.LineTo(
-            (float)(line.End.X),
-            (float)(line.End.Y));
-        return path;
-    }
-
-    public static SKPath ToSKPath(this RectangleShapeViewModel rectangle)
-    {
+            (float)lineShape.End.X,
+            (float)lineShape.End.Y);
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this RectangleShapeViewModel rectangleShape)
+    {
+        if (rectangleShape.TopLeft is null || rectangleShape.BottomRight is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.AddRect(
-            SkiaSharpDrawUtil.CreateRect(rectangle.TopLeft, rectangle.BottomRight),
-            SKPathDirection.Clockwise);
-        return path;
-    }
-
-    public static SKPath ToSKPath(this EllipseShapeViewModel ellipse)
-    {
+            SkiaSharpDrawUtil.CreateRect(rectangleShape.TopLeft, rectangleShape.BottomRight));
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this EllipseShapeViewModel ellipseShape)
+    {
+        if (ellipseShape.TopLeft is null || ellipseShape.BottomRight is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.AddOval(
-            SkiaSharpDrawUtil.CreateRect(ellipse.TopLeft, ellipse.BottomRight),
-            SKPathDirection.Clockwise);
-        return path;
-    }
-
-    public static SKPath ToSKPath(this ImageShapeViewModel image)
-    {
+            SkiaSharpDrawUtil.CreateRect(ellipseShape.TopLeft, ellipseShape.BottomRight));
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this ImageShapeViewModel imageShape)
+    {
+        if (imageShape.TopLeft is null || imageShape.BottomRight is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.AddRect(
-            SkiaSharpDrawUtil.CreateRect(image.TopLeft, image.BottomRight),
-            SKPathDirection.Clockwise);
-        return path;
-    }
-
-    public static SKPath ToSKPath(this ArcShapeViewModel arc)
-    {
+            SkiaSharpDrawUtil.CreateRect(imageShape.TopLeft, imageShape.BottomRight));
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this ArcShapeViewModel arcShape)
+    {
+        if (arcShape.Point1 is null
+            || arcShape.Point2 is null
+            || arcShape.Point3 is null
+            || arcShape.Point4 is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         var a = new GdiArc(
-            Point2.FromXY(arc.Point1.X, arc.Point1.Y),
-            Point2.FromXY(arc.Point2.X, arc.Point2.Y),
-            Point2.FromXY(arc.Point3.X, arc.Point3.Y),
-            Point2.FromXY(arc.Point4.X, arc.Point4.Y));
+            Point2.FromXY(arcShape.Point1.X, arcShape.Point1.Y),
+            Point2.FromXY(arcShape.Point2.X, arcShape.Point2.Y),
+            Point2.FromXY(arcShape.Point3.X, arcShape.Point3.Y),
+            Point2.FromXY(arcShape.Point4.X, arcShape.Point4.Y));
         var rect = new SKRect(
-            (float)(a.X),
-            (float)(a.Y),
+            (float)a.X,
+            (float)a.Y,
             (float)(a.X + a.Width),
             (float)(a.Y + a.Height));
         path.AddArc(rect, (float)a.StartAngle, (float)a.SweepAngle);
         return path;
     }

-    public static SKPath ToSKPath(this CubicBezierShapeViewModel cubicBezier)
-    {
+    public static SKPath? ToSKPath(this CubicBezierShapeViewModel cubicBezierShape)
+    {
+        if (cubicBezierShape.Point1 is null
+            || cubicBezierShape.Point2 is null
+            || cubicBezierShape.Point3 is null
+            || cubicBezierShape.Point4 is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.MoveTo(
-            (float)(cubicBezier.Point1.X),
-            (float)(cubicBezier.Point1.Y));
+            (float)cubicBezierShape.Point1.X,
+            (float)cubicBezierShape.Point1.Y);
         path.CubicTo(
-            (float)(cubicBezier.Point2.X),
-            (float)(cubicBezier.Point2.Y),
-            (float)(cubicBezier.Point3.X),
-            (float)(cubicBezier.Point3.Y),
-            (float)(cubicBezier.Point4.X),
-            (float)(cubicBezier.Point4.Y));
-        return path;
-    }
-
-    public static SKPath ToSKPath(this QuadraticBezierShapeViewModel quadraticBezier)
-    {
+            (float)cubicBezierShape.Point2.X,
+            (float)cubicBezierShape.Point2.Y,
+            (float)cubicBezierShape.Point3.X,
+            (float)cubicBezierShape.Point3.Y,
+            (float)cubicBezierShape.Point4.X,
+            (float)cubicBezierShape.Point4.Y);
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this QuadraticBezierShapeViewModel quadraticBezierShape)
+    {
+        if (quadraticBezierShape.Point1 is null
+            || quadraticBezierShape.Point2 is null
+            || quadraticBezierShape.Point3 is null)
+        {
+            return null;
+        }
         var path = new SKPath
         {
             FillType = SKPathFillType.Winding
         };
         path.MoveTo(
-            (float)(quadraticBezier.Point1.X),
-            (float)(quadraticBezier.Point1.Y));
+            (float)quadraticBezierShape.Point1.X,
+            (float)quadraticBezierShape.Point1.Y);
         path.QuadTo(
-            (float)(quadraticBezier.Point2.X),
-            (float)(quadraticBezier.Point2.Y),
-            (float)(quadraticBezier.Point3.X),
-            (float)(quadraticBezier.Point3.Y));
-        return path;
-    }
-
-    public static SKPath ToSKPath(this TextShapeViewModel text)
-    {
-        var path = new SKPath
-        {
-            FillType = SKPathFillType.Winding
-        };
-
-        if (!(text.GetProperty(nameof(TextShapeViewModel.Text)) is string tbind))
-        {
-            tbind = text.Text;
-        }
-
-        if (tbind is null)
-        {
-            return path;
-        }
-
-        using var pen = SkiaSharpDrawUtil.GetSKPaint(tbind, text.Style, text.TopLeft, text.BottomRight, out var origin);
-        using var outlinePath = pen.GetTextPath(tbind, origin.X, origin.Y);
+            (float)quadraticBezierShape.Point2.X,
+            (float)quadraticBezierShape.Point2.Y,
+            (float)quadraticBezierShape.Point3.X,
+            (float)quadraticBezierShape.Point3.Y);
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this TextShapeViewModel textShape)
+    {
+        if (textShape.TopLeft is null
+            || textShape.BottomRight is null
+            || textShape.Style is null)
+        {
+            return null;
+        }
+        var path = new SKPath
+        {
+            FillType = SKPathFillType.Winding
+        };
+
+        var boundText = textShape.GetProperty(nameof(TextShapeViewModel.Text)) as string ?? textShape.Text;
+        if (boundText is null)
+        {
+            return null;
+        }
+
+        using var pen = SkiaSharpDrawUtil.GetSKPaint(
+            boundText,
+            textShape.Style,
+            textShape.TopLeft,
+            textShape.BottomRight,
+            out var origin);
+
+        using var outlinePath = pen.GetTextPath(boundText, origin.X, origin.Y);
         using var fillPath = pen.GetFillPath(outlinePath);

-        path.AddPath(fillPath, SKPathAddMode.Append);
-
-        return path;
-    }
-
-    public static SKPath ToSKPath(this PathShapeViewModel pathShapeViewModel)
+        path.AddPath(fillPath);
+
+        return path;
+    }
+
+    public static SKPath? ToSKPath(this PathShapeViewModel pathShapeViewModel)
     {
         var fillType = pathShapeViewModel.FillRule == FillRule.EvenOdd ? SKPathFillType.EvenOdd : SKPathFillType.Winding;
         var path = new SKPath
@@ -432,7 +538,10 @@

         foreach (var pathFigure in pathShapeViewModel.Figures)
         {
-            CreateFigure(pathFigure, path);
+            if (!CreateFigure(pathFigure, path))
+            {
+                return null;
+            }
         }

         return path;
@@ -468,7 +577,7 @@
     {
         using var builder = new SKPath.OpBuilder();

-        for (int i = 0; i < paths.Count; i++)
+        for (var i = 0; i < paths.Count; i++)
         {
             builder.Add(paths[i], ops[i]);
         }
@@ -490,7 +599,7 @@
         }
         else
         {
-            for (int i = 1; i < paths.Count; i++)
+            for (var i = 1; i < paths.Count; i++)
             {
                 var next = result.Op(paths[i], op);
                 if (next is { })
@@ -502,4 +611,4 @@
             }
         }
     }
-}+}


fix: Fixes the creation of federated echanges

--- src/Elders.Cronus.Transport.RabbitMQ/RabbitMqInfrastructure.cs
+++ src/Elders.Cronus.Transport.RabbitMQ/RabbitMqInfrastructure.cs
@@ -39,7 +39,7 @@
                 if (ChecksIfHavePublishedLanguageConfigurations())
                     logger.Warn(() => "Missing configurations for public rabbitMq.");
                 else
-                    CreatePublishedLanguageConnection(pub, publicOptions);
+                    CreatePublishedLanguageConnection(priv, publicOptions);
             }
             catch (Exception ex)
             {
@@ -64,7 +64,7 @@
             }
         }

-        private void CreatePublishedLanguageConnection(RabbitMqManagementClient client, PublicRabbitMqOptions publicOptions)
+        private void CreatePublishedLanguageConnection(RabbitMqManagementClient downstreamClient, PublicRabbitMqOptions publicOptions)
         {
             IEnumerable<string> publicExchangeNames = publicRabbitMqNamer.GetExchangeNames(typeof(IPublicEvent));
             IEnumerable<string> signalExchangeNames = signalRabbitMqNamer.GetExchangeNames(typeof(ISignal));
@@ -84,7 +84,7 @@
                             MaxHops = publicOptions.FederatedExchange.MaxHops
                         }
                     };
-                    client.CreateFederatedExchange(federatedExchange, options.VHost);
+                    downstreamClient.CreateFederatedExchange(federatedExchange, options.VHost);
                 }
             }

@@ -101,7 +101,7 @@
                         FederationUpstream = publicOptions.VHost + $"--{exchange.ToLower()}"
                     }
                 };
-                client.CreatePolicy(policy, options.VHost);
+                downstreamClient.CreatePolicy(policy, options.VHost);
             }
         }
     }


Adds an extension method to register options in the DI

--- src/Elders.Cronus/Hosting/CronusServiceCollectionExtensions.cs
+++ src/Elders.Cronus/Hosting/CronusServiceCollectionExtensions.cs
@@ -2,9 +2,11 @@
 using System.Collections.Concurrent;
 using System.Linq;
 using Elders.Cronus.Discoveries;
+using Elders.Cronus.Hosting;
 using Elders.Cronus.MessageProcessing;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;

 namespace Elders.Cronus
 {
@@ -83,6 +85,18 @@

             return services;
         }
+
+        public static IServiceCollection AddOptions<TOptions, TOptionsProvider>(this IServiceCollection services)
+            where TOptions : class, new()
+            where TOptionsProvider : CronusOptionsProviderBase<TOptions>
+        {
+            services.AddSingleton<IConfigureOptions<TOptions>, TOptionsProvider>();
+            services.AddSingleton<IOptionsChangeTokenSource<TOptions>, TOptionsProvider>();
+            services.AddSingleton<IOptionsFactory<TOptions>, TOptionsProvider>();
+
+            return services;
+        }
+
     }

     public static class SubscriberCollectionServiceCollectionExtensions


(#404) Fix default captured screen for RTL

--- src/GongSolutions.WPF.DragDrop/Utilities/DragDropExtensions.cs
+++ src/GongSolutions.WPF.DragDrop/Utilities/DragDropExtensions.cs
@@ -127,7 +127,7 @@
                 {
                     var transformGroup = new TransformGroup();
                     transformGroup.Children.Add(new ScaleTransform(-1, 1));
-                    transformGroup.Children.Add(new TranslateTransform(bounds.Size.Width - 1, 0));
+                    transformGroup.Children.Add(new TranslateTransform(bounds.Size.Width, 0));
                     ctx.PushTransform(transformGroup);
                 }


Lucene.Net.Analysis.Common: Optimized Hunspell Dictionary by caching compiled regular expression instead of compiling it in a tight loop

--- src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs
+++ src/Lucene.Net.Analysis.Common/Analysis/Hunspell/Dictionary.cs
@@ -107,7 +107,8 @@
         internal bool needsOutputCleaning;

         // LUCENENET: Added so we can get better performance than creating the regex in every tight loop.
-        private static Regex whitespacePattern = new Regex("\\s+", RegexOptions.Compiled);
+        private static readonly Regex whitespacePattern = new Regex("\\s+", RegexOptions.Compiled);
+        private static readonly Regex leadingDigitPattern = new Regex("[^0-9]", RegexOptions.Compiled);

         /// <summary>
         /// Creates a new <see cref="Dictionary"/> containing the information read from the provided <see cref="Stream"/>s to hunspell affix
@@ -675,8 +676,8 @@
             return Encoding.GetEncoding(encoding);
         }

-        private static Regex windowsCodePagePattern = new Regex("^(?:microsoft-)?cp-?(125[0-8])$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
-        private static Regex thaiCodePagePattern = new Regex("^tis-?620(?:-?2533)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+        private static readonly Regex windowsCodePagePattern = new Regex("^(?:microsoft-)?cp-?(125[0-8])$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+        private static readonly Regex thaiCodePagePattern = new Regex("^tis-?620(?:-?2533)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

         /// <summary>
@@ -1053,7 +1054,7 @@
                 for (int i = 0; i < rawFlagParts.Length; i++)
                 {
                     // note, removing the trailing X/leading I for nepali... what is the rule here?!
-                    string replacement = Regex.Replace(rawFlagParts[i], "[^0-9]", "");
+                    string replacement = leadingDigitPattern.Replace(rawFlagParts[i], "");
                     // note, ignoring empty flags (this happens in danish, for example)
                     if (replacement.Length == 0)
                     {


Improve field naming.

Improve field naming.

--- src/MsgPack.Rpc.Client/Rpc/Client/Protocols/ClientTransport.cs
+++ src/MsgPack.Rpc.Client/Rpc/Client/Protocols/ClientTransport.cs
@@ -109,7 +109,7 @@
 			get { return Interlocked.CompareExchange( ref this._isInShutdown, 0, 0 ) != 0; }
 		}

-		private int _isInServerShutdown;
+		private int _isServerShutdown;

 		private EventHandler<ShutdownCompletedEventArgs> _shutdownCompleted;

@@ -294,7 +294,7 @@
 		private void OnProcessFinished()
 		{
 			if ( Interlocked.CompareExchange( ref this._isInShutdown, 0, 0 ) == 1
-				|| Interlocked.CompareExchange( ref this._isInServerShutdown, 0, 0 ) == 1 )
+				|| Interlocked.CompareExchange( ref this._isServerShutdown, 0, 0 ) == 1 )
 			{
 				if ( this._pendingNotificationTable.Count == 0 && this._pendingRequestTable.Count == 0 )
 				{
@@ -560,7 +560,7 @@

 			Contract.EndContractBlock();

-			if ( Interlocked.CompareExchange( ref this._isInServerShutdown, 0, 0 ) == 1 )
+			if ( Interlocked.CompareExchange( ref this._isServerShutdown, 0, 0 ) == 1 )
 			{
 				throw new RpcErrorMessage( RpcError.TransportError, "Server did shutdown socket.", null ).ToException();
 			}
@@ -770,7 +770,7 @@

 			if ( context.BytesTransferred == 0 )
 			{
-				if ( Interlocked.Exchange( ref this._isInServerShutdown, 1 ) == 0 )
+				if ( Interlocked.Exchange( ref this._isServerShutdown, 1 ) == 0 )
 				{
 					// recv() returns 0 when the server socket shutdown gracefully.
 					MsgPackRpcClientProtocolsTrace.TraceEvent(


ExtensionService uses IDirectoryFinder instead of a concrete implementation.

--- src/NUnitEngine/nunit.engine.core/Services/ExtensionService.cs
+++ src/NUnitEngine/nunit.engine.core/Services/ExtensionService.cs
@@ -52,7 +52,7 @@

         private readonly IFileSystem _fileSystem;
         private readonly IAddinsFileReader _addinsReader;
-        private readonly DirectoryFinder _directoryFinder;
+        private readonly IDirectoryFinder _directoryFinder;

         public IList<Assembly> RootAssemblies { get; } = new List<Assembly>();

@@ -62,10 +62,15 @@
         }

         internal ExtensionService(bool isRunningOnAgent, IAddinsFileReader addinsReader, IFileSystem fileSystem)
+            : this(isRunningOnAgent, addinsReader, fileSystem, new DirectoryFinder(fileSystem))
+        {
+        }
+
+        internal ExtensionService(bool isRunningOnAgent, IAddinsFileReader addinsReader, IFileSystem fileSystem, IDirectoryFinder directoryFinder)
         {
             _addinsReader = addinsReader;
             _fileSystem = fileSystem;
-            _directoryFinder = new DirectoryFinder(_fileSystem);
+            _directoryFinder = directoryFinder;
             _isRunningOnAgent = isRunningOnAgent;
         }


Enabling indexing on Page content type during setup

--HG--
branch : dev

--- src/Orchard.Web/Modules/Orchard.Setup/Services/SetupService.cs
+++ src/Orchard.Web/Modules/Orchard.Setup/Services/SetupService.cs
@@ -18,6 +18,7 @@
 using Orchard.Environment.ShellBuilders;
 using Orchard.Environment.Descriptor;
 using Orchard.Environment.Descriptor.Models;
+using Orchard.Indexing;
 using Orchard.Localization;
 using Orchard.Localization.Services;
 using Orchard.Reports.Services;
@@ -210,7 +211,7 @@
                         //.WithPart("TagsPart")
                         //.WithPart("LocalizationPart")
                         .Creatable()
-                        //.Indexed()
+                        .Indexed()
                         );
                     contentDefinitionManager.AlterPartDefinition("BodyPart", cfg => cfg
                         .WithSetting("BodyPartSettings.FlavorDefault", BodyPartSettings.FlavorDefaultDefault));


Fix device model creation

Fix device model creation

--- src/Repairis.Application/DeviceModels/DeviceModelAppService.cs
+++ src/Repairis.Application/DeviceModels/DeviceModelAppService.cs
@@ -34,7 +34,7 @@

         public async Task<DeviceModel> FindDeviceModelAsync(DeviceModelBasicEntityDto input)
         {
-            return await _deviceModelDomainService.FindDeviceModelAsync(input.DeviceModelName, input.DeviceCategoryName, input.BrandName);
+            return await _deviceModelDomainService.FindDeviceModelAsync(input.DeviceCategoryName, input.BrandName, input.DeviceModelName);
         }

         public async Task<DeviceModelBasicEntityDto> GetDeviceModelAsync(int id)
@@ -49,24 +49,18 @@

         public async Task<bool> ExistsAsync(DeviceModelBasicEntityDto input)
         {
-            return await _deviceModelDomainService.ExistsAsync(input.DeviceModelName, input.DeviceCategoryName, input.BrandName);
+            return await _deviceModelDomainService.ExistsAsync(input.DeviceCategoryName, input.BrandName, input.DeviceModelName);
         }

         public async Task<DeviceModel> GetOrCreateAsync(DeviceModelBasicEntityDto input)
         {
-            return await _deviceModelDomainService.GetOrCreateAsync(input.DeviceModelName, input.DeviceCategoryName, input.BrandName);
+            return await _deviceModelDomainService.GetOrCreateAsync(input.DeviceCategoryName, input.BrandName, input.DeviceModelName);

         }

         public async Task CreateDeviceModelAsync(DeviceModelBasicEntityDto input)
         {
-            await
-                _deviceModelDomainService.CreateAsync(input.DeviceModelName, input.DeviceCategoryName, input.BrandName);
-
-            Logger.Info("DeviceModels: Created a new device model: " +
-                        input.BrandName + " " +
-                        input.DeviceModelName + " (" +
-                        input.DeviceCategoryName + ")");
+            await _deviceModelDomainService.CreateAsync(input.DeviceCategoryName, input.BrandName, input.DeviceModelName);
         }


Tweak to minimize the number of null object entries in the serialized queue

--- src/Splunk.Client.Helpers/Splunk/Client/Helpers/MockContext.cs
+++ src/Splunk.Client.Helpers/Splunk/Client/Helpers/MockContext.cs
@@ -140,6 +140,7 @@
                 {
                     var serializer = new DataContractJsonSerializer(typeof(Queue<Recording>));
                     Directory.CreateDirectory(RecordingDirectoryName);
+                    Recordings.TrimExcess();

                     using (var stream = new FileStream(RecordingFilename, FileMode.Create))
                     {


Redefine the unicode output condition for nanoserver/IoT for more function (#4074)

--- src/System.Management.Automation/engine/InitialSessionState.cs
+++ src/System.Management.Automation/engine/InitialSessionState.cs
@@ -5329,7 +5329,7 @@
         internal const string DefaultMoreFunctionText = @"
 param([string[]]$paths)
 # Nano needs to use Unicode, but Windows and Linux need the default
-$OutputEncoding = if ($IsWindows -and $IsCoreCLR) {
+$OutputEncoding = if ([System.Management.Automation.Platform]::IsNanoServer -or [System.Management.Automation.Platform]::IsIoT) {
     [System.Text.Encoding]::Unicode
 } else {
     [System.Console]::OutputEncoding


removes comments/notes

removes comments/notes

--- src/Umbraco.Web.BackOffice/Security/UmbracoSecureDataFormat.cs
+++ src/Umbraco.Web.BackOffice/Security/UmbracoSecureDataFormat.cs
@@ -23,13 +23,6 @@

         public string Protect(AuthenticationTicket data, string purpose)
         {
-            // TODO: What about 'purpose'?
-
-            // TODO: We used to cast this, not sure if this is needed
-            //var backofficeIdentity = (UmbracoBackOfficeIdentity)data.Principal.Identity;
-
-            // TODO: The below seems irrelevant except for the Expires changes, do we need that?
-
             //create a new ticket based on the passed in tickets details, however, we'll adjust the expires utc based on the specified timeout mins
             var ticket = new AuthenticationTicket(data.Principal,
                 new AuthenticationProperties(data.Properties.Items)
@@ -56,8 +49,6 @@
         /// <returns></returns>
         public AuthenticationTicket Unprotect(string protectedText, string purpose)
         {
-            // TODO: What about 'purpose'?
-
             AuthenticationTicket decrypt;
             try
             {


Fix documentation mistake.

Fix documentation mistake.

--- src/Website/Views/Documentation/Scripts_ExternalModules.cshtml
+++ src/Website/Views/Documentation/Scripts_ExternalModules.cshtml
@@ -14,7 +14,7 @@
 {
     public void Configure(ModuleConfiguration moduleConfiguration, ICassetteApplication application)
     {
-        modules.Add(
+        moduleConfiguration.Add(
             new ExternalScriptModule("twitter", "http://platform.twitter.com/widgets.js")
             {
                 Location = "body" // Module render location can be set here if required.


Fix typo (== vs. !=) in GenerateUniqueName

--- src/Workspaces/Core/Portable/Shared/Utilities/NameGenerator.cs
+++ src/Workspaces/Core/Portable/Shared/Utilities/NameGenerator.cs
@@ -138,7 +138,7 @@

         public static string GenerateUniqueName(string baseName, string extension, Func<string, bool> canUse)
         {
-            if (!string.IsNullOrEmpty(extension) && extension[0] == '.')
+            if (!string.IsNullOrEmpty(extension) && extension[0] != '.')
             {
                 extension = "." + extension;
             }


_cachedPackages is now a local variable. fixes problems with packages not showing up after install. #3762

--- src/AssemblyLoader.cs
+++ src/AssemblyLoader.cs
@@ -765,7 +765,6 @@
         public static bool IsAssemblyReference(string filePath) => DummyLocalPackage.IsAssemblyReference(filePath);

         private const string ResourceAssemblyExtension = ".resources.dll";
-        static readonly HashSet<IPackage> _cachedPackages = new HashSet<IPackage>();
         static readonly Dictionary<string, string> _packageAssemblyCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
         static readonly Dictionary<string, KeyValuePair<string, IPackage>> _fileCache = new Dictionary<string, KeyValuePair<string, IPackage>>(StringComparer.OrdinalIgnoreCase);
         static Dictionary<string, Assembly> _loadedAssemblyCache;
@@ -957,10 +956,11 @@
                     _packageAssemblyCache.Clear();
                     _fileCache.Clear();

+                    var set = new HashSet<IPackage>();
                     var sorter = new HighestPackageSorter(ExecutingFrameworkName, repository);
                     foreach (var p in sorter.GetPackagesByDependencyOrder(repository))
                     {
-                        if (!_cachedPackages.Add(p))
+                        if (!set.Add(p))
                             continue;
                         CacheFiles(p);
                     }


Fix AuthResult parsing.

Fix AuthResult parsing.

--- src/client/Microsoft.Identity.Client/UI/AuthorizationResult.cs
+++ src/client/Microsoft.Identity.Client/UI/AuthorizationResult.cs
@@ -46,25 +46,7 @@
             Dictionary<string, string> uriParams = CoreHelpers.ParseKeyValueList(
                 resultData.Substring(1), '&', true, null);

-            var authResult = FromParsedValues(uriParams);
-
-            if (uriParams.ContainsKey(TokenResponseClaim.Code))
-            {
-                authResult.Code = uriParams[TokenResponseClaim.Code];
-            }
-            else if (webAuthenticationResult.StartsWith("msauth://", StringComparison.OrdinalIgnoreCase))
-            {
-                authResult.Code = webAuthenticationResult;
-            }
-            else
-            {
-                return FromStatus(
-                   AuthorizationStatus.UnknownError,
-                   MsalError.AuthenticationFailed,
-                   MsalErrorMessage.AuthorizationServerInvalidResponse);
-            }
-
-            return authResult;
+            return FromParsedValues(uriParams, webAuthenticationResult);
         }

         public static AuthorizationResult FromPostData(byte[] postData)
@@ -101,7 +83,7 @@
             return result;
         }

-        private static AuthorizationResult FromParsedValues(Dictionary<string, string> parameters)
+        private static AuthorizationResult FromParsedValues(Dictionary<string, string> parameters, string url = null)
         {
             if (parameters.ContainsKey(TokenResponseClaim.Error))
             {
@@ -112,27 +94,43 @@
                         : null);
             }

-            var result = new AuthorizationResult
+            var authResult = new AuthorizationResult
             {
                 Status = AuthorizationStatus.Success
             };

             if (parameters.ContainsKey(OAuth2Parameter.State))
             {
-                result.State = parameters[OAuth2Parameter.State];
+                authResult.State = parameters[OAuth2Parameter.State];
             }

             if (parameters.ContainsKey(TokenResponseClaim.CloudInstanceHost))
             {
-                result.CloudInstanceHost = parameters[TokenResponseClaim.CloudInstanceHost];
+                authResult.CloudInstanceHost = parameters[TokenResponseClaim.CloudInstanceHost];
             }

             if (parameters.ContainsKey(TokenResponseClaim.ClientInfo))
             {
-                result.ClientInfo = parameters[TokenResponseClaim.ClientInfo];
+                authResult.ClientInfo = parameters[TokenResponseClaim.ClientInfo];
             }

-            return result;
+            if (parameters.ContainsKey(TokenResponseClaim.Code))
+            {
+                authResult.Code = parameters[TokenResponseClaim.Code];
+            }
+            else if (!string.IsNullOrEmpty(url) && url.StartsWith("msauth://", StringComparison.OrdinalIgnoreCase))
+            {
+                authResult.Code = url;
+            }
+            else
+            {
+                return FromStatus(
+                   AuthorizationStatus.UnknownError,
+                   MsalError.AuthenticationFailed,
+                   MsalErrorMessage.AuthorizationServerInvalidResponse);
+            }
+
+            return authResult;
         }

         internal static AuthorizationResult FromStatus(AuthorizationStatus status)


- fix MT issue in IO - add passive mode IO - update codedoc - fix #68 - fix #67

--- src/ConsoleMenu/IO.cs
+++ src/ConsoleMenu/IO.cs
@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using System.Threading;

 namespace ConsoleMenu
 {
@@ -22,45 +23,68 @@

 		private static readonly Stack<Frame> _Frames = new Stack<Frame> ();

+		private static readonly ManualResetEvent _InputAvailable = new ManualResetEvent (false);
+
+		/// <summary>
+		/// If no input is queued already and passive mode is enabled, QueryInput will block until input is available.
+		/// If no input is queued already and passive mode is disabled, QueryInput will prompt the user for input.
+		///
+		/// PassiveMode is disabled by default.
+		/// </summary>
+		public static bool PassiveMode
+		{
+			get;
+			set;
+		}
+
 		/// <summary>
 		/// Returns the next available line of input.
 		///
-		/// If buffered input is available, its next line will be returned. Else, the user will be prompted for input.
+		/// Empty input (whitespace only) will always be ignored.
 		///
-		/// Empty input (whitespace only) will be ignored.
+		/// If buffered input is available, its next line will be returned.
+		///
+		/// If no bufferd input is available, the call will block. Depending on PassiveMode either the user
+		/// will be prompted for input, or the method will wait until input was added to the queue.
 		/// </summary>
 		/// <param name="prompt">
 		/// Prompt string, or null if no prompt string should be displayed.
+		///
+		/// In passive mode, the prompt will never be displayed.
 		/// </param>
 		public static string QueryInput (string prompt)
 		{
 			for (; ; ) {
-				var input = GetNextFrameInput ();
+				string input = null;

-				if (input == null) {
-					if (prompt != null) {
-						Console.Write (prompt + " ");
+				lock (_Frames) {
+					while (_Frames.Any ()) {
+						var f = _Frames.Peek ();
+						if (!f.E.MoveNext ()) {
+							_Frames.Pop ();
+							continue;
+						}
+						input = f.E.Current;
 					}
-					input = Console.ReadLine ();
+
+					if (input == null) {
+						if (!PassiveMode) {
+							if (prompt != null) {
+								Console.Write (prompt + " ");
+							}
+							input = Console.ReadLine ();
+						}
+						else {
+							_InputAvailable.Reset ();
+							_InputAvailable.WaitOne ();
+						}
+					}
 				}

 				if (!string.IsNullOrWhiteSpace (input)) {
 					return input;
 				}
 			}
-		}
-
-		private static string GetNextFrameInput ()
-		{
-			while (_Frames.Any ()) {
-				var f = _Frames.Peek ();
-				if (!f.E.MoveNext ()) {
-					_Frames.Pop ();
-					continue;
-				}
-				return f.E.Current;
-			}
-			return null;
 		}

 		/// <summary>
@@ -74,7 +98,10 @@
 				throw new ArgumentNullException ("source");
 			}

-			_Frames.Push (new Frame (source));
+			lock (_Frames) {
+				_Frames.Push (new Frame (source));
+				_InputAvailable.Set ();
+			}
 		}

 		/// <summary>


Add methods to disable returning private scope methods/fields

--- src/DotNet/TypeDef.cs
+++ src/DotNet/TypeDef.cs
@@ -540,37 +540,64 @@

 		/// <summary>
 		/// Resolves a method or a field. The <see cref="MemberRef.Class"/> (owner type) is
-		/// ignored when resolving the method/field.
+		/// ignored when resolving the method/field. Private scope methods/fields are not returned.
 		/// </summary>
 		/// <param name="memberRef">A method/field reference</param>
 		/// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c>
 		/// if it couldn't be resolved.</returns>
 		public IMemberForwarded Resolve(MemberRef memberRef) {
+			return Resolve(memberRef, false);
+		}
+
+		/// <summary>
+		/// Resolves a method or a field. The <see cref="MemberRef.Class"/> (owner type) is
+		/// ignored when resolving the method/field.
+		/// </summary>
+		/// <param name="memberRef">A method/field reference</param>
+		/// <param name="allowPrivateScope"><c>true</c> if this method can return private scope
+		/// methods/fields, <c>false</c> if private scope methods/fields are not referencable.</param>
+		/// <returns>A <see cref="MethodDef"/> or a <see cref="FieldDef"/> instance or <c>null</c>
+		/// if it couldn't be resolved.</returns>
+		public IMemberForwarded Resolve(MemberRef memberRef, bool allowPrivateScope) {
 			if (memberRef == null)
 				return null;

 			var methodSig = memberRef.MethodSig;
 			if (methodSig != null)
-				return ResolveMethod(memberRef.Name, methodSig);
+				return ResolveMethod(memberRef.Name, methodSig, allowPrivateScope);

 			var fieldSig = memberRef.FieldSig;
 			if (fieldSig != null)
-				return ResolveField(memberRef.Name, fieldSig);
+				return ResolveField(memberRef.Name, fieldSig, allowPrivateScope);

 			return null;
 		}

 		/// <summary>
-		/// Resolves a method
+		/// Resolves a method. Private scope methods are not returned.
 		/// </summary>
 		/// <param name="name">Method name</param>
 		/// <param name="sig">Method signature</param>
 		/// <returns>The first method that matches or <c>null</c> if none found</returns>
 		public MethodDef ResolveMethod(UTF8String name, MethodSig sig) {
+			return ResolveMethod(name, sig, false);
+		}
+
+		/// <summary>
+		/// Resolves a method
+		/// </summary>
+		/// <param name="name">Method name</param>
+		/// <param name="sig">Method signature</param>
+		/// <param name="allowPrivateScope"><c>true</c> if this method can return private scope
+		/// methods, <c>false</c> if private scope methods are not referencable.</param>
+		/// <returns>The first method that matches or <c>null</c> if none found</returns>
+		public MethodDef ResolveMethod(UTF8String name, MethodSig sig, bool allowPrivateScope) {
 			if (UTF8String.IsNull(name) || sig == null)
 				return null;
 			var comparer = new SigComparer(0);
 			foreach (var method in Methods) {
+				if (!allowPrivateScope && method.IsPrivateScope)
+					continue;
 				if (!UTF8String.Equals(method.Name, name))
 					continue;
 				if (comparer.Equals(method.MethodSig, sig))
@@ -580,16 +607,30 @@
 		}

 		/// <summary>
-		/// Resolves a field
+		/// Resolves a field. Private scope fields are not returned.
 		/// </summary>
 		/// <param name="name">Field name</param>
 		/// <param name="sig">Field signature</param>
 		/// <returns>The first field that matches or <c>null</c> if none found</returns>
 		public FieldDef ResolveField(UTF8String name, FieldSig sig) {
+			return ResolveField(name, sig, false);
+		}
+
+		/// <summary>
+		/// Resolves a field
+		/// </summary>
+		/// <param name="name">Field name</param>
+		/// <param name="sig">Field signature</param>
+		/// <param name="allowPrivateScope"><c>true</c> if this method can return private scope
+		/// fields, <c>false</c> if private scope fields are not referencable.</param>
+		/// <returns>The first field that matches or <c>null</c> if none found</returns>
+		public FieldDef ResolveField(UTF8String name, FieldSig sig, bool allowPrivateScope) {
 			if (UTF8String.IsNull(name) || sig == null)
 				return null;
 			var comparer = new SigComparer(0);
 			foreach (var field in Fields) {
+				if (!allowPrivateScope && field.IsPrivateScope)
+					continue;
 				if (!UTF8String.Equals(field.Name, name))
 					continue;
 				if (comparer.Equals(field.FieldSig, sig))


Avoid checking metadata in restore tests.

There appear to be some differences at the tick level.

--- Duplicati/UnitTest/DisruptionTests.cs
+++ Duplicati/UnitTest/DisruptionTests.cs
@@ -80,7 +80,7 @@
                 foreach (string filepath in partialVersionFiles)
                 {
                     string filename = Path.GetFileName(filepath);
-                    Assert.IsTrue(TestUtils.CompareFiles(filepath, Path.Combine(this.RESTOREFOLDER, filename ?? String.Empty), filename, true));
+                    Assert.IsTrue(TestUtils.CompareFiles(filepath, Path.Combine(this.RESTOREFOLDER, filename ?? String.Empty), filename, false));
                 }
             }

@@ -115,7 +115,7 @@
                 foreach (string filepath in fullVersionFiles)
                 {
                     string filename = Path.GetFileName(filepath);
-                    Assert.IsTrue(TestUtils.CompareFiles(filepath, Path.Combine(this.RESTOREFOLDER, filename ?? String.Empty), filename, true));
+                    Assert.IsTrue(TestUtils.CompareFiles(filepath, Path.Combine(this.RESTOREFOLDER, filename ?? String.Empty), filename, false));
                 }
             }
         }


count occurence in sorted order

count occurence in sorted order

--- EPIProblems/Sorting/CountOccurence.cs
+++ EPIProblems/Sorting/CountOccurence.cs
@@ -27,6 +27,7 @@
 					currentCharCount = 1;
 				}
 			}
+			result += "(" + array[array.Length - 1] + "," + currentCharCount + ")";
 			return result;
 		}
 	}


[Modify] Polish it

[Modify] Polish it

--- websocket-sharp/Server/HttpServer.cs
+++ websocket-sharp/Server/HttpServer.cs
@@ -388,9 +388,13 @@
     /// <summary>
     /// Gets or sets the name of the realm associated with the server.
     /// </summary>
+    /// <remarks>
+    /// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as
+    /// the name of the realm.
+    /// </remarks>
     /// <value>
     /// A <see cref="string"/> that represents the name of the realm. The default value is
-    /// <c>"SECRET AREA"</c>.
+    /// <see langword="null"/>.
     /// </value>
     public string Realm {
       get {


[Modify] Edit it

[Modify] Edit it

--- websocket-sharp/Server/HttpServer.cs
+++ websocket-sharp/Server/HttpServer.cs
@@ -1026,19 +1026,31 @@
     }

     /// <summary>
-    /// Stops receiving the incoming requests, and closes the connections with
-    /// the specified <paramref name="code"/> and <paramref name="reason"/> for
-    /// the WebSocket connection close.
-    /// </summary>
+    /// Stops receiving incoming requests and closes each connection.
+    /// </summary>
+    /// <remarks>
+    /// This method does nothing if the server is not started,
+    /// it is shutting down, or it has already stopped.
+    /// </remarks>
     /// <param name="code">
-    /// A <see cref="ushort"/> that represents the status code indicating
-    /// the reason for the WebSocket connection close. The status codes are
-    /// defined in <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
-    /// Section 7.4</see> of RFC 6455.
+    ///   <para>
+    ///   A <see cref="ushort"/> that represents the status code
+    ///   indicating the reason for the WebSocket connection close.
+    ///   </para>
+    ///   <para>
+    ///   The status codes are defined in
+    ///   <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
+    ///   Section 7.4</see> of RFC 6455.
+    ///   </para>
     /// </param>
     /// <param name="reason">
-    /// A <see cref="string"/> that represents the reason for the WebSocket
-    /// connection close. The size must be 123 bytes or less.
+    ///   <para>
+    ///   A <see cref="string"/> that represents the reason for
+    ///   the WebSocket connection close.
+    ///   </para>
+    ///   <para>
+    ///   The size must be 123 bytes or less in UTF-8.
+    ///   </para>
     /// </param>
     /// <exception cref="ArgumentOutOfRangeException">
     ///   <para>


Integrate spotlight beatmap badge in info overlay

--- osu.Game/Overlays/BeatmapSet/BeatmapSetHeaderContent.cs
+++ osu.Game/Overlays/BeatmapSet/BeatmapSetHeaderContent.cs
@@ -39,8 +39,11 @@
         private readonly Box coverGradient;
         private readonly OsuSpriteText title, artist;
         private readonly AuthorInfo author;
+
         private readonly ExplicitContentBeatmapPill explicitContentPill;
+        private readonly SpotlightBeatmapPill spotlightPill;
         private readonly FeaturedArtistBeatmapPill featuredArtistPill;
+
         private readonly FillFlowContainer downloadButtonsContainer;
         private readonly BeatmapAvailability beatmapAvailability;
         private readonly BeatmapSetOnlineStatusPill onlineStatusPill;
@@ -127,6 +130,13 @@
                                                 Margin = new MarginPadding { Left = 5, Bottom = 4 }, // To better lineup with the font
                                             },
                                             explicitContentPill = new ExplicitContentBeatmapPill
+                                            {
+                                                Alpha = 0f,
+                                                Anchor = Anchor.BottomLeft,
+                                                Origin = Anchor.BottomLeft,
+                                                Margin = new MarginPadding { Left = 10, Bottom = 4 },
+                                            },
+                                            spotlightPill = new SpotlightBeatmapPill
                                             {
                                                 Alpha = 0f,
                                                 Anchor = Anchor.BottomLeft,
@@ -258,6 +268,7 @@
                     artist.Text = new RomanisableString(setInfo.NewValue.ArtistUnicode, setInfo.NewValue.Artist);

                     explicitContentPill.Alpha = setInfo.NewValue.HasExplicitContent ? 1 : 0;
+                    spotlightPill.Alpha = setInfo.NewValue.FeaturedInSpotlight ? 1 : 0;
                     featuredArtistPill.Alpha = setInfo.NewValue.TrackId != null ? 1 : 0;

                     onlineStatusPill.FadeIn(500, Easing.OutQuint);


Simpler extensions generator with namespace & program class (#787)

--- bld/ExtensionsGenerator/Program.cs
+++ bld/ExtensionsGenerator/Program.cs
@@ -14,277 +14,284 @@
 //
 #endregion

-namespace MoreLinq.ExtensionsGenerator
-{
-    using System;
-    using System.Collections.Generic;
-    using System.Collections.Immutable;
-    using System.Globalization;
-    using System.IO;
-    using System.Linq;
-    using System.Reflection;
-    using System.Text.RegularExpressions;
-    using Microsoft.CodeAnalysis;
-    using Microsoft.CodeAnalysis.CSharp;
-    using Microsoft.CodeAnalysis.CSharp.Syntax;
-    using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
-
-    static class Program
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
+
+try
+{
+    Run(args);
+    return 0;
+}
+catch (Exception e)
+{
+    Console.Error.WriteLine(e.ToString());
+    return 0xbad;
+}
+
+static void Run(IEnumerable<string> args)
+{
+    var dir = Directory.GetCurrentDirectory();
+
+    string includePattern = null;
+    string excludePattern = null;
+    var debug = false;
+    var usings = new List<string>();
+    var noClassLead = false;
+
+    using (var arg = args.GetEnumerator())
     {
-        static void Run(IEnumerable<string> args)
+        while (arg.MoveNext())
         {
-            var dir = Directory.GetCurrentDirectory();
-
-            string includePattern = null;
-            string excludePattern = null;
-            var debug = false;
-            var usings = new List<string>();
-            var noClassLead = false;
-
-            using (var arg = args.GetEnumerator())
+            switch (arg.Current)
             {
-                while (arg.MoveNext())
-                {
-                    switch (arg.Current)
-                    {
-                        case "-i":
-                        case "--include":
-                            includePattern = Read(arg, MissingArgValue);
-                            break;
-                        case "-x":
-                        case "--exclude":
-                            excludePattern = Read(arg, MissingArgValue);
-                            break;
-                        case "-u":
-                        case "--using":
-                            usings.Add(Read(arg, MissingArgValue));
-                            break;
-                        case "--no-class-lead":
-                            noClassLead = true;
-                            break;
-                        case "-d":
-                        case "--debug":
-                            debug = true;
-                            break;
-                        case "":
-                            continue;
-                        default:
-                            dir = arg.Current[0] != '-'
-                                ? arg.Current
-                                : throw new Exception("Invalid argument: " + arg.Current);
-                            break;
-                    }
-                }
-
-                static Exception MissingArgValue() =>
-                    new InvalidOperationException("Missing argument value.");
+                case "-i":
+                case "--include":
+                    includePattern = Read(arg, MissingArgValue);
+                    break;
+                case "-x":
+                case "--exclude":
+                    excludePattern = Read(arg, MissingArgValue);
+                    break;
+                case "-u":
+                case "--using":
+                    usings.Add(Read(arg, MissingArgValue));
+                    break;
+                case "--no-class-lead":
+                    noClassLead = true;
+                    break;
+                case "-d":
+                case "--debug":
+                    debug = true;
+                    break;
+                case "":
+                    continue;
+                default:
+                    dir = arg.Current[0] != '-'
+                        ? arg.Current
+                        : throw new Exception("Invalid argument: " + arg.Current);
+                    break;
             }
-
-            static Func<string, bool>
-                PredicateFromPattern(string pattern, bool @default) =>
-                    string.IsNullOrEmpty(pattern)
-                    ? delegate { return @default; }
-                    : new Func<string, bool>(new Regex(pattern).IsMatch);
-
-            var includePredicate = PredicateFromPattern(includePattern, true);
-            var excludePredicate = PredicateFromPattern(excludePattern, false);
-
-            var thisAssemblyName = typeof(Program).GetTypeInfo().Assembly.GetName();
-
-            //
-            // Type abbreviations are used to abbreviate all generic type
-            // parameters into a letter from the alphabet. So for example, a
-            // method with generic type parameters `TSource` and `TResult` will
-            // become `a` and `b`. This is used later for sorting and stabilizes
-            // the sort irrespective of how the type parameters are named or
-            // renamed in the source.
-            //
-
-            var abbreviatedTypeNodes = Enumerable
-                .Range(0, 26)
-                .Select(a => (char) ('a' + a))
-                .Select(ch => new SimpleTypeKey(ch.ToString()))
-                .ToArray();
-
-        var q =
-
-            from ms in new[]
-            {
-                from fp in Directory.EnumerateFiles(dir, "*.cs")
-                where !excludePredicate(fp) && includePredicate(fp)
-                orderby fp
-                //
-                // Find all class declarations where class name is
-                // `MoreEnumerable`. Note that this is irrespective of
-                // namespace, which is out of sheer laziness.
-                //
-                from cd in
-                    CSharpSyntaxTree
-                        .ParseText(File.ReadAllText(fp), CSharpParseOptions.Default.WithPreprocessorSymbols("MORELINQ"))
-                        .GetRoot()
-                        .SyntaxTree
-                        .GetCompilationUnitRoot()
-                        .DescendantNodes().OfType<ClassDeclarationSyntax>()
-                where (string) cd.Identifier.Value == "MoreEnumerable"
-                //
-                // Get all method declarations where method:
-                //
-                // - has at least one parameter
-                // - extends a type (first parameter uses the `this` modifier)
-                // - is public
-                // - isn't marked as being obsolete
-                //
-                from md in cd.DescendantNodes().OfType<MethodDeclarationSyntax>()
-                let mn = (string) md.Identifier.Value
-                where md.ParameterList.Parameters.Count > 0
-                   && md.ParameterList.Parameters.First().Modifiers.Any(m => (string)m.Value == "this")
-                   && md.Modifiers.Any(m => (string)m.Value == "public")
-                   && md.AttributeLists.SelectMany(al => al.Attributes).All(a => a.Name.ToString() != "Obsolete")
-                //
-                // Build a dictionary of type abbreviations (e.g. TSource -> a,
-                // TResult -> b, etc.) for the method's type parameters. If the
-                // method is non-generic, then this will be null!
-                //
-                let typeParameterAbbreviationByName =
-                    md.TypeParameterList
-                     ?.Parameters
-                      .Select((e, i) => (Original: e.Identifier.ValueText, Alias: abbreviatedTypeNodes[i]))
-                      .ToDictionary(e => e.Original, e => e.Alias)
-                //
-                // Put everything together. While we mostly care about the
-                // method declaration, the rest of the information is captured
-                // for the purpose of stabilizing the code generation order and
-                // debugging (--debug).
-                //
-                select new
-                {
-                    Syntax = md,
-                    Name = md.Identifier.ToString(),
-                    TypeParameterCount = md.TypeParameterList?.Parameters.Count ?? 0,
-                    TypeParameterAbbreviationByName = typeParameterAbbreviationByName,
-                    ParameterCount = md.ParameterList.Parameters.Count,
-                    SortableParameterTypes =
-                        from p in md.ParameterList.Parameters
-                        select CreateTypeKey(p.Type,
-                                             n => typeParameterAbbreviationByName != null
-                                               && typeParameterAbbreviationByName.TryGetValue(n, out var a) ? a : null),
-                }
-            }
-            from e in ms.Select((m, i) => (SourceOrder: i + 1, Method: m))
-            orderby
-                e.Method.Name,
-                e.Method.TypeParameterCount,
-                e.Method.ParameterCount,
-                new TupleTypeKey(ImmutableList.CreateRange(e.Method.SortableParameterTypes))
+        }
+
+        static Exception MissingArgValue() =>
+            new InvalidOperationException("Missing argument value.");
+    }
+
+    static Func<string, bool>
+        PredicateFromPattern(string pattern, bool @default) =>
+            string.IsNullOrEmpty(pattern)
+            ? delegate { return @default; }
+            : new Func<string, bool>(new Regex(pattern).IsMatch);
+
+    var includePredicate = PredicateFromPattern(includePattern, true);
+    var excludePredicate = PredicateFromPattern(excludePattern, false);
+
+    var thisAssemblyName = typeof(TypeKey).GetTypeInfo().Assembly.GetName();
+
+    //
+    // Type abbreviations are used to abbreviate all generic type
+    // parameters into a letter from the alphabet. So for example, a
+    // method with generic type parameters `TSource` and `TResult` will
+    // become `a` and `b`. This is used later for sorting and stabilizes
+    // the sort irrespective of how the type parameters are named or
+    // renamed in the source.
+    //
+
+    var abbreviatedTypeNodes = Enumerable
+        .Range(0, 26)
+        .Select(a => (char) ('a' + a))
+        .Select(ch => new SimpleTypeKey(ch.ToString()))
+        .ToArray();
+
+    var q =
+
+        from ms in new[]
+        {
+            from fp in Directory.EnumerateFiles(dir, "*.cs")
+            where !excludePredicate(fp) && includePredicate(fp)
+            orderby fp
+            //
+            // Find all class declarations where class name is
+            // `MoreEnumerable`. Note that this is irrespective of
+            // namespace, which is out of sheer laziness.
+            //
+            from cd in
+                CSharpSyntaxTree
+                    .ParseText(File.ReadAllText(fp), CSharpParseOptions.Default.WithPreprocessorSymbols("MORELINQ"))
+                    .GetRoot()
+                    .SyntaxTree
+                    .GetCompilationUnitRoot()
+                    .DescendantNodes().OfType<ClassDeclarationSyntax>()
+            where (string) cd.Identifier.Value == "MoreEnumerable"
+            //
+            // Get all method declarations where method:
+            //
+            // - has at least one parameter
+            // - extends a type (first parameter uses the `this` modifier)
+            // - is public
+            // - isn't marked as being obsolete
+            //
+            from md in cd.DescendantNodes().OfType<MethodDeclarationSyntax>()
+            let mn = (string) md.Identifier.Value
+            where md.ParameterList.Parameters.Count > 0
+               && md.ParameterList.Parameters.First().Modifiers.Any(m => (string)m.Value == "this")
+               && md.Modifiers.Any(m => (string)m.Value == "public")
+               && md.AttributeLists.SelectMany(al => al.Attributes).All(a => a.Name.ToString() != "Obsolete")
+            //
+            // Build a dictionary of type abbreviations (e.g. TSource -> a,
+            // TResult -> b, etc.) for the method's type parameters. If the
+            // method is non-generic, then this will be null!
+            //
+            let typeParameterAbbreviationByName =
+                md.TypeParameterList
+                 ?.Parameters
+                  .Select((e, i) => (Original: e.Identifier.ValueText, Alias: abbreviatedTypeNodes[i]))
+                  .ToDictionary(e => e.Original, e => e.Alias)
+            //
+            // Put everything together. While we mostly care about the
+            // method declaration, the rest of the information is captured
+            // for the purpose of stabilizing the code generation order and
+            // debugging (--debug).
+            //
             select new
             {
-                e.Method,
-                e.SourceOrder,
-            };
-
-            q = q.ToArray();
-
-            if (debug)
+                Syntax = md,
+                Name = md.Identifier.ToString(),
+                TypeParameterCount = md.TypeParameterList?.Parameters.Count ?? 0,
+                TypeParameterAbbreviationByName = typeParameterAbbreviationByName,
+                ParameterCount = md.ParameterList.Parameters.Count,
+                SortableParameterTypes =
+                    from p in md.ParameterList.Parameters
+                    select CreateTypeKey(p.Type,
+                                         n => typeParameterAbbreviationByName != null
+                                           && typeParameterAbbreviationByName.TryGetValue(n, out var a) ? a : null),
+            }
+        }
+        from e in ms.Select((m, i) => (SourceOrder: i + 1, Method: m))
+        orderby
+            e.Method.Name,
+            e.Method.TypeParameterCount,
+            e.Method.ParameterCount,
+            new TupleTypeKey(ImmutableList.CreateRange(e.Method.SortableParameterTypes))
+        select new
+        {
+            e.Method,
+            e.SourceOrder,
+        };
+
+    q = q.ToArray();
+
+    if (debug)
+    {
+        var ms =
+            //
+            // Example of what this is designed to produce:
+            //
+            // 083: Lag<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult
+            // 084: Lag<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult
+            // 085: Lead<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult
+            // 086: Lead<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult
+            //
+            from e in q
+            let m = e.Method
+            select new
             {
-                var ms =
-                    //
-                    // Example of what this is designed to produce:
-                    //
-                    // 083: Lag<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult
-                    // 084: Lag<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult
-                    // 085: Lead<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult
-                    // 086: Lead<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult
-                    //
-                    from e in q
-                    let m = e.Method
-                    select new
-                    {
-                        m.Name,
-
-                        SourceOrder = e.SourceOrder.ToString("000", CultureInfo.InvariantCulture),
-
-                        TypeParameters =
-                            m.TypeParameterCount == 0
-                            ? string.Empty
-                            : "<" + string.Join(", ", from a in m.TypeParameterAbbreviationByName
-                                                      select a.Value) + ">",
-                        Parameters =
-                            "(" + string.Join(", ", m.SortableParameterTypes) + ")",
-
-                        Abbreviations =
-                            m.TypeParameterCount == 0
-                            ? string.Empty
-                            : " where " + string.Join(", ", from a in m.TypeParameterAbbreviationByName
-                                                            select a.Value + " = " + a.Key),
-                    }
-                    into e
-                    select e.SourceOrder + ": "
-                         + e.Name + e.TypeParameters + e.Parameters + e.Abbreviations;
-
-                foreach (var m in ms)
-                    Console.Error.WriteLine(m);
+                m.Name,
+
+                SourceOrder = e.SourceOrder.ToString("000", CultureInfo.InvariantCulture),
+
+                TypeParameters =
+                    m.TypeParameterCount == 0
+                    ? string.Empty
+                    : "<" + string.Join(", ", from a in m.TypeParameterAbbreviationByName
+                                              select a.Value) + ">",
+                Parameters =
+                    "(" + string.Join(", ", m.SortableParameterTypes) + ")",
+
+                Abbreviations =
+                    m.TypeParameterCount == 0
+                    ? string.Empty
+                    : " where " + string.Join(", ", from a in m.TypeParameterAbbreviationByName
+                                                    select a.Value + " = " + a.Key),
             }
-
-            var indent = new string(' ', 4);
-            var indent2 = indent + indent;
-            var indent3 = indent2 + indent;
-
-            var baseImports = new []
-            {
-                "System",
-                "System.CodeDom.Compiler",
-                "System.Collections.Generic",
-                "System.Diagnostics.CodeAnalysis",
-            };
-
-            var imports =
-                from ns in baseImports.Concat(usings)
-                select indent + $"using {ns};";
-
-            var classes =
-                from md in q
-                select md.Method.Syntax into md
-                group md by (string) md.Identifier.Value into g
-                select new
-                {
-                    Name = g.Key,
-                    Overloads =
-                        from md in g
-                        select
-                            MethodDeclaration(md.ReturnType, md.Identifier)
-                                .WithAttributeLists(md.AttributeLists)
-                                .WithModifiers(md.Modifiers)
-                                .WithTypeParameterList(md.TypeParameterList)
-                                .WithConstraintClauses(md.ConstraintClauses)
-                                .WithParameterList(md.ParameterList)
-                                .WithExpressionBody(
-                                    ArrowExpressionClause(
-                                        InvocationExpression(
-                                            MemberAccessExpression(
-                                                SyntaxKind.SimpleMemberAccessExpression,
-                                                IdentifierName("MoreEnumerable"),
-                                                IdentifierName(md.Identifier)),
-                                            ArgumentList(
-                                                SeparatedList(
-                                                    from p in md.ParameterList.Parameters
-                                                    select Argument(IdentifierName(p.Identifier)),
-                                                    Enumerable.Repeat(ParseToken(",").WithTrailingTrivia(Space),
-                                                                      md.ParameterList.Parameters.Count - 1))))
-                                            .WithLeadingTrivia(Space))
-                                        .WithLeadingTrivia(Whitespace(indent3)))
-                                .WithSemicolonToken(ParseToken(";").WithTrailingTrivia(LineFeed))
-                }
-                into m
-                select (!noClassLead ? $@"
-    /// <summary><c>{m.Name}</c> extension.</summary>
-
-    [GeneratedCode(""{thisAssemblyName.Name}"", ""{thisAssemblyName.Version}"")]" : null) + $@"
-    public static partial class {m.Name}Extension
-    {{
+            into e
+            select e.SourceOrder + ": "
+                 + e.Name + e.TypeParameters + e.Parameters + e.Abbreviations;
+
+        foreach (var m in ms)
+            Console.Error.WriteLine(m);
+    }
+
+    var indent = new string(' ', 4);
+    var indent2 = indent + indent;
+    var indent3 = indent2 + indent;
+
+    var baseImports = new []
+    {
+        "System",
+        "System.CodeDom.Compiler",
+        "System.Collections.Generic",
+        "System.Diagnostics.CodeAnalysis",
+    };
+
+    var imports =
+        from ns in baseImports.Concat(usings)
+        select indent + $"using {ns};";
+
+    var classes =
+        from md in q
+        select md.Method.Syntax into md
+        group md by (string) md.Identifier.Value into g
+        select new
+        {
+            Name = g.Key,
+            Overloads =
+                from md in g
+                select
+                    MethodDeclaration(md.ReturnType, md.Identifier)
+                        .WithAttributeLists(md.AttributeLists)
+                        .WithModifiers(md.Modifiers)
+                        .WithTypeParameterList(md.TypeParameterList)
+                        .WithConstraintClauses(md.ConstraintClauses)
+                        .WithParameterList(md.ParameterList)
+                        .WithExpressionBody(
+                            ArrowExpressionClause(
+                                InvocationExpression(
+                                    MemberAccessExpression(
+                                        SyntaxKind.SimpleMemberAccessExpression,
+                                        IdentifierName("MoreEnumerable"),
+                                        IdentifierName(md.Identifier)),
+                                    ArgumentList(
+                                        SeparatedList(
+                                            from p in md.ParameterList.Parameters
+                                            select Argument(IdentifierName(p.Identifier)),
+                                            Enumerable.Repeat(ParseToken(",").WithTrailingTrivia(Space),
+                                                              md.ParameterList.Parameters.Count - 1))))
+                                    .WithLeadingTrivia(Space))
+                                .WithLeadingTrivia(Whitespace(indent3)))
+                        .WithSemicolonToken(ParseToken(";").WithTrailingTrivia(LineFeed))
+        }
+        into m
+        select (!noClassLead ? $@"
+/// <summary><c>{m.Name}</c> extension.</summary>
+
+[GeneratedCode(""{thisAssemblyName.Name}"", ""{thisAssemblyName.Version}"")]" : null) + $@"
+public static partial class {m.Name}Extension
+{{
 {string.Join(null, from mo in m.Overloads select mo.ToFullString())}
-    }}";
-
-            var template = $@"
+}}";
+
+    var template = $@"
 #region License and Terms
 // MoreLINQ - Extensions to LINQ to Objects
 //
@@ -319,158 +326,142 @@
 {string.Join("\n", imports)}
 {string.Join("\n", classes)}
 }}
-            ";
-
-            Console.WriteLine(template.Trim()
-                                      // normalize line endings
-                                      .Replace("\r", string.Empty)
-                                      .Replace("\n", Environment.NewLine));
+    ";
+
+    Console.WriteLine(template.Trim()
+                              // normalize line endings
+                              .Replace("\r", string.Empty)
+                              .Replace("\n", Environment.NewLine));
+}
+
+static TypeKey CreateTypeKey(TypeSyntax root,
+                             Func<string, TypeKey> abbreviator = null)
+{
+    return Walk(root ?? throw new ArgumentNullException(nameof(root)));
+
+    TypeKey Walk(TypeSyntax ts) => ts switch
+    {
+        PredefinedTypeSyntax pts => new SimpleTypeKey(pts.ToString()),
+        NullableTypeSyntax nts   => new NullableTypeKey(Walk(nts.ElementType)),
+        IdentifierNameSyntax ins => abbreviator?.Invoke(ins.Identifier.ValueText)
+                                    ?? new SimpleTypeKey(ins.ToString()),
+        GenericNameSyntax gns =>
+            new GenericTypeKey(gns.Identifier.ToString(),
+                               ImmutableList.CreateRange(gns.TypeArgumentList.Arguments.Select(Walk))),
+        ArrayTypeSyntax ats =>
+            new ArrayTypeKey(Walk(ats.ElementType),
+                             ImmutableList.CreateRange(from rs in ats.RankSpecifiers
+                                                       select rs.Rank)),
+        TupleTypeSyntax tts =>
+            new TupleTypeKey(ImmutableList.CreateRange(from te in tts.Elements
+                                                       select Walk(te.Type))),
+        _ => throw new NotSupportedException("Unhandled type: " + ts)
+    };
+}
+
+static T Read<T>(IEnumerator<T> e, Func<Exception> errorFactory = null)
+{
+    if (!e.MoveNext())
+        throw errorFactory?.Invoke() ?? new InvalidOperationException();
+    return e.Current;
+}
+
+//
+// Logical type nodes designed to be structurally sortable based on:
+//
+// - Type parameter count
+// - Name
+// - Array rank, if an array
+// - Each type parameter (recursively)
+//
+
+abstract class TypeKey : IComparable<TypeKey>
+{
+    protected TypeKey(string name) => Name = name;
+
+    public string Name { get; }
+    public abstract ImmutableList<TypeKey> Parameters { get; }
+
+    public virtual int CompareTo(TypeKey other)
+        => ReferenceEquals(this, other) ? 0
+         : other == null ? 1
+         : Parameters.Count.CompareTo(other.Parameters.Count) is {} lc and not 0 ? lc
+         : string.Compare(Name, other.Name, StringComparison.Ordinal) is {} nc and not 0 ? nc
+         : CompareParameters(other);
+
+    protected virtual int CompareParameters(TypeKey other) =>
+        Compare(Parameters, other.Parameters);
+
+    protected static int Compare(IEnumerable<TypeKey> a, IEnumerable<TypeKey> b) =>
+        a.Zip(b, (us, them) => (Us: us, Them: them))
+         .Select(e => e.Us.CompareTo(e.Them))
+         .FirstOrDefault(e => e != 0);
+}
+
+sealed class SimpleTypeKey : TypeKey
+{
+    public SimpleTypeKey(string name) : base(name) {}
+    public override string ToString() => Name;
+    public override ImmutableList<TypeKey> Parameters => ImmutableList<TypeKey>.Empty;
+}
+
+abstract class ParameterizedTypeKey : TypeKey
+{
+    protected ParameterizedTypeKey(string name, TypeKey parameter) :
+        this(name, ImmutableList.Create(parameter)) {}
+
+    protected ParameterizedTypeKey(string name, ImmutableList<TypeKey> parameters) :
+        base(name) => Parameters = parameters;
+
+    public override ImmutableList<TypeKey> Parameters { get; }
+}
+
+sealed class GenericTypeKey : ParameterizedTypeKey
+{
+    public GenericTypeKey(string name, ImmutableList<TypeKey> parameters) :
+        base(name, parameters) {}
+
+    public override string ToString() =>
+        Name + "<" + string.Join(", ", Parameters) + ">";
+}
+
+sealed class NullableTypeKey : ParameterizedTypeKey
+{
+    public NullableTypeKey(TypeKey underlying) : base("?", underlying) {}
+    public override string ToString() => Parameters.Single() + "?";
+}
+
+sealed class TupleTypeKey : ParameterizedTypeKey
+{
+    public TupleTypeKey(ImmutableList<TypeKey> parameters) :
+        base("()", parameters) {}
+
+    public override string ToString() =>
+        "(" + string.Join(", ", Parameters) + ")";
+}
+
+sealed class ArrayTypeKey : ParameterizedTypeKey
+{
+    public ArrayTypeKey(TypeKey element, IEnumerable<int> ranks) :
+        base("[]", element) => Ranks = ImmutableList.CreateRange(ranks);
+
+    public ImmutableList<int> Ranks { get; }
+
+    public override string ToString() =>
+        Parameters.Single() + string.Concat(from r in Ranks
+                                            select "[" + string.Concat(Enumerable.Repeat(",", r - 1)) + "]");
+
+    protected override int CompareParameters(TypeKey other)
+    {
+        if (other is ArrayTypeKey a)
+        {
+            if (Ranks.Count.CompareTo(a.Ranks.Count) is {} rlc and not 0)
+                return rlc;
+            if (Ranks.Zip(a.Ranks, (us, them) => (Us: us, Them: them))
+                     .Aggregate(0, (c, r) => c == 0 ? r.Us.CompareTo(r.Them) : c) is {} rc and not 0)
+                return rc;
         }

-        public static TypeKey CreateTypeKey(TypeSyntax root,
-                                            Func<string, TypeKey> abbreviator = null)
-        {
-            return Walk(root ?? throw new ArgumentNullException(nameof(root)));
-
-            TypeKey Walk(TypeSyntax ts) => ts switch
-            {
-                PredefinedTypeSyntax pts => new SimpleTypeKey(pts.ToString()),
-                NullableTypeSyntax nts   => new NullableTypeKey(Walk(nts.ElementType)),
-                IdentifierNameSyntax ins => abbreviator?.Invoke(ins.Identifier.ValueText)
-                                            ?? new SimpleTypeKey(ins.ToString()),
-                GenericNameSyntax gns =>
-                    new GenericTypeKey(gns.Identifier.ToString(),
-                                       ImmutableList.CreateRange(gns.TypeArgumentList.Arguments.Select(Walk))),
-                ArrayTypeSyntax ats =>
-                    new ArrayTypeKey(Walk(ats.ElementType),
-                                     ImmutableList.CreateRange(from rs in ats.RankSpecifiers
-                                                               select rs.Rank)),
-                TupleTypeSyntax tts =>
-                    new TupleTypeKey(ImmutableList.CreateRange(from te in tts.Elements
-                                                               select Walk(te.Type))),
-                _ => throw new NotSupportedException("Unhandled type: " + ts)
-            };
-        }
-
-        static T Read<T>(IEnumerator<T> e, Func<Exception> errorFactory = null)
-        {
-            if (!e.MoveNext())
-                throw errorFactory?.Invoke() ?? new InvalidOperationException();
-            return e.Current;
-        }
-
-        static int Main(string[] args)
-        {
-            try
-            {
-                Run(args);
-                return 0;
-            }
-            catch (Exception e)
-            {
-                Console.Error.WriteLine(e.ToString());
-                return 0xbad;
-            }
-        }
+        return base.CompareParameters(other);
     }
-
-    //
-    // Logical type nodes designed to be structurally sortable based on:
-    //
-    // - Type parameter count
-    // - Name
-    // - Array rank, if an array
-    // - Each type parameter (recursively)
-    //
-
-    abstract class TypeKey : IComparable<TypeKey>
-    {
-        protected TypeKey(string name) => Name = name;
-
-        public string Name { get; }
-        public abstract ImmutableList<TypeKey> Parameters { get; }
-
-        public virtual int CompareTo(TypeKey other)
-            => ReferenceEquals(this, other) ? 0
-             : other == null ? 1
-             : Parameters.Count.CompareTo(other.Parameters.Count) is {} lc and not 0 ? lc
-             : string.Compare(Name, other.Name, StringComparison.Ordinal) is {} nc and not 0 ? nc
-             : CompareParameters(other);
-
-        protected virtual int CompareParameters(TypeKey other) =>
-            Compare(Parameters, other.Parameters);
-
-        protected static int Compare(IEnumerable<TypeKey> a, IEnumerable<TypeKey> b) =>
-            a.Zip(b, (us, them) => (Us: us, Them: them))
-             .Select(e => e.Us.CompareTo(e.Them))
-             .FirstOrDefault(e => e != 0);
-    }
-
-    sealed class SimpleTypeKey : TypeKey
-    {
-        public SimpleTypeKey(string name) : base(name) {}
-        public override string ToString() => Name;
-        public override ImmutableList<TypeKey> Parameters => ImmutableList<TypeKey>.Empty;
-    }
-
-    abstract class ParameterizedTypeKey : TypeKey
-    {
-        protected ParameterizedTypeKey(string name, TypeKey parameter) :
-            this(name, ImmutableList.Create(parameter)) {}
-
-        protected ParameterizedTypeKey(string name, ImmutableList<TypeKey> parameters) :
-            base(name) => Parameters = parameters;
-
-        public override ImmutableList<TypeKey> Parameters { get; }
-    }
-
-    sealed class GenericTypeKey : ParameterizedTypeKey
-    {
-        public GenericTypeKey(string name, ImmutableList<TypeKey> parameters) :
-            base(name, parameters) {}
-
-        public override string ToString() =>
-            Name + "<" + string.Join(", ", Parameters) + ">";
-    }
-
-    sealed class NullableTypeKey : ParameterizedTypeKey
-    {
-        public NullableTypeKey(TypeKey underlying) : base("?", underlying) {}
-        public override string ToString() => Parameters.Single() + "?";
-    }
-
-    sealed class TupleTypeKey : ParameterizedTypeKey
-    {
-        public TupleTypeKey(ImmutableList<TypeKey> parameters) :
-            base("()", parameters) {}
-
-        public override string ToString() =>
-            "(" + string.Join(", ", Parameters) + ")";
-    }
-
-    sealed class ArrayTypeKey : ParameterizedTypeKey
-    {
-        public ArrayTypeKey(TypeKey element, IEnumerable<int> ranks) :
-            base("[]", element) => Ranks = ImmutableList.CreateRange(ranks);
-
-        public ImmutableList<int> Ranks { get; }
-
-        public override string ToString() =>
-            Parameters.Single() + string.Concat(from r in Ranks
-                                                select "[" + string.Concat(Enumerable.Repeat(",", r - 1)) + "]");
-
-        protected override int CompareParameters(TypeKey other)
-        {
-            if (other is ArrayTypeKey a)
-            {
-                if (Ranks.Count.CompareTo(a.Ranks.Count) is {} rlc and not 0)
-                    return rlc;
-                if (Ranks.Zip(a.Ranks, (us, them) => (Us: us, Them: them))
-                         .Aggregate(0, (c, r) => c == 0 ? r.Us.CompareTo(r.Them) : c) is {} rc and not 0)
-                    return rc;
-            }
-
-            return base.CompareParameters(other);
-        }
-    }
-}
+}


screenshot.cs: fixes for the screenshot box inside screenshot_Mousemove()

--- kagv/screenshot.cs
+++ kagv/screenshot.cs
@@ -87,35 +87,47 @@

         private void screenshot_MouseMove(object sender, MouseEventArgs e)
         {
-            if( ismousedown)
+            if (ismousedown)
             {
                 gp = this.CreateGraphics();
                 gp.Clear(this.BackColor);
                 Pen p = new Pen(Color.Red);
                 p.Width = 4;

-                int rec_width=0, rec_height=0;
                 if (e.X > ClickedCoords.X)
-                {
-                    rec_width = e.X - ClickedCoords.X;
-                    rec_height = e.Y - ClickedCoords.Y;
                     shot = new Rectangle(
-                    ClickedCoords.X
-                    , ClickedCoords.Y
-                    , rec_width
-                    , rec_height);
-                }
-                else
-                {
-                    shot = new Rectangle(e.X, ClickedCoords.Y,
-                                         ClickedCoords.X-e.X, e.Y-ClickedCoords.Y
-                                            );
+                                         ClickedCoords.X,
+                                         ClickedCoords.Y,
+                                         e.X - ClickedCoords.X,
+                                         e.Y - ClickedCoords.Y
+                                        );
+                else if (e.X < ClickedCoords.X)
+                    shot = new Rectangle(
+                                         e.X,
+                                         ClickedCoords.Y,
+                                         ClickedCoords.X - e.X,
+                                         e.Y - ClickedCoords.Y
+                                        );

-                }
+                if (e.Y < ClickedCoords.Y)
+                    shot = new Rectangle(
+                                         ClickedCoords.X,
+                                         e.Y,
+                                         e.X - ClickedCoords.X,
+                                         ClickedCoords.Y - e.Y
+                                        );
+
+                if (e.Y < ClickedCoords.Y && e.X < ClickedCoords.X)
+                    shot = new Rectangle(
+                                         e.X,
+                                         e.Y,
+                                         ClickedCoords.X - e.X,
+                                         ClickedCoords.Y - e.Y
+                                        );

                 if (shot.Width <= 0 || shot.Height <= 0)
                     return;
-
+
                 gp.DrawRectangle(
                     p
                     , shot);