コード例 #1
0
        private static async Task CreateGateToRestaurant(IGremlinClient client, string gate, string restaurant, int distanceInMinutes)
        {
            string gremlinCode = $@"
				g.V()
					.has('id', '{gate}')
					.addE('gateToRestaurant')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{restaurant}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: GateToRestaurant '{gate}' > '{restaurant}'");

            gremlinCode = $@"
				g.V()
					.has('id', '{restaurant}')
					.addE('restaurantToGate')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{gate}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: RestaurantToGate '{restaurant}' > '{gate}'");
        }
コード例 #2
0
        private static async Task CreateTerminalToTerminal(IGremlinClient client, string terminal1, string terminal2, int distanceInMinutes)
        {
            string gremlinCode = $@"
				g.V()
					.has('id', '{terminal1}')
					.addE('terminalToNextTerminal')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{terminal2}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: TerminalToNextTerminal '{terminal1}' > '{terminal2}'");

            gremlinCode = $@"
				g.V()
					.has('id', '{terminal2}')
					.addE('terminalToPrevTerminal')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{terminal1}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: TerminalToPrevTerminal '{terminal2}' > '{terminal1}'");
        }
コード例 #3
0
        private static async Task CreateGateToGate(IGremlinClient client, string gate1, string gate2, int distanceInMinutes)
        {
            string gremlinCode = $@"
				g.V()
					.has('id', '{gate1}')
					.addE('gateToNextGate')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{gate2}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: GateToNextGate '{gate1}' > '{gate2}'");

            gremlinCode = $@"
				g.V()
					.has('id', '{gate2}')
					.addE('gateToPrevGate')
					.property('distanceInMinutes', {distanceInMinutes})
					.to(
						g.V()
							.has('id', '{gate1}'))"                            ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created edge: GateToPrevGate '{gate2}' > '{gate1}'");
        }
コード例 #4
0
        /// <summary>
        /// Submits the given gremlin query to the Cosmos Db instance and returns the results.
        /// </summary>
        /// <param name="gremlinQuery">The gremlin query.</param>
        /// <returns>Returns the results</returns>
        /// <exception cref="ArgumentNullException">gremlinQuery</exception>
        public async Task <GraphResult> QueryAsync(string gremlinQuery)
        {
            if (gremlinQuery == null)
            {
                throw new ArgumentNullException(nameof(gremlinQuery));
            }

            var rawResultSet = await _gremlinClient.SubmitAsync <JToken>(gremlinQuery);

            // Because SubmitAsync() above handles JToken differently from all other types, we
            // have to do the normal processing (that it would do for any other type) here.
            var resultList = new List <JToken>();

            foreach (var rawJToken in rawResultSet)
            {
                var processedJToken = (JToken)this._graphSONReader.ToObject(rawJToken);
                foreach (var d in processedJToken)
                {
                    resultList.Add(d);
                }
            }
            var newResultSet = new ResultSet <JToken>(resultList, rawResultSet.StatusAttributes);

            return(new GraphResult(newResultSet));
        }
コード例 #5
0
        /// <summary>
        /// Submits a request message as an asynchronous operation where only a single result gets returned.
        /// </summary>
        /// <remarks>If multiple results are received from Gremlin Server, then only the first gets returned. Use <see cref="SubmitAsync{T}"/> instead when you expect a collection of results.</remarks>
        /// <typeparam name="T">The type of the expected result.</typeparam>
        /// <param name="gremlinClient">The <see cref="IGremlinClient"/> that submits the request.</param>
        /// <param name="requestMessage">The <see cref="ScriptRequestMessage"/> to send.</param>
        /// <returns>A single result received from the Gremlin Server.</returns>
        /// <exception cref="Exceptions.ResponseException">Thrown when a response is received from Gremlin Server that indicates that an error occurred.</exception>
        public static async Task <T> SubmitWithSingleResultAsync <T>(this IGremlinClient gremlinClient,
                                                                     ScriptRequestMessage requestMessage)
        {
            var resultCollection = await gremlinClient.SubmitAsync <T>(requestMessage).ConfigureAwait(false);

            return(resultCollection.FirstOrDefault());
        }
コード例 #6
0
        private async Task <IEnumerable <Traverser> > SubmitBytecodeAsync(Guid requestid, Bytecode bytecode)
        {
            var requestMsg =
                RequestMessage.Build(Tokens.OpsBytecode)
                .Processor(Processor)
                .OverrideRequestId(requestid)
                .AddArgument(Tokens.ArgsGremlin, bytecode)
                .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
                { "g", _traversalSource }
            });

            if (IsSessionBound)
            {
                requestMsg.AddArgument(Tokens.ArgsSession, _sessionId);
            }

            var optionsStrategyInst = bytecode.SourceInstructions.Find(
                s => s.OperatorName == "withStrategies" && s.Arguments[0] is OptionsStrategy);

            if (optionsStrategyInst != null)
            {
                OptionsStrategy optionsStrategy = optionsStrategyInst.Arguments[0];
                foreach (KeyValuePair <string, dynamic> pair in optionsStrategy.Configuration)
                {
                    if (_allowedKeys.Contains(pair.Key))
                    {
                        requestMsg.AddArgument(pair.Key, pair.Value);
                    }
                }
            }

            return(await _client.SubmitAsync <Traverser>(requestMsg.Create()).ConfigureAwait(false));
        }
コード例 #7
0
        /// <summary>
        /// Submits the request to Cosmos DB.
        /// </summary>
        /// <param name="gremlinClient">The gremlin client.</param>
        /// <param name="query">The query.</param>
        /// <returns></returns>
        private static Task <ResultSet <dynamic> > SubmitRequest(IGremlinClient 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}");

                // On error, ResponseException.StatusAttributes will include the common StatusAttributes for successful requests, as well as
                // additional attributes for retry handling and diagnostics.
                // These include:
                //  x-ms-retry-after-ms         : The number of milliseconds to wait to retry the operation after an initial operation was throttled. This will be populated when
                //                              : attribute 'x-ms-status-code' returns 429.
                //  x-ms-activity-id            : Represents a unique identifier for the operation. Commonly used for troubleshooting purposes.
                PrintStatusAttributes(e.StatusAttributes);
                Console.WriteLine(
                    $"\t[\"x-ms-retry-after-ms\"] : {GetValueAsString(e.StatusAttributes, "x-ms-retry-after-ms")}");
                Console.WriteLine(
                    $"\t[\"x-ms-activity-id\"] : {GetValueAsString(e.StatusAttributes, "x-ms-activity-id")}");

                throw;
            }
        }
コード例 #8
0
        private static async Task ClearGraph(IGremlinClient client)
        {
            string gremlinCode = @"g.V().drop()";

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine("Graph has been cleared");
        }
コード例 #9
0
        /// <summary>
        /// Submits a request message that consists of a script with bindings as an asynchronous operation where only a single result gets returned.
        /// </summary>
        /// <remarks>If multiple results are received from Gremlin Server, then only the first gets returned. Use <see cref="SubmitAsync{T}"/> instead when you expect a collection of results.</remarks>
        /// <typeparam name="T">The type of the expected result.</typeparam>
        /// <param name="gremlinClient">The <see cref="IGremlinClient"/> that submits the request.</param>
        /// <param name="requestScript">The Gremlin request script to send.</param>
        /// <param name="bindings">Bindings for parameters used in the requestScript.</param>
        /// <returns>A single result received from the Gremlin Server.</returns>
        /// <exception cref="Exceptions.ResponseException">Thrown when a response is received from Gremlin Server that indicates that an error occurred.</exception>
        public static async Task <T> SubmitWithSingleResultAsync <T>(this IGremlinClient gremlinClient,
                                                                     string requestScript,
                                                                     Dictionary <string, object> bindings = null)
        {
            var resultCollection = await gremlinClient.SubmitAsync <T>(requestScript, bindings).ConfigureAwait(false);

            return(resultCollection.FirstOrDefault());
        }
コード例 #10
0
            public async Task <ResultSet <TResult> > SubmitAsync <TResult>(RequestMessage requestMessage)
            {
                var resultSet = await _baseClient.SubmitAsync <TResult>(requestMessage);

                _observer(requestMessage, resultSet.StatusAttributes);

                return(resultSet);
            }
コード例 #11
0
        /// <summary>
        /// Submits the given gremlin query to the Cosmos Db instance.
        /// </summary>
        /// <param name="gremlinQuery">The gremlin query.</param>
        /// <returns>Returns the results</returns>
        /// <exception cref="ArgumentNullException">gremlinQuery</exception>
        public Task <IReadOnlyCollection <JToken> > SubmitAsync(string gremlinQuery)
        {
            if (gremlinQuery == null)
            {
                throw new ArgumentNullException(nameof(gremlinQuery));
            }

            return(_gremlinClient.SubmitAsync <JToken>(gremlinQuery));
        }
コード例 #12
0
        private static async Task CreateGate(IGremlinClient client, string id)
        {
            string gremlinCode = $@"
				g.addV('gate')
					.property('id', '{id}')
					.property('city', 'LA')"                    ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created vertex: Gate '{id}'");
        }
コード例 #13
0
        /// <summary>
        /// Submits the given gremlin query to the Cosmos Db instance and returns the results.
        /// </summary>
        /// <param name="gremlinQuery">The gremlin query.</param>
        /// <returns>Returns the results</returns>
        /// <exception cref="ArgumentNullException">gremlinQuery</exception>
        public async Task <GraphResult> QueryAsync(string gremlinQuery)
        {
            if (gremlinQuery == null)
            {
                throw new ArgumentNullException(nameof(gremlinQuery));
            }

            var resultSet = await _gremlinClient.SubmitAsync <JToken>(gremlinQuery);

            return(new GraphResult(resultSet));
        }
コード例 #14
0
        /// <summary>
        /// Submits a request message that consists of a script with bindings as an asynchronous operation.
        /// </summary>
        /// <typeparam name="T">The type of the expected results.</typeparam>
        /// <param name="gremlinClient">The <see cref="IGremlinClient"/> that submits the request.</param>
        /// <param name="requestScript">The Gremlin request script to send.</param>
        /// <param name="bindings">Bindings for parameters used in the requestScript.</param>
        /// <returns>An enumerable collection of the data returned from the server.</returns>
        /// <exception cref="Exceptions.ResponseException">Thrown when a response is received from Gremlin Server that indicates that an error occurred.</exception>
        public static async Task <IEnumerable <T> > SubmitAsync <T>(this IGremlinClient gremlinClient, string requestScript,
                                                                    Dictionary <string, object> bindings = null)
        {
            var requestMessage = new ScriptRequestMessage
            {
                Arguments = new ScriptRequestArguments {
                    GremlinScript = requestScript, Bindings = bindings
                }
            };

            return(await gremlinClient.SubmitAsync <T>(requestMessage).ConfigureAwait(false));
        }
コード例 #15
0
 public async Task <IEnumerable <Dictionary <string, object> > > ExecuteQuery(string query)
 {
     try
     {
         IGremlinClient graphclient = GremlinClient();
         return(await graphclient.SubmitAsync <Dictionary <string, object> >(query));
     }
     catch (ResponseException e)
     {
         throw new GraphRepositoryException(e.Message, e);
     }
 }
コード例 #16
0
        private async Task ExecuteMultipleLongRunningRequestsInParallel(IGremlinClient gremlinClient, int nrRequests,
                                                                        int requestRunningTimeInMs)
        {
            var tasks = new List <Task>(nrRequests);

            for (var i = 0; i < nrRequests; i++)
            {
                tasks.Add(gremlinClient.SubmitAsync(_requestMessageProvider.GetSleepMessage(requestRunningTimeInMs)));
            }

            await Task.WhenAll(tasks);
        }
コード例 #17
0
        private static async Task CreateRestaurant(IGremlinClient client, string id, decimal rating, decimal averagePrice)
        {
            string gremlinCode = $@"
				g.addV('restaurant')
					.property('id', '{id}')
					.property('city', 'LA')
					.property('rating', {rating})
					.property('averagePrice', {averagePrice})"                    ;

            await client.SubmitAsync(gremlinCode);

            Console.WriteLine($"Created vertex: Restaurant '{id}'");
        }
コード例 #18
0
        private async Task <IEnumerable <Traverser> > SubmitBytecodeAsync(Guid requestid, Bytecode bytecode)
        {
            var requestMsg =
                RequestMessage.Build(Tokens.OpsBytecode)
                .Processor(Tokens.ProcessorTraversal)
                .OverrideRequestId(requestid)
                .AddArgument(Tokens.ArgsGremlin, bytecode)
                .AddArgument(Tokens.ArgsAliases, new Dictionary <string, string> {
                { "g", _traversalSource }
            })
                .Create();

            return(await _client.SubmitAsync <Traverser>(requestMsg).ConfigureAwait(false));
        }
コード例 #19
0
        /// <summary>
        ///     Submits a request message that consists of a script with bindings as an asynchronous operation.
        /// </summary>
        /// <typeparam name="T">The type of the expected results.</typeparam>
        /// <param name="gremlinClient">The <see cref="IGremlinClient" /> that submits the request.</param>
        /// <param name="requestScript">The Gremlin request script to send.</param>
        /// <param name="bindings">Bindings for parameters used in the requestScript.</param>
        /// <returns>A collection of the data returned from the server.</returns>
        /// <exception cref="Exceptions.ResponseException">
        ///     Thrown when a response is received from Gremlin Server that indicates
        ///     that an error occurred.
        /// </exception>
        public static async Task <IReadOnlyCollection <T> > SubmitAsync <T>(this IGremlinClient gremlinClient,
                                                                            string requestScript,
                                                                            Dictionary <string, object> bindings = null)
        {
            var msgBuilder = RequestMessage.Build(Tokens.OpsEval).AddArgument(Tokens.ArgsGremlin, requestScript);

            if (bindings != null)
            {
                msgBuilder.AddArgument(Tokens.ArgsBindings, bindings);
            }
            var msg = msgBuilder.Create();

            return(await gremlinClient.SubmitAsync <T>(msg).ConfigureAwait(false));
        }
コード例 #20
0
        /// <summary>
        /// Submits the given gremlin query to the Cosmos Db instance and returns the results.
        /// </summary>
        /// <param name="gremlinQuery">The gremlin query.</param>
        /// <returns>Returns the results</returns>
        /// <param name="caller">Method name or property name of the caller.</param>
        /// <param name="filePath">Full path of the source file that contains the caller. The full path is the path at compile time.</param>
        /// <param name="sourceLineNumber">Line number in the source file from which the method is called.</param>
        /// <exception cref="ArgumentNullException">gremlinQuery</exception>
        public async Task <GraphResult> QueryAsync(
            string gremlinQuery,
            [CallerMemberName] string caller        = "",
            [CallerFilePath] string filePath        = "",
            [CallerLineNumber] int sourceLineNumber = 0)
        {
            if (gremlinQuery == null)
            {
                throw new ArgumentNullException(nameof(gremlinQuery));
            }

            var resultSet = await _gremlinClient.SubmitAsync <JToken>(gremlinQuery);

            return(new GraphResult(resultSet));
        }
コード例 #21
0
        private static async Task RunAirportQuery(IGremlinClient client, string gremlinCode)
        {
            IReadOnlyCollection <dynamic> results = await client.SubmitAsync <dynamic>(gremlinCode);

            int count = 0;

            foreach (dynamic result in results)
            {
                count++;
                dynamic jResult = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result));
                JArray  steps   = (JArray)jResult["objects"];

                int userStep = 0;
                int totalDistanceInMinutes = 0;
                int i = 0;

                Console.WriteLine();
                Console.WriteLine($"Choice # {count}");

                foreach (JToken step in steps)
                {
                    i++;
                    if (step["type"].Value <string>() == "vertex")
                    {
                        userStep++;
                        string userStepCaption = (userStep == 1 ? "Start at" : (i == steps.Count ? "Arrive at" : "Go to"));
                        string vertexInfo      = $"{userStep}. {userStepCaption} {step["label"]} = {step["id"]}";

                        if (step["label"].Value <string>() == "restaurant")
                        {
                            vertexInfo += $", rating = {step["properties"]["rating"][0]["value"]}";
                            vertexInfo += $", avg price = {step["properties"]["averagePrice"][0]["value"]}";
                        }

                        vertexInfo += $" ({totalDistanceInMinutes} min)";
                        Console.WriteLine(vertexInfo);
                    }
                    else
                    {
                        int distanceInMinutes = step["properties"]["distanceInMinutes"].Value <int>();
                        totalDistanceInMinutes += distanceInMinutes;
                        string edgeInfo = $"    ({step["label"]} = {distanceInMinutes} min)";
                        Console.WriteLine(edgeInfo);
                    }
                }
            }
        }
コード例 #22
0
 /// <summary>
 ///     Submits a request message as an asynchronous operation without returning the result received from the Gremlin
 ///     Server.
 /// </summary>
 /// <param name="gremlinClient">The <see cref="IGremlinClient" /> that submits the request.</param>
 /// <param name="requestMessage">The <see cref="RequestMessage" /> to send.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 /// <exception cref="Exceptions.ResponseException">
 ///     Thrown when a response is received from Gremlin Server that indicates
 ///     that an error occurred.
 /// </exception>
 public static async Task <GremlinResponse> SubmitAsync(this IGremlinClient gremlinClient, RequestMessage requestMessage)
 {
     return(await gremlinClient.SubmitAsync <object>(requestMessage).ConfigureAwait(false));
 }
コード例 #23
0
 public async Task <ResultSet <TResult> > SubmitAsync <TResult>(RequestMessage requestMessage)
 {
     return(await _baseClient.SubmitAsync <TResult>(await _transformation(requestMessage)));
 }
コード例 #24
0
 /// <summary>
 /// Submits a request message as an asynchronous operation without returning the result received from the Gremlin Server.
 /// </summary>
 /// <param name="gremlinClient">The <see cref="IGremlinClient"/> that submits the request.</param>
 /// <param name="requestMessage">The <see cref="ScriptRequestMessage"/> to send.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 /// <exception cref="Exceptions.ResponseException">Thrown when a response is received from Gremlin Server that indicates that an error occurred.</exception>
 public static async Task SubmitAsync(this IGremlinClient gremlinClient, ScriptRequestMessage requestMessage)
 {
     await gremlinClient.SubmitAsync <object>(requestMessage).ConfigureAwait(false);
 }
コード例 #25
0
 /// <summary>
 /// Submits a request message that consists of a script with bindings as an asynchronous operation without returning the result received from the Gremlin Server.
 /// </summary>
 /// <param name="gremlinClient">The <see cref="IGremlinClient"/> that submits the request.</param>
 /// <param name="requestScript">The Gremlin request script to send.</param>
 /// <param name="bindings">Bindings for parameters used in the requestScript.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 /// <exception cref="Exceptions.ResponseException">Thrown when a response is received from Gremlin Server that indicates that an error occurred.</exception>
 public static async Task SubmitAsync(this IGremlinClient gremlinClient, string requestScript,
                                      Dictionary <string, object> bindings = null)
 {
     await gremlinClient.SubmitAsync <object>(requestScript, bindings).ConfigureAwait(false);
 }
コード例 #26
0
 private IEnumerable <string> RetrieveKeys()
 {
     return(_gremlinClient.SubmitAsync <string>(SideEffectKeysMessage()).Result);
 }