private GremlinServer InitiateGraph() { string containerLink = "/dbs/" + database + "/colls/" + container; var gremlinServer = new GremlinServer(hostname: host, port: port, enableSsl: true, username: containerLink, password: key); return(gremlinServer); }
static void Main(string[] args) { var authKey = "YOURKEYHERE"; var gremlinServer = new GremlinServer( "YOURURLHERE.gremlin.cosmosdb.azure.com", 443, enableSsl: true, username: $"/dbs/cloudguru/colls/people", password: authKey); using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType)) { var query = "g.V()"; var task = gremlinClient.SubmitAsync <dynamic>(query); task.Wait(); foreach (var result in task.Result) { string output = JsonConvert.SerializeObject(result); Console.WriteLine(String.Format("\tResult:\n\t{0}", output)); } } Console.ReadKey(); }
private void ExecuteQuery(GremlinServer gremlinServer, string query) { using (var client = new GremlinClient(gremlinServer, new GraphSON3Reader(), new GraphSON3Writer(), GremlinClient.GraphSON2MimeType)) { // Create async task to execute the Gremlin query. var resultSet = SubmitRequest(client, query).Result; if (resultSet.Count > 0) { Console.WriteLine("\tResult:"); foreach (var result in resultSet) { // The vertex results are formed as Dictionaries with a nested dictionary for their properties string output = JsonConvert.SerializeObject(result); Console.WriteLine($"\t{output}"); } Console.WriteLine(); } // Print the status attributes for the result set. // This includes the following: // x-ms-status-code : This is the sub-status code which is specific to Cosmos DB. // x-ms-total-request-charge : The total request units charged for processing a request. // x-ms-total-server-time-ms : The total time executing processing the request on the server. //PrintStatusAttributes(resultSet.StatusAttributes); Console.WriteLine(); } }
public async Task ShouldUseSpecifiedEvaluationTimeout() { var gremlinServer = new GremlinServer(TestHost, TestPort); using (var gremlinClient = new GremlinClient(gremlinServer)) { const long timeOutInMs = 1L; const int scriptSleepTimeInMs = 5000; var sleepScript = _requestMessageProvider.GetSleepGremlinScript(scriptSleepTimeInMs); var requestMsg = RequestMessage.Build(Tokens.OpsEval) .AddArgument(Tokens.ArgsGremlin, sleepScript) .AddArgument(Tokens.ArgsEvalTimeout, timeOutInMs) .Create(); var evaluationStopWatch = new Stopwatch(); evaluationStopWatch.Start(); var thrownException = await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg)); evaluationStopWatch.Stop(); Assert.Contains("ServerTimeout", thrownException.Message); Assert.Contains(timeOutInMs.ToString(), thrownException.Message); Assert.True(evaluationStopWatch.ElapsedMilliseconds < scriptSleepTimeInMs); } }
public async Task ResponseBatchesShouldBeReassembled() { const int batchSize = 2; var expectedResult = new List <int> { 1, 2, 3, 4, 5 }; var requestScript = $"{nameof(expectedResult)}"; var bindings = new Dictionary <string, object> { { nameof(expectedResult), expectedResult } }; var requestMessage = new ScriptRequestMessage { Arguments = new ScriptRequestArguments { BatchSize = batchSize, GremlinScript = requestScript, Bindings = bindings } }; var gremlinServer = new GremlinServer(TestHost, TestPort); using (var gremlinClient = new GremlinClient(gremlinServer)) { var response = await gremlinClient.SubmitAsync <int>(requestMessage); Assert.Equal(expectedResult, response); } }
public GremlinNetLanguageConnector(string gremlinHostname, string username, string password, int port = 8182, bool enableSsl = true, ILogging logger = null) : base(logger) { _key = $"{gremlinHostname.ToLower()}.{username.ToLower()}.{port}"; _server = new GremlinServer(gremlinHostname, port, enableSsl, username, password); InitializeClient(); }
public void Configure(IWebJobsBuilder builder) { builder.AddSwashBuckle(Assembly.GetExecutingAssembly()); builder.AddAzureFunctionsToken(new TokenAzureB2COptions() { AzureB2CSingingKeyUri = new Uri(Env.GetEnvironmentVariable("AuthSigningKey")), Audience = Env.GetEnvironmentVariable("AuthAudience"), Issuer = Env.GetEnvironmentVariable("AuthIssuer") }); builder.Services.AddHttpClient(); builder.Services.AddSingleton((s) => { GremlinServer gremlinServer = new GremlinServer(Env.GetEnvironmentVariable("CosmosGremlinHost"), int.Parse(Env.GetEnvironmentVariable("CosmosPort")), enableSsl: true, username: "******" + Env.GetEnvironmentVariable("CosmosDatabaseName") + "/colls/" + Env.GetEnvironmentVariable("CosmosGraphName"), password: Env.GetEnvironmentVariable("CosmosKey")); IGremlinClient gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); return(gremlinClient); }); builder.Services.AddSingleton((s) => { IB2CGraphClient b2CGraphClient = new B2CGraphClient(); return(b2CGraphClient); }); }
public WebSocketGremlinQueryExecutor( GremlinServer gremlinServer, IGremlinClientFactory clientFactory, string alias = "g") { _alias = alias; _aliasArgs = new Dictionary <string, string> { { "g", _alias } }; _lazyGremlinClient = new SmarterLazy <IGremlinClient>( async logger => { try { return(await Task.Run(() => clientFactory.Create( gremlinServer, JsonNetMessageSerializer.GraphSON3, new ConnectionPoolSettings(), _ => { }))); } catch (Exception ex) { logger.LogError(ex, $"Failure creating an instance of {nameof(IGremlinClient)}."); throw; } }); }
public async Task ShouldReturnResultWithoutDeserializingItForJsonElementType() { var gremlinServer = new GremlinServer(TestHost, TestPort); using var gremlinClient = new GremlinClient(gremlinServer); const string gremlinScript = "'someString'"; var response = await gremlinClient.SubmitWithSingleResultAsync <JsonElement>(gremlinScript); //Expected: /* { * "@type": "g:List", * "@value": [ * "someString" * ] * }*/ Assert.IsType <JsonElement>(response); Assert.Equal("g:List", response.GetProperty("@type").GetString()); var valueProperty = response.GetProperty("@value"); Assert.NotNull(valueProperty); Assert.Equal(1, valueProperty.GetArrayLength()); Assert.Equal("someString", (valueProperty[0].GetString())); }
private static async Task InsertInGraph(IEnumerable <string> tags, dynamic doc, KeyVault kvService, TraceWriter log) { var hostname = await GetSecret("gremlin_endpoint", kvService); var port = await GetSecret("gremlin_port", kvService); var database = "pets"; var collection = "checks"; var authKey = Environment.GetEnvironmentVariable("gremlin_key"); var portToUse = 443; portToUse = int.TryParse(port, out portToUse) ? portToUse : 443; var gremlinServer = new GremlinServer(hostname, portToUse, enableSsl: true, username: "******" + database + "/colls/" + collection, password: authKey); var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); foreach (var tag in tags) { log.Info("--- --- Checking vertex for tag " + tag); await TryAddTag(gremlinClient, tag, log); } var queries = AddPetToGraphQueries(doc, tags); log.Info("--- --- Adding vertex for pet checkin "); foreach (string query in queries) { await gremlinClient.SubmitAsync <dynamic>(query); } }
public async Task ShouldSaveVariableBetweenRequestsInSession() { var gremlinServer = new GremlinServer(TestHost, TestPort); var sessionId = Guid.NewGuid().ToString(); using (var gremlinClient = new GremlinClient(gremlinServer, sessionId: sessionId)) { await gremlinClient.SubmitAsync <int>("x = 1"); var expectedResult = new List <int> { 3 }; var response = await gremlinClient.SubmitAsync <int>("x + 2"); Assert.Equal(expectedResult, response); } using (var gremlinClient = new GremlinClient(gremlinServer, sessionId: sessionId)) { try { await gremlinClient.SubmitAsync <int>("x"); Assert.True(false, "The 'x' variable should not exist after session close"); } catch (Exception) { // do nothing } } }
private static async Task ExecutePartitionedGraphQueriesAsync() { try { GremlinServer server = new GremlinServer( ConfigurationManager.AppSettings["GremlinServerEndPoint"], int.Parse(ConfigurationManager.AppSettings["GremlinServerPort"]), true, "/dbs/" + ConfigurationManager.AppSettings["Database"] + "/colls/" + ConfigurationManager.AppSettings["Collection"], ConfigurationManager.AppSettings["PrimaryKey"]); using (GremlinClient gClient = new GremlinClient(server)) { Console.WriteLine("---------------------------------------------------------------------"); foreach (KeyValuePair <string, string> gremlinQuery in Program.gremlinQueries) { Console.WriteLine("Executing: " + gremlinQuery.Key); Console.WriteLine("---------------------------------------------------------------------"); await ExecuteGremlinServerQueryAsync(gClient, gremlinQuery.Value); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public IActionResult Gremlin(string query) { try { // var hostname = _configuration.GetSection("AzureCosmos").GetSection("HostName").Value; // var port = int.Parse(_configuration.GetSection("AzureCosmos").GetSection("Port").Value); // var authKey = _configuration.GetSection("AzureCosmos").GetSection("AuthKey").Value; // var database = _configuration.GetSection("AzureCosmos").GetSection("Database").Value; // var graph = _configuration.GetSection("AzureCosmos").GetSection("Graph").Value; // var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, username: "******" + database + "/colls/" + graph, password: authKey); // var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); var endpoint = _configuration.GetSection("AWS").GetSection("NeptuneEndpoint").Value; var gremlinServer = new GremlinServer(endpoint, 8182, enableSsl: true); var gremlinClient = new GremlinClient(gremlinServer); var users = gremlinClient.SubmitAsync <dynamic>(query).Result; //return Json(users); string res = JsonConvert.SerializeObject(users); string pre = JsonFormatter.Format(res); return(Content(pre, "application/json")); } catch (Exception ex) { string res = JsonConvert.SerializeObject(new { message = ex.Message, stackTrace = ex.StackTrace }); string pre = JsonFormatter.Format(res); return(Content(pre, "application/json")); } }
public async Task ConnectingViaDriversTest() { // tag::connectingViaDrivers[] // script var gremlinServer = new GremlinServer("localhost", 8182); using (var gremlinClient = new GremlinClient(gremlinServer)) { var bindings = new Dictionary <string, object> { { "name", "marko" } }; var response = await gremlinClient.SubmitWithSingleResultAsync <object>("g.V().has('person','name',name).out('knows')", bindings); } // bytecode using (var gremlinClient = new GremlinClient(new GremlinServer("localhost", 8182))) { var g = Traversal().WithRemote(new DriverRemoteConnection(gremlinClient)); var list = g.V().Has("person", "name", "marko").Out("knows").ToList(); } // end::connectingViaDrivers[] }
public GremlinClientFactory(ICosmosGraphDbSettings settings) { Guard.ArgumentNotNull(settings, nameof(settings)); Guard.IsNullOrWhiteSpace(settings.EndPointUrl, nameof(settings.EndPointUrl)); Guard.IsNullOrWhiteSpace(settings.ApiKey, nameof(settings.ApiKey)); Guard.IsNullOrWhiteSpace(settings.ContainerPath, nameof(settings.ContainerPath)); _server = new GremlinServer(settings.EndPointUrl, settings.Port, true, settings.ContainerPath, settings.ApiKey); _connectionPoolSettings = new ConnectionPoolSettings() { MaxInProcessPerConnection = settings.MaxInProcessPerConnection ?? 32, PoolSize = settings.PoolSize ?? 4, ReconnectionAttempts = settings.ReconnectionAttempts ?? 4, ReconnectionBaseDelay = TimeSpan.FromMilliseconds(settings.ReconnectionBaseDelay ?? 500) }; _webSocketConfiguration = new Action <ClientWebSocketOptions>(options => { options.KeepAliveInterval = TimeSpan.FromSeconds(settings.KeepAliveInterval ?? 10); }); }
public async Task <dynamic> Get(string query, string collectionId) { List <dynamic> results = new List <dynamic>(); GremlinServer server = GetServer(collectionId); using (GremlinClient gremlinClient = new GremlinClient(server, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType)) { List <Task> tasks = new List <Task>(); string[] queries = query.Split(';'); //split query on ; to allow for multiple queries foreach (string q in queries) { if (!string.IsNullOrEmpty(q)) { string singleQuery = q.Trim(); await ExecuteQuery(gremlinClient, singleQuery) .ContinueWith( (task) => { results.Add(new { queryText = singleQuery, queryResult = task.Result }); } ); } } } return(results); }
public GremlinExecutor(CosmosDbConnection config, IConsole console) { _console = console; _server = GremlinExecutor.GetGremlinServer(config); _partitionKey = config.PartitionKey; _client = new GremlinClient(_server, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); }
public async Task ShouldReturnResultWithoutDeserializingItForJTokenType() { var gremlinServer = new GremlinServer(TestHost, TestPort); using (var gremlinClient = new GremlinClient(gremlinServer)) { var gremlinScript = "'someString'"; var response = await gremlinClient.SubmitWithSingleResultAsync <JToken>(gremlinScript); //Expected: /* { * "@type": "g:List", * "@value": [ * "someString" * ] * }*/ Assert.IsType <JObject>(response); Assert.Equal("g:List", response["@type"]); var jArray = response["@value"] as JArray; Assert.NotNull(jArray); Assert.Equal(1, jArray.Count); Assert.Equal("someString", (jArray[0] as JValue)?.Value); } }
// Starts a console application that executes every Gremlin query in the gremlinQueries dictionary. static void Main(string[] args) { var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, username: "******" + database + "/colls/" + collection, password: authKey); using (var gremlinClient = new GremlinClient(gremlinServer)) { foreach (var query in gremlinQueries) { Console.WriteLine(String.Format("Running this query: {0}: {1}", query.Key, query.Value)); // Create async task to execute the Gremlin query. var task = gremlinClient.SubmitAsync <dynamic>(query.Value); task.Wait(); foreach (var result in task.Result) { // The vertex results are formed as Dictionaries with a nested dictionary for their properties string output = JsonConvert.SerializeObject(result); Console.WriteLine(String.Format("\tResult:\n\t{0}", output)); } Console.WriteLine(); } } // Exit program Console.WriteLine("Done. Press any key to exit..."); Console.ReadLine(); }
/// <summary> /// Initializes a new instance of the <see cref="GraphClient"/> class. /// </summary> /// <param name="gremlinHostname">The hostname.</param> /// <param name="databaseName">Name of the database (case-sensitive).</param> /// <param name="graphName">Name of the graph.</param> /// <param name="accessKey">The access key.</param> /// <param name="port">The port number.</param> /// <param name="useSSL"><c>True</c> to use SSL.</param> public GraphClient(string gremlinHostname, string databaseName, string graphName, string accessKey, int port = 443, bool useSSL = true) { var server = new GremlinServer(gremlinHostname, port, useSSL, $"/dbs/{databaseName}/colls/{graphName}", accessKey); _gremlinClient = new GremlinClient(server, new GraphSONJTokenReader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); }
public GremlinHealthCheck(GremlinOptions options) { _ = options ?? throw new ArgumentNullException(nameof(options)); _ = options.Hostname ?? throw new ArgumentNullException(nameof(options.Hostname)); _server = new GremlinServer(options.Hostname, options.Port, options.EnableSsl); }
public async Task ShouldReassembleResponseBatches() { const int batchSize = 2; var expectedResult = new List <int> { 1, 2, 3, 4, 5 }; var requestScript = $"{nameof(expectedResult)}"; var bindings = new Dictionary <string, object> { { nameof(expectedResult), expectedResult } }; var requestMessage = RequestMessage.Build(Tokens.OpsEval) .AddArgument(Tokens.ArgsBatchSize, batchSize) .AddArgument(Tokens.ArgsGremlin, requestScript) .AddArgument(Tokens.ArgsBindings, bindings) .Create(); var gremlinServer = new GremlinServer(TestHost, TestPort); using (var gremlinClient = new GremlinClient(gremlinServer)) { var response = await gremlinClient.SubmitAsync <int>(requestMessage); Assert.Equal(expectedResult, response); } }
private static void ProcessGremlinCommandsFile(string infile) { List <string> commands = ReadLines(infile); GremlinServer gremlinServer = CreateGremlinServer(); using (var gremlinClient = new GremlinClient( gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType)) { Console.WriteLine($"gremlinClient: {gremlinClient}"); for (int i = 0; i < commands.Count(); i++) { string command = commands.ElementAt(i); Console.WriteLine("---"); Console.WriteLine($"{i} Command: {command}"); var resultSet = SubmitRequest(gremlinClient, command).Result; if (resultSet.Count > 0) { Console.WriteLine("Result:"); foreach (var result in resultSet) { string output = JsonConvert.SerializeObject(result); Console.WriteLine($"{output}"); } Console.WriteLine(); } PrintStatusAttributes(resultSet.StatusAttributes); Console.WriteLine(); } } }
public ProfileContext() { ConnectionPoolSettings connectionPoolSettings = new ConnectionPoolSettings() { MaxInProcessPerConnection = 10, PoolSize = 30, ReconnectionAttempts = 3, ReconnectionBaseDelay = TimeSpan.FromMilliseconds(500) }; var webSocketConfiguration = new Action <ClientWebSocketOptions>(options => { options.KeepAliveInterval = TimeSpan.FromSeconds(10); }); var gremlinServer = new GremlinServer(_host, 443, enableSsl: true, username: ContainerLink, password: _primaryKey); _client = new GremlinClient( gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType, connectionPoolSettings, webSocketConfiguration); }
public static void CreateClient() { var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, username: "******" + database + "/colls/" + collection, password: authKey); gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); }
public void SubmittingScriptsWithAuthenticationTest() { // tag::submittingScriptsWithAuthentication[] var username = "******"; var password = "******"; var gremlinServer = new GremlinServer("localhost", 8182, true, username, password); // end::submittingScriptsWithAuthentication[] }
public ConnectionFactory(GremlinServer gremlinServer, IMessageSerializer messageSerializer, WebSocketSettings webSocketSettings, string sessionId) { _gremlinServer = gremlinServer; _messageSerializer = messageSerializer; _sessionId = sessionId; _webSocketSettings = webSocketSettings; }
public void ShouldBuildCorrectUri(string host, int port) { var gremlinServer = new GremlinServer(host, port); var uri = gremlinServer.Uri; Assert.Equal($"ws://{host}:{port}/gremlin", uri.AbsoluteUri); }
public GraphClientWrapper() { var gremlinServer = new GremlinServer(EndpointUrl, Port, true, "/dbs/" + Database + "/colls/" + Collection, PrimaryKey); _gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); }
protected override void BeginProcessing() { WriteVerbose("Connecting GremlinClient"); var server = new GremlinServer(Hostname, Port, EnableSsl, Credential.UserName, Credential.GetNetworkCredential().Password); Client = new GremlinClient(server, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType); }