public ContactsDto Update(ContactsDto contactsDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/ContactsApi/"+ contactsDto.Id, contactsDto).Result;
         return response.Content.ReadAsAsync<ContactsDto>().Result;
     }
 }
Example #2
2
        public async void GetLocation()
        {
            Geoposition pos = await _geolocator.GetGeopositionAsync();
            var pin = new MapIcon()
            {
                Location = pos.Coordinate.Point,
                Title = "You are here!",
                Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Image/Location_Icon.png")),
                NormalizedAnchorPoint = new Point() { X = 0.32, Y = 0.78 },
            };
            map.MapElements.Add(pin);
            await map.TrySetViewAsync(pos.Coordinate.Point, 15);
            (App.Current as App).User.user_x = pos.Coordinate.Point.Position.Latitude.ToString();
            (App.Current as App).User.user_y = pos.Coordinate.Point.Position.Longitude.ToString();
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri(@"http://pubbus-coeus.azurewebsites.net/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await client.PutAsJsonAsync("api/users/" + (App.Current as App).User.user_id, (App.Current as App).User);

                    //Printf("Da cap nhat vi tri: " + (App.Current as App).User.user_x + ":" + (App.Current as App).User.user_y);
                }
                catch (Exception ex)
                {
                    Printf(ex.Message);
                }
            }
        }
 static bool UpdateProduct(ProductViewModel newProduct)
 {
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(baseURL);
     var response = client.PutAsJsonAsync("api/Products/", newProduct).Result;
     client.Dispose();
     return response.Content.ReadAsAsync<bool>().Result;
 }
 public Company Update(Company company)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:17348/api/company/" + company.Id, company).Result;
         return response.Content.ReadAsAsync<Company>().Result;
     }
 }
Example #5
0
        public void Main(string[] args)
        {
            var config = new Configuration().AddEnvironmentVariables();
            string urlOptimizer = config.Get("URLOptimizerJobs") ?? "http://localhost:5004/api/Jobs/";
            Console.WriteLine("Mortgage calculation service listening to {0}", urlOptimizer);

            bool WarnNoMoreJobs = true;
            while (true)
            {
                try
                {
                    var httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    List<Job> jobs = httpClient.GetAsync(urlOptimizer).Result.Content.ReadAsAsync<List<Job>>().Result;

                    List<Job> remainingJobs = jobs.FindAll(j => !j.Taken);
                    if (remainingJobs.Count == 0)
                    {
                        if (WarnNoMoreJobs)
                        {
                            Console.WriteLine("No more jobs !");
                            WarnNoMoreJobs = false;
                        }
                        Task.Delay(1000).Wait();
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("{0} job(s) remaining", remainingJobs.Count);
                        WarnNoMoreJobs = true;
                    }
                    Random engine = new Random(DateTime.Now.Millisecond);
                    Job Taken = remainingJobs[engine.Next(remainingJobs.Count)];
                    Taken.Taken = true;
                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();

                    // The calculation is completely simulated, and does not correspond to any real financial computing
		    // We thus only wait for a given delay and send a random amount for the total cost
		    // Should one be interested in the kind of computation that can truly use scaling, one can take a look
		    // at the use of Genetic Algorithms as shown as in https://github.com/jp-gouigoux/PORCAGEN
                    Task.Delay(20).Wait();
                    Taken.Done = true;
                    Taken.TotalMortgageCost = Convert.ToDecimal(engine.Next(1000));

                    httpClient.PutAsJsonAsync<Job>(urlOptimizer + Taken.Id, Taken).Result.EnsureSuccessStatusCode();
                }
                catch
                {
                    Task.Delay(1000).Wait();
                }
            }
        }
 public ActionResult Edit(bill bill)
 {
     try
     {
         var APIResponse = httpClient.PutAsJsonAsync <bill>(baseAddress + "updateBill/", bill).ContinueWith(postTask => postTask.Result.EnsureSuccessStatusCode());
         return(RedirectToAction("Index"));
     }
     catch
     {
         return(View());
     }
 }
 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);
 }
        public void User_Is_Added_To_Queue()
        {
            var client = new HttpClient();

            string name = "hello";
            string key = Convert.ToString(Guid.NewGuid());
            string format = "https://qcue-live.firebaseio.com/queues/{0}/{1}.json";

            string uri = String.Format(format, key, name);

            var queue = new Q
            {
                ShortCode = "TEST",
                Users = new Dictionary<string, QUser>
                 {
                    {
                        Convert.ToString(Guid.NewGuid()),
                        new QUser
                        {
                            Id = "red",
                            State = "waiting"
                        }
                    }
                 }
            };

            var json = JsonConvert.SerializeObject(queue);
            var result = client.PutAsJsonAsync(uri, queue).Result;

            result.EnsureSuccessStatusCode();
        }
        /// <summary>
        /// Runs an HttpClient issuing a POST request against the controller.
        /// </summary>
        static async void RunClient()
        {
            var handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential("Boris", "xyzxyz");
            var client = new System.Net.Http.HttpClient(handler);

            var bizMsgDTO = new BizMsgDTO
            {
                Name = "Boris",
                Date = DateTime.Now,
                User = "******",
            };

            // *** POST/CREATE BizMsg
            Uri address = new Uri(_baseAddress, "/api/BizMsgService");
            HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO);

            // Check that response was successful or throw exception
            // response.EnsureSuccessStatusCode();

            // BizMsg result = await response.Content.ReadAsAsync<BizMsg>();
            // Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id);
            Console.WriteLine(response.StatusCode + " - " + response.Headers.Location);

            // *** PUT/UPDATE BizMsg
            var testID = response.Headers.Location.AbsolutePath.Split('/')[3];
            bizMsgDTO.Name = "Boris Momtchev";
            response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO);
            Console.WriteLine(response.StatusCode);

            // *** DELETE BizMsg
            response = await client.DeleteAsync(address.ToString() + "/" + testID);
            Console.WriteLine(response.StatusCode);
        }
Example #10
0
        static async Task RunAsync_Update()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:2614/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    VideoDTO video = new VideoDTO { title = "shen-demo" };
                    HttpResponseMessage response = await client.PutAsJsonAsync("Videoes/ca161757-8196-4454-ae26-d0d70e9cb679", video);
                    response.EnsureSuccessStatusCode();

                    if (response.IsSuccessStatusCode)
                    {
                        VideoDTO videoDTO = await response.Content.ReadAsAsync<VideoDTO>();
                    }
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }

            }
        }
        public async Task <T> PutAsync <P, T>(string relativePath, P submittingData, string mediaType = "application/json")
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(BaseUrl);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));

                HttpResponseMessage response = null;
                if (submittingData.GetType() == typeof(FormUrlEncodedContent))
                {
                    response = await client.PutAsync(relativePath, ((FormUrlEncodedContent)Convert.ChangeType(submittingData, typeof(FormUrlEncodedContent))));
                }
                else if ((mediaType?.ToLower()).Contains("xml"))
                {
                    response = await client.PutAsXmlAsync <P>(relativePath, submittingData);
                }
                else
                {
                    response = await client.PutAsJsonAsync <P>(relativePath, submittingData);
                }

                response.EnsureSuccessStatusCode();
                T result = await response.Content.ReadAsAsync <T>();

                return(result);
            }
        }
Example #12
0
        internal static async Task <HttpStatusCode> EditScheduled(ScheduleTranferDto transfer)
        {
            HttpResponseMessage response = await httpClient.PutAsJsonAsync(
                "api/schedule", transfer);

            return(response.StatusCode);
        }
Example #13
0
        public async Task<IEnumerable<Event>> ProcessAsync(Event evnt)
        {
            var importRecordExtracted = evnt.GetBody<ImportRecordExtracted>();
            var elasticSearchUrl = _configurationValueProvider.GetValue(Constants.ElasticSearchUrlKey);

            var client = new HttpClient();
            var url = string.Format("{0}/import/{1}/{2}", elasticSearchUrl,
                importRecordExtracted.IndexType,
                importRecordExtracted.Id);
            var responseMessage = await client.PutAsJsonAsync(url, importRecordExtracted);

           if (!responseMessage.IsSuccessStatusCode)
            {
                throw new ApplicationException("Indexing failed. " 
                    + responseMessage.ToString());
            }

            return new[]
            {
                new Event(new NewIndexUpserted()
                {
                    IndexUrl = url
                }) 
            };
        }
        public async Task AddActivityGoal()
        {
            var session = await Login();
            var currentSeed = Guid.NewGuid();

            using (var client = new HttpClient { BaseAddress = new Uri(ServerUrl) })
            {
                client.AcceptJson().AddSessionHeader(session.Id);

                var form = new Activity { Name = $"Name.{currentSeed}", Description = $"Description.{currentSeed}" };

                // Add Activity with valid data
                var activityResponse = await client.PostAsJsonAsync($"/api/activities", form);
                Assert.Equal(HttpStatusCode.Created, activityResponse.StatusCode);

                var activity = await activityResponse.Content.ReadAsJsonAsync<Activity>();
                Assert.Equal($"Name.{currentSeed}", activity.Name);

                var goalForm = new ActivityGoalForm { Description = $"Description.{currentSeed}" };
                activityResponse = await client.PutAsJsonAsync($"/api/activities/{activity.Id}/goal", goalForm);
                Assert.Equal(HttpStatusCode.OK, activityResponse.StatusCode);

                activity = await activityResponse.Content.ReadAsJsonAsync<Activity>();
                Assert.Equal(1, activity.Goals.Count);
            }
        }
Example #15
0
        public ActionResult Edit(Promotion promo)
        {
            //try
            //{
            //    promo.date_updated = DateTime.Now;
            //    promo.code = collection["code"];
            //    promo.name = collection["name"];
            //    promo.description = collection["description"];
            //    promo.ext_desc = collection["ext_desc"];
            //    promo.start = DateTime.Parse(collection["start"]);
            //    promo.end = DateTime.Parse(collection["end"]);
            //    db.SaveChanges();
            //    var valid = new { start = promo.start.ToShortDateString(), end = promo.end.ToShortDateString() };
            //    return Json(new { status = "success", message = "Customer information updated", promo = promo, validity = valid});
            //}
            //catch
            //{
            //    return Json(new { status = "error", message = "Something went wrong. " });
            //}

            client.BaseAddress = new Uri(url);
            var putTask = client.PutAsJsonAsync <Promotion>(string.Format("promo/{0}", promo.ID), promo);

            putTask.Wait();
            var result = putTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var promotion = result.Content.ReadAsAsync <Promotion>().Result;
                var valid     = new { start = promo.start.ToShortDateString(), end = promo.end.ToShortDateString() };
                return(Json(new { status = "success", message = "Promotion created!", promo = promotion, validity = valid }));
            }
            return(Content("Something went wrong!"));
        }
Example #16
0
 public void Update(Login login)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "login/", login).Result;
     }
 }
 private async void sendReservationDataEdit()
 {
     HttpClient client = new HttpClient();
     string URL = "http://92.221.124.167";
     client.BaseAddress = new Uri(URL);
     HttpResponseMessage response = await client.PutAsJsonAsync("/rest/edit/reservation", reservation).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
     this.Close();
 }
 public void Update(Customer cus)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "customer/", cus).Result;
     }
 }
Example #19
0
 public void Update(Movie movie)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "movie/", movie).Result;
     }
 }
Example #20
0
 public void Update(Order ord)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync(ServerAddress.Address + "order/", ord).Result;
     }
 }
Example #21
0
        public async Task CreateDeleteOption()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(AzureUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var m = new LoadOptions() { SettingName = "Settingname" };

                HttpResponseMessage response = await client.PostAsJsonAsync(api, m);
                Assert.AreEqual(true, response.IsSuccessStatusCode);

                if (response.IsSuccessStatusCode)
                {
                    Uri newmUrl = response.Headers.Location;

                    // HTTPGET again
                    HttpResponseMessage responseget = await client.GetAsync(newmUrl);
                    Assert.AreEqual(true, responseget.IsSuccessStatusCode);

                    if (responseget.IsSuccessStatusCode)
                    {
						LoadOptions mget = await responseget.Content.ReadAsAsync<LoadOptions>();

                        Assert.AreEqual("Settingname", mget.SettingName);

                        // HTTP PUT
                        mget.SettingName = "ComHA";
                        var responsePut = await client.PutAsJsonAsync(newmUrl, mget);

                        // HTTPGET again2
                        HttpResponseMessage responseget2 = await client.GetAsync(newmUrl);
                        Assert.AreEqual(true, responseget2.IsSuccessStatusCode);

                        if (responseget2.IsSuccessStatusCode)
                        {
							LoadOptions mget2 = await responseget2.Content.ReadAsAsync<LoadOptions>();

                            Assert.AreEqual("ComHA", mget2.SettingName);
                        }

                        // HTTP DELETE
                        response = await client.DeleteAsync(newmUrl);

                        // HTTPGET again3
                        HttpResponseMessage responseget3 = await client.GetAsync(newmUrl);
						Assert.AreEqual(HttpStatusCode.NotFound, responseget3.StatusCode);

						if (responseget2.IsSuccessStatusCode)
                        {
                            Machine mget3 = await responseget3.Content.ReadAsAsync<Machine>();
                            Assert.IsNull(mget3);
                        }
                    }
                }
            }
        }
 public EnglishDto Update(EnglishDto englishDto)
 {
     using (var client = new HttpClient())
       {
       HttpResponseMessage response =
           client.PutAsJsonAsync("http://localhost:9372/api/EnglishApi" + englishDto.Id, englishDto).Result;
       return response.Content.ReadAsAsync<EnglishDto>().Result;
       }
 }
 public RoleDto Update(RoleDto roleDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/RoleApi/" + roleDto.Id, roleDto).Result;
         return response.Content.ReadAsAsync<RoleDto>().Result;
     }
 }
Example #24
0
 public Tag Update(Tag Tag)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:17348/api/Tag/" + Tag.Id, Tag).Result;
         return response.Content.ReadAsAsync<Tag>().Result;
     }
 }
 public PlayerDto Update(PlayerDto PlayerDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/PlayerApi/" + PlayerDto.Id, PlayerDto).Result;
         return response.Content.ReadAsAsync<PlayerDto>().Result;
     }
 }
Example #26
0
        public ActionResult Edit([Bind(Include = "id,category,dateSubject,description,subjectName,evaluate")] subject subject, int?nbEtoiles)
        {
            if (ModelState.IsValid)
            {
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var postTask = httpClient.PutAsJsonAsync <subject>(baseAddress + "ConsomiTounsi/subjects/Rating?nbEtoiles=" + nbEtoiles, subject);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(subject));
        }
Example #27
0
 public Genre Update(Genre Genre)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:53416/api/Genre?id=" + Genre.Id, Genre).Result;
         return response.Content.ReadAsAsync<Genre>().Result;
     }
 }
 public AboutDto Update(AboutDto aboutDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/AboutApi/"+ aboutDto.Id, aboutDto).Result;
         return response.Content.ReadAsAsync<AboutDto>().Result;
     }
 }
Example #29
0
 public Product Update(Product t)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:54980/api/products/" + t.ID, t).Result;
         return response.Content.ReadAsAsync<Product>().Result;
     }
 }
 public TournamentDto Update(TournamentDto tournamentDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/TournamentApi/"+ tournamentDto.Id, tournamentDto).Result;
         return response.Content.ReadAsAsync<TournamentDto>().Result;
     }
 }
 public Movie Update(Movie movie)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response = 
             client.PutAsJsonAsync("http://localhost:9885/api/Movie/" + movie.Id.ToString(), movie).Result;
         return response.Content.ReadAsAsync<Movie>().Result;
     }
 }
 public NewsDto Update(NewsDto newsDto)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:9372/api/NewsApi/" + newsDto.Id, newsDto).Result;
         return response.Content.ReadAsAsync<NewsDto>().Result;
     }
 }
Example #33
0
        /// <summary>
        /// Envía una petición a la url especificada con las opciones
        /// de configuración requerida
        /// </summary>
        /// <typeparam name="T">Tipo de dato a esperado</typeparam>
        /// <param name="Url">Url destino</param>
        /// <param name="Method">Tipo de método de la petición</param>
        /// <param name="Data">Objeto a enviar en la petición</param>
        /// <param name="TimeOut">Tiempo de espera en minutos</param>
        /// <returns></returns>
        public static T Request <T>(string Url, HttpMethodEnum Method, object Data = null, string Token = null, int TimeOut = 10)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                try
                {
                    client.Timeout = TimeSpan.FromMinutes(TimeOut);
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("text/plain"));
                    if (!string.IsNullOrEmpty(Token))
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
                    }
                    HttpResponseMessage response = null;

                    switch (Method)
                    {
                    case HttpMethodEnum.Get:
                        response = client.GetAsync(Url).Result;
                        break;

                    case HttpMethodEnum.PostJson:
                        response = client.PostAsJsonAsync(Url, Data).Result;
                        break;

                    case HttpMethodEnum.PutJson:
                        response = client.PutAsJsonAsync(Url, Data).Result;
                        break;

                    case HttpMethodEnum.Delete:
                        response = client.DeleteAsync(Url).Result;
                        break;

                    default:
                        break;
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        T result = response.Content.ReadAsAsync <T>().Result;
                        return(result);
                    }
                    else
                    {
                        return(default(T));
                    }
                }
                catch (Exception ex)
                {
                    // Excepciones
                    throw ex;
                }
            }
        }
Example #34
0
        public ActionResult Edit([Bind(Include = "id,decision,objet,state,typeReclamation,users_id")] reclamation reclamation)
        {
            reclamation.state = true;
            if (ModelState.IsValid)
            {
                httpClient.BaseAddress = new Uri("http://localhost:8082/");
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var postTask = httpClient.PutAsJsonAsync <reclamation>("ConsomiTounsi/Reclamation/updateReclamation?id=" + 2, reclamation);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(reclamation));
        }
Example #35
0
        public static async Task <TResult> PutAsJsonAsync <TResult>(this System.Net.Http.HttpClient httpClient, string url, object data = null)
        {
            var response = await httpClient.PutAsJsonAsync(url, data);

            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException(JsonSerializer.Serialize(response));
            }

            return(await response.ReadContentAsync <TResult>());
        }
        public async Task CreateTxtRecordAsync(DnsZone zone, string relativeRecordName, IEnumerable <string> values)
        {
            var urlTemplate = "/domains/{zone}/records/{type}/{name}";
            var url         = String.Format(urlTemplate, zone.Name, GodaddyConstants.DNS_TXT_RECORD, relativeRecordName);
            var txtRecord   = new GoDaddyDnsRecord()
            {
                name = relativeRecordName,
                data = string.Join(" ", values)
            };

            await _httpClient.PutAsJsonAsync <GoDaddyDnsRecord>(url, txtRecord);
        }
Example #37
0
 public ActionResult Edit(int id, PostForum cmt)
 {
     try
     {
         HttpClient Client = new System.Net.Http.HttpClient();
         Client.BaseAddress = new Uri(baseAddress);
         Client.PutAsJsonAsync <PostForum>("http://localhost:8081/SpringMVC/servlet/modify-post/" + id, cmt).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
         return(RedirectToAction("List", "PostForum"));
     }
     catch
     {
         return(View("List", "PostForum"));
     }
 }
Example #38
0
 public ActionResult Edit(int id, Comment cmt, int ide)
 {
     try
     {
         ViewBag.result = ide;
         HttpClient Client = new System.Net.Http.HttpClient();
         Client.BaseAddress = new Uri(baseAddress);
         Client.PutAsJsonAsync <Comment>("http://localhost:8080/SpringMVC/servlet/modify-Comment/" + id, cmt).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
         return(RedirectToAction("List", "Comment", new { id = ide }));
     }
     catch
     {
         return(View("List", "Comment", new { id = ide }));
     }
 }
Example #39
0
        public ActionResult Edit([Bind(Include = "numCoupon,couponValue,dateLimite,users_id,state")] exchange exchange)
        {
            //user id get it from session
            var postTask = httpClient.PutAsJsonAsync <exchange>(baseAddress + "ConsomiTounsi/Exchange/updateExchange/" + u.id, exchange);

            postTask.Wait();

            var result = postTask.Result;

            if (result.IsSuccessStatusCode)
            {
                return(RedirectToAction("Index"));
            }

            return(View(exchange));
        }
Example #40
0
        public ActionResult Edit([Bind(Include = "id,adresse,date,frais,poids,state,deliver_men_id")] delivery delivery, long?idDeliveryMen)
        {
            if (ModelState.IsValid)
            {
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var postTask = httpClient.PutAsJsonAsync <delivery>(baseAddress + "ConsomiTounsi/Delivery/updateDelivery?id=" + idDeliveryMen, delivery);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(delivery));
        }
Example #41
0
        static async Task <HttpStatusCode> UpdateProductAsync(NetworkParameters networkParameters)
        {
            HttpResponseMessage response = await _client.PutAsJsonAsync(
                $"api/values/{networkParameters.IP}/{networkParameters.HostName}", networkParameters);

            response.EnsureSuccessStatusCode();

            if (response.IsSuccessStatusCode)
            {
                _log.Debug("Params is sent: response.StatusCode = " + response.StatusCode);
            }
            else
            {
                _log.Error("Params is NOT sent: response.StatusCode = " + response.StatusCode);
            }

            return(response.StatusCode);
        }
        public ActionResult Edit([Bind(Include = "available,prime,id,latitude,longitude,email,username,actived,lat,lon")]  DeliveryMen delivery_men)
        {
            if (ModelState.IsValid)
            {
                delivery_men.latitude  = double.Parse(delivery_men.lat, System.Globalization.CultureInfo.InvariantCulture);
                delivery_men.longitude = double.Parse(delivery_men.lon, System.Globalization.CultureInfo.InvariantCulture);

                var postTask = httpClient.PutAsJsonAsync <DeliveryMen>(baseAddress + "ConsomiTounsi/DeliveryMen/" + delivery_men.id, delivery_men);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(delivery_men));
        }
        public ActionResult Edit([Bind(Include = "id,dateReparation,prixReparation,typePanne,state,idProduct")] reparation reparation, long?idProduct)
        {
            if (ModelState.IsValid)
            {
                httpClient.BaseAddress = new Uri("http://localhost:8082/");
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //user id get it from session
                var postTask = httpClient.PutAsJsonAsync <reparation>("ConsomiTounsi/Reparation/updateReparation/" + reparation.idProduct, reparation);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }
            return(View(reparation));
        }
Example #44
0
        private async Task <bool> UpdateCustomer(DtoCustomer customer)
        {
            bool result = false;

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.BaseAddress = new Uri(URL);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = await Task.FromResult(httpClient.PutAsJsonAsync("api/customer", customer).Result);

                response.EnsureSuccessStatusCode();

                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsAsync <bool>();
                }
            }

            return(result);
        }
        static void Main4()
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                person p = new person {
                    name = "Sourav", surname = "Kayal"
                };
                client.BaseAddress = new System.Uri("http://localhost:1565/");

                // System.Net.Http.HttpResponseMessage response = System.Net.Http.HttpClientExtensions.PutAsJsonAsync(client, "api/person", p).Result;
                System.Net.Http.HttpResponseMessage response = client.PutAsJsonAsync("api/person", p).Result;
                if (response.IsSuccessStatusCode)
                {
                    System.Console.Write("Success");
                }
                else
                {
                    System.Console.Write("Error");
                }
            }
        }
Example #46
0
        public async Task <HttpResponseMessage> InvokeHttpCall <TRequest>(HttpMethods method, TRequest request, System.Net.Http.HttpClient client,
                                                                          Uri endpointUri)
        {
            switch (method)
            {
            case HttpMethods.POST:
                return(await client.PostAsJsonAsync(endpointUri, request));

            case HttpMethods.GET:
                return(await client.GetAsync(endpointUri));

            case HttpMethods.DELETE:
                return(await client.DeleteAsync(endpointUri));

            case HttpMethods.PUT:
                return(await client.PutAsJsonAsync(endpointUri, request));

            default:
                throw new ArgumentOutOfRangeException(nameof(method), method, null);
            }
        }
 public static async Task <TResponseType> UpdateAsync <TPostObjectType>(string url, TPostObjectType postObject)
 {
     try
     {
         using (var response = await httpClient.PutAsJsonAsync(url, postObject))
         {
             await response.Content.ReadAsStringAsync().ContinueWith((Task <string> x) =>
             {
                 if (x.IsFaulted)
                 {
                     throw x.Exception;
                 }
                 _result = JsonConvert.DeserializeObject <TResponseType>(x.Result);
             });
         }
         return(_result);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #48
0
        public async Task UpdateGuest(int id, Guest nyGuest)
        {
            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(serverUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    var response = await client.PutAsJsonAsync("api/Guests/" + id, nyGuest);

                    if (response.IsSuccessStatusCode)
                    {
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        public void PutAsJsonAsync_Uri_WhenClientIsNull_ThrowsException()
        {
            HttpClient client = null;

            Assert.ThrowsArgumentNull(() => client.PutAsJsonAsync(new Uri("http://www.example.com"), new object()), "client");
        }
Example #50
0
        public async Task PutAsync <T>(string requestUri, int id, T entity)
        {
            var response = await _client.PutAsJsonAsync($"{requestUri}/{id}", entity);

            response.EnsureSuccessStatusCode();
        }
 public void PutAsJsonAsync_String_WhenUriIsNull_ThrowsException()
 {
     Assert.Throws <InvalidOperationException>(() => _client.PutAsJsonAsync((string)null, new object()),
                                               "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.");
 }
Example #52
0
        /// <summary>
        /// This method is for performing HTTP methods.
        /// Method will accept an object as a parameter which will have details like method, base URI, URL, content type and input payload if appicable.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Dictionary <string, string> HTTPInvoke(InputData input)
        {
            string output    = string.Empty;
            string endResult = string.Empty;
            Dictionary <string, string> outputDict = new Dictionary <string, string>();

            using (var client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(input.baseURI);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(input.ContentType));

                if ("GET".Equals(input.Method))
                {
                    if (!input.PayLoad.Equals(string.Empty))
                    {
                        Console.WriteLine("Input payload is not required for GET method.Hence, not considering!!");
                    }

                    var response = client.GetAsync(input.Url);
                    response.Wait();
                    var result = response.Result;
                    Console.WriteLine("Result : " + result);
                    var readTask = result.Content.ReadAsStringAsync();
                    readTask.Wait();

                    output = readTask.Result;
                    Console.WriteLine("Response Code  --->  " + result.StatusCode);
                    Console.WriteLine("Response  --->  " + output);

                    outputDict.Add("StatusCode", result.StatusCode.ToString());
                    outputDict.Add("Response", output);
                }
                else if ("POST".Equals(input.Method))
                {
                    var inputPayload = ReadInputPayload(input.PayLoad);
                    var response     = client.PostAsJsonAsync(input.Url, inputPayload);

                    response.Wait();
                    var result = response.Result;
                    Console.WriteLine("Result : " + result);

                    var readTask = result.Content.ReadAsStringAsync();
                    readTask.Wait();

                    output = readTask.Result;

                    Console.WriteLine("Response Code  --->  " + result.StatusCode);
                    Console.WriteLine("Response  --->  " + output);

                    outputDict.Add("StatusCode", result.StatusCode.ToString());
                    outputDict.Add("Response", output);
                }
                else if ("PUT".Equals(input.Method))
                {
                    var inputPayload = ReadInputPayload(input.PayLoad);
                    var response     = client.PutAsJsonAsync(input.Url, inputPayload);
                    response.Wait();

                    var result = response.Result;
                    Console.WriteLine("Result : " + result);
                    var readTask = result.Content.ReadAsStringAsync();
                    readTask.Wait();
                    output = readTask.Result;

                    Console.WriteLine("Response Code  --->  " + result.StatusCode);
                    Console.WriteLine("Response  --->  " + output);

                    outputDict.Add("StatusCode", result.StatusCode.ToString());
                    outputDict.Add("Response", output);
                }
                else if ("DELETE".Equals(input.Method))
                {
                    if (!input.PayLoad.Equals(string.Empty))
                    {
                        Console.WriteLine("Input payload is not required for DELETE method. Hence, not considering!!");
                    }

                    var response = client.DeleteAsync(input.Url);
                    response.Wait();

                    var result = response.Result;
                    Console.WriteLine("Result : " + result);
                    var readTask = result.Content.ReadAsStringAsync();
                    readTask.Wait();
                    output = readTask.Result;

                    Console.WriteLine("Response Code  --->  " + result.StatusCode);
                    Console.WriteLine("Response  --->  " + output);

                    outputDict.Add("StatusCode", result.StatusCode.ToString());
                    outputDict.Add("Response", output);
                }
            }
            return(outputDict);
        }
Example #53
-1
        static void Main()
        {
            var address = "http://localhost:920/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                var team = new Team {Id = 3, Name = "Los Angeles Kings"};
                var team2 = new Team { Name = "Boston Bruins" };
                var player = new Player {Name = "Tyler Bozak", Team = 1};

                Send(HttpMethod.Get, client, address + "api/teams");
                Send(HttpMethod.Get, client, address + "api/teams/1");
                Send(HttpMethod.Get, client, address + "api/teams/1/players");

                Console.WriteLine(client.PostAsJsonAsync(address+"api/teams", team).Result.StatusCode);
                Console.WriteLine();

                Console.WriteLine(client.PostAsJsonAsync(address+"api/teams/1/players", player).Result.StatusCode);
                Console.WriteLine();

                Console.WriteLine(client.PutAsJsonAsync(address + "api/teams/2", team2).Result.StatusCode);
                Console.WriteLine();

                Send(HttpMethod.Get, client, address + "api/teams");
                Send(HttpMethod.Get, client, address + "api/teams/1/players");
            }

            Console.ReadLine();
        }
Example #54
-1
        private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(products);

            //添加新的联系人
            Product product = new Product { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" };
            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products", product);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products/001");
            product = (await response.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.Name = "赵六";
            product.EmailAddress = "*****@*****.**";
            await httpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products/001", product);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/tyz/api/products/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);
        }
Example #55
-1
 public Rating Update(Rating Rating)
 {
     using (var client = new HttpClient())
     {
         HttpResponseMessage response =
             client.PutAsJsonAsync("http://localhost:17348/api/Rating/" + Rating.Id, Rating).Result;
         return response.Content.ReadAsAsync<Rating>().Result;
     }
 }