Inheritance: HttpMessageInvoker
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (CountryPhoneCode.SelectedItem != null)
            {
                var _id = Guid.NewGuid().ToString("N");
                var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode;
                var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName;
                var _name = FullName.Text;
                var _phoneNumber = PhoneNumber.Text;
                var _password = Password.Password;

                var client = new HttpClient()
                {
                    BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/")
                };

                var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password=" + _password + "&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode);

                var serializer = new DataContractJsonSerializer(typeof(User));
                var ms = new MemoryStream();
                var user = serializer.ReadObject(ms) as User;

                Frame.Navigate(typeof(MainPage), user);
            }
            else
            {
                MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!");
                await dialog.ShowAsync();
            }
        }
Example #2
1
        public void Create_New_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers");
                request.Content = new StringContent("Id = 7; Name = NewCustomer7");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'.");
                    Assert.IsNotNull(response.Headers.Location, "The location header should not have been null.");
                    Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'.");
                    Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'.");
                }

                // Put server back in original state
                request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7");
                client.Send(request);
            }
        }
        public void Mvc200RequestFW45BasicRequestSyntheticFiltering()
        {
            const string requestPath = "api/products";
            const string expectedRequestName = "GET products";
            string expectedRequestUrl = this.Config.ApplicationUri + "/" + requestPath;

            DateTimeOffset testStart = DateTimeOffset.UtcNow;

            //Call an applicaiton page
            var client = new HttpClient();
            var requestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(expectedRequestUrl),
                Method = HttpMethod.Get,
            };

            requestMessage.Headers.Add("User-Agent", "bingbot");

            var responseTask = client.SendAsync(requestMessage);
            responseTask.Wait(TimeoutInMs);
            var responseTextTask = responseTask.Result.Content.ReadAsStringAsync();
            responseTextTask.Wait(TimeoutInMs);
            Assert.IsTrue(responseTextTask.Result.StartsWith("[{"));

            var request = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(1, TimeoutInMs)[0];

            var testFinish = DateTimeOffset.UtcNow;

            this.TestWebApplicationHelper(expectedRequestName, expectedRequestUrl, "200", true, request, testStart, testFinish);
            Assert.AreEqual("Spider", request.OperationContext.SyntheticSource);
        }
        public ActionResult About(string searchString)
        {
            if(searchString=="" || searchString==null)
            {
                searchString = "Jurasic Park";
            }

               List<Movie> mo = new List<Movie>();

                string responseString = "";
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:51704/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = client.GetAsync("api/movie?name=" + searchString).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        responseString = response.Content.ReadAsStringAsync().Result;
                    }
                }

                string jsonInput=responseString; //

                System.Console.Error.WriteLine(responseString);

                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                mo= jsonSerializer.Deserialize<List<Movie>>(jsonInput);
            return View(mo);
        }
        private async void ButtonAccessResource_Click(object sender, RoutedEventArgs e)
        {
            var client = new HttpClient { 
                BaseAddress = _baseAddress 
            };

            if (_credential != null)
            {
                client.DefaultRequestHeaders.Authorization =
                           new AuthenticationHeaderValue("Bearer", _credential.AccessToken);
            }

            var response = await client.GetAsync("identity");
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                var md = new MessageDialog(response.ReasonPhrase);
                await md.ShowAsync();
                return;
            }

            var claims = await response.Content.ReadAsAsync<IEnumerable<ViewClaim>>();

            foreach (var claim in claims)
            {
                ListClaims.Items.Add(string.Format("{0}: {1}", claim.Type, claim.Value));
            }
        }
        /// <summary>
        /// Does setup of AutoCAD IO. 
        /// This method will need to be invoked once before any other methods of this
        /// utility class can be invoked.
        /// </summary>
        /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
        /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
        public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
        {
            try
            {
                String clientId = autocadioclientid;
                String clientSecret = autocadioclientsecret;

                Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
                container = new AIO.Operations.Container(uri);
                container.Format.UseJson();

                using (var client = new HttpClient())
                {
                    var values = new List<KeyValuePair<string, string>>();
                    values.Add(new KeyValuePair<string, string>("client_id", clientId));
                    values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    var requestContent = new FormUrlEncodedContent(values);
                    var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
                    _accessToken = resValues["token_type"] + " " + resValues["access_token"];
                    if (!string.IsNullOrEmpty(_accessToken))
                    {
                        container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
                container = null;
                throw;
            }
        }
        /// <summary>
        /// 非同步刷新最新資訊
        /// </summary>
        /// <returns></returns>
        public async Task RefreshAsync() {
            HttpClient client = new HttpClient();
            HtmlDocument HTMLDoc = new HtmlDocument();
            HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource));

            var script = HTMLDoc.DocumentNode.Descendants("script")
                .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray();

            var tempAry = script.First()
                .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select((x, i) => new { index = i, item = x })
                .GroupBy(x => Math.Floor(x.index / 4.0));

            this.LastPassed = null;
            this.Delay = new TimeSpan();

            foreach (var item in tempAry) {
                string[] temp = item.Select(x=>x.item).ToArray();
                if(temp[3] == "TRSearchResult.push('x')") {
                    this.LastPassed = await Station.GetStationByNameAsync(
                        innerString(temp[0],"'","'")
                        );
                }                
            }

            var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0);
            this.Delay= time;
        }
Example #8
0
        private void Initalize()
        {
            // Limit to maximum of 256 Connections
            ServicePointManager.DefaultConnectionLimit = 256;

            //Trust all certificates
            ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

            // TODO: Add Proxy Support
            Handler = new HttpClientHandler
            {
                AllowAutoRedirect = true,
                UseCookies = true,
                CookieContainer = new CookieContainer(),
                UseDefaultCredentials = false,
                Proxy = null,
                UseProxy = false
            };

            // Create the HTTP Client
            Client = new HttpClient(Handler);
            Client.DefaultRequestHeaders.Clear();
            Client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(0) };
            Client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            Client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
        }
Example #9
0
            public async void Run()
            {
                var httpClient = new HttpClient();
                HttpResponseMessage response = null;
                try
                {
                    response = await httpClient.GetAsync(_uri, _cancellationTokenSource.Token);
                    var remoteStream = await response.Content.ReadAsStreamAsync();
                    var localStream = await _file.OpenAsync(FileAccess.ReadAndWrite);
                    //response.Content.Headers.ContentLength;

                }
                catch (Exception ex)
                {
                    if(Error != null)
                        Error(this, new DownloadFileErrorArgs(ex, _file));
                    
                }
                finally
                {
                    if(response != null)
                        response.Dispose();
                }
                
            }
Example #10
0
 public static HttpResponseMessage HttpGet(Uri uri)
 {
     using (var client = new HttpClient())
     {
         return client.GetAsync(uri).Result;
     }
 }
 private async void UpdateContributors()
 {
     try
     {
         var vms = await Task.Run(async () =>
         {
             var hc = new HttpClient();
             var str = await hc.GetStringAsync(App.ContributorsUrl);
             using (var sr = new StringReader(str))
             {
                 var xml = XDocument.Load(sr);
                 return xml.Root
                           .Descendants("contributor")
                           .Where(
                               e =>
                               e.Attribute("visible") == null ||
                               e.Attribute("visible").Value.ToLower() != "false")
                           .Select(ContributorsViewModel.FromXml)
                           .ToArray();
             }
         });
         await DispatcherHelper.UIDispatcher.InvokeAsync(
             () =>
             {
                 this.Contributors.Clear();
                 this.Contributors.Add(new ContributorsViewModel("thanks to:", null));
                 vms.OrderBy(v => v.ScreenName ?? "~" + v.Name)
                    .ForEach(this.Contributors.Add);
             });
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
     }
 }
        public async Task<IList<JeuForain>> GetJeuxForainsAsync()
        {
            try
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, JEUXFORAINSURL);
                HttpClient httpClient = new HttpClient();

                HttpResponseMessage httpResponse = await httpClient.SendAsync(request);

                string content = await httpResponse.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                {
                    var json = JObject.Parse(content);

                    var records = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIJeuxForainsRecord>>(json["records"].ToString());

                    IList<JeuForain> values = new List<JeuForain>();

                    foreach (var jeux in records)
                        values.Add(jeux.Value);

                    return values;
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetJeuxForainsAsync : " + ex);
            }
            return null;
        }
 public override async Task<List<TimelineData>> GetTimelineAsync()
 {
    
     var token = await GetAccessTokenAsync();
     var client = new HttpClient { MaxResponseContentBufferSize = 1024 * 1024 };
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
     var response = await client.GetAsync(string.Format("{0}?screen_name={1}",
         StatusesUserTimeline, WebUtility.UrlEncode(ScreenName)));
    
     var json = JsonValue.Parse(await response.Content.ReadAsStringAsync());
     var statuses = json.GetArray();
     return statuses.Select(status => status.GetObject())
         .Select(status =>
         {
             var text = status.GetNamedString("text");
             var user = status.GetNamedObject("user");
             var created = status.GetNamedString("created_at");
             var name = user.GetNamedString("name");
             var screenname = user.GetNamedString("screen_name");
             var profileImageUrl = user.GetNamedString("profile_image_url_https");
             return new TweetData
             {
                 Title = string.Format("{0} / @{1}", name, screenname),
                 Body = text,
                 ImageUri = new Uri(profileImageUrl),
                 Name = name,
                 ScreenName = screenname,
                 CreatedAt = ParseCreatedString(created)
             };
         })
         .Cast<TimelineData>()
         .ToList();
 }
        private static async Task GetPeople(string address)
        {
            var uriBuilder = new UriBuilder(address);
            uriBuilder.Path = "api/Customer";

            using (var client = new HttpClient())
            {
                Console.WriteLine("Getting data without a version...");
                var response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();

                Console.WriteLine("Getting data for v1...");
                client.DefaultRequestHeaders.Add("api-version", "1");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();


                Console.WriteLine("Getting data for v2...");
                client.DefaultRequestHeaders.Remove("api-version");
                client.DefaultRequestHeaders.Add("api-version", "2");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();
            }
        }
Example #15
0
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <param name="region"></param>
        /// <returns>The last 10 games the summoner has played.</returns>
        public async Task<List<GameDTO>> GetSummonersRecentGamesAsync(Summoner summoner)
        {
            if (summoner == null)
            {
                throw new ArgumentNullException("summoner");
            }
            if (summoner.ID == 0)
            {
                throw new ArgumentException("Summoner ID should be a value larger than 0.");
            }

            string requestPath = string.Format("game/by-summoner/{0}/recent", summoner.ID);
            string url = BuildURL(summoner.Region, requestPath);

            using (HttpClient client = new HttpClient())
            using (HttpResponseMessage response = await client.GetAsync(url))
            using (HttpContent content = response.Content)
            {
                string contentStr = await content.ReadAsStringAsync();
                GameHistoryDTO gameHistoryDTO = await JsonConvert.DeserializeObjectAsync<GameHistoryDTO>(contentStr);
                if (gameHistoryDTO == null)
                {
                    return null;
                }
                return gameHistoryDTO.games;
            }
        }
Example #16
0
        public static HttpClient CreateHttpClient()
        {
            var baseAddress = new Uri("http://localhost:8080");

            var config = new HttpSelfHostConfiguration(baseAddress);

            // ?
            Setup.Configure(config);

            var server = new HttpSelfHostServer(config);

            var client = new HttpClient(server); // <--- MAGIC!

            try
            {
                client.BaseAddress = baseAddress;
                return client;

            }
            catch
            {
                client.Dispose();
                throw;
            }
        }
Example #17
0
        public IActionResult OAuth(string code)
        {
            if (string.IsNullOrEmpty(code))
              {
            throw new ArgumentException("Invalid parameters");
              }

              using (var client = new HttpClient())
              {
            var getTokenUri = this.BuildGetTokenUri(OAuthInfo.ClientId, OAuthInfo.SecretId, OAuthInfo.RedirectedUri, code);
            var response = client.GetAsync(getTokenUri);
            if (response.Result.IsSuccessStatusCode)
            {
              string result = response.Result.Content.ReadAsStringAsync().Result;
              var resultObjectTemplate = new { ok = false, access_token = string.Empty, error = string.Empty };
              var resultObject = JsonConvert.DeserializeAnonymousType(result, resultObjectTemplate);

              if (resultObject.ok)
              {
            this.ViewData["Message"] = $"You Slack token is: {resultObject.access_token}";
              }
              else
              {
            this.ViewData["Message"] = $"Unable to retrieve Slack token. Error: {resultObject.error}";
              }
            }
            else
            {
              throw new Exception(response.Result.ReasonPhrase);
            }
              }

              return this.View();
        }
Example #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Username:");
            var username = Console.ReadLine();
            Console.WriteLine("Password:");
            var password = Console.ReadLine();
            string uri = "http://localhost:3915/Account/Login";
            var client = new HttpClient();

            var response = client.PostAsync(uri, new User() { Username = username, Password = password }, new JsonMediaTypeFormatter()).Result;
            IEnumerable<string> values;
            response.Headers.TryGetValues("Set-Cookie", out values);
            if (null == values || string.IsNullOrEmpty(values.First()))
            {
                Console.WriteLine("Invalid Username or password;");
            }
            else 
            {
                string newUri = "http://localhost:3915/customer/get/1";
                string cookie = values.First();
                client.DefaultRequestHeaders.Add("Cookie", cookie);
                var getRequestResponse = client.GetAsync(newUri).Result;

                Customer customer = getRequestResponse.Content.ReadAsAsync<Customer>().Result;

                Console.WriteLine("Customer Id: {0}; Name: {1}", customer.Id, customer.Name);
            }

            Console.ReadLine();
        }
Example #19
0
 public GeciMeClient()
 {
     _httpClient = new HttpClient()
     {
         BaseAddress = new Uri("http://geci.me/api/lyric/")
     };
 }
Example #20
0
        public static async Task<string> LoadDataFromAPI(string apiAddress)
        {
            //method to check if user is authenticated and has valid details
            // if invalid details, response message will return unauthorised

            var rawAuthInfo = App.validAuthDetails;
            var authDetails = JsonConvert.DeserializeObject<ValidAuth>(rawAuthInfo);
            var rawData = "";

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authDetails.token_type, authDetails.access_token);
            HttpResponseMessage ResponseMsg = await httpClient.GetAsync(apiAddress);

            // check to see if request was successful or not
            if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.OK)
            {
                rawData = await ResponseMsg.Content.ReadAsStringAsync();

            }
            else if (ResponseMsg.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                rawData = "AuthInvalid";
            }
            return rawData;
        }
Example #21
0
        public async Task<string> TryDownloadPackageFromFeed(string packageId, string version)
        {
            try
            {
                var handler = new HttpClientHandler();
                handler.AllowAutoRedirect = false;
                using (var client = new HttpClient(handler))
                {
                    string requestUri = UrlHelper.V2FeedRootUrl + @"Package/" + packageId + @"/" + version;
                    var response = await client.GetAsync(requestUri).ConfigureAwait(false);

                    //print the header
                    WriteLine("HTTP status code : {0}", response.StatusCode);
                    WriteLine("HTTP header : {0}", response.Headers);
                    if (response.StatusCode == HttpStatusCode.Found)
                    {
                        return response.Headers.GetValues("Location").FirstOrDefault();
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (HttpRequestException hre)
            {
                WriteLine("Exception : {0}", hre.Message);
                return null;
            }
        }
 public ActionResult AddFinance(SearchFinanceModel model)
 {
     Session["Finance"] = null;
     IEnumerable<FinanceModel> objBE;
     using (var client = new HttpClient())
     {
         model.addFinance.insertUserId = base.CurrentUserID;
         client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["APIURI"]);
         client.DefaultRequestHeaders.Accept.Add(
             new MediaTypeWithQualityHeaderValue("application/json"));
         HttpResponseMessage response = client.PutAsJsonAsync("finance/SaveFinanceActivity", model.addFinance).Result;
         if (response.IsSuccessStatusCode)
         {
             string jsonResult = response.Content.ReadAsStringAsync().Result;
             if (!string.IsNullOrEmpty(jsonResult) && !jsonResult.Equals("[]"))
             {
                 objBE = JsonConvert.DeserializeObject<IEnumerable<FinanceModel>>(jsonResult);
                 model.addFinance.finance = objBE;
             }
             else
                 model.addFinance.finance = null;
         }
         model.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"];
         model.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"];
         model.addFinance.activityType = (IEnumerable<SelectListItem>)Session["ActivityType"];
         model.addFinance.processorCompany = (IEnumerable<SelectListItem>)Session["Processor"];
         ViewBag.SuccessMsg = Pecuniaus.Resources.Finance.Finance.FinanceAddedSuccessfully;
     }
     return View("Index", model);
 }
        /// <summary>
        ///  BETA Create a section group with a given name under a given notebookId
        /// </summary>
        /// <param name="debug">Run the code under the debugger</param>
        /// <param name="notebookId">parent notebook's Id</param>
        /// <param name="sectionName">name of the section group to create</param>
        /// <param name="provider"></param>
        /// <param name="apiRoute"></param>
        /// <remarks>Create section group using a application/json content type</remarks>
        /// <returns>The converted HTTP response message</returns>
        public static async Task<ApiBaseResponse> CreateSectionGroupInNotebook(bool debug, string notebookId, string sectionGroupName, AuthProvider provider, string apiRoute)
        {
            if (debug)
            {
                Debugger.Launch();
                Debugger.Break();
            }

            var client = new HttpClient();

            // Note: API only supports JSON response.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Not adding the Authentication header would produce an unauthorized call and the API will return a 401
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                await Auth.GetAuthToken(provider));

            // Prepare an HTTP POST request to the SectionGroups endpoint
            // The request body content type is application/json and requires a name property
            var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sectiongroups")
            {
                Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(createMessage);

            return await HttpUtils.TranslateResponse(response);
        }
        public async Task InvokeRequestResponseService(object scoreRequest, string baseUrl, string key)
        {
            using (var client = new HttpClient())
            {                                
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);

                client.BaseAddress = new Uri(baseUrl);


                HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                    Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseContent);
                }
            }
        }
        private static void SendImageSet(ImageSet imageSet)
        {
            var multipartContent = new MultipartFormDataContent();

            var imageSetJson = JsonConvert.SerializeObject(imageSet,
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

            multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset");

            int counter = 0;
            foreach (var image in imageSet.Images)
            {
                var imageContent = new ByteArrayContent(image.ImageData);
                imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType);
                multipartContent.Add(imageContent, "image" + counter++, image.FileName);
            }

            var response = new HttpClient()
                .PostAsync("http://localhost:53908/api/send", multipartContent)
                .Result;

            var responseContent = response.Content.ReadAsStringAsync().Result;
            Trace.Write(responseContent);
        }
Example #26
0
        public List<Crime> FetchCrimesNearLocation(Location location)
        {
            using (HttpClient client = new HttpClient())
            {

                client.BaseAddress = new Uri(AllStreetCrimesUri);
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                string uriQuerystring =
                    string.Format("?date=2013-07&lat={0}&lng={1}",
                         location.Latitude, location.Longitude  );

                HttpResponseMessage response = client.GetAsync(uriQuerystring).Result;
                if (response.IsSuccessStatusCode)
                {
                    var crimes = response.Content.ReadAsAsync<IEnumerable<Crime>>().Result;

                    return crimes.ToList();
                }
                else
                {
                    throw new Exception(
                        string.Format("{0} ({1})", (int) response.StatusCode, response.ReasonPhrase));
                }
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            var address = "http://localhost:900";
            var config = new HttpSelfHostConfiguration(address);
            config.MapHttpAttributeRoutes();

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server running at {0}. Press any key to exit", address);

                var client = new HttpClient() {BaseAddress = new Uri(address)};

                var persons = client.GetAsync("person").Result;
                Console.WriteLine(persons.Content.ReadAsStringAsync().Result);

                var newPerson = new Person {Id = 3, Name = "Luiz"};
                var response = client.PostAsJsonAsync("person", newPerson).Result;

                if (response.IsSuccessStatusCode)
                {
                    var person3 = client.GetAsync("person/3").Result;
                    Console.WriteLine(person3.Content.ReadAsStringAsync().Result);
                }

                Console.ReadLine();
            }

        }
        public ActionResult DetailMovie(string movieId,string youTubeId)
        {
            if (youTubeId == "" || youTubeId == null)
            {
                youTubeId = "";
            }

            DetailMovie movie = new Models.DetailMovie();

            string responseString = "";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:51704/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync("api/movie?IMDBid=" + movieId + "&YouTubeid=" + youTubeId).Result;
                if (response.IsSuccessStatusCode)
                {
                    responseString = response.Content.ReadAsStringAsync().Result;
                }
            }

            string jsonInput = responseString; //

            System.Console.Error.WriteLine(responseString);

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            movie = jsonSerializer.Deserialize<DetailMovie>(jsonInput);

            return View(movie);
        }
Example #29
0
        public void FakeServer_CapturesAllRequests()
        {
            using (var fakeServer = new FakeServer())
            {
                fakeServer.Start();
                var baseAddress = fakeServer.BaseUri;

                Action<Action, int> repeat = (a, times) =>
                {
                    for (var i = 0; i < times; i++)
                        a();
                };

                var url1 = "/request1";
                var url2 = "/request2";
                var url3 = "/request3";
                var url4 = "/request4";

                var httpClient = new HttpClient();
                httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait();
                repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2);
                repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3);
                repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4);

                fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3);
                fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4);
            }
        }
Example #30
0
        /// <summary>
        /// Restituisce i dati dell'utente
        /// </summary>
        public static async Task<Microsoft.Graph.User> GetMyInfoAsync()
        {
            //JObject jResult = null;

            try
            {
                HttpClient client = new HttpClient();
                var token = await OfficeHelper.GetTokenAsync();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // Endpoint dell'utente loggato
                Uri usersEndpoint = new Uri($"{serviceEndpoint}me");

                HttpResponseMessage response = await client.GetAsync(usersEndpoint);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<Microsoft.Graph.User>(responseContent);                    
                }
                else
                {
                    var msg = new MessageDialog("Non è stato possibile recuperare i dati dell'utente. Risposta del server: " + response.StatusCode);
                    await msg.ShowAsync();
                    return null;
                }
            }
            catch (Exception e)
            {
                var msg = new MessageDialog("Si è verificato il seguente errore: " + e.Message);
                await msg.ShowAsync();
                return null;
            }
        }