Collaborative drawing with MindFusion.Diagramming and SignalR

In this post we’ll show how to use the ASP.NET MVC diagram library and SignalR to implement collaborative drawing of diagrams. This can be useful in visual planning tools where users work together on a task, such as project management or mind-mapping applications.

The complete sample project is available here –
CollabMindMap.zip

Start by creating an ASP.NET MVC application in Visual Studio. Open Tools -> Library Package Manager -> Package Manager Console and install the MindFusion.Diagramming.Mvc package –

Install-Package MindFusion.Diagramming.Mvc 

While we are there, also install the SignalR package –

install-package Microsoft.AspNet.SignalR

From the project’s context menu, Add submenu, select OWIN startup class and add SignalR to the OWIN pipeline by calling –

app.MapSignalR();

Now lets add a diagram view to the home page at Views/Home/Index.cshtml, load the necessary script files and wire up diagram event handlers that will send change notifications to the hub –

@using MindFusion.Diagramming
@using MindFusion.Diagramming.Mvc

@{
    var diagView = new DiagramView("diagramView")
        .NodeCreatedScript("onNodeCreated")
        .NodeModifiedScript("onNodeModified")
        .NodeTextEditedScript("onNodeTextEdited")
        .LinkCreatedScript("onLinkCreated")
        .LinkModifiedScript("onLinkModified")
        .LinkTextEditedScript("onLinkTextEdited")
        .ControlLoadedScript("onDiagramLoaded")
        .SetAllowInplaceEdit(true);

    diagView.Diagram.DefaultShape = Shapes.Ellipse;
}

@Html.DiagramView(diagView, new { style = "width:700px; height:600px;" })

@section scripts
{
    @Scripts.Render("~/Scripts/jquery.signalR-2.0.0.js")
    @Scripts.Render("~/Scripts/MindMap.js")
    @Scripts.Render("~/signalr/hubs")
}

The hub will synchronize operations done on the diagram by one client by sending a notification to all other connected clients. From the project context menu add a SignalR hub class, naming it DiagramHub. The model class we’ll use to describe node changes looks like this –

public class NodeModel
{
    [JsonProperty("x")]
    public double X { get; set; }

    [JsonProperty("y")]
    public double Y { get; set; }

    [JsonProperty("width")]
    public double Width { get; set; }

    [JsonProperty("height")]
    public double Height { get; set; }

    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
}

Add these three methods to the hub class to synchronize node creation, move, resize and edit-text operations –

public void NodeCreated(NodeModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).nodeCreated(clientModel);
}
public void NodeModified(NodeModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).nodeModified(clientModel);
}
public void NodeTextEdited(NodeModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).nodeTextEdited(clientModel);
}

The diagram event handlers in MindMap.js fill in the model objects and call respective hub methods –

function onNodeCreated(s, e)
{
    var hubId = $.connection.hub.id;
    e.node.id = hubId + s.getItems().length;

    var r = e.node.bounds;
    var model =
    {
        id: e.node.id,
        x: r.x,
        y: r.y,
        width: r.width,
        height: r.height
    };
    
    diagramHub.server.nodeCreated(model);
}

function onNodeModified(s, e)
{
    var r = e.node.bounds;
    var model =
    {
        id: e.node.id,
        x: r.x,
        y: r.y,
        width: r.width,
        height: r.height
    };
    diagramHub.server.nodeModified(model);
}

function onNodeTextEdited(s, e)
{
    var model =
    {
        id: e.node.id,
        text: e.getNewText()
    };
    diagramHub.server.nodeTextEdited(model);
}

Handle notifications sent from server to clients by updating the diagram from received model objects –

$(function ()
{
    diagramHub = $.connection.diagramHub;
    diagramHub.client.nodeCreated = function (model)
    {
        var node = diagram.factory.createShapeNode(
            model.x, model.y, model.width, model.height);
        node.id = model.id;
    };
    diagramHub.client.nodeModified = function (model)
    {
        var node = findNode(model.id);
        node.setBounds(
            new MindFusion.Drawing.Rect(
                model.x, model.y, model.width, model.height),
            true);
    };
    diagramHub.client.nodeTextEdited = function (model)
    {
        var node = findNode(model.id);
        node.setText(model.text);
    };
    $.connection.hub.start();
});

Finally add these helper functions for finding items and storing a global diagram reference –

function onDiagramLoaded(s, e)
{
    diagram = s;
}

function findNode(id)
{
    for (var i = 0; i < diagram.nodes.length; i++)
    {
        var node = diagram.nodes[i];
        if (id == node.id)
            return node;
    }
    return null;
}

function findLink(id)
{
    for (var i = 0; i < diagram.links.length; i++)
    {
        var link = diagram.links[i];
        if (id == link.id)
            return link;
    }
    return null;
}

Start several copies of the application in separate browser instances on your system (or even on different machines if you publish it on IIS or Azure). Now start drawing nodes, moving them or editing their text – changes done on the diagram in one browser will be immediately reflected in all other browsers connected to the hub. However we aren’t yet synchronizing link operations; lets fix that –

public class LinkModel
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("originId")]
    public string OriginId { get; set; }

    [JsonProperty("destinationId")]
    public string DestinationId { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
}

Add following hub methods in server class –

public void LinkCreated(LinkModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).linkCreated(clientModel);
}
public void LinkModified(LinkModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).linkModified(clientModel);
}
public void LinkTextEdited(LinkModel clientModel)
{
    Clients.AllExcept(Context.ConnectionId).linkTextEdited(clientModel);
}

Call them from respective JavaScript handlers of diagram link events –

function onLinkCreated(s, e)
{
    var hubId = $.connection.hub.id;
    e.link.id = hubId + s.getItems().length;

    var model =
    {
        id: e.link.id,
        originId: e.link.getOrigin().id,
        destinationId: e.link.getDestination().id,
    };
    
    diagramHub.server.linkCreated(model);
}

function onLinkModified(s, e)
{
    var hubId = $.connection.hub.id;
    var model =
    {
        id: e.link.id,
        originId: e.link.getOrigin().id,
        destinationId: e.link.getDestination().id,
    };
    diagramHub.server.linkModified(model);
}

function onLinkTextEdited(s, e)
{
    var model =
    {
        id: e.link.id,
        text: e.getNewText()
    };
    diagramHub.server.linkTextEdited(model);
}

Handle link-related client notifications by creating or modifying links –

diagramHub.client.linkCreated = function (model)
{
    var link = diagram.factory.createDiagramLink(
        findNode(model.originId), findNode(model.destinationId));
    link.id = model.id;
};
diagramHub.client.linkModified = function (model)
{
    var link = findLink(model.id);
    link.setOrigin(findNode(model.originId));
    link.setDestination(findNode(model.destinationId));
};
diagramHub.client.linkTextEdited = function (model)
{
    var link = findLink(model.id);
    link.setText(model.text);
};

Now the application will also synchronize link operations across all connected clients. Here’s a small diagram synchronized between three different browsers –
collaborative mind map

The sample above uses MindFusion’s ASP.NET MVC API. Code for other frameworks will look similar as MindFusion maintains same diagramming model for multiple platforms. You can download the trial version of any MindFusion.Diagramming component from this page.

Enjoy!

Diagramming for ASP.NET, V5.5

Here is the list of the recent changes and additions to MindFusion WebForms Diagram control:

Resize table columns and rows

Note: This feature is not available in ImageMap mode.

Columns and rows of a TableNode can now be resized interactively if its AllowResizeColumns or AllowResizeRows properties are enabled. In order to resize, move the mouse pointer to the border line on column’s right side or row’s bottom side until it shows resize cursor and start dragging. The control raises TableColumnResizing and TableRowResizing events to let you validate new size or prevent resizing some elements. The TableColumnResized and TableRowResized events are raised after the operation completes.

Diagramming for ASP.NET: Table Nodes

Diagramming for ASP.NET: Table Nodes

Canvas mode improvements

  • Shape library files and ShapeLibraryLocation properties of DiagramView and ShapeListBox can now be used in Canvas mode.
  • Items can now be deleted using Backspace key when running on Mac.
  • Caption divider line in TableNode and ContainerNode is now rendered clipped when caption height is smaller than corner radius.
  • The TooltipDelay property specifies the delay in milliseconds before showing tooltips.
  • The Orientation property of NodeListView lets you set the view’s orientation to Horizontal or Vertical (members of Orientation enum).
  • Fixed overlaps in client-side TreeLayout when arranging nodes of different sizes.
  • Fixed a bug where deserialization of custom item classes worked correctly only if their names contained Node or Link suffix.
  • MsAjaxLocation and JQueryLocation properties let you change the location of external script libraries.
Diagramming for ASP.NET: Node Shapes

Diagramming for ASP.NET: Node Shapes

ImageMap mode improvements

  • Image generator implementation changed from Page to IHttpHandler , this makes it more lightweight avoiding the full page life-cycle.
  • Image generation is now implemented by the built-in ImageHandler class inside MindFusion.Common.WebForms assembly and it no longer requires adding external .aspx file to the project. Instead, it can be listed in web.config file:
    <handlers>
        <add name="ImageHandler" path="ImageGen.ashx" verb="GET" type="MindFusion.Common.WebForms.ImageHandler, MindFusion.Common.WebForms">
    </add></handlers>
  • For convenience, there is still optional ImageGen.ashx provided as external file for easier set-up of the project (add existing file instead of changing web.config).
  • ZoomControl no longer draws using <canvas> element when running in ImageMap mode, but uses ImageHandler to generate bitmaps.

API changes

ZoomControl can now be used with other MindFusion components and has been moved to MindFusion.Common.WebForms namespace and assembly.

Here is a direct link to download the trial version:

Download MindFusion.Diagramming for ASP.NET, V5.5 Trial Version

Technical support
MindFusion support team is happy to assist you with any questions you might have about Diagramming for ASP.NET or any other of our products. You can leave a message at the discussion board, use the help desk or e-mail support@mindfusion.eu.. We strive to provide competent and detailed answers to your questions within hours of receiving them.

About Diagramming for ASP.NET: An advanced WebForms programming component that offers all the functionality that is needed for creating, styling and presenting attractive flowcharts, hierarchies, trees, graphs, schemes, diagrams and many more. The control offers numerous utility methods, path finding and cycle detection, rich event set and many useful user interaction features like tool tips, multiple selection, copy/paste to/from Windows clipboard and many more.

NetDiagram offers more than 100 predefined node shapes, scrollable tables, 13 automatic layouts and many more. You can check the online demo to see some of the features in action. The control includes many samples, detailed documentation and step-by-step tutorials. Every features is duly documented and there’s plenty of code to copy. The component is not only powerful and scalable, but easy to learn and fun to use.

MindFusion.WebForms Pack, 2015.R1

MindFusion announceс а неш release of our WebForms suite of components. Here is an overview of the most important new features:

Licensing

We no longer make separate trial build of the control assemblies. Instead there is a new LicenseKey property, which disables a component’s evaluation mode. If your application contains more than one control by MindFusion, you could call MindFusion.Licensing.LicenseManager.AddLicense(key) to specify the key once instead of setting it per each control. License key strings are listed on the Keys & Downloads page at MindFusion’s customer portal.

Zoom control

The ZoomControl class from MindFusion.Common.WebForms lets users change interactively the current zoom level and scroll position of a DiagramView or a MapView. To set it up, add a ZoomControl element to the page and set the control’s TargetId property to the id of the view. The control has numerous properties for customizing its appearance.

ASP.NET Diagrammer: The Zoom control

ASP.NET Diagrammer: The Zoom control

Visual Studio 2015 Toolbox Support

MindFusion.WebForms components can now be installed automatically into Visual Studio 2015 toolbox palette.

chartMindFusion.Charting

Custom Formatting of Labels for Line charts

Line charts now support custom formatting of labels. To use custom formatting, set LabelFormat to NumberFormat.Custom and use LabelCustomFormat.

Sorted Bars

The algorithm for sorting of bars has been improved. Bars in a series or in clusters can be sorted in ascending or descending order – use the SortOrder property. You can also sort each series/cluster with the SortSeriesBy property. Bar can be sorted with their colors preserved if SortColor is set to true.

ASP.NET Chart: The Bar chart control

ASP.NET Chart: The Bar chart control

MindFusion WebForms DiagrammerMindFusion.Diagramming

Canvas mode improvements

  • Shape property of TableNode and ContainerNode is now supported in Canvas mode.
  • CellFrameStyle and EnableStyledText properties of TableNode are now supported in Canvas mode.
  • CellTextEditedScript event raised when users edit the text of table cells.
  • CreateEditControlScript event lets you create custom DOM element or fragment to use as in-place text editor.
  • NodeListView raises nodeSelected event when the user selects a node.
  • Load XML files from client side by calling loadFromXml method of Diagram class.
  • as well many more new properties and events.

Styled text in Canvas mode

The EnableStyledText property of ShapeNode allows using HTML-like formatting tags to apply various attributes to the node’s text. At this time the component supports the following formatting tags:

<b> specifies bold text
<i> specifies italic text
<u> specifies underlined text
<color=value> specifies text color
<br /> specifies line break

Zoom control

(not available in JavaApplet mode)
The ZoomControl class lets users change interactively the current zoom level and scroll position of a DiagramView. To set it up, add a ZoomControl element to the page and set the control’s TargetId property to the id of a DiagramView. The control offers numerous customization properties like ZoomStep, ScrollStep and various appearance setting properties such as Fill, BorderColor, CornerRadius and TickPosition.

WebForms Gauge Control by MindFusionMindFusion.Gauges

Linear and oval gauge controls have been added to MindFusion.WebForms pack. The gauges are drawn on client side using HTML Canvas API. Users can change gauge values interactively by dragging their elements.

The ASP.NET Gauge control

The ASP.NET Gauge control

WebForms Scheduler by MindFusionMindFusion.Scheduling

Horizontal Timetable view

Horizontal layout has been added to the Timetable view. The horizontal timetable view displays a collection of rows where each row represents the allotment of resources to distinct hours of a day; the rows in this view represent dates, tasks, locations, contacts or resources.

ASP.NET UI Suite of controlsMindFusion.UI

The bundled jQuery version has been upgraded to 1.11.2.

You can read further details about the release at the announcement page at MindFUsion discussion board.

The trial version of the new MindFusion.WebForms Pack is available for direct download from this link:

Download MindFusion ASP.NET Pack 2015.R1

About MindFusion.WebForms Pack: A set of WebForms components that add great variety of features to your ASP.NET application with a few mouse clicks. The pack contains advanced components for diagramming, scheduling, charting and UI (Accordion, ColorPicker, TabControl, Window, WindowHost, DockControl, Button, Slideshow, Zoom and more). Each tool boasts easy to learn and use API and is quickly integrated into any web application that targets the ASP.NET platform. The controls support numerous options for styling, data import / export, user interaction and offer rich event set. There are plenty of samples and step-by-step tutorials as well detailed documentation.

Use the features page for each of the tools to find out more about its capabilities and the numerous ways it can boost your performance and speed up the development of your application:

Visit the buy page for details on the licensing scheme and prices. If you have questions please contact us. We shall be happy to assist you.

Diagramming for ASP.NET, V5.4.1 & Diagramming for ASP.NET MVC, V2.4

MindFusion is pleased to announce the new releases of its Diagramming components for ASP.NET MVC and ASP.NET. We have added the following new useful features:

Styled text
The ShapeNode.EnableStyledText property allows using HTML-like formatting tags to apply various attributes to the node’s text. At this time the components support the following formatting tags:

  • <b> specifies bold text
  • <i> specifies italic text
  • <u> specifies underlined text
  • <color=value> specifies text color
  • <br /> specifies line break
Styled text in an ASP.NET/ASP.NET MVC diagram

Styled text in an ASP.NET/ASP.NET MVC diagram

Improved text rendering

  • We have gratly improved the general text rendering quality. The components now remove scale transformations applied for MeasureUnit and ZoomFactor before drawing text on the canvas, and instead specify a scaled font size, which helps improve text appearance in Firefox and older versions of Chrome.
  • You can draw the items’ text underlined. To enable this, set the underline attribute of the Font class.
  • Font styles can be specified via Style instance by setting its FontStyle property.

License keys

MindFusion no longer provides separate trial and licensed versions of its components. Instead, you should set the LicenseKey property to disable a component’s evaluation mode and stop displaying trial messages. If your application has more than one Diagram instance or other controls by MindFusion, a single call to MindFusion.Licensing.LicenseManager.AddLicense(key) is enough to specify the key for all the controls. You can find your license key strings listed on the Keys & Downloads page at your http://clientsarea.eu account.

Miscellaneous

  • You can draw items using dashed lines in browsers that support the setLineDash function. To enable this, set the Pen.DashStyle property of DiagramItem or the StrokeDashStyle property of Style.
  • Client-side TreeLayout supports organizational charts with assistant nodes as in Microsoft Office diagrams. You can mark nodes as assistants if you set node.LayoutTraits[TreeLayout.Assistant] to a member of the AssistantType enumeration. Set
    TreeLayout.enableAssistants = true; 
    

    to arrange assistant nodes in a separate branch between the main node levels.

  • Specify if separate connected components of a graph should be arranged horizontally or vertically relatively to each other by setting the multipleGraphsPlacement attribute of layout classes.
  • The type of LinkLabel.Margin property has been changed from number to Thickness, letting you specify different margin sizes at each side of the label.
  • Masters for Start and Arrow7 shapes are added to VisioExporter template file.
  • VisioImporter now tries to preserve ShapeNode.Shape when importing from files created by VisioExporter.

The trial versions of the controls are available for download from the links below:

Download MindFusion.Diagramming for ASP.NET, V5.4.1

Download MindFusion.Diagramming for ASP.NET MVC, V2.4

MindFusion support team is happy to assist you with any questions you might have about Diagramming for ASP.NET MVC, Diagramming for ASP.NET or any other of our products. You can leave a message at the discussion board, use the help desk or e-mail support@mindfusion.eu.. We strive to provide competent and detailed answers to your questions within hours of receiving them.

About Diagramming for ASP.NET Component: An advanced WebForms programming component that offers all the functionality that is needed for creating, styling and presenting attractive flowcharts, hierarchies, trees, graphs, schemes, diagrams and many more. The control offers numerous utility methods, path finding and cycle detection, rich event set and many useful user interaction features like tool tips, multiple selection, copy/paste to/from Windows clipboard and many more.

NetDiagram offers over 100 predefined node shapes, scrollable tables, 13 automatic layouts and many more. You can check the online demo to see some of the features in action. The control includes many samples, detailed documentation and step-by-step tutorials. Every features is duly documented and there’s plenty of code to copy. The component is not only powerful and scalable, but easy to learn and fun to use.

About Diagramming for ASP.NET MVC Control: It is a multi-purpose diagramming tool that consists of two parts: a .NET class library running on the server and a client side control implemented in JavaScript. The server side .NET library implements a flow-diagramming object model that lets you define structures such as trees, flowcharts and graphs. Every element in the diagram is easily accessible and the whole diagram is rendered as part of an HTML page by just calling the DiagramView extension method.

On the client the diagram is rendered by a DiagramView JavaScript control that draws its content on an HTML Canvas. The user is able to add nodes and links simply by drawing them with the mouse. There is also a NodeListView control, which lets users create new nodes via drag and drop.

MvcDiagram also supports various automatic layout algorithms that will make every diagram easy to understand and nice to look at. The diagram can also be easily serialized in binary or XML format. Exporting is done in a variety of formats including Pdf, Svg, Visio and more. You can read details about the components at the MvcDiagram features page.

New Versions for Diagramming for ASP.NET, JavaScript and ASP.NET MVC

MindFusion has released new versions of its diagramming components for JavaScript, ASP.NET and ASP.NET MVC. The new features are almost identical and we list them below:

Zoom control
You can use the ZoomControl class to let users change interactively the current zoom level and scroll position of a DiagramView. First, add a ZoomControl element to the page and set the control’s TargetId property to the id of a DiagramView. Then set the ZoomStep and ScrollStep properties to specify the amount added to diagram’s zoom level or scroll position by ZoomControl’s buttons. You can customize the control’s appearance by setting properties such as Fill, BorderColor, CornerRadius and TickPosition.

Note: The Zoom control is not available in JavaApplet mode in Diagramming for ASP.NET.

The zoom control.

The zoom control.

Shadow styles
The Diagram.ShadowsStyle property and ShadowsStyle enumeration let you switch shadow rendering order between rendering all shadows in a single background layer (OneLevel) and drawing each shadow close to its node, possibly overlapping other nodes (ZOrder). ShadowsStyle.None lets you disable shadows altogether.

Miscellaneous

  • Set the LinkLabel.Brush property to fill the background of link labels.
  • Number of link segments can now be set by calling the DiagramLink.setSegmentCount() method.
  • The BackgroundImageAlign property specifies the alignment of diagram’s BackgroundImage.
  • The TextPadding property specifies the padding distance between the borders of a node and its text.
  • Nodes of all classes can be rotated.

You can download the trie versions of the components from the following links:

Download Diagramming for ASP.NET, V5.4

Download Diagramming for JavaScript, V2.2

Download Diagramming for ASP.NET MVC, V2.3

About Diagramming for JavaScript, ASP.NET and ASP.NET MVC: Web developers can use the tools to draw impressive diagrams, schemes, flowcharts, trees and many more. They are browser independent, easy to use and integrate into any web application. The components supports a variety of predefined node shapes, customizable links, rich event set and many appearance options.

The user interaction model includes resizing / moving / selecting and modifying any diagram element. The tools boast an elegant API, which is documented in details as well numerous step-by-step guides and tutorials. Various samples are provided to let you learn quickly how to use the most important features each library. The diagramming components are not only the perfect choice for creating any type of diagram in the browser – they can also arrange it the way you wish with a mouse click using one of the automatic graph layout algorithms. For more details about the features of each component, please visit its page: