public async Task PassesCorrectStreamHeader_WhenUseStreamIsTrue() { var httpClient = Substitute.For<IHttpClient>(); httpClient .SendAsync(Arg.Any<HttpRequestMessage>()) .Returns(callInfo => { throw new NotImplementedException(); }); var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data"), httpClient); try { await graphClient.ConnectAsync(); } // ReSharper disable EmptyGeneralCatchClause catch (NotImplementedException) { // This will fail because we're not giving it the right // HTTP response, but we only care about the request for now } // ReSharper restore EmptyGeneralCatchClause var httpCall = httpClient.ReceivedCalls().Last(); var httpRequest = (HttpRequestMessage) httpCall.GetArguments()[0]; Assert.IsTrue(httpRequest.Headers.Contains("X-Stream")); Assert.Contains("true", httpRequest.Headers.GetValues("X-Stream").ToList()); }
public void RootNode_ShouldThrowInvalidOperationException_WhenNotConnectedYet() { var graphClient = new GraphClient(new Uri("http://foo/db/data"), null); // ReSharper disable ReturnValueOfPureMethodIsNotUsed graphClient.RootNode.ToString(); // ReSharper restore ReturnValueOfPureMethodIsNotUsed }
public void CredentialsPreservedAllTheWayThroughToHttpStack() { var httpClient = Substitute.For<IHttpClient>(); httpClient .SendAsync(Arg.Any<HttpRequestMessage>()) .Returns(callInfo => { throw new NotImplementedException(); }); var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data"), httpClient); try { graphClient.Connect(); } // ReSharper disable EmptyGeneralCatchClause catch (NotImplementedException) { // This will fail because we're not giving it the right // HTTP response, but we only care about the request for now } // ReSharper restore EmptyGeneralCatchClause var httpCall = httpClient.ReceivedCalls().Last(); var httpRequest = (HttpRequestMessage) httpCall.GetArguments()[0]; StringAssert.AreEqualIgnoringCase("Basic", httpRequest.Headers.Authorization.Scheme); StringAssert.AreEqualIgnoringCase("dXNlcm5hbWU6cGFzc3dvcmQ=", httpRequest.Headers.Authorization.Parameter); }
public void PassesCorrectStreamHeader_WhenUseStreamIsFalse() { var httpClient = Substitute.For<IHttpClient>(); httpClient .SendAsync(Arg.Any<HttpRequestMessage>()) .Throws(new NotImplementedException()); var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data"), httpClient); graphClient.ExecutionConfiguration.UseJsonStreaming = false; try { graphClient.Connect(); } // ReSharper disable EmptyGeneralCatchClause catch (NotImplementedException) { // This will fail because we're not giving it the right // HTTP response, but we only care about the request for now } // ReSharper restore EmptyGeneralCatchClause var httpCall = httpClient.ReceivedCalls().Last(); var httpRequest = (HttpRequestMessage)httpCall.GetArguments()[0]; Assert.IsFalse(httpRequest.Headers.Contains("X-Stream")); }
public GraphClient CreateGraphClient() { if (!recordedResponses.Keys.Any(r => r.Resource == "" || r.Resource == "/")) Add(MockRequest.Get(""), MockResponse.NeoRoot()); var httpClient = GenerateHttpClient(BaseUri); var graphClient = new GraphClient(new Uri(BaseUri), httpClient); return graphClient; }
public async Task GraphClientCanListAppRole() { // Arrange var sut = new GraphClient(_clientOptions); // Act var response = await sut.ListAppRoleRequest("73b80d45-6fd0-4382-825a-eeb3b6f62e88"); // Assert Assert.True(response.StatusCode != System.Net.HttpStatusCode.NotFound); Assert.True(response.StatusCode != System.Net.HttpStatusCode.BadRequest); }
public async Task GraphClientCanGetGroupByName() { // Arrange var sut = new GraphClient(_clientOptions); // Act var response = await sut.GetGroupByName("R IT BuildSource developerautomation-xavgy"); // Assert Assert.True(response.StatusCode != System.Net.HttpStatusCode.NotFound); Assert.True(response.StatusCode != System.Net.HttpStatusCode.BadRequest); }
public UnitOfWork(GraphClient graphClient) : base(graphClient) { Ensure.That(nameof(graphClient)).IsNotNull(); #region Repositories #region Refugee var refugeeRepository = new RefugeeRepository(); refugeeRepository.SetGraphClient(graphClient); RefugeeRepository = refugeeRepository; #endregion #region HotSpot var hotSpotRepository = new HotSpotRepository(); hotSpotRepository.SetGraphClient(graphClient); HotSpotRepository = hotSpotRepository; #endregion #endregion #region Relationship Managers #region HotSpot var hotSpotRelationshipManager = new HotSpotRelationshipManager(); hotSpotRelationshipManager.SetGraphClient(graphClient); HotSpotRelationshipManager = hotSpotRelationshipManager; #endregion #region Refugee var refugeeRelationshipManager = new RefugeeRelationshipManager(); refugeeRelationshipManager.SetGraphClient(graphClient); RefugeeRelationshipManager = refugeeRelationshipManager; #endregion #endregion }
/// <summary> /// For all dnn role to b2c group mappings configured in DnnRoleMappings.config, and that exist in AzureB2C tenant, insure that roles exist on dnn. /// </summary> /// <param name="portalId">PortalID of the dnn portal where roles are created.</param> /// <param name="settings">Configuration settings for module</param> /// <returns>Logging message(s) of job execution.</returns> internal string SyncRoles(int portalId, AzureConfig settings) { try { if (CustomRoleMappings == null || CustomRoleMappings.RoleMapping == null || CustomRoleMappings.RoleMapping.Length == 0) { return("No role mappings configured. See DnnRoleMappings.config in module root folder."); } else { if (string.IsNullOrEmpty(settings.AADApplicationId) || string.IsNullOrEmpty(settings.AADApplicationKey)) { throw new Exception($"AAD application ID or key are not valid on portal {portalId}"); } var graphClient = new GraphClient(settings.AADApplicationId, settings.AADApplicationKey, settings.TenantId); // Add roles from AAD B2C var aadGroups = graphClient.GetAllGroups(""); if (aadGroups != null && aadGroups.Values != null) { foreach (var mapGroup in CustomRoleMappings.RoleMapping) { var dnnRole = Security.Roles.RoleController.Instance.GetRoleByName(portalId, mapGroup.DnnRoleName); var aadGroup = aadGroups.Values.FirstOrDefault(s => s.DisplayName == mapGroup.B2cRoleName); if (dnnRole == null && aadGroup != null) { // Create role var roleId = Security.Roles.RoleController.Instance.AddRole(new Security.Roles.RoleInfo { RoleName = mapGroup.B2cRoleName, Description = aadGroup.Description, PortalID = portalId, Status = Security.Roles.RoleStatus.Approved, RoleGroupID = -1, AutoAssignment = false, IsPublic = false }); } } } } return($"Successfully synchronized portal {portalId}"); } catch (Exception e) { return($"Error while synchronizing the roles from portal {portalId}: {e}"); } }
internal static async Task Main() { using (var graphClient = new GraphClient("your-gremlin-host-name", "your-db-name", "your-graph-name", "your-access-key")) { var g = graphClient.CreateTraversalSource(); //add vertices/edges using strongly-typed objects var personV = new PersonVertex { Ages = new[] { 4, 6, 23 }, Id = "person-12345", Label = "some-label", Name = "my name" }; var purchasedE = new PersonPurchasedProductEdge { Id = "person-12345_purchased_product-12345" }; var productV = new ProductVertex { Id = "product-12345" }; var test = g.AddV(personV).As("person") .AddV(productV).As("product") .AddE(purchasedE).From("person").To("product"); Console.WriteLine(test.ToGremlinQuery()); //traverse vertices/edges with strongly-typed objects var query = g.V("1").Cast <PersonVertex>() .Out(s => s.Purchases) .InE(s => s.People) .OutV() .Property(v => v.Name, "test") .Property(v => v.Ages, new[] { 5, 6 }) .Property(v => v.Ages, 7); Console.WriteLine(query.ToGremlinQuery()); var response = await graphClient.QueryAsync(query); Console.WriteLine(); Console.WriteLine("Response:"); foreach (var result in response) { var json = JsonConvert.SerializeObject(result); Console.WriteLine(json); } } Console.WriteLine(); Console.WriteLine("All done..."); Console.ReadKey(); }
static void Main(string[] args) { var client = new GraphClient(new Uri("http://*****:*****@what.why") .AndWhere((Person p2) => p2.Email == "*****@*****.**") .Return(() => Return.As <IEnumerable <string> >("[n IN nodes(path) | n.email]")); var path = query.Results.Single(); var path_length = path.Count() - 1; //Delete //client.Cypher // .Match("(person:Person {email: {personEmail}})") // .WithParam("personEmail", "test1") // .Delete("person") // .ExecuteWithoutResults //Delete //client.Cypher // .Match("(person:Person {email: {personEmail}})") // .WithParam("personEmail", "test1") // .Delete("person") // .ExecuteWithoutResults(); //Create //var person = new Person() { Email = "*****@*****.**", Name = "A1", Surname = "B1" }; //client.Cypher // .Create("(np:Person {newPerson})") // .WithParam("newPerson", person) // .ExecuteWithoutResults(); //Create relationship //client.Cypher // .Match("(p1:Person {email: {p1Email}})", "(p2:Person {email: {p2Email}})") // .WithParam("p1Email", "*****@*****.**") // .WithParam("p2Email", "*****@*****.**") // .Create("(p1)-[:FOLLOW]->(p2)") // .ExecuteWithoutResults(); // Delete relationship //client.Cypher // .Match("(p1:Person {email: {p1Email}})-[r:FOLLOW]->(p2:Person {email: {p2Email}})") // .WithParam("p1Email", "*****@*****.**") // .WithParam("p2Email", "*****@*****.**") // .Delete("r") // .ExecuteWithoutResults(); }
public void addUserNode(string user_email) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "1234"); var newUser = new User { email = user_email }; client.Connect(); client.Cypher .Create("(user:User {newUser})") .WithParam("newUser", newUser) .ExecuteWithoutResults(); }
/// <summary> /// Initialisiert den Bootloader /// </summary> /// <param name="container"></param> /// <returns></returns> public static Container Init(Container container) { GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "extra"); client.Connect(); container.RegisterInstance(client); RegisterDaos(container); RegisterServices(container); return(container); }
public ActionResult SiteInCommon(string reportClient) { var neo4jClient = new GraphClient(new Uri("http://localhost:7474/db/data")); neo4jClient.Connect(); var orders = neo4jClient.Cypher.Match("(client:Client)-[ORDERED_FROM]-(place:Place)") .Where((ClientModel client) => client.idClient == reportClient) .Return(place => place.As <PlaceModel>()) .Results; return(View()); }
public ActionResult OrderReport(string reportClient) { var neo4jClient = new GraphClient(new Uri("http://localhost:7474/db/data")); neo4jClient.Connect(); var orders = neo4jClient.Cypher.Match("(client:Client)-[ORDERED]-(order:Order)") .Where((ClientModel client) => client.idClient == reportClient) .Return(order => order.As <OrderModel>()) .Results; return(View(orders)); }
public LogIn() { InitializeComponent(); client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "blizanci"); try { client.Connect(); } catch (Exception exc) { MessageBox.Show(exc.Message); } }
public void ShouldParseRootApiResponseFromAuthenticatedConnection() { using (var testHarness = new RestTestHarness() { { MockRequest.Get(""), MockResponse.NeoRoot() } }) { var httpClient = testHarness.GenerateHttpClient("http://foo/db/data"); var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data"), httpClient); graphClient.Connect(); Assert.Equal("/node", graphClient.RootApiResponse.Node); } }
public void DeleteUser(UserDTONeo4j user) { using (var client = new GraphClient(new Uri(_connectionString), _login, _password)) { client.Connect(); client.Cypher .Match("(user1:User)-[r:Follower]-()") .Where("user1.Username = {username}") .WithParam("username", user.Username) .Delete("r,user1") .ExecuteWithoutResults(); } }
public GraphClient CreateGraphClient() { if (!recordedResponses.Keys.Any(r => r.Resource == "" || r.Resource == "/")) { Add(MockRequest.Get(""), MockResponse.NeoRoot()); } var httpClient = GenerateHttpClient(BaseUri); var graphClient = new GraphClient(new Uri(BaseUri), httpClient); return(graphClient); }
private DataSet() { PrijavljenKorisnik = null; client = new GraphClient(new Uri("http://localhost:7474/db/data"), "admin", "admin"); try { client.Connect(); } catch (Exception exc) { } }
public void CreateUser(UserDTONeo4j user) { using (var client = new GraphClient(new Uri(_connectionString), _login, _password)) { client.Connect(); client.Cypher.Create("(user:User { Username: {username}, Following: {following}, Followers: {followers}, })") .WithParam("username", user.Username) .WithParam("following", user.Following) .WithParam("followers", user.Followers) .ExecuteWithoutResults(); } }
static CommandLineBuilder BuildCommandLine(GraphClient client, IEnumerable <Command> commands) { var rootCommand = client.BuildRootCommand(); rootCommand.Description = "Microsoft Graph CLI"; foreach (var command in commands) { rootCommand.AddCommand(command); } return(new CommandLineBuilder(rootCommand)); }
private void Form1_Load(object sender, EventArgs e) { this.cbType.SelectedIndex = 0; client = new GraphClient(new Uri("http://localhost:11011/db/data"), "neo4j", "root"); try { client.Connect(); } catch (Exception exc) { MessageBox.Show(exc.Message); } }
public void DeleteUser(UserLableDTO u) { using (var client = new GraphClient(new Uri(connectionString), login, pass)) { client.Connect(); client.Cypher .Match("(user1:User)-[r:Friends]-()") .Where("user1.User_Id = {p_id}") .WithParam("p_id", u.User_Id) .Delete("r,user1") .ExecuteWithoutResults(); } }
public static bool Connect(string uri, string username, string password) { client = new GraphClient(new Uri(uri), username, password); try { client.Connect(); return(true); } catch (Exception e) { return(false); } }
public static IGraphClient ConfigGraph() { //Use an IoC container and register as a Singleton var url = ConfigurationManager.AppSettings["GraphDBUrl"]; var user = ConfigurationManager.AppSettings["GraphDBUser"]; var password = ConfigurationManager.AppSettings["GraphDBPassword"]; var client = new GraphClient(new Uri(url), user, password); client.Connect(); GraphClient = client; return(GraphClient); }
private void RegistrationDoctors_Load(object sender, EventArgs e) { panelRegistrationDoctors.BackColor = Color.FromArgb(100, 0, 0, 0); client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "bolnica"); try { client.Connect(); } catch (Exception exc) { MessageBox.Show(exc.Message); } }
public static GraphClient GraphClient() { if (graphClient == null) { graphClient = new GraphClient(new Uri("http://localhost:7474/db/data"), "", ""); } if (!graphClient.IsConnected) { graphClient.Connect(); } return(graphClient); }
public int PoveziBazu() { client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "123"); try { client.Connect(); } catch (Exception exc) { return(-1); } return(1); }
public static bool Connect() { try { client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "neo4j123"); client.Connect(); return(true); } catch (Exception exc) { return(false); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.Configure <Neo4jDbSettings>(Configuration.GetSection("Neo4jDbSettings")); services.AddScoped <IGraphClient, GraphClient>(provider => { var options = provider.GetService <IOptions <Neo4jDbSettings> >(); var client = new GraphClient(new Uri(options.Value.uri), username: options.Value.username, password: options.Value.password); client.Connect(); return(client); }); services.AddNeo4jAnnotations <ApplicationContext>(); //services.AddNeo4jAnnotations(); services.AddIdentity <ApplicationUser, IdentityRole>(options => { //var dataProtectionPath = Path.Combine(HostingEnvironment.WebRootPath, "identity-artifacts"); //options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie"; //options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(dataProtectionPath); options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = true; }) .AddUserStore <UserStore <ApplicationUser> >() .AddRoleStore <RoleStore <IdentityRole> >() .AddDefaultTokenProviders(); //// Services used by identity ////services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme); //services.AddAuthentication(options => //{ // // This is the Default value for ExternalCookieAuthenticationScheme // options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; //new IdentityCookieOptions().ExternalCookieAuthenticationScheme; //}); // Hosting doesn't add IHttpContextAccessor by default services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddOptions(); services.AddDataProtection(); services.AddMvc(); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); }
public GraphClient CreateGraphClient(Neo4jVersion neoVersion) { if (!recordedResponses.Keys.Any(r => r.Resource == "" || r.Resource == "/")) { MockResponse response; switch (neoVersion) { case Neo4jVersion.Neo19: response = MockResponse.NeoRoot(1, 9, 0); break; case Neo4jVersion.Neo20: response = MockResponse.NeoRoot20(); break; case Neo4jVersion.Neo22: response = MockResponse.NeoRoot(2, 2, 0); break; case Neo4jVersion.Neo225: response = MockResponse.NeoRoot(2, 2, 5); break; case Neo4jVersion.Neo226: response = MockResponse.NeoRoot(2, 2, 6); break; case Neo4jVersion.Neo23: response = MockResponse.NeoRoot(2, 3, 0); break; case Neo4jVersion.Neo30: response = MockResponse.NeoRoot(3, 0, 0); break; case Neo4jVersion.Neo40: response = MockResponse.NeoRoot(4, 0, 0); break; default: throw new ArgumentOutOfRangeException(nameof(neoVersion), neoVersion, null); } Add(MockRequest.Get(""), response); } var httpClient = GenerateHttpClient(BaseUri); var graphClient = new GraphClient(new Uri(BaseUri), httpClient); return(graphClient); }
static void Main(string[] args) { try { GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data")); client.Connect(); // Create nodes and relationship MyNode node1 = new MyNode() { Name = "Test 1" }; MyNode node2 = new MyNode() { Name = "Test 2" }; NodeReference <MyNode> node1ref = client.Create <MyNode>(node1); NodeReference <MyNode> node2ref = client.Create <MyNode>(node2); MyRelationShip rel12 = new MyRelationShip(node2ref); var Rel1 = client.CreateRelationship <MyNode, MyRelationShip>(node1ref, rel12); MyNode node3 = new MyNode() { Name = "Test 3" }; NodeReference <MyNode> node3ref = client.Create <MyNode>(node3); MyRelationShip rel13 = new MyRelationShip(node3ref); var Rel13 = client.CreateRelationship <MyNode, MyRelationShip>(node1ref, rel13); var query = client.Cypher.Start(new { n1 = node1ref }) .Match("n1-[:MYRELATIONSHIP]->targetnode") .Return <MyNode>(targetnode => targetnode.As <MyNode>()); var res = query.Results; int i = 0; foreach (MyNode n in res) { i++; Console.WriteLine(i + ". Name: '" + n.Name + "'"); } } catch (NeoException ex) { Console.WriteLine(ex.ToString()); } Console.ReadKey(); }
private static void CleanupProperties() { var client = new GraphClient(new Uri("http://*****:*****@localhost:7474/db/data")); client.Connect(); var data = client.Cypher .Match("(device:Device)") .Return(device => device.As <Device>()) .Results.ToList(); foreach (var result in data) { if (result.SN != result.SN.Trim()) { client.Cypher .Match("(device:Device {SN: {sn}})") .Set("device.SN = {trimsn}") .WithParams(new { sn = result.SN, trimsn = result.SN.Trim() }) .ExecuteWithoutResults(); } if (result.AssetTag != result.AssetTag.Trim()) { client.Cypher .Match("(device:Device {AssetTag: {asset}})") .Set("device.AssetTag = {trimasset}") .WithParams(new { asset = result.AssetTag, trimasset = result.AssetTag.Trim() }) .ExecuteWithoutResults(); } if (result.WSAsset != result.WSAsset.Trim()) { client.Cypher .Match("(device:Device {WSAsset: {wsasset}})") .Set("device.WSAsset = {trimwsasset}") .WithParams(new { wsasset = result.WSAsset, trimwsasset = result.WSAsset.Trim() }) .ExecuteWithoutResults(); } } }
// POST api/values public void Post([FromBody] Medication medication) { var client = new GraphClient(new Uri("http://*****:*****@localhost:7474/db/data")); client.Connect(); var query = client.Cypher .Create("(medication:Medication {newMed})") .WithParam("newMed", medication); var queryText = query.Query.QueryText; var queryParams = query.Query.QueryParameters; query.ExecuteWithoutResults(); }
void Foo() { IGraphClient graph = new GraphClient(new Uri("")); // Based on http://wiki.neo4j.org/content/Image:Warehouse.png // Can create nodes from POCOs var frameStore = graph.Create( new StorageLocation { Name = "Frame Store" }); var mainStore = graph.Create( new StorageLocation { Name = "Main Store" }); // Can create a node with outgoing relationships var frame = graph.Create( new Part { Name = "Frame" }, new StoredIn(frameStore)); // Can create multiple outgoing relationships and relationships with payloads graph.Create( new Product { Name = "Trike", Weight = 2 }, new StoredIn(mainStore), new Requires(frame, new Requires.Payload { Count = 1 })); // Can create relationships in both directions graph.Create( new Part { Name = "Pedal" }, new StoredIn(frameStore), new Requires(frame, new Requires.Payload { Count = 2 }) { Direction = RelationshipDirection.Incoming }); var wheel = graph.Create( new Part { Name = "Wheel" }, new Requires(frame, new Requires.Payload { Count = 2 }) { Direction = RelationshipDirection.Incoming }); // Can create implicit incoming relationships graph.Create( new StorageLocation { Name = "Wheel Store" }, new StoredIn(wheel)); // Can create relationships against the root node graph.Create( new StorageLocation {Name = "Auxillary Store"}, new StoredIn(wheel), new OwnedBy(graph.RootNode)); }
public void ShouldFormatUserAgentCorrectly() { var graphClient = new GraphClient(new Uri("http://localhost")); var userAgent = graphClient.ExecutionConfiguration.UserAgent; Assert.IsTrue(Regex.IsMatch(userAgent, @"Neo4jClient/\d+\.\d+\.\d+\.\d+"), "User agent should be in format Neo4jClient/1.2.3.4"); }
public void ShouldThrowInvalidOperationExceptionIfNotConnected() { var client = new GraphClient(new Uri("http://foo")); client.ExecuteScalarGremlin("", null); }
public void ExecuteMultipleStatementInOneRequestHttpRequest() { const string headerName = "MyTestHeader"; const string headerValue = "myTestHeaderValue"; var customHeaders = new NameValueCollection { {headerName, headerValue} }; var initTransactionRequest = MockRequest.PostJson("/transaction", @"{ 'statements': [{'statement': 'MATCH n\r\nRETURN count(n)', 'resultDataContents':[], 'parameters': {}}, {'statement': 'MATCH t\r\nRETURN count(t)', 'resultDataContents':[], 'parameters': {}}]}"); var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { initTransactionRequest, MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1), "http://foo/db/data/transaction/1") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }) { var response = MockResponse.NeoRoot20(); testHarness.Add(MockRequest.Get(""), response); var httpClient = testHarness.GenerateHttpClient("http://foo/db/data"); testHarness.CreateAndConnectTransactionalGraphClient(); ITransactionalGraphClient client = new GraphClient(new Uri("http://foo/db/data"), httpClient); client.Connect(); using (var transaction = client.BeginTransaction()) { // dummy query to generate request var rawClient = client as IRawGraphClient; if (rawClient == null) { Assert.Fail("ITransactionalGraphClient is not IRawGraphClient"); } var queries = new List<CypherQuery>() { client.Cypher .Match("n") .Return(n => n.Count()) .Query, client.Cypher .Match("t") .Return(t => t.Count()) .Query }; httpClient.ClearReceivedCalls(); rawClient.ExecuteMultipleCypherQueriesInTransaction(queries, customHeaders); transaction.Commit(); var calls = httpClient.ReceivedCalls().ToList(); Assert.IsNotEmpty(calls); HttpRequestMessage requestMessage = null; foreach (var call in calls) { if (call.GetArguments().Single().GetType() == typeof (HttpRequestMessage)) { requestMessage = (HttpRequestMessage) call.GetArguments().Single(); } } Assert.IsNotNull(requestMessage); var customHeader = requestMessage.Headers.Single(h => h.Key == headerName); Assert.IsNotNull(customHeader); Assert.AreEqual(headerValue, customHeader.Value.Single()); } } }
public void BeginTransactionShouldFailWithoutConnectingFirst() { var client = new GraphClient(new Uri("http://foo/db/data"), null); client.BeginTransaction(); }
public void SendsCommandWithCorrectTimeout() { const int expectedMaxExecutionTime = 100; const string queryText = @"START d=node({p0}), e=node({p1}) MATCH p = allShortestPaths( d-[*..15]-e ) RETURN p"; var parameters = new Dictionary<string, object> { {"p0", 215}, {"p1", 219} }; var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set,CypherResultFormat.Transactional ,maxExecutionTime: expectedMaxExecutionTime); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.Get(""), MockResponse.NeoRoot() }, { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'data' : [ [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/0', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/247', 'http://foo/db/data/relationship/257' ], 'end' : 'http://foo/db/data/node/219' } ], [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/1', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/248', 'http://foo/db/data/relationship/258' ], 'end' : 'http://foo/db/data/node/219' } ] ], 'columns' : [ 'p' ] }") } }) { var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri); var graphClient = new GraphClient(new Uri(testHarness.BaseUri), httpClient); graphClient.Connect(); httpClient.ClearReceivedCalls(); ((IRawGraphClient)graphClient).ExecuteGetCypherResults<object>(cypherQuery); var call = httpClient.ReceivedCalls().Single(); var requestMessage = (HttpRequestMessage)call.GetArguments()[0]; var maxExecutionTimeHeader = requestMessage.Headers.Single(h => h.Key == "max-execution-time"); Assert.AreEqual(expectedMaxExecutionTime.ToString(CultureInfo.InvariantCulture), maxExecutionTimeHeader.Value.Single()); } }
public void SendsCommandWithCustomHeaders() { const string queryText = "MATCH n SET n.Value = 'value'"; const int expectedMaxExecutionTime = 100; const string headerName = "MyTestHeader"; const string headerValue = "myTestHeaderValue"; var customHeaders = new NameValueCollection(); customHeaders.Add(headerName, headerValue); var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Set, CypherResultFormat.DependsOnEnvironment, maxExecutionTime: expectedMaxExecutionTime, customHeaders: customHeaders); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.Get(""), MockResponse.NeoRoot() }, { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Http((int) HttpStatusCode.OK) } }) { var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri); var graphClient = new GraphClient(new Uri(testHarness.BaseUri), httpClient); graphClient.Connect(); httpClient.ClearReceivedCalls(); ((IRawGraphClient)graphClient).ExecuteCypher(cypherQuery); var call = httpClient.ReceivedCalls().Single(); var requestMessage = (HttpRequestMessage)call.GetArguments()[0]; var maxExecutionTimeHeader = requestMessage.Headers.Single(h => h.Key == "max-execution-time"); Assert.AreEqual(expectedMaxExecutionTime.ToString(CultureInfo.InvariantCulture), maxExecutionTimeHeader.Value.Single()); var customHeader = requestMessage.Headers.Single(h => h.Key == headerName); Assert.IsNotNull(customHeader); Assert.AreEqual(headerValue, customHeader.Value.Single()); } }
public void RootNode_ShouldThrowInvalidOperationException_WhenNotConnectedYet() { var graphClient = new GraphClient(new Uri("http://foo/db/data"), null); var ex = Assert.Throws<InvalidOperationException>(() => graphClient.RootNode.ToString()); Assert.AreEqual("The graph client is not connected to the server. Call the Connect method first.", ex.Message); }
public void UserInfoPreservedInRootUri() { var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data")); Assert.That(graphClient.RootUri.OriginalString, Is.EqualTo("http://*****:*****@foo/db/data")); }
public void ShouldThrowInvalidOperationExceptionIfNotConnected() { var client = new GraphClient(new Uri("http://foo")); client.Delete(123, DeleteMode.NodeOnly); }
public GraphClient CreateGraphClient(Neo4jVersion neoVersion) { if (!recordedResponses.Keys.Any(r => r.Resource == "" || r.Resource == "/")) { MockResponse response; switch (neoVersion) { case Neo4jVersion.Neo19: response = MockResponse.NeoRoot(); break; case Neo4jVersion.Neo20: response = MockResponse.NeoRoot20(); break; case Neo4jVersion.Neo22: response = MockResponse.NeoRoot(2,2,0); break; case Neo4jVersion.Neo225: response = MockResponse.NeoRoot(2,2,5); break; case Neo4jVersion.Neo226: response = MockResponse.NeoRoot(2,2,6); break; case Neo4jVersion.Neo23: response = MockResponse.NeoRoot(2,3,0); break; default: throw new ArgumentOutOfRangeException("neoVersion", neoVersion, null); } Add(MockRequest.Get(""), response); } var httpClient = GenerateHttpClient(BaseUri); var graphClient = new GraphClient(new Uri(BaseUri), httpClient); return graphClient; }
public void ShouldFormatAuthorisationHeaderCorrectly() { const string username = "******"; const string password = "******"; var expectedHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))); var graphClient = new GraphClient(new Uri("http://localhost"), username, password); var httpClient = (HttpClientWrapper) graphClient.ExecutionConfiguration.HttpClient; Assert.AreEqual(expectedHeader, httpClient.AuthenticationHeaderValue.Parameter); }
public void ShouldSendCustomUserAgent() { // Arrange var httpClient = Substitute.For<IHttpClient>(); var graphClient = new GraphClient(new Uri("http://localhost"), httpClient); var expectedUserAgent = graphClient.ExecutionConfiguration.UserAgent; httpClient .SendAsync(Arg.Do<HttpRequestMessage>(message => { // Assert Assert.IsTrue(message.Headers.Contains("User-Agent"), "Contains User-Agent header"); var userAgent = message.Headers.GetValues("User-Agent").Single(); Assert.AreEqual(expectedUserAgent, userAgent, "User-Agent header value is correct"); })) .Returns(ci => { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'cypher' : 'http://foo/db/data/cypher', 'batch' : 'http://foo/db/data/batch', 'node' : 'http://foo/db/data/node', 'node_index' : 'http://foo/db/data/index/node', 'relationship_index' : 'http://foo/db/data/index/relationship', 'reference_node' : 'http://foo/db/data/node/123', 'neo4j_version' : '1.5.M02', 'extensions_info' : 'http://foo/db/data/ext', 'extensions' : { 'GremlinPlugin' : { 'execute_script' : 'http://foo/db/data/ext/GremlinPlugin/graphdb/execute_script' } } }") }; var task = new Task<HttpResponseMessage>(() => response); task.Start(); return task; }); // Act graphClient.Connect(); }
public void ShouldParseRootApiResponseFromAuthenticatedConnection() { using (var testHarness = new RestTestHarness() { { MockRequest.Get(""), MockResponse.NeoRoot() } }) { var httpClient = testHarness.GenerateHttpClient("http://foo/db/data"); var graphClient = new GraphClient(new Uri("http://*****:*****@foo/db/data"), httpClient); graphClient.Connect(); Assert.AreEqual("/node", graphClient.RootApiResponse.Node); } }
public void ShouldThrowInvalidOperationExceptionIfNotConnected() { var client = new GraphClient(new Uri("http://foo")); Assert.Throws<InvalidOperationException>(() => client.ExecuteGetAllNodesGremlin<object>("", null)); }
public void BeginTransactionShouldFailWithoutConnectingFirst() { var client = new GraphClient(new Uri("http://foo/db/data"), null); Assert.That(() => client.BeginTransaction(), Throws.InvalidOperationException); }
public void ShouldThrowInvalidOperationExceptionIfNotConnected() { var client = new GraphClient(new Uri("http://foo")); client.Get<object>((NodeReference)123); }
public void ShouldFireOnCompletedEvenWhenException() { var httpClient = Substitute.For<IHttpClient>(); httpClient .SendAsync(Arg.Any<HttpRequestMessage>()) .Returns(callInfo => { throw new NotImplementedException(); }); var graphClient = new GraphClient(new Uri("http://foo/db/data"), httpClient); OperationCompletedEventArgs operationCompletedArgs = null; graphClient.OperationCompleted+= (s, e) => { operationCompletedArgs = e; }; // act Assert.Throws<NotImplementedException>(() => graphClient.Connect()); Assert.NotNull(operationCompletedArgs); Assert.That(operationCompletedArgs.HasException); Assert.AreEqual(typeof(NotImplementedException), operationCompletedArgs.Exception.GetType()); }
public void ShouldThrowInvalidOperationExceptionIfNotConnected() { var client = new GraphClient(new Uri("http://foo")); client.DeleteRelationship(123); }
public void DoesntSendMaxExecutionTime_WhenNotAddedToQuery() { const string queryText = @"START d=node({p0}), e=node({p1}) MATCH p = allShortestPaths( d-[*..15]-e ) RETURN p"; var parameters = new Dictionary<string, object> { {"p0", 215}, {"p1", 219} }; var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.Get(""), MockResponse.NeoRoot() }, { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'data' : [ [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/0', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/247', 'http://foo/db/data/relationship/257' ], 'end' : 'http://foo/db/data/node/219' } ], [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/1', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/248', 'http://foo/db/data/relationship/258' ], 'end' : 'http://foo/db/data/node/219' } ] ], 'columns' : [ 'p' ] }") } }) { var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri); var graphClient = new GraphClient(new Uri(testHarness.BaseUri), httpClient); graphClient.Connect(); httpClient.ClearReceivedCalls(); ((IRawGraphClient)graphClient).ExecuteGetCypherResults<object>(cypherQuery); var call = httpClient.ReceivedCalls().Single(); var requestMessage = (HttpRequestMessage)call.GetArguments()[0]; Assert.IsFalse(requestMessage.Headers.Any(h => h.Key == "max-execution-time")); } }
public void DoesntSetHeaders_WhenNotSet() { const string queryText = "MATCH n SET n.Value = 'value'"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.Get(""), MockResponse.NeoRoot() }, { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Http((int) HttpStatusCode.OK) } }) { var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri); var graphClient = new GraphClient(new Uri(testHarness.BaseUri), httpClient); graphClient.Connect(); httpClient.ClearReceivedCalls(); ((IRawGraphClient)graphClient).ExecuteCypher(cypherQuery); var call = httpClient.ReceivedCalls().Single(); var requestMessage = (HttpRequestMessage)call.GetArguments()[0]; Assert.IsFalse(requestMessage.Headers.Any(h => h.Key == "max-execution-time")); } }