public void Execute_Edge_DataSetFilled() { GraphClient session = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.E()"); GraphCommandOperation cosmosdbQuery = new GraphCommandFactory().Instantiate(session, statement, null).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(session.CreateClientOperation(), cosmosdbQuery); var ds = engine.Execute(); Assert.That(ds.Tables, Has.Count.EqualTo(1)); Assert.That(ds.Tables[0].Rows, Has.Count.EqualTo(3)); Assert.That(ds.Tables[0].Columns, Has.Count.EqualTo(7)); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("id")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("label")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("type")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("inV")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("outV")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("inVLabel")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("outVLabel")); var outVs = new List <object>(); var inVs = new List <object>(); foreach (DataRow row in ds.Tables[0].Rows) { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { if (row.Table.Columns[i].ColumnName == "outV") { outVs.Add(row.ItemArray[i]); } else if (row.Table.Columns[i].ColumnName == "inV") { inVs.Add(row.ItemArray[i]); } } } foreach (var expectedInV in new[] { "mary", "ben", "robin" }) { Assert.That(inVs, Has.Member(expectedInV)); } foreach (var expectedOutV in new[] { "thomas", "ben" }) { Assert.That(outVs, Has.Member(expectedOutV)); } foreach (DataRow row in ds.Tables[0].Rows) { Assert.That(row["id"], Is.Not.Null.Or.Empty); Assert.That(row["inVLabel"], Is.EqualTo("person")); Assert.That(row["outVLabel"], Is.EqualTo("person")); Assert.That(row["label"], Is.EqualTo("knows")); Assert.That(row["type"], Is.EqualTo("edge")); } }
public void CanHandle_OtherKindOfClient_False() { var client = Mock.Of <IClient>(); var query = Mock.Of <IQuery>(); var factory = new GraphCommandFactory(); Assert.That(factory.CanHandle(client), Is.False); }
public void CanHandle_GraphClient_True() { var client = new GraphClient("xyz", "graphs", base64AuthKey, "db", "FoF"); var query = Mock.Of <IQuery>(); var factory = new GraphCommandFactory(); Assert.That(factory.CanHandle(client), Is.True); }
public void Instantiate_GraphClientAndQuery_CommandNotNull() { var client = new GraphClient("xyz", "graphs", base64AuthKey, "db", "FoF"); var query = Mock.Of <IQuery>(); var factory = new GraphCommandFactory(); var command = factory.Instantiate(client, query); Assert.That(command, Is.Not.Null); }
public void Instantiate_GraphClientAndQuery_ClientCorrectType() { var client = new GraphClient("xyz", "graphs", base64AuthKey, "db", "FoF"); var query = Mock.Of <IQuery>(); var factory = new GraphCommandFactory(); var command = factory.Instantiate(client, query); var impl = command.Client; Assert.That(impl, Is.Not.Null); Assert.That(impl, Is.InstanceOf <GraphClientOperation>()); }
public void Execute_Vertex_DataSetFilled() { GraphClient session = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.V()"); GraphCommandOperation cosmosdbQuery = new GraphCommandFactory().Instantiate(session, statement, null).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(session.CreateClientOperation(), cosmosdbQuery); var ds = engine.Execute(); Assert.That(ds.Tables, Has.Count.EqualTo(1)); Assert.That(ds.Tables[0].Rows, Has.Count.EqualTo(4)); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("id")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("label")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("type")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("firstName")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("age")); var firstNames = new List <object>(); var ages = new List <object>(); foreach (DataRow row in ds.Tables[0].Rows) { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { if (row.Table.Columns[i].ColumnName == "firstName") { firstNames.Add(row.ItemArray[i]); } else if (row.Table.Columns[i].ColumnName == "age") { ages.Add(row.ItemArray[i]); } } } foreach (var expectedFirstName in new[] { "Thomas", "Mary", "Ben", "Robin" }) { Assert.That(firstNames, Has.Member(expectedFirstName)); } foreach (var expectedAge in new object[] { 44, DBNull.Value, 39 }) { Assert.That(ages, Has.Member(expectedAge)); } foreach (DataRow row in ds.Tables[0].Rows) { Assert.That(row["id"], Is.Not.Null.Or.Empty); Assert.That(row["label"], Is.EqualTo("person")); Assert.That(row["type"], Is.EqualTo("vertex")); } }
public void Execute_NullString_ScalarReturned() { GraphClient client = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.V('thomas').values('lastName')"); GraphCommandOperation commandOperation = new GraphCommandFactory().Instantiate(client, statement, null).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(client.CreateClientOperation(), commandOperation); var count = engine.ExecuteScalar(); Assert.That(count, Is.Null); }
public void Execute_String_ScalarReturned() { GraphClient session = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.V('mary').values('lastName')"); GraphCommandOperation cosmosdbQuery = new GraphCommandFactory().Instantiate(session, statement, null).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(session.CreateClientOperation(), cosmosdbQuery); var count = engine.ExecuteScalar(); Assert.That(count, Is.EqualTo("Andersen")); }
public void Execute_ListOfString_ListReturned() { GraphClient session = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.V().values('lastName')"); GraphCommandOperation cosmosdbQuery = new GraphCommandFactory().Instantiate(session, statement, null).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(session.CreateClientOperation(), cosmosdbQuery); var count = engine.ExecuteList <string>(); Assert.That(count, Has.Member("Andersen")); Assert.That(count, Has.Member("Miller")); Assert.That(count, Has.Member("Wakefield")); }
public void Instantiate_NoParameter_CorrectResultSet() { GraphClient client = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var query = Mock.Of <IQuery>( x => x.Statement == "g.V()" ); var factory = new GraphCommandFactory(); var cosmosdbQuery = (factory.Instantiate(client, query, null).Implementation) as GraphCommandOperation; var statement = cosmosdbQuery.Create(); var session = client.CreateClientOperation(); var results = session.Run(statement); Assert.That(results.Count, Is.EqualTo(4)); }
public void Execute_ProjectionOfObjects_DataSetFilled() { GraphClient session = new GraphClientFactory().Instantiate(ConnectionStringReader.GetLocaleGraph()) as GraphClient; var statement = Mock.Of <IQuery>(x => x.Statement == "g.V().project('FirstName','KnowsCount').by('firstName').by(out().Count())"); GraphCommandOperation cosmosdbQuery = new GraphCommandFactory().Instantiate(session, statement).Implementation as GraphCommandOperation; var engine = new GraphExecutionEngine(session.CreateClientOperation(), cosmosdbQuery); var ds = engine.Execute(); Assert.That(ds.Tables, Has.Count.EqualTo(1)); Assert.That(ds.Tables[0].Rows, Has.Count.EqualTo(4)); Assert.That(ds.Tables[0].Columns, Has.Count.EqualTo(2)); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("FirstName")); Assert.That(ds.Tables[0].Columns.Cast <DataColumn>().Select(x => x.ColumnName), Has.Member("KnowsCount")); var firstNames = new List <object>(); var knowsCount = new List <object>(); foreach (DataRow row in ds.Tables[0].Rows) { for (int i = 0; i < ds.Tables[0].Columns.Count; i++) { if (row.Table.Columns[i].ColumnName == "FirstName") { firstNames.Add(row.ItemArray[i]); } else if (row.Table.Columns[i].ColumnName == "KnowsCount") { knowsCount.Add(row.ItemArray[i]); } } } foreach (var expectedFirstName in new[] { "Thomas", "Mary", "Ben", "Robin" }) { Assert.That(firstNames, Has.Member(expectedFirstName)); } foreach (var expectedKnowsCount in new object[] { 2, 1, 0 }) { Assert.That(knowsCount, Has.Member(expectedKnowsCount)); } }
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 }
public async Task TestSimple() { Simple.Place cave = new Simple.Place() { name = "Cave of Hobbit" }; Simple.Place restaurant = new Simple.Place() { name = "Restaurant Green Dragon" }; Simple.Place europe = new Simple.Place() { name = "Europe", country = GraphProperty.Create("country", "AT", "MetaTag1", "Austria").AddValue("FI", "MetaTag1", "Finnland") }; Simple.Path hobbitPath = new Simple.Path(cave, restaurant, 2); //TODO: find out why 2.3 has an issue await client.CreateGraphDocumentAsync <Simple.Place>(collection, cave); await client.CreateGraphDocumentAsync <Simple.Place>(collection, restaurant); await client.CreateGraphDocumentAsync <Simple.Place>(collection, europe); await client.CreateGraphDocumentAsync <Simple.Path>(collection, hobbitPath); MemoryGraph partialGraph = new MemoryGraph(); string gremlinQueryStatement = "g.V().hasLabel('place')"; Console.WriteLine($"Executing gremlin query as string: {gremlinQueryStatement}"); var germlinQuery = client.CreateGremlinQuery <Vertex>(collection, gremlinQueryStatement); while (germlinQuery.HasMoreResults) { // It is not required to pass in a context like partialGraph here. This parameter can be omitted. foreach (var result in await germlinQuery.ExecuteNextAsyncAsPOCO <Simple.Place>(partialGraph)) { Console.WriteLine($"Vertex ==> Label:{result.Label} Name:{result.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. /// ================================================================================================= // Connect with GraphConnection object graphConnection = GraphConnectionFactory.Create(client, collection); // Drop previous context (optional if the same graph) partialGraph.Drop(); Microsoft.Azure.Graphs.GraphCommand cmd = GraphCommandFactory.Create(graphConnection); GraphTraversal placeTrav = cmd.g().V().HasLabel("place"); GraphTraversal edgeTrav = cmd.g().E().HasLabel("path"); { Console.WriteLine("Retrieving all places with 'NextAsPOCO'-Extension on GraphTraversal "); // Returns a list of all vertices for place var places = await placeTrav.NextAsPOCO <Simple.Place>(partialGraph); foreach (Simple.Place place in places) { Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}"); } } // Drop previous context (optional if the same graph) partialGraph.Drop(); IGraphSerializer <Simple.Place> placeGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Simple.Place>(partialGraph); foreach (var p in placeTrav) { IList <Simple.Place> places = placeGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each call foreach (Simple.Place place in places) { Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}"); Console.WriteLine("Serializing to CosmosDB internal represenation: "); string docDBJson = placeGraphSerializer.ConvertToDocDBJObject(place).ToString(); Console.WriteLine($"JSON ==> {docDBJson}"); } } Console.WriteLine("Iterating over GraphTraversal Paths (Edges) and deserializing GraphSON to custom object "); IGraphSerializer <Simple.Path> pathGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Simple.Path>(partialGraph); foreach (var p in edgeTrav) { IList <Simple.Path> paths = pathGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each loop foreach (Simple.Path path in paths) { Console.WriteLine($"Edge ==> Label:{path.Label} Weight:{path.weight}"); Console.WriteLine("Serializing to CosmosDB internal represenation: "); string docDBJson = pathGraphSerializer.ConvertToDocDBJObject(path).ToString(); Console.WriteLine($"JSON ==> {docDBJson}"); } } #endregion }
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 }
static async Task Demo() { try { Console.WriteLine("========================================================="); Console.WriteLine("Demo for the SpectoLogic.Azure.CosmosDB Extension Library"); Console.WriteLine("(c) by SpectoLogic e.U. 2017"); Console.WriteLine("written by Andreas Pollak"); Console.WriteLine("Licensed under the MIT License"); Console.WriteLine("========================================================="); // Connect with DocumentClient and create necessary Database and Collection Console.Write("Creating Collection 'thehobbit'..."); DocumentClient client = await CosmosDBHelper.ConnectToCosmosDB(Account_DemoBuild_Hobbit, Account_DemoBuild_Hobbit_Key); Database db = await CosmosDBHelper.CreateOrGetDatabase(client, "demodb"); DocumentCollection collection = await CosmosDBHelper.CreateCollection(client, db, "thehobbit", 400, null, null, false); Console.WriteLine("Done"); Console.WriteLine("---------------------------------------------------------"); Console.WriteLine("DEMO: Delivery Demo "); Console.WriteLine("---------------------------------------------------------"); Delivery.Demo d = new Delivery.Demo(); await d.Execute(client, collection); Console.WriteLine("---------------------------------------------------------"); Console.WriteLine("DEMO: Create custom objects and populate cosmosdb graph"); Console.WriteLine("---------------------------------------------------------"); Place cave = new Place() { name = "Cave of Hobbit" }; Place restaurant = new Place() { name = "Restaurant Green Dragon" }; Place europe = new Place() { name = "Europe", country = GraphProperty.Create("country", "AT", "MetaTag1", "Austria").AddValue("FI", "MetaTag1", "Finnland") }; Path hobbitPath = new Path(cave, restaurant, 2); //TODO: find out why 2.3 has an issue await client.CreateGraphDocumentAsync <Place>(collection, cave); await client.CreateGraphDocumentAsync <Place>(collection, restaurant); await client.CreateGraphDocumentAsync <Place>(collection, europe); await client.CreateGraphDocumentAsync <Path>(collection, hobbitPath); Console.WriteLine("----------------------------------------------------------------------------------"); Console.WriteLine("DEMO: Usage of 'ExecuteNextAsyncAsPOCO<T>'-Extension Method on typed Gremlin Query"); Console.WriteLine("----------------------------------------------------------------------------------"); MemoryGraph partialGraph = new MemoryGraph(); string gremlinQueryStatement = "g.V().hasLabel('place')"; Console.WriteLine($"Executing gremlin query as string: {gremlinQueryStatement}"); var germlinQuery = client.CreateGremlinQuery <Vertex>(collection, gremlinQueryStatement); while (germlinQuery.HasMoreResults) { // It is not required to pass in a context like partialGraph here. This parameter can be omitted. foreach (var result in await germlinQuery.ExecuteNextAsyncAsPOCO <Place>(partialGraph)) { Console.WriteLine($"Vertex ==> Label:{result.Label} Name:{result.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. /// ================================================================================================= Console.WriteLine("--------------------------------------------------------------------"); Console.WriteLine("DEMO: Usage of 'NextAsPOCO<T>' with GraphCommand and GraphTraversal "); Console.WriteLine("--------------------------------------------------------------------"); Console.Write("Connecting with GraphConnection object..."); // Connect with GraphConnection object graphConnection = GraphConnectionFactory.Create(client, collection); Console.WriteLine("Done"); // Drop previous context (optional if the same graph) partialGraph.Drop(); Microsoft.Azure.Graphs.GraphCommand cmd = GraphCommandFactory.Create(graphConnection); GraphTraversal placeTrav = cmd.g().V().HasLabel("place"); GraphTraversal edgeTrav = cmd.g().E().HasLabel("path"); { Console.WriteLine("Retrieving all places with 'NextAsPOCO'-Extension on GraphTraversal "); // Returns a list of all vertices for place var places = await placeTrav.NextAsPOCO <Place>(partialGraph); foreach (Place place in places) { Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}"); } } Console.WriteLine("--------------------------------------------------------------------"); Console.WriteLine("DEMO: Direct Usage of GraphSerializer<T> with GraphTraversal "); Console.WriteLine("--------------------------------------------------------------------"); // Drop previous context (optional if the same graph) partialGraph.Drop(); Console.WriteLine("Iterating over GraphTraversal Places (Vertices) and deserializing GraphSON to custom object "); IGraphSerializer <Place> placeGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Place>(partialGraph); foreach (var p in placeTrav) { IList <Place> places = placeGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each call foreach (Place place in places) { Console.WriteLine($"Vertex ==> Label:{place.Label} Name:{place.name}"); Console.WriteLine("Serializing to CosmosDB internal represenation: "); string docDBJson = placeGraphSerializer.ConvertToDocDBJObject(place).ToString(); Console.WriteLine($"JSON ==> {docDBJson}"); } } Console.WriteLine("Iterating over GraphTraversal Paths (Edges) and deserializing GraphSON to custom object "); IGraphSerializer <Path> pathGraphSerializer = GraphSerializerFactory.CreateGraphSerializer <Path>(partialGraph); foreach (var p in edgeTrav) { IList <Path> paths = pathGraphSerializer.DeserializeGraphSON(p); // Returns more than one result in each loop foreach (Path path in paths) { Console.WriteLine($"Edge ==> Label:{path.Label} Weight:{path.weight}"); Console.WriteLine("Serializing to CosmosDB internal represenation: "); string docDBJson = pathGraphSerializer.ConvertToDocDBJObject(path).ToString(); Console.WriteLine($"JSON ==> {docDBJson}"); } } #endregion } catch (Exception ex) { Console.WriteLine("\nError:"); Console.WriteLine($"Demo failed with {ex.Message}."); } }