示例#1
0
 public HttpResponseMessage getAllSites(int city_id)
 {
     using (smart_trip_dbEntities se = new smart_trip_dbEntities())
     {
         var sites = se.sites.Where(s => s.city_id != null && s.city_id == city_id).ToList();
         return(rh.HandleResponse(new { city_sites = sites }));
     }
 }
 public HttpResponseMessage getRoute(int routeId)
 {
     using (smart_trip_dbEntities se = new smart_trip_dbEntities())
     {
         var route = se.routes.Where(s => s.id == routeId).ToList();
         return(rh.HandleResponse(new { route = route }));
     }
 }
示例#3
0
 public HttpResponseMessage getAll()
 {
     using (smart_trip_dbEntities se = new smart_trip_dbEntities())
     {
         var cities = se.cities.ToList();
         return(rh.HandleResponse(new { cities = cities }));
     }
 }
        public async Task HandleUserResponse()
        {
            // Arrange
            var responseHandler = new ResponseHandler(new Serializer());
            var hrm             = new HttpResponseMessage()
            {
                Content = new StringContent(@"{
                    ""id"": ""123"",
                    ""givenName"": ""Joe"",
                    ""surName"": ""Brown"",
                    ""@odata.type"":""test""
                }", Encoding.UTF8, "application/json")
            };

            hrm.Headers.Add("test", "value");

            // Act
            var user = await responseHandler.HandleResponse <User>(hrm);

            //Assert
            Assert.Equal("123", user.Id);
            Assert.Equal("Joe", user.GivenName);
            Assert.Equal("Brown", user.Surname);
            Assert.Equal("OK", user.AdditionalData["statusCode"]);
            var headers = (JObject)(user.AdditionalData["responseHeaders"]);

            Assert.Equal("value", (string)headers["test"][0]);
        }
示例#5
0
        public RootResponse Root()
        {
            ResponseHandler <RootResponse> responseHandler = new ResponseHandler <RootResponse>();

            var response = HttpClient.GetAsync(_serverUri).Result;

            return(responseHandler.HandleResponse(response).Result);
        }
        private async Task RetryRequestWithTransientFaultAsync(IGraphServiceClient client, BatchRequestContent batchRequestContent, Dictionary <string, HttpResponseMessage> responses, List <SignIn> signIns, int retryCount)
        {
            BatchRequestContent  retryBatchRequestContent = new BatchRequestContent();
            BatchResponseContent batchResponseContent;
            Random random;
            double delta;

            client.AssertNotNull(nameof(client));
            batchRequestContent.AssertNotNull(nameof(batchRequestContent));
            responses.AssertNotNull(nameof(responses));


            if (responses.Any(r => IsTransient(r.Value)))
            {
                if (retryCount <= 3)
                {
                    foreach (KeyValuePair <string, HttpResponseMessage> item in responses.Where(r => IsTransient(r.Value)))
                    {
                        retryBatchRequestContent.AddBatchRequestStep(batchRequestContent.BatchRequestSteps[item.Key]);
                    }

                    random = new Random();
                    delta  = (Math.Pow(2.0, retryCount) - 1.0) *
                             random.Next((int)(DefaultClientBackoff.TotalMilliseconds * 0.8), (int)(DefaultClientBackoff.TotalMilliseconds * 1.2));

                    await Task.Delay((int)Math.Min(DefaultMinBackoff.TotalMilliseconds + delta, DefaultMaxBackoff.TotalMilliseconds), CancellationToken).ConfigureAwait(false);

                    batchResponseContent = await client.Batch.Request().PostAsync(retryBatchRequestContent, CancellationToken).ConfigureAwait(false);

                    await ParseBatchResponseAsync(client, retryBatchRequestContent, batchResponseContent, signIns, retryCount).ConfigureAwait(false);
                }
                else
                {
                    ErrorResponse           errorResponse;
                    List <ServiceException> exceptions      = new List <ServiceException>();
                    ResponseHandler         responseHandler = new ResponseHandler(new Serializer());
                    string rawResponseBody;

                    foreach (KeyValuePair <string, HttpResponseMessage> item in responses.Where(item => !item.Value.IsSuccessStatusCode))
                    {
                        rawResponseBody = null;

                        if (item.Value.Content?.Headers.ContentType.MediaType == "application/json")
                        {
                            rawResponseBody = await item.Value.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }

                        errorResponse = await responseHandler.HandleResponse <ErrorResponse>(item.Value).ConfigureAwait(false);

                        exceptions.Add(new ServiceException(errorResponse.Error, item.Value.Headers, item.Value.StatusCode, rawResponseBody));
                    }

                    throw new AggregateException(exceptions);
                }
            }
        }
示例#7
0
        private static async Task GraphBatchingSequential(GraphServiceClient graphClient)
        {
            // Create a batch request content "container"
            var batchRequestContent = new BatchRequestContent();

            // Prepare some requests to add to the batch
            var userRequest      = graphClient.Users["*****@*****.**"].Request().Select("Id,DisplayName");
            var userDriveRequest = graphClient.Users["*****@*****.**"].Drive.Request().Select("Id,WebUrl");

            var userHttpRequest      = new HttpRequestMessage(HttpMethod.Get, userRequest.RequestUrl);
            var userDriveHttpRequest = new HttpRequestMessage(HttpMethod.Get, userDriveRequest.RequestUrl);

            var userRequestId      = batchRequestContent.AddBatchRequestStep(new BatchRequestStep("1", userHttpRequest));
            var userDriveRequestId = batchRequestContent.AddBatchRequestStep(new BatchRequestStep("2", userDriveHttpRequest,
                                                                                                  (new string[] { "1" }).ToList()));

            // Execute the batch request
            var returnedResponse = await graphClient.Batch.Request().PostAsync(batchRequestContent);

            // Process batch responses
            var responseHandler = new ResponseHandler(new Serializer());

            // Now process the dependencies
            var userResponse = await returnedResponse
                               .GetResponseByIdAsync("1");

            if (userResponse.IsSuccessStatusCode)
            {
                var user = await responseHandler.HandleResponse <User>(userResponse);

                Console.WriteLine($"{user.Id} - {user.DisplayName}");
            }

            var userDriveResponse = await returnedResponse
                                    .GetResponseByIdAsync("2");

            if (userDriveResponse.IsSuccessStatusCode)
            {
                var drive = await responseHandler.HandleResponse <Drive>(userDriveResponse);

                Console.WriteLine($"{drive.Id} - {drive.WebUrl}");
            }
        }
示例#8
0
        public async Task <IActionResult> Index()
        {
            var request = this._graphServiceClient.Me.Request().GetHttpRequestMessage();

            request.Properties["User"] = HttpContext.User;
            var response = await this._graphServiceClient.HttpProvider.SendAsync(request);

            var handler = new ResponseHandler(new Serializer());
            var user    = await handler.HandleResponse <User>(response);

            return(View(user));
        }
示例#9
0
        public async Task <object> Call(IHttpHandler httpHandler, string baseUrl, HttpApiArguments arguments, HttpApiInstrumenter apiInstrumenter = null)
        {
            async void ApplyArguments(Func <IHttpArgumentHandler, string, object, Task> applier)
            {
                foreach (var item in ArgumentHandlers)
                {
                    var name = item.Key;
                    if (arguments.TryGetValue(name, out var argument))
                    {
                        var handler = item.Value;
                        await applier(handler, name, argument);
                    }
                }
            }

            HttpApiRequest GetRequest()
            {
                var request = new HttpApiRequest {
                    Url = Url.CreateUrl(baseUrl), Method = HttpMethod, Headers = Headers.ToList()
                };

                ApplyArguments(async(handler, name, argument) => await handler.ApplyArgument(request, name, argument));

                if (!request.Headers.Exists(x => x.Name == "Content-Type") && request.Body != null)
                {
                    var contentType = request.Body.Accept(new ContentTypeCalculator());
                    request.Headers.Add(new HttpHeader("Content-Type", contentType));
                }

                return(request);
            }

            async Task <HttpHandlerResponse> GetResponse(HttpApiRequest request)
            {
                return(await httpHandler.Call(request));
            }

            async Task <object> GetResult(HttpApiRequest request, HttpHandlerResponse response)
            {
                ApplyArguments(async(handler, name, argument) => await handler.ApplyArgument(response.ApiResponse, name, argument));
                return(await ResponseHandler.HandleResponse(request, response.ApiResponse));
            }

            IHttpApiInstrumentation instrumentation = new DefaultHttpApiInstrumentation(GetRequest, GetResponse, GetResult);

            if (apiInstrumenter != null)
            {
                instrumentation = apiInstrumenter(this, arguments, instrumentation);
            }

            return(await MakeCall(instrumentation));
        }
示例#10
0
        public HttpResponseMessage login(UserConnection user)
        {
            using (smart_trip_dbEntities se = new smart_trip_dbEntities())
            {
                var user_ = getUserIfExists(se, user.userName, user.password, user.deviceToken);
                if (user_ == null)
                {
                    user_              = new users();
                    user_.uname        = user.userName;
                    user_.password     = user.password;
                    user_.device_token = user.deviceToken;
                    se.users.Add(user_);
                    se.SaveChanges();
                }

                var cities            = se.cities.ToList();
                var sites             = se.sites.Where(s => s.city_id == 1).ToList();
                var categories        = se.sites_types.ToList();
                var recommandedRoutes = se.routes.Where(s => s.rate != null && s.rate >= 4).ToList();

                return(rh.HandleResponse(new { user = user_, sites = sites, cities = cities, categories = categories, recommanded_routes = recommandedRoutes }));
            }
        }
示例#11
0
        /// <summary>
        ///     The next page of results or null when there is no more results
        /// </summary>
        /// <returns></returns>
        public async Task <Page <T> > NextPage()
        {
            if (Links.Next == null)
            {
                return(null);
            }

            var responseHandler = new ResponseHandler <Page <T> >();
            var uri             = new Uri(Links.Next.Href);

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(uri);

                return(await responseHandler.HandleResponse(response));
            }
        }
        /// <summary>
        /// Executes a request using the default context and processes the
        /// response using the given response handler.
        /// </summary>
        /// <remarks>
        /// Executes a request using the default context and processes the
        /// response using the given response handler. The content entity associated
        /// with the response is fully consumed and the underlying connection is
        /// released back to the connection manager automatically in all cases
        /// relieving individual
        /// <see cref="Apache.Http.Client.ResponseHandler{T}">Apache.Http.Client.ResponseHandler&lt;T&gt;
        ///     </see>
        /// s from having to manage
        /// resource deallocation internally.
        /// </remarks>
        /// <param name="target">
        /// the target host for the request.
        /// Implementations may accept <code>null</code>
        /// if they can still determine a route, for example
        /// to a default target or by inspecting the request.
        /// </param>
        /// <param name="request">the request to execute</param>
        /// <param name="responseHandler">the response handler</param>
        /// <param name="context">
        /// the context to use for the execution, or
        /// <code>null</code> to use the default context
        /// </param>
        /// <returns>the response object as generated by the response handler.</returns>
        /// <exception cref="System.IO.IOException">in case of a problem or the connection was aborted
        ///     </exception>
        /// <exception cref="Apache.Http.Client.ClientProtocolException">in case of an http protocol error
        ///     </exception>
        public virtual T Execute <T, _T1>(HttpHost target, IHttpRequest request, ResponseHandler
                                          <_T1> responseHandler, HttpContext context) where _T1 : T
        {
            Args.NotNull(responseHandler, "Response handler");
            HttpResponse response = Execute(target, request, context);
            T            result;

            try
            {
                result = responseHandler.HandleResponse(response);
            }
            catch (Exception t)
            {
                HttpEntity entity = response.GetEntity();
                try
                {
                    EntityUtils.Consume(entity);
                }
                catch (Exception t2)
                {
                    // Log this exception. The original exception is more
                    // important and will be thrown to the caller.
                    this.log.Warn("Error consuming content after an exception.", t2);
                }
                if (t is RuntimeException)
                {
                    throw (RuntimeException)t;
                }
                if (t is IOException)
                {
                    throw (IOException)t;
                }
                throw new UndeclaredThrowableException(t);
            }
            // Handling the response was successful. Ensure that the content has
            // been fully consumed.
            HttpEntity entity_1 = response.GetEntity();

            EntityUtils.Consume(entity_1);
            return(result);
        }
示例#13
0
        public void GetMessages(IEventAggregator _eventAggregator)
        {
            ResponseHandler._eventAggregator = _eventAggregator;
            String response = "";

            // Bytes Array to receive Server Response.
            Byte[] data = new Byte[512];

            Task.Run(async() =>
            {
                // Read the Tcp Server Response Bytes.
                try
                {
                    Int32 bytes;
                    while ((bytes = await networkStream.ReadAsync(data, 0, data.Length)) != 0)
                    {
                        //Int32 bytes = await networkStream.ReadAsync(data, 0, data.Length);
                        response = System.Text.Encoding.UTF8.GetString(data, 0, bytes);
                        _eventAggregator?.GetEvent <UpdateUserConsole>().Publish(response);

                        if (response.Contains("BYE"))
                        {
                            ResponseHandler.Bye();
                            Disconnect();
                            break;
                        }

                        var responseTokens = response.Split(Environment.NewLine);
                        responseTokens     = responseTokens.Where(i => i != "").ToArray();


                        if (responseTokens.Last().Split(' ')[0] == outgoingTag)
                        {
                            //Here we can handle a server result (it means that the command execution is finished
                            //on server side and we can start handle its result on the server).
                            wholeServerResponse += response;
                            ResponseHandler.HandleResponse(outgoingCommand, response);
                            wholeServerResponse += "";
                        }
                        else if (response.Split(' ')[0] == "*" || response.Split(' ')[0] == "+")
                        {
                            //Over here we can add a condition for a currently occuring command
                            //for an instance, sending encryption keys if the server response is "+",
                            //or when we want to read the information a bit by a bit.
                            wholeServerResponse += response;
                        }
                        else
                        {
                            //Illegal server response. Should usually not be the case.
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show("You are now disconnected from the server.");
                    Disconnect();
                    ResponseHandler.Bye();
                    //System.Windows.MessageBox.Show(ex.Message);
                    //break;
                }
            });
        }