### Fail Fast Principle Example Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Illustrates the 'fail fast' and 'exit fast' coding style by checking for a null argument at the beginning of a method and throwing an exception immediately. ```csharp // Ok public void SomeMethod(ISomething something) { // Check for known failure condition and exit quickly if (something is null) throw new ArgumentNullException(nameof(something)); var things = _somethingElse.GetThoseThings(); // ... } // Bad public void SomeMethod(ISomething something) { if (something != null) { var things = _somethingElse.GetThoseThings(); // Lots of logic here that a maintainer has to scroll through. } else { // This should be moved to the top of the method throw new ArgumentNullException(nameof(something)); } } ``` -------------------------------- ### Random Layout Algorithm Example Source: https://context7.com/kernelith/graphshape/llms.txt Applies the Random layout algorithm to place vertices within specified bounds. This is useful for initial visualization or when no specific arrangement is required. It requires vertex sizes and types to be defined. Ensure GraphShape and QuikGraph namespaces are imported. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); for (int i = 0; i < 10; i++) graph.AddVertex($"V{i}"); var vertexSizes = graph.Vertices.ToDictionary(v => v, v => new Size(40, 40)); var vertexTypes = graph.Vertices.ToDictionary(v => v, v => RandomVertexType.Free); var parameters = new RandomLayoutParameters { Bounds = new Size(800, 600) // Layout area bounds }; var algorithm = new RandomLayoutAlgorithm, IBidirectionalGraph>>( graph, null, vertexSizes, vertexTypes, parameters); algorithm.Compute(); ``` -------------------------------- ### LinLog Layout Algorithm Example Source: https://context7.com/kernelith/graphshape/llms.txt Applies the LinLog layout algorithm to a graph with two clusters connected by a bridge. This algorithm uses logarithmic attraction and linear repulsion forces, effective for graphs with community structure. Ensure GraphShape and QuikGraph namespaces are imported. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); // Create a graph with two clusters // Cluster 1 graph.AddEdgeRange(new[] { new Edge("A1", "A2"), new Edge("A2", "A3"), new Edge("A3", "A1") }); // Cluster 2 graph.AddEdgeRange(new[] { new Edge("B1", "B2"), new Edge("B2", "B3"), new Edge("B3", "B1") }); // Bridge between clusters graph.AddEdge(new Edge("A2", "B2")); var parameters = new LinLogLayoutParameters { AttractionExponent = 1.0, // Controls attraction strength RepulsiveExponent = 0.0 // Controls repulsion strength }; var algorithm = new LinLogLayoutAlgorithm, IBidirectionalGraph>>( graph, parameters); algorithm.Compute(); // Clusters will be visually separated var positions = algorithm.VerticesPositions; ``` -------------------------------- ### ISOM Layout Algorithm Example Source: https://context7.com/kernelith/graphshape/llms.txt Applies the ISOM (Inverted Self-Organizing Map) layout algorithm. This algorithm uses a self-organizing approach to position vertices iteratively. Key parameters include dimensions, epochs, and cooling/adaptation rates. Ensure GraphShape and QuikGraph namespaces are imported. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("Center", "N"), new Edge("Center", "S"), new Edge("Center", "E"), new Edge("Center", "W"), new Edge("N", "NE"), new Edge("E", "NE"), new Edge("S", "SE"), new Edge("E", "SE") }); var parameters = new ISOMLayoutParameters { Width = 500, Height = 500, MaxEpoch = 2000, RadiusConstantTime = 100, InitialRadius = 5, MinRadius = 1, CoolingFactor = 2, InitialAdaption = 0.9, MinAdaption = 0.0 }; var algorithm = new ISOMLayoutAlgorithm, IBidirectionalGraph>>( graph, parameters); algorithm.Compute(); ``` -------------------------------- ### Compound FDP Layout Algorithm Example Source: https://context7.com/kernelith/graphshape/llms.txt Applies the Compound FDP (Force-Directed Placement) algorithm for graphs with nested structures. It handles parent-child relationships between vertices. Requires definitions for vertex sizes, borders, and inner layout types. Ensure GraphShape and QuikGraph namespaces are imported. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("Container1", "Node1"), new Edge("Container1", "Node2"), new Edge("Container2", "Node3"), new Edge("Node1", "Node3"), new Edge("Node2", "Node3") }); var vertexSizes = graph.Vertices.ToDictionary(v => v, v => new Size(60, 40)); var vertexBorders = new Dictionary { ["Container1"] = new Thickness(5), ["Container2"] = new Thickness(5) }; var layoutTypes = new Dictionary { ["Container1"] = CompoundVertexInnerLayoutType.Automatic, ["Container2"] = CompoundVertexInnerLayoutType.Automatic }; var parameters = new CompoundFDPLayoutParameters { IdealEdgeLength = 50, ElasticConstant = 0.005, RepulsionConstant = 150, GravitationFactor = 8 }; var algorithm = new CompoundFDPLayoutAlgorithm, IBidirectionalGraph>>( graph, null, vertexSizes, vertexBorders, layoutTypes, parameters); algorithm.Compute(); ``` -------------------------------- ### LINQ Filter, Order, and Select Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Place 'Where' clauses before other query clauses to ensure subsequent operations work on a filtered dataset. This example filters by author, orders by publication year, and selects the result. ```csharp var tolkienBooks = books.Where(x => x.Author == "Tolkien") .OrderBy(x => x.PublicationYear) .Select(x); ``` -------------------------------- ### Interface Implementation Class Naming in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Suffix interface implementation classes with the non-prefixed interface name. For example, a class implementing 'ISomething' should be named 'ThisSomething'. ```csharp public class ThisSomething : ISomething { } ``` -------------------------------- ### C# Method Signature Line Breaks Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md When a C# method signature exceeds the line length limit, break each parameter onto a new, indented line, starting with the first parameter. ```csharp public void SomeMethodWithLongSignature( SomeObject parameter1, SomeOtherObject parameter2, SomeTestObject parameter3, SomeFinalObject parameter4) { } ``` -------------------------------- ### Use StandardLayoutAlgorithmFactory in C# Source: https://context7.com/kernelith/graphshape/llms.txt Demonstrates creating layout algorithms dynamically and checking requirements like overlap removal or edge routing. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("A", "B"), new Edge("B", "C"), new Edge("C", "D") }); var factory = new StandardLayoutAlgorithmFactory, IBidirectionalGraph>>(); // List available algorithms Console.WriteLine("Available algorithms:"); foreach (var algorithmType in factory.AlgorithmTypes) { Console.WriteLine($" - {algorithmType}"); } // Output: Circular, Tree, FR, BoundedFR, KK, ISOM, LinLog, Sugiyama, CompoundFDP, Random // Create layout context var sizes = graph.Vertices.ToDictionary(v => v, v => new Size(60, 30)); var context = new LayoutContext, IBidirectionalGraph>>( graph, null, // initial positions sizes, LayoutMode.Simple); // Create algorithm by name string algorithmType = "FR"; if (factory.IsValidAlgorithm(algorithmType)) { var parameters = factory.CreateParameters(algorithmType, null); var algorithm = factory.CreateAlgorithm(algorithmType, context, parameters); algorithm?.Compute(); // Check if additional processing is needed bool needsOverlapRemoval = factory.NeedOverlapRemoval(algorithmType); bool needsEdgeRouting = factory.NeedEdgeRouting(algorithmType); Console.WriteLine($"{algorithmType}: NeedsOverlapRemoval={needsOverlapRemoval}, NeedsEdgeRouting={needsEdgeRouting}"); } ``` -------------------------------- ### Implement Kamada-Kawai Layout in C# Source: https://context7.com/kernelith/graphshape/llms.txt Configures and executes the KK spring-model layout algorithm, including progress tracking via event subscription. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("Node1", "Node2"), new Edge("Node1", "Node3"), new Edge("Node2", "Node4"), new Edge("Node3", "Node4"), new Edge("Node4", "Node5"), new Edge("Node5", "Node6") }); // Configure KK layout parameters var parameters = new KKLayoutParameters { Width = 800, Height = 600, MaxIterations = 500, K = 1.0, // Spring constant LengthFactor = 1.0, // Multiplier for ideal edge length DisconnectedMultiplier = 0.5, // Distance factor for disconnected components ExchangeVertices = true // Allow vertex position swapping for optimization }; var algorithm = new KKLayoutAlgorithm, IBidirectionalGraph>>( graph, parameters); // Subscribe to progress updates algorithm.ProgressChanged += (sender, percent) => { Console.WriteLine($"Layout progress: {percent:F1}%"); }; algorithm.Compute(); // Get final positions var positions = algorithm.VerticesPositions; Console.WriteLine($"Layout computed for {positions.Count} vertices"); ``` -------------------------------- ### Simplify object creation with initializers Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use object and collection initializers to simplify the instantiation of complex types. ```csharp // Ok var myObjects = new List { new SomeObject("value1"), new SomeObject("value2"), }; var studentById = new Dictionary { [123456] = new Student { Name = "John Doe", Age = 17} }, [456789] = new Student { Name = "Dany Doe", Age = 16} }, }; ``` -------------------------------- ### Manage GraphLayout in C# Code-Behind Source: https://context7.com/kernelith/graphshape/llms.txt Demonstrates programmatic graph creation, layout configuration, and manual relayout triggers. ```csharp using GraphShape.Controls; using QuikGraph; // Code-behind usage public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // Create and bind a graph var graph = new BidirectionalGraph>(); var vertices = new object[] { "Start", "Process1", "Process2", "End" }; graph.AddVertexRange(vertices); graph.AddEdgeRange(new IEdge[] { new Edge("Start", "Process1"), new Edge("Start", "Process2"), new Edge("Process1", "End"), new Edge("Process2", "End") }); // Configure layout graphLayout.LayoutAlgorithmType = "Sugiyama"; graphLayout.OverlapRemovalAlgorithmType = "FSA"; graphLayout.OverlapRemovalConstraint = AlgorithmConstraints.Automatic; graphLayout.AsyncCompute = true; // Set the graph (triggers layout computation) graphLayout.Graph = graph; } private void RelayoutButton_Click(object sender, RoutedEventArgs e) { graphLayout.Relayout(); // Recompute layout from scratch } private void ContinueLayoutButton_Click(object sender, RoutedEventArgs e) { graphLayout.ContinueLayout(); // Continue from current positions } } ``` -------------------------------- ### Initialize arrays concisely Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use collection initializer syntax for arrays on declaration, or var with explicit instantiation. ```csharp string[] vowels1 = { "a", "e", "i", "o", "u" }; // If you use explicit instantiation, you can use var. var vowels2 = new string[] { "a", "e", "i", "o", "u" }; // If you specify an array size, you must initialize the elements one at a time. var vowels3 = new string[5]; vowels3[0] = "a"; vowels3[1] = "e"; // Etc ``` -------------------------------- ### Create wrappers for static dependencies Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md Define interfaces and wrappers for static .NET classes to improve testability and control behavior. ```csharp public interface IFile { bool Exists(string path); } public class FileWrapper : IFile { public bool Exists(string path) { return File.Exists(path); } } ``` -------------------------------- ### Simple Tree Layout Algorithm in C# Source: https://context7.com/kernelith/graphshape/llms.txt Arranges vertices hierarchically from a root. Supports multiple layout directions and configurable gaps. Uses BFS or DFS for spanning tree generation. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; // Create a tree-like graph structure var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("Root", "Child1"), new Edge("Root", "Child2"), new Edge("Root", "Child3"), new Edge("Child1", "Grandchild1"), new Edge("Child1", "Grandchild2"), new Edge("Child2", "Grandchild3"), new Edge("Child3", "Grandchild4"), new Edge("Child3", "Grandchild5") }); var vertexSizes = graph.Vertices.ToDictionary(v => v, v => new Size(80, 40)); var parameters = new SimpleTreeLayoutParameters { Direction = LayoutDirection.TopToBottom, // Tree grows downward VertexGap = 20, // Horizontal gap between siblings LayerGap = 50, // Vertical gap between layers SpanningTreeGeneration = SpanningTreeGeneration.BFS // Use breadth-first search }; var algorithm = new SimpleTreeLayoutAlgorithm, IBidirectionalGraph>>( graph, vertexSizes, parameters); algorithm.Compute(); // Vertices arranged in tree hierarchy // Root at top, children below, grandchildren at bottom ``` -------------------------------- ### Implement Fruchterman-Reingold Layout in C# Source: https://context7.com/kernelith/graphshape/llms.txt Configures and executes the FR force-directed layout algorithm to calculate vertex positions for a bidirectional graph. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; // Create a graph with vertices and edges var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("A", "B"), new Edge("A", "C"), new Edge("B", "D"), new Edge("C", "D"), new Edge("D", "E") }); // Configure FR layout parameters var parameters = new FreeFRLayoutParameters { MaxIterations = 200, InitialTemperature = 10.0, Lambda = 0.95, // Cooling factor for exponential cooling CoolingFunction = FRCoolingFunction.Exponential }; // Create and run the layout algorithm var algorithm = new FRLayoutAlgorithm, IBidirectionalGraph>>( graph, parameters); algorithm.Compute(); // Access computed vertex positions foreach (var vertex in graph.Vertices) { Point position = algorithm.VerticesPositions[vertex]; Console.WriteLine($"Vertex {vertex}: X={position.X:F2}, Y={position.Y:F2}"); } // Output: // Vertex A: X=45.32, Y=78.91 // Vertex B: X=123.45, Y=56.78 // Vertex C: X=89.12, Y=145.67 // Vertex D: X=167.89, Y=112.34 // Vertex E: X=234.56, Y=89.01 ``` -------------------------------- ### C# Comment Formatting Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/general-coding-guidelines.md Demonstrates the required spacing and style for single-line comments. ```csharp // This is a example comment. It showcases // the way comment must be written. ``` -------------------------------- ### Manage disposable objects with using Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use the using statement to ensure Dispose is called on IDisposable objects, replacing manual try-finally blocks. ```csharp // This try-finally statement only calls Dispose in the finally block var someDisposableObject = new DisposableObject(); try { // ... } finally { someDisposableObject.Dispose(); } // You can do the same thing with a using statement using (var someDisposableObject = new DisposableObject()) { // ... } ``` -------------------------------- ### Circular Layout Algorithm in C# Source: https://context7.com/kernelith/graphshape/llms.txt Arranges graph vertices in a circle. Requires vertex sizes to be defined. The circle radius is automatically calculated. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); string[] vertices = { "V1", "V2", "V3", "V4", "V5", "V6" }; foreach (var v in vertices) graph.AddVertex(v); graph.AddEdgeRange(new[] { new Edge("V1", "V2"), new Edge("V2", "V3"), new Edge("V3", "V4"), new Edge("V4", "V5"), new Edge("V5", "V6"), new Edge("V6", "V1") // Complete the cycle }); // Define vertex sizes (required for circular layout) var vertexSizes = new Dictionary(); foreach (var v in vertices) { vertexSizes[v] = new Size(50, 30); // Width=50, Height=30 } var algorithm = new CircularLayoutAlgorithm, IBidirectionalGraph>>( graph, vertexSizes, new CircularLayoutParameters()); algorithm.Compute(); // Vertices are now arranged in a circle foreach (var kvp in algorithm.VerticesPositions) { Console.WriteLine($"{kvp.Key}: ({kvp.Value.X:F2}, {kvp.Value.Y:F2})"); } ``` -------------------------------- ### Sugiyama (Hierarchical) Layout Algorithm in C# Source: https://context7.com/kernelith/graphshape/llms.txt Produces hierarchical layouts for DAGs by organizing vertices into layers and minimizing edge crossings. Supports configurable directions, gaps, and edge routing. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; // Create a DAG representing a dependency graph var graph = new BidirectionalGraph>(); graph.AddVerticesAndEdgeRange(new[] { new Edge("Start", "TaskA"), new Edge("Start", "TaskB"), new Edge("TaskA", "TaskC"), new Edge("TaskB", "TaskC"), new Edge("TaskB", "TaskD"), new Edge("TaskC", "End"), new Edge("TaskD", "End") }); var vertexSizes = graph.Vertices.ToDictionary(v => v, v => new Size(100, 50)); var parameters = new SugiyamaLayoutParameters { Direction = LayoutDirection.TopToBottom, LayerGap = 30, // Gap between layers SliceGap = 20, // Gap between vertices in same layer MinimizeEdgeLength = true, OptimizeWidth = false, EdgeRouting = SugiyamaEdgeRouting.Orthogonal // Use orthogonal edge routing }; var algorithm = new SugiyamaLayoutAlgorithm, IBidirectionalGraph>>( graph, null, // Initial positions (optional) vertexSizes, parameters); algorithm.Compute(); // Access edge routing information foreach (var edge in graph.Edges) { var routePoints = algorithm.EdgeRoutes[edge]; Console.WriteLine($"Edge {edge.Source} -> {edge.Target} has {routePoints?.Length ?? 0} route points"); } ``` -------------------------------- ### C# Code Commenting Structure Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/general-coding-guidelines.md Illustrates the recommended placement of comments relative to code blocks. ```csharp int[] scores = GetScores(); // Calculate the average int count = scores.Count; double sum = scores.Sum(); double average = sum / count; Console.WriteLine(x.Average); ``` -------------------------------- ### Implement Static Empty Property for Empty Instances Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md When a class represents a concept that can have an empty state, implement a static read-only `Empty` property. This provides a convenient and canonical way to access the empty instance. ```csharp public class SomeObject { public static readonly SomeObject Empty = new SomeObject(); // ... } ``` -------------------------------- ### Field Naming Convention in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Prefix all private fields with an underscore '_'. If a file's existing style differs, that style takes precedence. ```csharp public class SomeClass { private ISomething _thisSomething; } ``` -------------------------------- ### Configure GraphLayout State Tracking for Animation Source: https://context7.com/kernelith/graphshape/llms.txt Enable and utilize state tracking in the GraphLayout control for animating layout changes. This allows navigation through intermediate layout states and access to state-specific information. ```csharp // Configure state tracking graphLayout.ShowAllStates = true; // Store all intermediate states // After layout completes, navigate through states int totalStates = graphLayout.StateCount; Console.WriteLine($"Total layout states: {totalStates}"); // Jump to a specific state graphLayout.StateIndex = 0; // Go to initial state // Animate through states for (int i = 0; i < graphLayout.StateCount; i++) { graphLayout.StateIndex = i; await Task.Delay(100); // Wait between states } // Access current state information var currentState = graphLayout.LayoutState; Console.WriteLine($"State {currentState.StateIndex}: Computed in {currentState.ComputationTime}"); ``` -------------------------------- ### C# Property Backing Field Placement Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Define property-backing fields immediately before their corresponding properties in C#. ```csharp private string _name; public string Name { get => _name; set => _name = value; } ``` -------------------------------- ### Track Layout Algorithm Progress Source: https://context7.com/kernelith/graphshape/llms.txt Monitor the progress of layout algorithms during long-running computations. Event handlers can be attached to 'ProgressChanged' and 'IterationEnded' to receive updates and optionally abort the process. ```csharp using GraphShape; using GraphShape.Algorithms.Layout; using QuikGraph; var graph = new BidirectionalGraph>(); // ... add vertices and edges ... var algorithm = new FRLayoutAlgorithm, IBidirectionalGraph>>( graph, new FreeFRLayoutParameters { MaxIterations = 500 }); // Track progress algorithm.ProgressChanged += (sender, percent) => { Console.WriteLine($"Progress: {percent:F1}%"); // Update progress bar in UI }; // Track iterations algorithm.IterationEnded += (sender, args) => { Console.WriteLine($"Iteration {args.Iteration}: {args.StatusInPercent:F1}% - {args.Message}"); // Access intermediate positions var positions = args.VerticesPositions; // Optionally abort if (ShouldCancel) args.Abort = true; }; // Run asynchronously await Task.Run(() => algorithm.Compute()); Console.WriteLine("Layout complete!"); ``` -------------------------------- ### C# Allman Style Braces Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use Allman style braces for C# code, where each brace begins on a new line. Exceptions are allowed for single return or throw statements. ```csharp if (a == b) { c = d; } ``` ```csharp if (a == b) return; ``` ```csharp if (a == b) { c = d; } ``` ```csharp if (a == b) c = d; else { c = e; } ``` -------------------------------- ### Extension Class and File Naming in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Name extension classes and files by the type being extended. Remove the 'I' prefix for extensions of interfaces. This promotes discoverability of extension methods. ```csharp // SomeClassExtensions.cs public static class SomeClassExtensions { public static int ToInt(this SomeClass input) { // ... } } // Or public interface ISomething { } public static class SomethingExtensions { } ``` -------------------------------- ### Refactor misleading method names Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md Avoid negative method names that cause double negatives. Use descriptive names that accurately reflect the method's side effects. ```csharp // The method name includes the text "Not" and returns a boolean value. // This could create scenarios where callers are performing double // negatives, which are hard to read. private static bool IsNotConnected(SocketWrapper socket, string serverName) { // The behavior of the method currently checks if socket is connected to the provided // server. If not it tries to connect to it. But this is not reflected in the method name // at all and is only discoverable by a developer inspecting the code. if (socket.Server != serverName) { socket.Disconnect(); } if (socket.IsConnected()) return false; return !socket.Connect(serverName); } ``` ```csharp private static bool TryConnect(SocketWrapper socket, string serverName) { // ... } ``` -------------------------------- ### Implement FSA Overlap Removal in C# Source: https://context7.com/kernelith/graphshape/llms.txt Uses the FSAAlgorithm to compute minimal displacements for overlapping vertex rectangles. ```csharp using GraphShape; using GraphShape.Algorithms.OverlapRemoval; // Define rectangles representing vertex bounding boxes var rectangles = new Dictionary { ["V1"] = new Rect(0, 0, 100, 50), ["V2"] = new Rect(50, 25, 100, 50), // Overlaps with V1 ["V3"] = new Rect(80, 60, 100, 50), // Overlaps with V2 ["V4"] = new Rect(200, 0, 100, 50) // No overlap }; var parameters = new OverlapRemovalParameters { HorizontalGap = 10, // Minimum horizontal gap between rectangles VerticalGap = 10 // Minimum vertical gap between rectangles }; var algorithm = new FSAAlgorithm(rectangles, parameters); algorithm.Compute(); // Get adjusted positions foreach (var kvp in algorithm.Rectangles) { Console.WriteLine($"{kvp.Key}: Position=({kvp.Value.X:F2}, {kvp.Value.Y:F2})"); } ``` -------------------------------- ### Style Vertices and Edges with DataTemplates Source: https://context7.com/kernelith/graphshape/llms.txt Customizes the visual appearance of graph elements using WPF DataTemplates and Styles. ```xml ``` -------------------------------- ### Implement Null Object Pattern for Empty Interfaces Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md When an interface implementation does nothing, use the Null Object Pattern. This provides a default, non-operational implementation, adhering to the interface contract without requiring explicit null checks. ```csharp public interface ISomething { DateTime GetDateTime(string parameter); } public class NullSomething : ISomething { public DateTime GetDateTime(string parameter) { return default(DateTime); } } ``` -------------------------------- ### Declare local variables with appropriate types Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Specify explicit types for idiomatic types, but use var when the type is clear from the context. ```csharp // When the type of a variable is clear from the context, use var otherwise explicit it string var1 = "A string"; int var2 = 27; int var3 = Convert.ToInt32(Console.ReadLine()); int var4 = SomeFunction(); var var5 = new SomeClass(); SomeClass var6 = SomeOtherFunction(); ``` -------------------------------- ### C# Auto-Properties Formatting Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Define C# auto-properties on a single line for conciseness. ```csharp public int Property { get; set; } ``` ```csharp public int Property { get; set; } ``` -------------------------------- ### Filter and Select LINQ Query Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use method syntax for LINQ queries and meaningful variable names. Filters data based on author and selects book names. ```csharp var tolkienBooks = books.Where(x => x.Author == "Tolkien") .Select(x => x.Name); ``` -------------------------------- ### Implement Typed GraphLayout Source: https://context7.com/kernelith/graphshape/llms.txt Uses generic GraphLayout for custom vertex and edge types to ensure type safety. ```csharp using GraphShape.Controls; using QuikGraph; // Define custom vertex class public class MyVertex { public string Id { get; set; } public string Label { get; set; } public override string ToString() => Label; } // Define custom edge class public class MyEdge : Edge { public string Label { get; set; } public MyEdge(MyVertex source, MyVertex target, string label = null) : base(source, target) { Label = label; } } // Create typed graph layout public class MyGraphLayout : GraphLayout> { public MyGraphLayout() { // Default configuration LayoutAlgorithmType = "KK"; OverlapRemovalAlgorithmType = "FSA"; } } // Usage var graph = new BidirectionalGraph(); var v1 = new MyVertex { Id = "1", Label = "Node 1" }; var v2 = new MyVertex { Id = "2", Label = "Node 2" }; var v3 = new MyVertex { Id = "3", Label = "Node 3" }; graph.AddVertexRange(new[] { v1, v2, v3 }); graph.AddEdgeRange(new[] { new MyEdge(v1, v2, "Edge 1-2"), new MyEdge(v2, v3, "Edge 2-3"), new MyEdge(v1, v3, "Edge 1-3") }); var graphLayout = new MyGraphLayout(); graphLayout.Graph = graph; ``` -------------------------------- ### Explicit Scope vs. Implicit Scope Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Demonstrates the use of explicit scope/visibility modifiers (public, private) for class members, which is preferred over implicit scope. ```csharp // Ok public class Something { private const int MaximumAge = 100; public int Age { get; set; } public void SayHello() { Console.WriteLine("Hello"); } } // Bad class Something { const int MaximumAge = 100; int Age { get; set; } void SayHello() { Console.WriteLine("Hello"); } } ``` -------------------------------- ### C# Empty Constructors Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Constructors in C# with no bodies are not shortened and should be formatted with braces on separate lines. ```csharp public SomeClass() { } ``` ```csharp public SomeClass(string parameter) : base(parameter) { } ``` -------------------------------- ### Implement One Way FSA Overlap Removal in C# Source: https://context7.com/kernelith/graphshape/llms.txt Uses OneWayFSAAlgorithm to restrict vertex movement to a single dimension, preserving alignment in the other. ```csharp using GraphShape; using GraphShape.Algorithms.OverlapRemoval; var rectangles = new Dictionary { ["A"] = new Rect(0, 0, 80, 40), ["B"] = new Rect(60, 0, 80, 40), // Horizontal overlap ["C"] = new Rect(120, 0, 80, 40) // Horizontal overlap }; var parameters = new OneWayFSAParameters { HorizontalGap = 15, VerticalGap = 15, Way = OneWayFSAWay.Horizontal // Only adjust horizontal positions }; var algorithm = new OneWayFSAAlgorithm(rectangles, parameters); algorithm.Compute(); // Rectangles now have no horizontal overlaps, vertical positions unchanged ``` -------------------------------- ### Pascal Casing for Types and Methods in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use Pascal casing for public type names, method names, and constants. This convention enhances code readability and maintainability. ```csharp public class SomeClass { private const int DefaultSize = 100; public void SomeMethod() { } } ``` -------------------------------- ### Prefer Abstract Return Types in Interfaces Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md Use abstract return types like IEnumerable and IReadOnlyDictionary for public members to promote flexibility and prevent unintended modifications. Avoid concrete types like IList and IDictionary unless modifications are intended. ```csharp public interface IStudentDataProvider { IEnumerable GetAll(); IReadOnlyDictionary GetStudentByNameDictionary(); } ``` ```csharp public interface IStudentDataProvider { IList GetAll(); IDictionary GetStudentByNameDictionary(); } ``` -------------------------------- ### C# Supporting Method Placement Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Define non-shared supporting methods in C# immediately following the method they support, or use local methods declared at the end of the method. ```csharp public void DoSomethingInteresting() { // ... int something = GetSomething(); // ... int anotherThing = GetAnotherThing(); } private int GetSomething() { // ... } private int GetAnotherThing() { // ... } ``` ```csharp // Local method variant public void DoSomethingCompletelyDifferent() { int something = GetSomething(); // ... #region Local function int GetSomething() { // ... } #endregion } ``` -------------------------------- ### Define generic type parameters Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md Use 'T' for single generic types and descriptive names for multiple generic types. ```csharp public interface ISomething ``` ```csharp public interface IService ``` -------------------------------- ### Perform case-insensitive string comparisons Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use StringComparison.InvariantCultureIgnoreCase for case-insensitive checks instead of converting string casing. ```csharp string str1 = "Some string value"; string str2 = "SoMe STRing ValuE"; // Ok if (str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase)) { return true; } // Ok if (string.Equals(str1, str2, StringComparison.InvariantCultureIgnoreCase)) { return true; } // Bad if (value1.ToLower() == value2.ToLower()) { return true; } ``` -------------------------------- ### C# Base/This Constructor Calls Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Calls to base or this constructors in C# should be placed on an indented, separate line. ```csharp public SomeClass(string parameter) : base(parameter) { } ``` -------------------------------- ### Configure GraphLayout in XAML Source: https://context7.com/kernelith/graphshape/llms.txt Defines a GraphLayout control within a WPF Window, specifying layout and overlap removal algorithms. ```xml ``` -------------------------------- ### Camel Casing for Local Variables and Arguments in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Employ camel casing for local variable names and method arguments. This distinguishes them from type and method names. ```csharp public void SomeMethod(int someNumber) { int number; // ... } ``` -------------------------------- ### Concatenate strings with interpolation Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use string interpolation for concise concatenation of short strings. ```csharp string displayName = $"{person.LastName}, {person.FirstName}"; ``` -------------------------------- ### Append strings efficiently in loops Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use StringBuilder for appending strings within loops to improve performance with large amounts of text. ```csharp string phrase = "A long sentence"; var manyPhrases = new StringBuilder(); for (int i = 0; i < 10000; ++i) { manyPhrases.Append(phrase); } ``` -------------------------------- ### C# Brace Spacing Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Avoid blank lines between sets of closing braces in C# to maintain a compact structure. ```csharp if (a == b) { if (c == d) { if (e == f) { DoSomething(); } } } // The blank line above this brace should be removed. ``` -------------------------------- ### Interface Naming Convention in C# Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Prefix interface names with 'I' to clearly identify them as interfaces. This convention aids in distinguishing interfaces from concrete classes. ```csharp public interface ISomething { } ``` -------------------------------- ### C# Multi-line Conditional Statements Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md For multi-line conditional statements in C#, place the conditional operator at the beginning of each line for clarity. ```csharp public bool SomeMethod() { return !(myVar || myOtherVar || something || somethingElse) && string.IsNullOrWhiteSpace(myStr) && !string.IsNullOrWhiteSpace(myOtherStr); } ``` ```csharp public bool SomeMethod() { return !(myVar || myOtherVar || something || somethingElse) && string.IsNullOrWhiteSpace(myStr) && !string.IsNullOrWhiteSpace(myOtherStr); } ``` -------------------------------- ### LINQ Join with Anonymous Type Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use aliases to ensure correct capitalization (Pascal casing) for property names of anonymous types when joining collections. ```csharp var booksInfo = books.Join( authors, book => book.Author, author => author.Name, (book, author) => new { Book = book, Author = author }); ``` -------------------------------- ### Decompose Cache Provider Interface Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-best-practices.md Decompose a monolithic ICacheProvider into separate ICacheReader and ICacheWriter interfaces. This improves clarity and separation of concerns, making the intent of callers more explicit. ```csharp // Instead of doing this... public interface ICacheProvider { void RemoveObjects(string keys); void RemoveObject(string key); bool TryGetObject(string key, out object value); void SetObject(string key, object obj); void InsertObject(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration); } // Consider decomposing the interfaces like this public interface ICacheReader { bool TryGetObject(string key, out object value); } public interface ICacheWriter { void RemoveObjects(string keys); void RemoveObject(string key); void SetObject(string key, object obj); void InsertObject(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration); } ``` -------------------------------- ### Anonymous Type with Explicit Properties Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use explicit property names on anonymous types and prefer placing each property on a separate line for clarity. ```csharp var anonymousObj = { Property1 = sourceA.Property1, Property2 = sourceB.Property2 }; ``` -------------------------------- ### Validate method arguments for null Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Check for null values in public, protected, and internal method arguments to prevent unexpected null reference exceptions. ```csharp public void Something(object obj) { if (obj is null) throw new ArgumentNullException(nameof(obj)); } ``` -------------------------------- ### C# Generic Type Constraints Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Bring constraints for generic types in C# onto separate, indented lines for improved readability. ```csharp public abstract class SomeBase : SomeClass where TArg1 : ISomething, new() where TArg2 : class { } ``` -------------------------------- ### Validate constructor arguments for null Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Use the null-coalescing operator to throw ArgumentNullException during object construction. ```csharp public class A { private readonly B _b; public A(B b) { _b = b ?? throw new ArgumentNullException(nameof(b)); } } ``` -------------------------------- ### C# Blank Lines After Closing Braces Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Include blank lines after closing braces in C# when the next statement is not part of a continuing construct like if/else or try/catch/finally. ```csharp public static string ToCamelCase(string text) { if (string.IsNullOrWhiteSpace(text)) { return text; } return char.ToLower(text[0]) + text.Substring(1); } ``` ```csharp public static string ToCamelCase(string text) { if (string.IsNullOrWhiteSpace(text)) return text; return char.ToLower(text[0]) + text.Substring(1); } ``` ```csharp public static string ToCamelCase(string text) { if (string.IsNullOrWhiteSpace(text)) { return text; } return char.ToLower(text[0]) + text.Substring(1); } ``` -------------------------------- ### LINQ Join with Renamed Properties Source: https://github.com/kernelith/graphshape/blob/master/docs/documentation/guidelines/csharp-coding-guidelines.md Rename properties in the result of a LINQ join when property names can be ambiguous, to clarify their meaning. ```csharp var books = books.Join( authors, book => book.Author, author => author.Name, (book, author) => new { BookName = book.Name, AuthorId = author.Id }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.