Esempio n. 1
0
        public async Task TestDeliveryExperimental()
        {
            MemoryGraph partialGraph = new MemoryGraph();

            #region EXPERIMENTAL DEMO
            /// =================================================================================================
            /// IMPORTANT: The following code makes use of the internal GraphTraversal class, which should not
            /// be used according to the documentation of Microsofts Graph Library. Use at your own risk.
            /// =================================================================================================
            var          graphConnection = GraphConnectionFactory.Create(client, collection);
            GraphCommand cmd             = GraphCommandFactory.Create(graphConnection);
            partialGraph.Drop();

            GraphTraversal personTrav = cmd.g().V().HasLabel("Person");
            {
                var persons = await personTrav.NextAsPOCO <IEndpointVertex>(partialGraph);

                foreach (Delivery.Person p in persons)
                {
                    Console.WriteLine($"Vertex ==> Label:{p.Label} Name:{p.FirstName}");
                }
            }
            #endregion
        }
        private static async Task <bool> UploadEdge(Edge edge)
        {
            var sourceNodePrimaryKey = nodes[edge.SourceNode].NodeIdAttribute;
            var destNodePrimaryKey   = nodes[edge.DestinationNode].NodeIdAttribute;

            var graphCommand = new GraphCommand(connection);

            // Get all existing edges so we can check if the edge already exist before inserting
            var getAllEdgeInternalInstruction = graphCommand.g().E().Values("EdgeId_Internal");
            var allEdgesInternalIds           = await getAllEdgeInternalInstruction.NextAsync();

            // Get list of all files in the directory for this edge
            var files = Directory.GetFiles(edge.PathToData).ToList();

            foreach (string filePath in files)
            {
                var lines = File.ReadAllLines(filePath).ToList();
                foreach (var line in lines)
                {
                    List <string> values = line.Split('\t').ToList();
                    Dictionary <string, string> keyval = new Dictionary <string, string>();

                    for (var i = 0; i < edge.Attributes.Count; i++)
                    {
                        keyval.Add(edge.Attributes[i], values[i]);
                    }

                    try
                    {
                        var insertEdgeInstruction = graphCommand.g().V().Has(sourceNodePrimaryKey, keyval[sourceNodePrimaryKey]).AddE(edge.SourceNode + edge.DestinationNode);
                        var edgeInternalId        = edge.Name;

                        foreach (var item in keyval)
                        {
                            if (item.Key != sourceNodePrimaryKey && item.Key != destNodePrimaryKey)
                            {
                                insertEdgeInstruction = insertEdgeInstruction.Property(item.Key, item.Value);
                            }

                            if (edge.PrimaryAttributes.Contains(item.Key))
                            {
                                edgeInternalId += item.Value;
                            }
                        }

                        insertEdgeInstruction = insertEdgeInstruction.Property("EdgeId_Internal", edgeInternalId).To(graphCommand.g().V().Has(destNodePrimaryKey, keyval[destNodePrimaryKey]));

                        if (!allEdgesInternalIds.Contains(edgeInternalId))
                        {
                            var resultInsert = await insertEdgeInstruction.NextAsync();

                            if (resultInsert.Count == 0 || resultInsert[0] == "[]")
                            {
                                throw new Exception("Could not insert edge");
                            }
                            Interlocked.Increment(ref counterUploaded);
                        }
                        else
                        {
                            Interlocked.Increment(ref counterExist);
                        }

                        Console.Write("\rUploaded " + counterUploaded + " edges and found " + counterExist + " existing edges");
                    }
                    catch (Exception ex)
                    {
                        errors.Add(edge.Name + " (" + ex + ") : " + JsonConvert.SerializeObject(keyval) + "\n");
                    }
                }
            }

            return(true);
        }
        private static async Task <bool> UploadNode(Node node)
        {
            var graphCommand = new GraphCommand(connection);

            // Get all existing edges so we can check if the edge already exist before inserting
            var getAllNodeInternalInstruction = graphCommand.g().V().Values("NodeId_Internal");
            var allNodesInternalIds           = await getAllNodeInternalInstruction.NextAsync();

            // Get list of all files in the directory for this node
            var files = Directory.GetFiles(node.PathToData).ToList();

            foreach (var filePath in files)
            {
                var lines = File.ReadAllLines(filePath).ToList();

                foreach (var line in lines)
                {
                    var values = line.Split('\t').ToList();
                    try
                    {
                        var insertNodeInstruction = graphCommand.g().AddV(node.Name);
                        var nodeInternalId        = node.Name;

                        for (int i = 0; i < node.Attributes.Count; i++)
                        {
                            insertNodeInstruction = insertNodeInstruction.Property(node.Attributes[i], values[i]);
                            if (node.PrimaryAttributes.Contains(node.Attributes[i]))
                            {
                                nodeInternalId += values[i];
                            }
                        }

                        insertNodeInstruction = insertNodeInstruction.Property("NodeId_Internal", nodeInternalId);

                        if (!allNodesInternalIds.Contains(nodeInternalId))
                        {
                            List <string> resultInsert = await insertNodeInstruction.NextAsync();

                            if (resultInsert.Count == 0 || resultInsert[0] == "[]")
                            {
                                throw new Exception("Could not insert node");
                            }

                            Interlocked.Increment(ref counterUploaded);
                        }
                        else
                        {
                            Interlocked.Increment(ref counterExist);
                        }

                        Console.Write("\rUploaded " + counterUploaded + " nodes and found " + counterExist + " existing nodes");
                    }
                    catch (Exception ex)
                    {
                        errors.Add(node.Name + " (" + ex + ") : " + JsonConvert.SerializeObject(values) + "\n");
                    }
                }
            }

            return(true);
        }
        public async Task Execute(DocumentClient client, DocumentCollection collection)
        {
            MemoryGraph context = new MemoryGraph();

            Person andreas = new Person()
            {
                FirstName = "Andreas", LastName = "Pollak"
            };
            Person tina = new Person()
            {
                FirstName = "Tina", LastName = "Pollak"
            };
            Place vienna = new Place()
            {
                name = "Vienna"
            };
            Place venice = new Place()
            {
                name = "Venice"
            };

            // Add EndPoints
            context.Add(andreas, tina, vienna, venice);

            DeliveryByCar   andreasTotina          = new DeliveryByCar(andreas, tina, 1);
            DeliveryByCar   andreasToVienna        = new DeliveryByCar(andreas, vienna, 1);
            DeliveryByCar   andreasToVenice        = new DeliveryByCar(andreas, venice, 5);
            DeliveryByTrain andreasToVeniceByTrain = new DeliveryByTrain(andreas, venice, 3, "TR0012");
            DeliveryByTrain tinaToViennaByTrain    = new DeliveryByTrain(tina, vienna, 2, "TR0042");

            // Add Paths/Edges
            context.Add(andreasTotina, andreasToVienna, andreasToVenice, andreasToVeniceByTrain, tinaToViennaByTrain);

            await client.UpsertGraphDocumentsAsync(collection, context);

            MemoryGraph partialGraph = new MemoryGraph();

            /// Try both queries in both directions first vertices then edges then edges and vertices
            var query = client.CreateGremlinQuery <Vertex>(collection, "g.V()");

            foreach (var result in await query.ExecuteNextAsyncAsPOCO <IEndpointVertex>(partialGraph))
            {
                Console.WriteLine(result.GetType().Name);
            }
            var edgeQuery = client.CreateGremlinQuery <Edge>(collection, "g.E()");

            foreach (var result in await edgeQuery.ExecuteNextAsyncAsPOCO <IDeliveryEdge>(partialGraph))
            {
                Console.WriteLine(result.GetType().Name);
            }

            #region EXPERIMENTAL DEMO
            /// =================================================================================================
            /// IMPORTANT: The following code makes use of the internal GraphTraversal class, which should not
            /// be used according to the documentation of Microsofts Graph Library. Use at your own risk.
            /// =================================================================================================
            var          graphConnection = GraphConnectionFactory.Create(client, collection);
            GraphCommand cmd             = GraphCommandFactory.Create(graphConnection);
            partialGraph.Drop();

            GraphTraversal personTrav = cmd.g().V().HasLabel("Person");
            {
                var persons = await personTrav.NextAsPOCO <IEndpointVertex>(partialGraph);

                foreach (Person p in persons)
                {
                    Console.WriteLine($"Vertex ==> Label:{p.Label} Name:{p.FirstName}");
                }
            }
            #endregion
        }