/// <summary> /// Initializes a new instance of the <see cref="KDocumentBase"/> class. /// </summary> public CSDocument(Microsoft.CodeAnalysis.Document document) { this.IsGraphActive = true; this.Document = document; this.Name = document.Name; this.FilePath = document.FilePath; this.AvalonDocument = new ICSharpCode.AvalonEdit.Document.TextDocument() { FileName = this.Name, Text = File.ReadAllText(document.FilePath) }; this.AvalonDocument.TextChanged += AvalonDocument_TextChanged; if (File.Exists(this.GraphFilePath)) { _graph = GraphSerializer.Deserialize <CSGraph>(File.ReadAllText(this.GraphFilePath)); } else { _graph = new CSGraph(); } this.Graph.Name = Path.GetFileNameWithoutExtension(document.Name); this.Graph.FilePath = this.GraphFilePath; this.Graph.Document = document; _graph.GraphChanged += _graph_GraphChanged; _graph.NodeChanged += _graph_NodeChanged; _graph.NodeSelectionChanged += _graph_NodeSelectionChanged; _graph.CodeChanged += _graph_CodeChanged; OnNodeSelectionChanged(); }
public void Serialize_SerializedPrettyJsonIsValid() { // Arrange var node = new TestNode(99); var expected = new SerializedNode(node); string serializedNode; using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { // Act GraphSerializer.Serialize(writer, expected, true); writer.Flush(); serializedNode = Encoding.UTF8.GetString(stream.ToArray()); } using (var reader = new StringReader(serializedNode)) { // Assert var serializer = new JsonSerializer(); var actual = (SerializedNode)serializer.Deserialize(reader, typeof(SerializedNode)); Assert.Equal(expected.NodeType, actual.NodeType); Assert.Equal(((TestNode)expected.Node).SomeValue, ((TestNode)actual.Node).SomeValue); } }
public static void MyClassInitialize(TestContext testContext) { GraphSerializer gSrz = null; gSrz = new GraphSerializer(); m_graph = gSrz.Deserialize(@"c:\temp\training\car_graph.xml"); }
public void SaveGraph_LoadGraph_ReturnsEqualGraph( int obstaclePercent, int[] graphParams) { graphAssembler = new GraphAssemble( vertexFactory, coordinateFactory, graphFactory, costFactory, radarFactory); IGraph deserialized; var graph = graphAssembler.AssembleGraph( obstaclePercent, graphParams); var serializer = new GraphSerializer( formatter, vertexConverter, graphFactory); using (var stream = new MemoryStream()) { serializer.SaveGraph(graph, stream); stream.Seek(0, SeekOrigin.Begin); deserialized = serializer.LoadGraph(stream); } Assert.AreEqual(graph, deserialized); Assert.AreNotSame(graph, deserialized); }
public static void WriteToFile(string path, RequestGraph graph) { GraphSerializer.WriteToFile <RequestGraph, RequestNode>( path, graph, WriteGraphProperties, WriteNode); }
public static OperationGraph ReadFromFile(string path) { return(GraphSerializer.ReadFromFile( path, new OperationGraph(), (s, j, g) => { }, ReadNode)); }
public static void WriteToFile(string path, OperationGraph graph) { GraphSerializer.WriteToFile <OperationGraph, OperationNode>( path, graph, (h, g) => { }, WriteNode); }
public static RequestGraph ReadFromFile(string path) { return(GraphSerializer.ReadFromFile( path, new RequestGraph(), ReadGraphProperty, ReadNode)); }
protected bool DumpCFG() { using (Operation engineOp = L.Begin("Writing GraphML for control-flow graphs.")) { Dictionary <SourceRoutineSymbol, string> graphs = new Dictionary <SourceRoutineSymbol, string>(SourceRoutinesCompiler.ControlFlowGraphs.Count); XmlWriterSettings settings = new XmlWriterSettings() { Async = false, Encoding = Encoding.UTF32, Indent = true, IndentChars = " ", CloseOutput = false }; SourceRoutinesCompiler.ControlFlowGraphs.AsParallel().WithDegreeOfParallelism(MaxConcurrencyLevel).ForEach(graph => { StringBuilder s = new StringBuilder(1000); using (XmlWriter xw = XmlWriter.Create(s, settings)) { GraphSerializer.SerializeControlFlowGraph(graph.Value, xw); xw.Flush(); graphs.Add(graph.Key, s.ToString()); } }); if (OnlyTime) { engineOp.Complete(); return(true); } int count = 0; foreach (var g in graphs) { FileInfo outputFile = new FileInfo($"{OutputFile}-{++count}.graphml"); if (outputFile.Exists) { L.Warn("Overwriting existing output file {0}.", outputFile.FullName); } try { using (StreamWriter sw = new StreamWriter(outputFile.OpenWrite(), new UnicodeEncoding(false, true))) { sw.Write(g.Value); sw.Flush(); } L.Debug("Wrote GraphML for routine {0} in PHP source file {1} to file {2}.", g.Key.Name, g.Key.ContainingFile.SyntaxTree.FilePath, outputFile.FullName); } catch (IOException ioe) { L.Error(ioe, "I/O exception writing to file {file}", outputFile.FullName); } catch (Exception e) { L.Error(e, "Unknown exception writing to file {file}", outputFile.FullName); } } engineOp.Complete(); } return(true); }
public static void WriteToGraphvizFile(string path, OperationGraph graph) { var builder = new StringBuilder(); GraphSerializer.WriteToGraphvizFile( path, graph, n => GetNodeLabel(builder, n)); }
private Graph LoadGraphFromInfoFile() { GraphSerializer gSrz = null; Graph g = null; gSrz = new GraphSerializer(); g = gSrz.Deserialize(GRAPH_INFO_FILE); return(g); }
public void Test_Deserialize() { GraphSerializer gSrz = null; Graph g = null; gSrz = new GraphSerializer(); g = gSrz.Deserialize(GRAPH_INFO_FILE); Assert.AreEqual("Carmelia area roadmap as graph model", g.Description); }
public void Deserialize_Should_Throw_WhenGraphTypeNotFound() { var sgraph = new SGraph() { Type = "NonExistingType" }; var str = JsonConvert.SerializeObject(sgraph); Assert.That(() => GraphSerializer.Deserialize(str), Throws.InvalidOperationException); }
private void Save_Click(object sender, RoutedEventArgs e) { var dlg = new SaveFileDialog { Filter = "All files|*.*", Title = "Select layout file name", FileName = "laytest.xml" }; if (dlg.ShowDialog() == true) { GraphSerializer.Serialize(dlg.OpenFile(), myArea.LogicCore.Graph); } }
public void Serialize_Should_Throw_WhenNodeTypeNameNotSupported_ByCustomResolver() { var graphType = new GraphTypeWithResolver(); var graph = new GraphModel(graphType); var nodeType = new SourceNode(); var node = nodeType.CreateNode(); graph.AddNode(node); Assert.That(() => GraphSerializer.Serialize(graph), Throws.InvalidOperationException); }
private static string GetSerializeString(SerializedNode node, bool pretty = false) { string serializedNode; using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { // Act GraphSerializer.Serialize(writer, node, pretty); writer.Flush(); serializedNode = Encoding.UTF8.GetString(stream.ToArray()); } return(serializedNode); }
/// <summary> /// Works simmilar to ExecuteNextAsyc<T> from IDocumentQuery<T> and allows to deserialize the results /// to custom objects of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="gremlinQuery">ExtensionObject IDocumentQuery</param> /// <param name="context">Context that can store GraphElements. If you retrieved vertices and then an edge refering to those vertices they will be automatically linked.</param> /// <returns></returns> public static async Task <IList <T> > ExecuteNextAsyncAsPOCO <T>(this IDocumentQuery gremlinQuery, IGraphContext context = null) // where T : new() { List <T> result = new List <T>(); IGraphSerializer serializer = null; Type targetType = typeof(T); if (gremlinQuery.GetType().GenericTypeArguments[0] != typeof(Vertex)) { IDocumentQuery <Edge> edgeQuery = gremlinQuery as IDocumentQuery <Edge>; var resultSet = await edgeQuery.ExecuteNextAsync <Edge>(); foreach (Edge e in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(e, out string inVTypeString, out string outVTypeString); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(e, out object edge); result.Add((T)edge); } } else { IDocumentQuery <Vertex> vertexQuery = gremlinQuery as IDocumentQuery <Vertex>; var resultSet = await vertexQuery.ExecuteNextAsync <Vertex>(); foreach (Vertex v in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(v); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(v, out object vertex); result.Add((T)vertex); } } return(result); }
/// <summary>asdsf </summary> public static byte[] GetSerializedGraph() { var graph = DirectedGraph.CreateEmpty(7); graph.AddEdge(new DirectedEdge(graph.Vertices[0], graph.Vertices[5])); graph.AddEdge(new DirectedEdge(graph.Vertices[1], graph.Vertices[0])); graph.AddEdge(new DirectedEdge(graph.Vertices[1], graph.Vertices[5])); graph.AddEdge(new DirectedEdge(graph.Vertices[2], graph.Vertices[1])); graph.AddEdge(new DirectedEdge(graph.Vertices[2], graph.Vertices[5])); graph.AddEdge(new DirectedEdge(graph.Vertices[3], graph.Vertices[4])); graph.AddEdge(new DirectedEdge(graph.Vertices[4], graph.Vertices[2])); graph.AddEdge(new DirectedEdge(graph.Vertices[4], graph.Vertices[3])); graph.AddEdge(new DirectedEdge(graph.Vertices[5], graph.Vertices[6])); graph.AddEdge(new DirectedEdge(graph.Vertices[6], graph.Vertices[4])); return(GraphSerializer.Serialize(graph)); }
public void Deserialize_CanDeserializePrettyJson() { // Arrange var node = new TestNode(99); var expected = new SerializedNode(node); var serializedNode = GetSerializeString(expected, true); using (var reader = new StringReader(serializedNode)) { // Act var actual = GraphSerializer.Deserialize(reader); // Assert Assert.Equal(expected.NodeType, actual.NodeType); Assert.Equal(((TestNode)expected.Node).SomeValue, ((TestNode)actual.Node).SomeValue); } }
public void Deserialize_Should_Throw_WhenNodeTypeNotFound_ByCustomResolver() { var sgraph = new SGraph() { Type = typeof(GraphTypeWithResolver).FullName }; var snode = new SNode() { Type = "NonExistingType" }; sgraph.AddNode(snode); var str = JsonConvert.SerializeObject(sgraph); Assert.That(() => GraphSerializer.Deserialize(str), Throws.InvalidOperationException); }
/// <summary>asdsf </summary> public static byte[] GetSerializedWeightedGraph() { var graph = DirectedWeightedGraph.CreateEmpty(8); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[0], graph.Vertices[1], 2)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[0], graph.Vertices[6], 6)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[1], graph.Vertices[2], 7)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[1], graph.Vertices[4], 2)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[2], graph.Vertices[3], 3)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[4], graph.Vertices[5], 2)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[4], graph.Vertices[6], 1)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[5], graph.Vertices[2], 1)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[5], graph.Vertices[7], 2)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[6], graph.Vertices[7], 4)); graph.AddEdge(new DirectedWeightedEdge(graph.Vertices[7], graph.Vertices[3], 1)); return(GraphSerializer.Serialize(graph)); }
/// <summary> /// Loads a graph from a file. /// </summary> private void LoadGraph() { string path = this.FileSelector.GetFileNameForOpening(); if (!string.IsNullOrEmpty(path)) { try { var graph = GraphSerializer.ReadFromXmlFile(path); this.GraphViewModel.Graph = graph; } catch (GraphSerializationException ex) { Logger.Error("Loading graph form path '" + path + "' failed.", ex); this.MessageHandler.ShowError(ex.Message); } } }
/// <summary> /// Saves a graph to a file. /// </summary> private void SaveGraph() { string path = this.FileSelector.GetFileNameForSaving(); if (!string.IsNullOrEmpty(path)) { try { var graph = this.GraphViewModel.Graph; GraphSerializer.SaveAsXmlFile(graph, path); } catch (GraphSerializationException ex) { Logger.Error("Saving graph to path '" + path + "' failed.", ex); this.MessageHandler.ShowError(ex.Message); } } }
public void Deserialize_Should_Return_BrokenConnections(string fromNodeId, string fromPortId, string toNodeId, string toPortId) { var sgraph = new SGraph() { Type = typeof(GraphType).FullName }; var snode1 = new SNode() { Id = "1", Type = typeof(NodeWithProperties).FullName, Properties = "{}" }; var snode2 = new SNode() { Id = "2", Type = typeof(NodeWithProperties).FullName, Properties = "{}" }; sgraph.AddNode(snode1); sgraph.AddNode(snode2); var sconnection = new SConnection() { FromNodeId = fromNodeId, FromPortId = fromPortId, ToNodeId = toNodeId, ToPortId = toPortId, }; sgraph.AddConnection(sconnection); var brokenConnections = new List <SConnection>(); var str = JsonConvert.SerializeObject(sgraph); GraphSerializer.Deserialize(str, brokenConnections); Assert.That(brokenConnections, Has.Count.EqualTo(1)); var c = brokenConnections[0]; Assert.That(c.FromNodeId, Is.EqualTo(sconnection.FromNodeId)); Assert.That(c.FromPortId, Is.EqualTo(sconnection.FromPortId)); Assert.That(c.ToNodeId, Is.EqualTo(sconnection.ToNodeId)); Assert.That(c.ToPortId, Is.EqualTo(sconnection.ToPortId)); }
public void Deserialize_Should_Fix_ConnectionDirection() { var sgraph = new SGraph() { Type = typeof(GraphType).FullName }; var snode1 = new SNode() { Id = "1", Type = typeof(NodeWithProperties).FullName, Properties = "{}" }; var snode2 = new SNode() { Id = "2", Type = typeof(NodeWithProperties).FullName, Properties = "{}" }; sgraph.AddNode(snode1); sgraph.AddNode(snode2); // this connection has inverted direction: In -> Out var sconnection = new SConnection() { FromNodeId = "2", FromPortId = "In", ToNodeId = "1", ToPortId = "Out", }; sgraph.AddConnection(sconnection); var str = JsonConvert.SerializeObject(sgraph); var graph = GraphSerializer.Deserialize(str); Assert.That(graph.Connections.Count, Is.EqualTo(1)); var c = graph.Connections[0]; Assert.That(c.From.Node.Id, Is.EqualTo("1")); Assert.That(c.From.Id, Is.EqualTo("Out")); Assert.That(c.To.Node.Id, Is.EqualTo("2")); Assert.That(c.To.Id, Is.EqualTo("In")); }
private void Load_Click(object sender, RoutedEventArgs e) { var dlg = new OpenFileDialog { Filter = "All files|*.*", Title = "Select layout file", FileName = "laytest.xml" }; if (dlg.ShowDialog() != true) { return; } try { myArea.LogicCore.Graph = GraphSerializer.DeSerialize(dlg.OpenFile()); myArea.GenerateGraph(); } catch (Exception ex) { MessageBox.Show(string.Format("Failed to load layout file:\n {0}", ex)); } }
public void SaveGraph_LoadGraph_NotSerializableCoordinate_ThrowsCantSerializeGraphException( int obstaclePercent, int[] graphParams) { graphAssembler = new GraphAssemble( vertexFactory, notSerializableCoordinateFactory, graphFactory, costFactory, radarFactory); var graph = graphAssembler.AssembleGraph( obstaclePercent, graphParams); var serializer = new GraphSerializer( formatter, vertexConverter, graphFactory); Assert.Throws <CantSerializeGraphException>(() => { using var stream = new MemoryStream(); serializer.SaveGraph(graph, stream); stream.Seek(0, SeekOrigin.Begin); serializer.LoadGraph(stream); }); }
/// <summary> /// Loads a graph from a file if path is supplied as argument. /// </summary> /// <returns><c>null</c> if no path is supplied, otherwise the graph.</returns> private static IGraph <NodeData, EdgeData> LoadGraph() { var path = Environment.GetCommandLineArgs().ElementAtOrDefault(1); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return(null); } else { try { var graph = GraphSerializer.ReadFromXmlFile(path); Logger.Debug("Loaded graph from path: " + path); return(graph); } catch (GraphSerializationException ex) { Logger.Error("Loading graph form path '" + path + "' failed.", ex); MessageBox.Show(ex.Message, Palmmedia.WpfGraph.UI.Properties.Resources.Error); return(null); } } }
public void Deserialize_Should_Throw_WhenNullGraph() { Assert.That(() => GraphSerializer.Deserialize(null), Throws.ArgumentNullException); }
/// <summary> /// Can be called on a GraphTraversal to retrieve Vertices or Edges as custom objects. /// </summary> /// <typeparam name="T">Type of custom object that represents the Vertex or Edge</typeparam> /// <param name="trav">Extension Object GraphTraversal</param> /// <param name="context">Context that can store GraphElements. If you retrieved vertices and then an edge refering to those vertices they will be automatically linked.</param> /// <returns></returns> public static async Task <IList <T> > NextAsPOCO <T>(this GraphTraversal trav, IGraphContext context = null) // where T : new() { IGraphSerializer serializer = null; List <T> result = new List <T>(); /// Verify if the OutputFormat of the GraphCommand was set to GraphSON! Type graphTraversalType = typeof(GraphTraversal); Type targetType = typeof(T); FieldInfo outputFormatPropertyInfo = graphTraversalType.GetField("outputFormat", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); string outputFormat = outputFormatPropertyInfo.GetValue(trav).ToString(); if (!outputFormat.StartsWith("GraphSON")) { throw new Exception("OutputFormat of GraphCommand needs to be set to GRAPHSON!"); } // GraphSerializer<T> serializer = GraphSerializerFactory.CreateGraphSerializer<T>(context); // Edges and Vertices must be treated separately if (GraphSerializer.GetElementType(typeof(T)) == GraphElementType.Edge) { List <Edge> resultSet = await trav.NextAsModelAsync <Edge>(); foreach (Edge e in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(e, out string inVTypeString, out string outVTypeString); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(e, out object edge); result.Add((T)edge); } } else { List <Vertex> resultSet = await trav.NextAsModelAsync <Vertex>(); foreach (Vertex v in resultSet) { string typeString = GraphSerializer.GetTypePropertyString(v); if (String.IsNullOrEmpty(typeString)) { serializer = GraphSerializerFactory.CreateGraphSerializer(context, targetType); // Try to instantiate T } else { serializer = GraphSerializerFactory.CreateGraphSerializer(context, typeString); } serializer.Convert(v, out object vertex); result.Add((T)vertex); } //Alternative implementation TODO: Measure speed //========================== //foreach (var graphSON in trav) //{ // List<T> partialResult = serializer.DeserializeGraphSON(graphSON); // foreach (T r in partialResult) // result.Add(r); //} } return(result); }