Пример #1
0
            // Read the body upfront , add as a ValueProvider
            public override Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
            {
                HttpRequestMessage request = actionContext.ControllerContext.Request;
                HttpContent        content = request.Content;
                FormDataCollection fd      = content?.ReadAsAsync <FormDataCollection>(cancellationToken).Result;

                if (fd != null)
                {
                    IValueProvider vp = new NameValuePairsValueProvider(fd, CultureInfo.InvariantCulture);
                    request.Properties.Add(Key, vp);
                }

                return(base.ExecuteBindingAsync(actionContext, cancellationToken));
            }
Пример #2
0
        private static async Task <T> GetAsync <T>(string url)
        {
            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url))
                    using (HttpContent content = response.Content)
                    {
                        try
                        {
                            T result = await content.ReadAsAsync <T>();

                            return(result);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
        }
Пример #3
0
        public async Task ReadAs_WithModelNameAndHttpActionContext()
        {
            // Arrange
            int                expected = 30;
            HttpContent        content  = FormContent("a=30");
            FormDataCollection formData = await content.ReadAsAsync <FormDataCollection>();

            using (HttpConfiguration configuration = new HttpConfiguration())
            {
                HttpActionContext actionContext = CreateActionContext(configuration);

                // Act
                int actual = (int)formData.ReadAs(typeof(int), "a", actionContext);

                // Assert
                Assert.Equal <int>(expected, actual);
            }
        }
Пример #4
0
        public virtual Task <object> ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable <MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)
        {
            HttpContent content = request.Content;

            if (content == null)
            {
                object defaultValue = MediaTypeFormatter.GetDefaultValueForType(type);
                if (defaultValue == null)
                {
                    return(TaskHelpers.NullResult());
                }
                else
                {
                    return(TaskHelpers.FromResult(defaultValue));
                }
            }
            return(content.ReadAsAsync(type, formatters, formatterLogger));
        }
        public void ReadAs_WithHttpActionContext()
        {
            // Arrange
            int                expected = 30;
            HttpContent        content  = FormContent("=30");
            FormDataCollection formData = content.ReadAsAsync <FormDataCollection>().Result;

            using (HttpConfiguration configuration = new HttpConfiguration())
            {
                HttpActionContext actionContext = CreateActionContext(configuration);

                // Act
                int actual = formData.ReadAs <int>(actionContext);

                // Assert
                Assert.Equal <int>(expected, actual);
            }
        }
        /// <summary>
        /// Function To Get All Flight For Current Comapny With HttpClien Request(Get).
        /// </summary>
        /// <param name="token" name="url"></param>
        /// <returns>IList</returns>
        private IList <Flight> GetAllFlightsForCurrentCompany(string token, string url)
        {
            IList <Flight> flights = new List <Flight>();

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                using (HttpResponseMessage response = client.GetAsync(url).Result)
                {
                    using (HttpContent content = response.Content)
                    {
                        flights = content.ReadAsAsync <IList <Flight> >().Result;
                    }
                }
            }
            return(flights);
        }
Пример #7
0
        public virtual Task <object> ReadContentAsync(
            HttpRequestMessage request,
            Type type,
            IEnumerable <MediaTypeFormatter> formatters,
            IFormatterLogger formatterLogger,
            CancellationToken cancellationToken
            )
        {
            HttpContent content = request.Content;

            if (content == null)
            {
                object defaultValue = MediaTypeFormatter.GetDefaultValueForType(type);
                if (defaultValue == null)
                {
                    return(TaskHelpers.NullResult());
                }
                else
                {
                    return(Task.FromResult(defaultValue));
                }
            }

            try
            {
                return(content.ReadAsAsync(type, formatters, formatterLogger, cancellationToken));
            }
            catch (UnsupportedMediaTypeException exception)
            {
                // If there is no Content-Type header, provide a better error message
                string errorFormat =
                    content.Headers.ContentType == null
                        ? SRResources.UnsupportedMediaTypeNoContentType
                        : SRResources.UnsupportedMediaType;

                throw new HttpResponseException(
                          request.CreateErrorResponse(
                              HttpStatusCode.UnsupportedMediaType,
                              Error.Format(errorFormat, exception.MediaType.MediaType),
                              exception
                              )
                          );
            }
        }
Пример #8
0
        //This code is tightly coupled to Templeton. If parsing fails, we capture the full json payload, the error
        //then log it upstream.
        internal async Task <string> GetJobIdFromServerResponse(HttpContent content)
        {
            Contract.AssertArgNotNull(content, "content");
            try
            {
                var result = await content.ReadAsAsync <JObject>();

                Contract.Assert(result != null);

                JToken jobId;
                Contract.Assert(result.TryGetValue(JobSubmissionConstants.JobIdPropertyName, out jobId));
                Contract.Assert(jobId != null);
                return(jobId.ToString());
            }
            catch (Exception ex)
            {
                throw new HttpParseException(ex.Message);
            }
        }
Пример #9
0
        //This code is tightly coupled to Templeton. If parsing fails, we capture the full json payload, the error
        //then log it upstream.
        internal async Task <List <string> > GetJobIdListFromServerResponse(HttpContent content)
        {
            Contract.AssertArgNotNull(content, "content");
            try
            {
                var result = await content.ReadAsAsync <JArray>();

                if (result == null || !result.HasValues)
                {
                    return(new List <string>());
                }
                var ret = result.Values <string>();
                return(ret.ToList());
            }
            catch (Exception ex)
            {
                throw new HttpParseException(ex.Message);
            }
        }
Пример #10
0
        public async Task ReadMultipleParameters()
        {
            // Basic container class with multiple fields
            HttpContent        content = FormContent("X=3&Y=4");
            FormDataCollection fd      = await content.ReadAsAsync <FormDataCollection>();

            Assert.Equal(
                3,
                fd.ReadAs <int>("X", requiredMemberSelector: null, formatterLogger: null)
                );
            Assert.Equal(
                "3",
                fd.ReadAs <string>("X", requiredMemberSelector: null, formatterLogger: null)
                );
            Assert.Equal(
                4,
                fd.ReadAs <int>("Y", requiredMemberSelector: null, formatterLogger: null)
                );
        }
Пример #11
0
        public async Task GetMessages()
        {
            IsLoading = true;

            HttpContent resContent = await MainWindowViewModel.ServerService.GetMessages(_channelId);

            IsLoading = false;

            if (resContent == null)
            {
                return;
            }

            List <Message> messages = await resContent.ReadAsAsync(typeof(List <Message>)) as List <Message>;

            messages?.Reverse();

            //DisplayMessages(ConvertMessagesTimestamps(messages));
        }
Пример #12
0
        private async Task <FoxResponse> GetData(string url)
        {
            //We will make a GET request to a really cool website...

            //string baseUrl = "https://www.mercadobitcoin.net/api/BTC/ticker/";
            //The 'using' will help to prevent memory leaks.
            //Create a new instance of HttpClient
            using (HttpClient client = new HttpClient())

                //Setting up the response...

                using (HttpResponseMessage res = await client.GetAsync(url))
                    using (HttpContent content = res.Content)
                    {
                        var data = await content.ReadAsAsync <FoxResponse>();

                        return(data);
                    }
        }
Пример #13
0
        public static Task <test> GetAll()
        {
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage res = client.GetAsync(baseURL + "products/getall").Result)
                {
                    using (HttpContent content = res.Content)
                    {
                        var data = content.ReadAsAsync <Task <test> >().Result;
                        if (data != null)
                        {
                            return(data);
                        }
                    }
                }
            }

            return(null);
        }
Пример #14
0
        public static Object Extract(HttpContent content, Type commandType)
        {
            var read = content.ReadAsAsync(commandType);

            read.Wait();

            //reset the internal stream position to allow the WebAPI pipeline to read it again.
            content.ReadAsStreamAsync()
            .ContinueWith(t =>
            {
                if (t.Result.CanSeek)
                {
                    t.Result.Seek(0, SeekOrigin.Begin);
                }
            })
            .Wait();

            return(read.Result);
        }
        public async Task <WWClassLib.Models.GeoLookup.RootObject> GetGeoLookUp(int zip)
        {
            try
            {
                string path = $"{Constants.WeatherUndergroundGeolookup}{zip}.json";

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    using (HttpResponseMessage response = await client.GetAsync(path))  //we are actually making the call here
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            using (HttpContent content = response.Content)
                            {
                                // ... Read the string.
                                //string result = await content.ReadAsStringAsync();

                                //instead of reading the string, let's convert the JSON into objects and return those
                                var result = await content.ReadAsAsync <WWClassLib.Models.GeoLookup.RootObject>();

                                return(result);
                            }
                        }
                        else
                        {
                            Debug.WriteLine($"Error {response.ReasonPhrase}");
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error {ex.Message}");
                Debug.WriteLine($"StackTrace {ex.StackTrace}");
                return(null);
            }
        }
Пример #16
0
        public async Task Read_As_WithHttpActionContextAndCustomModelBinder()
        {
            // Arrange
            int                expected = 15;
            HttpContent        content  = FormContent("a=30");
            FormDataCollection formData = await content.ReadAsAsync <FormDataCollection>();

            using (HttpConfiguration configuration = new HttpConfiguration())
            {
                configuration.Services.Insert(typeof(ModelBinderProvider), 0, new CustomIntModelBinderProvider());

                HttpActionContext actionContext = CreateActionContext(configuration);

                // Act
                int actual = (int)formData.ReadAs(typeof(int), "a", actionContext);

                // Assert
                Assert.Equal(expected, actual);
            }
        }
Пример #17
0
        public async Task Read_As_NoServicesChangeInConfig()
        {
            // Arrange
            HttpContent        content  = FormContent("a=30");
            FormDataCollection formData = await content.ReadAsAsync <FormDataCollection>();

            using (HttpConfiguration configuration = new HttpConfiguration())
            {
                // Act
                HttpControllerSettings settings            = new HttpControllerSettings(configuration);
                HttpConfiguration      clonedConfiguration =
                    HttpConfiguration.ApplyControllerSettings(settings, configuration);
                int actual = (int)formData.ReadAs(typeof(int), "a", requiredMemberSelector: null,
                                                  formatterLogger: (new Mock <IFormatterLogger>()).Object, config: configuration);

                // Assert
                Assert.Equal(30, actual);
                Assert.Same(clonedConfiguration.Services, configuration.Services);
            }
        }
        store IRepository <store> .Find(string stor_id)
        {
            string path = @_root + @"StoreList/" + stor_id;

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    store sto = responseContent.ReadAsAsync <store>().Result;

                    return(sto);
                }
            }

            return(null);
        }
        public booksOnOrder Find(string ord_num)
        {
            string path = @_root + @"BookOrderList/" + ord_num;

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    booksOnOrder bo = responseContent.ReadAsAsync <booksOnOrder>().Result;

                    return(bo);
                }
            }

            return(null);
        }
Пример #20
0
        public T Deserialize <T>(HttpContent serializedObject)
        {
            var task = serializedObject.ReadAsAsync <T>(new[] { JsonMediaTypeFormatter });

            task.Wait();

            if (task.IsFaulted || (task.Exception != null))
            {
                throw new ArgumentException($"Could not read the content as type '{typeof (T)}'.");
            }

            if (task.IsCanceled)
            {
                throw new ApplicationException("Deserialization task was canceled.");
            }

            var result = task.Result;

            return(result);
        }
Пример #21
0
        /// <summary>
        /// Gets a competitor with the given WSCD_ID, if they exist.
        /// </summary>
        /// <param name="WSCD_ID">The ID to find a participant by.</param>
        /// <returns>If a competitor exists, returns that competitor as a participant. If not, returns an empty competitor.</returns>
        private static async Task <Participant> GetCompetitor(int WSCD_ID)
        {
            //Using https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client for the GET route
            var    client        = new HttpClient();
            string path          = "https://dancefellowsapi.azurewebsites.net/";
            string pathExtension = "Competitors/GetCompetitor/" + WSCD_ID;

            Participant retrievedParticipant = new Participant();

            try
            {
                var rawParticipantPackage = await client.GetAsync(path + pathExtension);

                //Type type = rawParticipant.GetType();
                if (rawParticipantPackage.IsSuccessStatusCode)
                {
                    HttpContent rawParticipant       = rawParticipantPackage.Content;
                    JObject     rawParticipantObject = rawParticipant.ReadAsAsync <JObject>().Result;
                    if (rawParticipantObject["id"] != null && rawParticipantObject["wsdC_ID"] != null && rawParticipantObject["firstName"] != null && rawParticipantObject["lastName"] != null && rawParticipantObject["minLevel"] != null && rawParticipantObject["maxLevel"] != null)
                    {
                        retrievedParticipant.ID        = (int)rawParticipantObject["id"];
                        retrievedParticipant.WSC_ID    = (int)rawParticipantObject["wsdC_ID"];
                        retrievedParticipant.FirstName = (string)rawParticipantObject["firstName"];
                        retrievedParticipant.LastName  = (string)rawParticipantObject["lastName"];
                        int minLevel = (int)rawParticipantObject["minLevel"];
                        int maxLevel = (int)rawParticipantObject["maxLevel"];
                        retrievedParticipant.MinLevel = (Level)minLevel;
                        retrievedParticipant.MaxLevel = (Level)maxLevel;
                        if (WSCD_ID > 0)
                        {
                            retrievedParticipant.EligibleCompetitor = true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return(retrievedParticipant);
        }
Пример #22
0
        public async Task <IHttpActionResult> Get(int id)
        {
            HttpClient client   = new HttpClient();
            string     hostname = "mycompany.visitors.crmsvc";
            string     port     = "81";

            try
            {
                Uri uri = new Uri($"http://{hostname}:{port}/api/crmdata/{id}");
                HttpResponseMessage response = await client.GetAsync(uri);

                HttpContent content    = response.Content;
                CRMData     returndata = await content.ReadAsAsync <CRMData>();

                return(Ok <CRMData>(returndata));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.NotFound, ex));
            }
        }
        List <store> IRepository <store> .FindAll()
        {
            List <store> stores = null;
            string       path   = @_root + "StoreList";

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    stores = responseContent.ReadAsAsync <List <store> >().Result;

                    return(stores);
                }
            }

            return(null);
        }
        public async Task <T> GetRequest <T>(string queryURL)
        {
            T result = default(T);

            using (HttpResponseMessage response = _client.GetAsync(queryURL).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    using (HttpContent content = response.Content)
                    {
                        result = await content.ReadAsAsync <T>();
                    }
                }
                else
                {
                    throw new HttpRequestException(response.ReasonPhrase);
                }
            }
            return(result);
        }
        public List <sales> FindAll()
        {
            List <sales> sales = null;
            string       path  = @_root + "SalesList";

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    sales = responseContent.ReadAsAsync <List <sales> >().Result;

                    return(sales);
                }
            }

            return(null);
        }
        List <book> IRepository <book> .FindAll()
        {
            List <book> book = null;
            string      path = @_root + "BookList";

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    book = responseContent.ReadAsAsync <List <book> >().Result;

                    return(book);
                }
            }

            return(null);
        }
        public book Find(string id)
        {
            book   book = null;
            string path = @_root + @"BookList/" + id;

            using (var client = new HttpClient())
            {
                var response = client.GetAsync(path).Result;

                if (response.IsSuccessStatusCode)
                {
                    HttpContent responseContent = response.Content;

                    book = responseContent.ReadAsAsync <book>().Result;

                    return(book);
                }
            }

            return(null);
        }
        /// <summary>
        /// Function To Get Admin By UserName With HttpClient Request(Get)
        /// </summary>
        /// <param name="token"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private Administrator GetAdminByUserName(string token, string url)
        {
            Administrator admin = new Administrator();

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                using (HttpResponseMessage response = client.GetAsync(url).Result)
                {
                    using (HttpContent content = response.Content)
                    {
                        if (admin != null)
                        {
                            return(admin = content.ReadAsAsync <Administrator>().Result);
                        }
                    }
                }
            }
            return(null);
        }
Пример #29
0
        public async Task <IActionResult> DetailAsync(int id)
        {
            var getSellerUri = new Uri("http://localhost:5003/api/SellerProduct/seller/" + id);
            var productUri   = new Uri("http://localhost:5002/api/Products/" + id);
            var seller       = new SellerModel();
            var product      = new ProductModel();

            // ... Use HttpClient.
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(getSellerUri))
                {
                    using (HttpContent content = response.Content)
                    {
                        // ... Read the string.
                        var res = await content.ReadAsAsync <string>();

                        seller = JsonConvert.DeserializeObject <SellerModel>(res);
                    }
                }
            }

            // ... Use HttpClient.
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(productUri))
                {
                    using (HttpContent content = response.Content)
                    {
                        // ... Read the string.
                        var result = await content.ReadAsStringAsync();

                        product = JsonConvert.DeserializeObject <ProductModel>(result);
                        var data = new KeyValuePair <SellerModel, ProductModel>(seller, product);
                        return(View(data));
                    }
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Calls the listing endpoint (/clinical-trials) of the clinical trials API
        /// </summary>
        /// <param name="query">Search query (without paging and fields to include) (optional)</param>
        /// <param name="size"># of results to return (optional)</param>
        /// <param name="from">Beginning index for results (optional)</param>
        /// <param name="includeFields">Fields to include (optional)</param>
        /// <param name="excludeFields">Fields to exclude (optional)</param>
        /// <returns>Collection of Clinical Trials</returns>
        public ClinicalTrialsCollection List(
            JObject query,
            int size = 10,
            int from = 0,
            string[] includeFields = null,
            string[] excludeFields = null
            )
        {
            ClinicalTrialsCollection rtnResults = null;

            //Handle Null include/exclude field
            query         = query ?? new JObject();
            includeFields = includeFields ?? new string[0];
            excludeFields = excludeFields ?? new string[0];

            //Make a copy of our search query so that we don't muck with the original.
            //(The query will need to contain the size, from, etc
            JObject requestBody = (JObject)query.DeepClone();

            requestBody.Add(new JProperty("size", size));
            requestBody.Add(new JProperty("from", from));

            if (includeFields.Length > 0)
            {
                requestBody.Add(new JProperty("include", includeFields));
            }

            if (excludeFields.Length > 0)
            {
                requestBody.Add(new JProperty("exclude", excludeFields));
            }

            //Get the HTTP response content from POST request
            HttpContent httpContent = ReturnPostRespContent("clinical-trials", requestBody);

            rtnResults = httpContent.ReadAsAsync <ClinicalTrialsCollection>().Result;

            return(rtnResults);
        }