Пример #1
0
        /// <summary>
        /// deletes a node
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete <T>(Guid id)
            where T : BaseGraphEntity, new()
        {
            using (var gremlinClient = new GremlinClient(this._graphServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
            {
                T   temp = new T(); // Just to get the correct label
                var task = gremlinClient.SubmitAsync <dynamic>($"g.V().hasLabel('{temp.Label}').hasId('{id}').drop()");
                task.Wait();

                if (task.Result.Count > 0)
                {
                    return(new OkResult());
                }
            }

            return(new NotFoundResult());
        }
        protected override async Task WaitUntilContainerStarted()
        {
            await base.WaitUntilContainerStarted();

            using (var client = new GremlinClient(new GremlinServer(Host, Port)))
            {
                var result = await Policy.TimeoutAsync(TimeSpan.FromMinutes(2))
                             .WrapAsync(Policy.Handle <WebSocketException>()
                                        .WaitAndRetryForeverAsync(iteration => TimeSpan.FromSeconds(2)))
                             .ExecuteAndCaptureAsync(() => client.SubmitAsync("1+1"));

                if (result.Outcome == OutcomeType.Failure)
                {
                    throw new Exception(result.FinalException.Message);
                }
            }
        }
Пример #3
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "users/{id}")] HttpRequest req,
            string id,
            ILogger log,
            [FunctionToken] FunctionTokenResult token,
            ExecutionContext context)
        {
            log.LogInformation($"{context?.FunctionName} processed a HTTP request.");

            // IMPORTANT: Authorization!
            var authResult = AuthValidation(req, token, id);

            if (!authResult.IsAuthorized)
            {
                return(authResult.ActionResult);
            }

            User user = null;

            try
            {
                var query    = GremlinHelper.GetVertexQuery <User>(id);
                var response = new GraphResponse(await GremlinClient.SubmitAsync <dynamic>(query));

                GremlinHelper.ThrowIfResponseInvalid(response);

                if (response.Entities == null || response.Entities.Count() < 1)
                {
                    return(new NotFoundResult());
                }

                GremlinHelper.GraphTelemetryEvent(TelemetryClient, "GraphVertexRetrieve", response, "vertex", "user");

                user = response.GetEntityAsType <User>();
            }
            catch (ResponseException ex)
            {
                GremlinHelper.HandleGraphResponseException(ex, log, context, TelemetryClient);
            }
            catch (Exception ex)
            {
                GremlinHelper.HandleGeneralException(ex, log, context, TelemetryClient);
            }

            return(user != null ? (ActionResult) new OkObjectResult(user) : new NotFoundResult());
        }
Пример #4
0
        public async Task InvalidOperationShouldThrowException()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var ivalidOperationName = "invalid";
                var requestMsg          = _requestMessageProvider.GetDummyMessage();
                requestMsg.Operation = ivalidOperationName;

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                Assert.Contains("MalformedRequest", thrownException.Message);
                Assert.Contains(ivalidOperationName, thrownException.Message);
            }
        }
Пример #5
0
        public async Task ShouldThrowForInvalidProcessor()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var invalidProcessorName = "invalid";
                var requestMsg           = RequestMessage.Build("").Processor(invalidProcessorName).Create();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync <dynamic>(requestMsg));

                Assert.Contains("InvalidRequestArguments", thrownException.Message);
                Assert.Contains(invalidProcessorName, thrownException.Message);
                Assert.Contains("OpProcessor", thrownException.Message);
            }
        }
Пример #6
0
        private static async Task CreateRestaurant(GremlinClient client,
                                                   string id,
                                                   decimal rating,
                                                   decimal averagePrice)
        {
            var gremlinCode = $@"
				g.addV('restaurant')
					.property('id', '{id}')
					.property('city', 'LA')
					.property('rating', {rating})
					.property('averagePrice', {averagePrice})
			"            ;

            await _databaseService.ExecuteQuery(client, gremlinCode);

            Console.WriteLine($"Created vertex: Restaurant '{id}'");
        }
Пример #7
0
        public DemoContext()
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            KeyVaultClient            keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            string cosmosDBHost     = GetDBHost(keyVaultClient).ConfigureAwait(false).GetAwaiter().GetResult().Value;
            string cosmosDBUsername = GetDBUsername(keyVaultClient).ConfigureAwait(false).GetAwaiter().GetResult().Value;
            string cosmosDBPassword = GetDBPassword(keyVaultClient).ConfigureAwait(false).GetAwaiter().GetResult().Value;

            this.server = new GremlinServer(
                cosmosDBHost,
                port: 443,
                enableSsl: true,
                username: cosmosDBUsername,
                password: cosmosDBPassword);
            this.client = new GremlinClient(server, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType);
        }
Пример #8
0
        public List <dynamic> Query(string query)
        {
            using (var gremlinClient = new GremlinClient(this._gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
            {
                var resultSet = gremlinClient.SubmitAsync <dynamic>(query).Result;

                var records = new List <dynamic>();
                if (resultSet.Count > 0)
                {
                    foreach (var result in resultSet)
                    {
                        records.Add(result);
                    }
                }
                return(records);
            }
        }
Пример #9
0
 public static void CreateReleaseYear(GremlinClient gc, string year)
 {
     //Get the director, add if not exists
     if (!EntityExists(gc, year, Year.Type))
     {
         string query = "g.addV('" + Year.Type +
                        "').property('id', '" + year + "').";
         var task = gc.SubmitAsync <dynamic>(query);
         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));
         }
     }
 }
Пример #10
0
 private static Task <ResultSet <dynamic> > SubmitRequest(
     GremlinClient gremlinClient, string command)
 {
     try
     {
         return(gremlinClient.SubmitAsync <dynamic>(command));
     }
     catch (ResponseException e)
     {
         Console.WriteLine("Request Error");
         Console.WriteLine($"StatusCode: {e.StatusCode}");
         PrintStatusAttributes(e.StatusAttributes);
         Console.WriteLine($"[\"x-ms-retry-after-ms\"] : { GetValueAsString(e.StatusAttributes, "x-ms-retry-after-ms")}");
         Console.WriteLine($"[\"x-ms-activity-id\"] : { GetValueAsString(e.StatusAttributes, "x-ms-activity-id")}");
         throw;
     }
 }
Пример #11
0
        /*****************************************************************************************************************************************/

        /**************************************************************** E D G E ****************************************************************/
        /// <summary>
        /// Reads an Edge ID
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="childId"></param>
        /// <returns></returns>
        public Guid ReadEdge(Guid parentId, Guid childId)
        {
            if (parentId == null || parentId == Guid.Empty || childId == null || childId == Guid.Empty)
            {
                return(Guid.Empty);
            }

            using (var gremlinClient = new GremlinClient(this._graphServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
            {
                List <string> parentIdsList = new List <string>();
                var           parentTest    = gremlinClient.SubmitAsync <dynamic>($"g.V().hasId('{parentId}').outE().Id()");
                parentTest.Wait();
                foreach (string id in parentTest.Result)
                {
                    parentIdsList.Add(id);
                }
                if ((parentIdsList.Count == 0))
                {
                    return(Guid.Empty);
                }

                List <string> childIdsList = new List <string>();
                var           childTest    = gremlinClient.SubmitAsync <dynamic>($"g.V().hasId('{childId}').inE().Id()");
                childTest.Wait();
                foreach (string id in childTest.Result)
                {
                    childIdsList.Add(id);
                }
                if ((childIdsList.Count == 0))
                {
                    return(Guid.Empty);
                }
                var edge   = gremlinClient.SubmitAsync <dynamic>($"g.E().hasId('{childId}').inE().Id()");
                var edgeId = parentIdsList.Where(item => childIdsList.Select(item2 => item2).Contains(item));

                try
                {
                    return(Guid.Parse(edgeId.FirstOrDefault()));
                }
                catch (System.ArgumentNullException)
                {
                    return(Guid.Empty);
                }
            }
        }
        /// <summary>
        /// Execute all queries from the query list
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private async Task ExecuteQueryList(GremlinClient client)
        {
            logService.Log($"Executing {queries.Count} queries");

            await queries.ParallelForEachAsync(async (query) => {
                try {
                    await client.SubmitAsync(query);
                    InternalLogToConsole();
                }
                catch (Exception e) {
                    logService.Log($"Failed to execute query: {query}");
                    logService.Log(e.Message);
                    lock (failureLock) {
                        failedQueries.Add(query);
                    }
                }
            }, maxDegreeOfParallelism : 10);
        }
Пример #13
0
        public async Task HandleResponseWithoutContent()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var gremlinScript = "g.V().has(propertyKey, propertyValue);";
                var bindings      = new Dictionary <string, object>
                {
                    { "propertyKey", "name" },
                    { "propertyValue", "unknownTestName" }
                };

                var response = await gremlinClient.SubmitWithSingleResultAsync <object>(gremlinScript, bindings);

                Assert.Null(response);
            }
        }
Пример #14
0
        public async Task UnsupportedLanguageShouldThrowException()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var unknownLanguage = "unknown";
                var requestMsg      = _requestMessageProvider.GetDummyMessage();
                requestMsg.Arguments.Language = unknownLanguage;

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                Assert.Contains("ScriptEvaluationError", thrownException.Message);
                Assert.Contains(unknownLanguage, thrownException.Message);
                Assert.Contains("Language", thrownException.Message);
            }
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                using (var client = new GremlinClient(_server))
                    using (var conn = new DriverRemoteConnection(client))
                    {
                        var g = Traversal().WithRemote(conn);
                        await g.Inject(0).Promise(t => t.Next());
                    }
            }
            catch (Exception ex)
            {
                return(new HealthCheckResult(status: context.Registration.FailureStatus, exception: ex));
            }

            return(HealthCheckResult.Healthy());
        }
        public static string AddCommunication(EmailSearch Communication, GremlinClient GremlinClient)
        {
            Dictionary <string, string> properties = new Dictionary <string, string>();

            properties.Add(CommunicationVertexPartitionKeyProperty, Communication.PartitionKey);
            properties.Add(CommunicationVertexRowKeyProperty, Communication.RowKey);
            properties.Add(CommunicationVertexSubjectProperty, Communication.EmailSubject);
            properties.Add(CommunicationVertexUTCTimeProperty, Communication.Timestamp.ToString());
            properties.Add(CommunicationVertexYearProperty, Communication.Timestamp.Year.ToString());
            properties.Add(CommunicationVertexMonthProperty, Communication.Timestamp.Month.ToString());
            properties.Add(CommunicationVertexDayProperty, Communication.Timestamp.Day.ToString());
            properties.Add(CommunicationVertexConversationIDProperty, Communication.EmailConversationId);
            properties.Add(CommunicationVertexReferenceKey, Communication.ReferenceKey);

            string communicationID = AddGraphVertex(GremlinClient, CommunicationVertexLabel, null, properties);

            return(communicationID);
        }
 private void InitializeClient()
 {
     if (gremlinClients.TryGetValue(_key, out _client))
     {
         return;
     }
     lock (lockObject)
     {
         if (gremlinClients.TryGetValue(_key, out _client))
         {
             return;
         }
         _client = new GremlinClient(_server, new InternalGraphSONReader1(),
                                     new GraphSON2Writer(),
                                     GremlinClient.GraphSON2MimeType, ConnectionPoolSettings, WebSocketConfiguration);
         gremlinClients.TryAdd(_key, _client);
     }
 }
        // <inheritdoc/>
        public async Task <string> ExecuteCustomQuery(string query)
        {
            using var client = new GremlinClient(server, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType);
            var resultSet = await client.SubmitAsync <dynamic>(query);

            JArray array = new JArray();

            foreach (var result in resultSet)
            {
                string jsonObject = JsonConvert.SerializeObject(result, new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented
                });
                array.Add(JsonConvert.DeserializeObject(jsonObject));
            }

            return(array.ToString());
        }
Пример #19
0
        public async Task InvalidProcessorShouldThrowException()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var invalidProcessorName = "invalid";
                var requestMsg           = _requestMessageProvider.GetDummyMessage();
                requestMsg.Processor = invalidProcessorName;

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                Assert.Contains("InvalidRequestArguments", thrownException.Message);
                Assert.Contains(invalidProcessorName, thrownException.Message);
                Assert.Contains("OpProcessor", thrownException.Message);
            }
        }
 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}";
     if (gremlinClients.TryGetValue(_key, out _client))
     {
         return;
     }
     lock (lockObject)
     {
         if (gremlinClients.TryGetValue(_key, out _client))
         {
             return;
         }
         var server = new GremlinServer(gremlinHostname, port, enableSsl, username, password);
         _client = new GremlinClient(server, new InternalGraphSONReader1(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType);
         gremlinClients.TryAdd(_key, _client);
     }
 }
Пример #21
0
        public async Task UseBindingsForScript()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var requestMsg = "a + b";
                var a          = 1;
                var b          = 2;
                var bindings   = new Dictionary <string, object> {
                    { "a", a }, { "b", b }
                };

                var response = await gremlinClient.SubmitWithSingleResultAsync <int>(requestMsg, bindings);

                Assert.Equal(a + b, response);
            }
        }
Пример #22
0
        private Task <ResultSet <dynamic> > SubmitRequest(GremlinClient gremlinClient, KeyValuePair <string, string> query)
        {
            try
            {
                return(gremlinClient.SubmitAsync <dynamic>(query.Value));
            }
            catch (ResponseException e)
            {
                Console.WriteLine("\tRequest Error!");

                // Print the Gremlin status code.
                Console.WriteLine($"\tStatusCode: {e.StatusCode}");



                throw;
            }
        }
        public static async Task RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req,
            TraceWriter log)
        {
            string graphDbConnectionString = ConfigurationManager.AppSettings["graphdbconnectionstring"];
            string graphHostname           = ConfigurationManager.AppSettings["graphhostname"];
            string database   = ConfigurationManager.AppSettings["database"];
            string collection = ConfigurationManager.AppSettings["collection"];
            string graphDbKey = ConfigurationManager.AppSettings["graphdbkey"];
            string graphDbUri = ConfigurationManager.AppSettings["graphdburi"];
            int    port       = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
            string username   = $"/dbs/{database}/colls/{collection}";

            log.Info($"username: {username}");

            var gremlinServer = new GremlinServer(graphHostname, port, enableSsl: true,
                                                  username: "******" + database + "/colls/" + collection,
                                                  password: graphDbKey);

            string localPath = req.RequestUri.LocalPath;

            log.Info($"C# function processed: {localPath}");



            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                foreach (var query in GremlinQueries)
                {
                    log.Info(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);
                        log.Info(String.Format("\tResult:\n\t{0}", output));
                    }
                }
            }
        }
Пример #24
0
        public async Task <dynamic> AddE([FromBody] JObject requestBody)
        {
            var outV      = (string)requestBody.SelectToken("outV");
            var edgeLabel = (string)requestBody.SelectToken("label");
            var inV       = (string)requestBody.SelectToken("inV");
            var subscribe = (string)requestBody.SelectToken("subscribe");

            if (subscribe == "yes")
            {
                // Event Grid subscription
                await RunSubscription(outV, inV, edgeLabel);
            }
            using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
            {
                var response = await gremlinClient.SubmitAsync <dynamic>($"g.V('{outV}').addE('{edgeLabel}').to(g.V('{inV}'))");

                return(response);
            }
        }
Пример #25
0
        public async Task ShouldReturnEnumerableResult()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var expectedResult = new List <int> {
                    1, 2, 3, 4, 5
                };
                var requestMsg = $"{nameof(expectedResult)}";
                var bindings   = new Dictionary <string, object> {
                    { nameof(expectedResult), expectedResult }
                };

                var response = await gremlinClient.SubmitAsync <int>(requestMsg, bindings);

                Assert.Equal(expectedResult, response);
            }
        }
 static void Main(string[] args)
 {
     try
     {
         if (args.Length != 1)
         {
             Console.WriteLine("Please enter a Gremlin/Graph Query.");
         }
         else
         {
             var azureConfig = new ConfigurationBuilder()
                               .SetBasePath(Environment.CurrentDirectory)
                               .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                               .Build()
                               .GetSection("AzureConfig");
             var hostname      = azureConfig["HostName"];
             var port          = Convert.ToInt32(azureConfig["Port"]);
             var authKey       = azureConfig["AuthKey"];
             var database      = azureConfig["Database"];
             var collection    = azureConfig["Collection"];
             var gremlinServer = new GremlinServer(
                 hostname, port, enableSsl: true,
                 username: $"/dbs/" + database + "/colls/" + collection,
                 password: authKey);
             using (var gremlinClient = new GremlinClient(gremlinServer,
                                                          new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
             {
                 var resultSet = AzureAsync(gremlinClient, args[0]);
                 Console.WriteLine("\n{{\"Returned\": \"{0}\"}}", resultSet.Result.Count);
                 foreach (var result in resultSet.Result)
                 {
                     string jsonOutput = JsonConvert.SerializeObject(result);
                     Console.WriteLine("{0}", jsonOutput);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("EXCEPTION: {0}", ex.Message);
     }
 }
 /// <summary>
 /// Connecting to Cosmos DB
 /// </summary>
 /// <param name="gremlinHostname">DBAccountName.gremlin.cosmosdb.azure.com</param>
 /// <param name="databaseName"></param>
 /// <param name="graphName"></param>
 /// <param name="accessKey"></param>
 public GremlinNetLanguageConnector(string gremlinHostname, string databaseName, string graphName, string accessKey, ILogging logger = null) : base(logger)
 {
     _key = $"{gremlinHostname.ToLower()}.{databaseName.ToLower()}.{graphName.ToLower()}";
     if (gremlinClients.TryGetValue(_key, out _client))
     {
         return;
     }
     lock (lockObject)
     {
         if (gremlinClients.TryGetValue(_key, out _client))
         {
             return;
         }
         var server = new GremlinServer(gremlinHostname, 443, true, $"/dbs/{databaseName}/colls/{graphName}", accessKey);
         _client = new GremlinClient(server, new InternalGraphSONReader1(),
                                     new GraphSON2Writer(),
                                     GremlinClient.GraphSON2MimeType, ConnectionPoolSettings, WebSocketConfiguration);
         gremlinClients.TryAdd(_key, _client);
     }
 }
Пример #28
0
        public async Task ShouldThrowForUnsupportedLanguage()
        {
            var gremlinServer = new GremlinServer(TestHost, TestPort);

            using (var gremlinClient = new GremlinClient(gremlinServer))
            {
                var unknownLanguage = "unknown";
                var requestMsg      =
                    RequestMessage.Build(Tokens.OpsEval)
                    .AddArgument(Tokens.ArgsGremlin, "1")
                    .AddArgument(Tokens.ArgsLanguage, unknownLanguage)
                    .Create();

                var thrownException =
                    await Assert.ThrowsAsync <ResponseException>(() => gremlinClient.SubmitAsync(requestMsg));

                Assert.Contains("ScriptEvaluationError", thrownException.Message);
                Assert.Contains(unknownLanguage, thrownException.Message);
            }
        }
Пример #29
0
        public async Task <CosmosResponse <T> > ExecuteGremlingSingle <T>(string queryString)
        {
            try
            {
                using (var client = new GremlinClient(_server))
                {
                    var result = await client.SubmitWithSingleResultAsync <T>(queryString);

                    return(new CosmosResponse <T> {
                        Result = result, RU = -1
                    });
                }
            }
            catch (Exception e)
            {
                return(new CosmosResponse <T> {
                    Error = e
                });
            }
        }
Пример #30
0
        public async Task <CosmosResponse <IEnumerable <T> > > ExecuteGremlingMulti <T>(string queryString)
        {
            try
            {
                using (var client = new GremlinClient(_server))
                {
                    var result = await client.SubmitAsync <T>(queryString);

                    return(new CosmosResponse <IEnumerable <T> > {
                        Result = result.ToArray(), RU = -1
                    });
                }
            }
            catch (Exception e)
            {
                return(new CosmosResponse <IEnumerable <T> > {
                    Error = e
                });
            }
        }