Example of Serialization in ASP.NET MVC Diagram Control
Serialization: save the diagram as a JSON file and load it again (or another diagram file), or send it through the server, which reads and writes it with UiDiagramSerializer. Change the diagram first to see it kept.
@Html.UiDiagram((UiDiagramOptions)ViewData["diagram"])
<p>
Serialization: save the diagram as a JSON file and load it again (or another diagram file), or send it through the server, which reads
and writes it with UiDiagramSerializer. Change the diagram first to see it kept.
</p>
<div class="d-flex flex-wrap gap-2 align-items-center mb-2">
<button type="button" class="btn btn-sm btn-outline-primary" data-serialize="save">Save to a file</button>
<label class="btn btn-sm btn-outline-primary mb-0" for="loadFile">Load a file</label>
<input type="file" id="loadFile" accept=".json,application/json" class="visually-hidden">
<button type="button" class="btn btn-sm btn-outline-primary" data-serialize="server">Through the server</button>
<button type="button" class="btn btn-sm btn-outline-secondary" data-serialize="clear">Clear</button>
</div>
@Html.UiDiagram((UiDiagramOptions)ViewData["diagram"])
<p class="small text-muted mt-2" id="diagramStatus" role="status" aria-live="polite"></p>
<script>
window.DiagramSamples = (function () {
'use strict';
function status(text) {
var el = document.getElementById('diagramStatus');
if (el) { el.textContent = text; }
}
function diagram() { return Lumen.get('serializationDiagram'); }
function counts() {
var d = diagram();
return d.nodes.length + ' nodes and ' + d.connectors.length + ' connectors';
}
function save() {
var url = URL.createObjectURL(new Blob([diagram().saveDiagram()], { type: 'application/json' }));
var a = document.createElement('a');
a.href = url;
a.download = 'diagram.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
status('Saved ' + counts() + ' as diagram.json.');
}
function throughServer() {
var token = Lumen._antiForgeryToken();
fetch('/DiagramDemo/RoundTrip', { method: 'POST', headers: { 'Content-Type': 'application/json', RequestVerificationToken: token }, body: diagram().saveDiagram() })
.then(function (r) { return r.text().then(function (t) { return { ok: r.ok, text: t }; }); })
.then(function (r) {
if (!r.ok) { status('The server refused it: ' + r.text); return; }
diagram().loadDiagram(r.text);
status('Sent through the server and loaded again: ' + counts() + '.');
});
}
document.addEventListener('click', function (e) {
var b = e.target.closest ? e.target.closest('[data-serialize]') : null;
if (!b) { return; }
var what = b.getAttribute('data-serialize');
if (what === 'save') { save(); }
else if (what === 'server') { throughServer(); }
else if (what === 'clear') { diagram().loadDiagram({ nodes: [], connectors: [] }); status('Cleared.'); }
});
document.addEventListener('change', function (e) {
if (!e.target || e.target.id !== 'loadFile' || !e.target.files.length) { return; }
var file = e.target.files[0];
e.target.value = '';
if (file.size > 5 * 1024 * 1024) { status('That file is larger than 5 MB.'); return; }
var reader = new FileReader();
reader.onload = function () {
status(diagram().loadDiagram(String(reader.result)) ? 'Loaded ' + file.name + ': ' + counts() + '.' : file.name + ' is not a diagram.');
};
reader.readAsText(file);
});
return {};
})();
</script>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class DiagramController : Controller
{
// The page is Views/Diagram/Serialization.cshtml; it draws what ViewData holds.
public ActionResult Serialization()
{
UiDiagramOptions o = FlowChart();
o.Id = "serializationDiagram";
o.Height = "460px";
o.AriaLabel = "Diagram to save and load";
o.OnSelectionChange = null;
ViewData["diagram"] = o;
return View();
}
private static UiDiagramNode Node(string id, double x, double y, string text, UiDiagramShapeType type = UiDiagramShapeType.Flow, string shape = "Process",
double width = 120, double height = 54, string fill = null)
{
var node = new UiDiagramNode
{
Id = id, OffsetX = x, OffsetY = y, Width = width, Height = height,
Shape = new UiDiagramShape { Type = type, Shape = shape },
Style = new UiDiagramStyle { Fill = fill }
};
if (text != null) { node.Annotations.Add(new UiDiagramAnnotation { Content = text }); }
return node;
}
private static UiDiagramConnector Link(string id, string from, string to, string label = null,
UiDiagramConnectorType type = UiDiagramConnectorType.Orthogonal)
{
var c = new UiDiagramConnector { Id = id, SourceID = from, TargetID = to, Type = type };
if (label != null) { c.Annotations.Add(new UiDiagramAnnotation { Content = label, Offset = new UiDiagramPoint { X = 0.5, Y = 0 } }); }
return c;
}
/// <summary>An order process, as a flow chart.</summary>
private static UiDiagramOptions FlowChart()
{
return new UiDiagramOptions
{
Id = "flowChart",
Height = "620px",
AriaLabel = "Order process flow chart",
Nodes = new List<UiDiagramNode>
{
Node("start", 300, 50, "New order", UiDiagramShapeType.Flow, "Terminator", fill: "#d9f2e6"),
Node("check", 300, 150, "Check stock", fill: "#e8f0fe"),
Node("inStock", 300, 270, "In stock?", UiDiagramShapeType.Flow, "Decision", 130, 80, "#fff4ce"),
Node("reorder", 520, 270, "Reorder from supplier", fill: "#e8f0fe"),
Node("pack", 300, 390, "Pack and ship", fill: "#e8f0fe"),
Node("invoice", 300, 490, "Send invoice", UiDiagramShapeType.Flow, "Document", fill: "#f3e8fd"),
Node("end", 300, 580, "Done", UiDiagramShapeType.Flow, "Terminator", fill: "#d9f2e6")
},
Connectors = new List<UiDiagramConnector>
{
Link("c1", "start", "check"), Link("c2", "check", "inStock"), Link("c3", "inStock", "pack", "Yes"), Link("c4", "inStock", "reorder", "No"),
Link("c5", "reorder", "check"), Link("c6", "pack", "invoice"), Link("c7", "invoice", "end")
},
OnSelectionChange = "DiagramSamples.selected"
};
}
/// <summary>
/// A diagram's JSON (what saveDiagram() gave) read by UiDiagramSerializer and written again: the Serialization sample's server side,
/// and the round-trip test's. 400 with the reason for JSON that is not a diagram.
/// </summary>
[HttpPost]
[ValidateJsonAntiForgeryToken]
public ActionResult RoundTrip()
{
string body;
Request.InputStream.Position = 0;
using (var reader = new StreamReader(Request.InputStream)) { body = reader.ReadToEnd(); }
List<UiDiagramNode> nodes;
List<UiDiagramConnector> connectors;
string error;
if (!UiDiagramSerializer.TryDeserialize(body, out nodes, out connectors, out error))
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Content(error, "text/plain");
}
return Content(UiDiagramSerializer.Serialize(nodes, connectors), "application/json");
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Diagrams with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@