protected void Page_Load(object sender, EventArgs e) { var cl = new RestClient("http://demo.vivapayments.com/"); //var cl = new RestClient("https://www.vivapayments.com/"); // production URL var req = new RestRequest("api/orders", Method.POST); req.AddObject(new OrderOptions() { Amount = 100 // Amount is in cents }); string MerchantId = Guid.Parse("1c204c59-9890-499c-bf5d-31e80dcdbdfd").ToString(); // the merchant id is found in the self-care environment (developers menu) string Password = "******"; // the password is set in the self-care environment (developers menu) cl.Authenticator = new HttpBasicAuthenticator(MerchantId, Password); // Do the post var res = cl.Execute<OrderResult>(req); // once the order code is successfully created, redirect to payment form to complete the payment if (res.Data.ErrorCode == 0) { Response.Redirect(this.vivaPaymentFormURL + res.Data.OrderCode.ToString()); } }
public ActionResult Create(SetTagDTO collection) { if (!Session["Role"].Equals("Admin")) { return RedirectToAction("Index", "Home"); } var request = new RestRequest("api/Tags/", Method.POST); var apiKey = Session["ApiKey"]; var UserId = Session["UserId"]; request.AddHeader("xcmps383authenticationkey", apiKey.ToString()); request.AddHeader("xcmps383authenticationid", UserId.ToString()); request.AddObject(collection); var queryResult = client.Execute(request); statusCodeCheck(queryResult); if (queryResult.StatusCode != HttpStatusCode.Created) { return View(); } else if (queryResult.StatusCode == HttpStatusCode.Forbidden) { return RedirectToAction("Login", "User"); } return RedirectToAction("Index"); }
private static void GetBoxScores(string authToken) { var start = 0; while (true) { var request = new RestRequest("/user/teams/football/boxScores"); request.AddHeader("Authorization", authToken); request.AddObject(new GetUserTeamsFootballBoxScores { Offset = start, Count = PageSize }); var response = _restClient.Execute<FootballBoxScoresResponse>(request); if (response.StatusCode == HttpStatusCode.OK) { foreach (var boxScore in response.Data.BoxScores) { var text = boxScore.AwayTeamName + " @ " + boxScore.HomeTeamName + " - " + boxScore.StatusDisplay; if (boxScore.Status == Status.Complete) { text = text + " (" + boxScore.AwayTeamAcronym + " " + boxScore.AwayScore + ", " + boxScore.HomeTeamAcronym + " " + boxScore.HomeScore + ")"; } Console.WriteLine(text); } if (response.Data.BoxScores.Count == 0 || response.Data.BoxScores.Count() == response.Data.TotalCount) break; start += response.Data.BoxScores.Count; } else if (response.StatusCode == HttpStatusCode.Unauthorized) throw new Exception("Auth token expired. Reauthenticate"); else throw new Exception(string.Format("Error getting box scores: {0}", response.StatusCode)); } }
private void refreshUsers() { var request = new rs.RestRequest(rs.Method.GET); request.RequestFormat = rs.DataFormat.Json; // URL paraméterek megadása (autentikációhoz) request.AddObject(new { u = textBox1.Text, p = textBox2.Text }); var response = userClient.Execute(request); if (response.StatusCode != System.Net.HttpStatusCode.OK) { MessageBox.Show(response.StatusDescription); return; } label1.Text = response.Content; listBox1.Items.Clear(); foreach (User u in new JsonSerializer().Deserialize <List <User> >(response)) { listBox1.Items.Add(u.username); } button3.Enabled = true; }
public ActionResult AddUser(User user) { var client = new RestClient(ServerBaseUrl + "UserRoles/AddUser"); RestRequest request = new RestRequest(Method.POST); request.AddObject(user); int intt= client.Execute<int>(request).Data; return RedirectToAction("AllUsers"); }
//public Sharing CreateSharing(int projectId, Sharing sharing) //{ // var request = new RestRequest(); // request.Resource = string.Format("projects/{0}/sharings.xml", projectId); // request.Method = Method.POST; // request.AddObject(sharing); // return Execute<Sharing>(request); //} public Sharing UpdateSharing(Sharing sharing) { var request = new RestRequest(); request.Resource = string.Format("projects/{0}/sharings/{1}.xml", sharing.Project.Id, sharing.Id); request.Method = Method.PUT; request.AddObject(sharing); return Execute<Sharing>(request); }
/// <summary> /// Using the API, you can create a new project in your account. /// </summary> /// <param name="project"></param> /// <returns></returns> public Project CreateProject(Project project) { var request = new RestRequest(); request.Resource = "projects.xml"; request.Method = Method.POST; request.AddObject(project); return Execute<Project>(request); }
public static bool Save(BoredModel model) { var client = new RestClient(BaseUrl); var request = new RestRequest("save/{ver}", Method.POST); request.AddUrlSegment("ver", Ver); request.AddObject(model); IRestResponse response = client.Execute(request); return response.StatusCode == System.Net.HttpStatusCode.OK; }
private static string Authenticate() { var request = new RestRequest("/authenticate", Method.POST); request.AddObject(new Authenticate { Username = Username, Password = Password }); var response = _restClient.Execute<AuthenticateResponse>(request); if (response.StatusCode == HttpStatusCode.OK) return response.Data.AuthToken; else if (response.StatusCode == HttpStatusCode.Unauthorized) throw new Exception("Invalid username/password"); else throw new Exception(string.Format("Error calling authenticate: {0}", response.StatusCode)); }
public LoginUserOutput LoginUser(LoginUserInput input) { RestHTTP http = new RestHTTP(); RestSharp.RestRequest req = new RestSharp.RestRequest("api/accounts/GetAccessTokenByUserName", RestSharp.Method.POST); req.AddObject(input); RestSharp.RestClient client = new RestSharp.RestClient(WebConfigurationManager.AppSettings["AuthServerAPI"]); var response = client.Execute <LoginUserOutput>(req); LoginUserOutput result = JsonConvert.DeserializeObject <LoginUserOutput>(response.Content, new ClaimConverter()); return(result); }
public void generarTipoKpi() { string[] tipoKpi = { "Ventas", "Prospectos", "Vendedores" }; RestClient client = new RestClient(ConfigurationManager.AppSettings["endpoint"]); RestRequest request = new RestRequest("tipo_kpi", Method.POST); request.RequestFormat = DataFormat.Json; for (int i = 0; i < tipoKpi.Length; i++) { TipoKpi nuevoTipo = new TipoKpi(tipoKpi[i]); request.AddObject(nuevoTipo); var response = client.Execute(request) as RestResponse; } }
public void PostMessage(SlackMessage message, params SlackAttachment[] attachments) { var request = new RestRequest("chat.postMessage", Method.POST) {RequestFormat = DataFormat.Json}; request.AddHeader("Content-Type", "application/json"); request.AddObject(message); if (attachments.Any()) { request.AddParameter("attachments", JsonConvert.SerializeObject(attachments)); } _restClient.ExecuteAsync(request, response => Trace.TraceInformation(string.Format("Slack response: {0}", response.Content))); }
public Order Create(CreateOrderRequest o) { var request = new RestRequest { Resource = _orderPath, Method = Method.POST, }; request.RequestFormat = DataFormat.Json; request.AddObject(o); var response = Client.ExecuteWithErrorCheck<Order>(request); return response.Data; }
public IRestResponse<OrderResult> CreateOrder(long amount, string sourceCode) { var cl = new RestClient(_BaseApiUrl); cl.Authenticator = new HttpBasicAuthenticator( _MerchantId.ToString(), _ApiKey); var req = new RestRequest(_PaymentsCreateOrderUrl, Method.POST); req.AddObject(new { Amount = amount, // Amount is in cents SourceCode = sourceCode }); return cl.Execute<OrderResult>(req); }
//Private Methods private LoginByLoginTokenOutput LoginByLoginToken(string accessToken) { var accessTokenObj = _CT.aToken.Deserialize(accessToken); LoginByLoginTokenInput Input = new LoginByLoginTokenInput() { LoginToken = accessTokenObj.AccessToken }; RestHTTP http = new RestHTTP(); RestSharp.RestRequest req = new RestSharp.RestRequest("api/auth/LoginByLoginToken", RestSharp.Method.POST); req.AddObject(Input); var response = http.HttpPost <LoginByLoginTokenOutput>(req); return(response); }
public OrderItem CreateWithData(long orderId,OrderItemRequest orderItem, Stream fileData) { var request = new RestRequest { Resource = _orderItemPath, Method = Method.POST }; request.AddParameter("orderId", orderId, ParameterType.UrlSegment); request.AddObject(orderItem, "Type", "Url", "Copies", "Sizing", "PriceToUser", "Md5Hash"); byte[] allData = new byte[fileData.Length]; fileData.Read(allData,0,allData.Length); request.AddFile("image",allData,"image.jpg"); var response = Client.ExecuteWithErrorCheck<OrderItem>(request); fileData.Dispose(); return response.Data; }
public void TestParameters() { var client = new RestClient("http://example.com"); var request = new RestRequest("resource/{id}", Method.POST); // adds to POST or URL querystring based on Method request.AddParameter("name", "value"); // replaces matching token in request.Resource request.AddUrlSegment("id", "123"); // add parameters for all properties on an object request.AddObject(new MyInt{myInt = 42}); // add files to upload (works with compatible verbs) // may throw a FileNotFoundException request.AddFile("name", "path"); }
public void UpdateToDo(Models.ToDo toDo, Action<bool> callbackAction) { var client = new RestClient("http://localhost:8888/ToDoServices/api/ToDo/Update"); var request = new RestRequest(Method.POST); request.AddObject(toDo); client.ExecuteAsync(request, (response, handle) => { if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent) { DispatcherHelper.CheckBeginInvokeOnUI(() => callbackAction.Invoke(true)); } else { callbackAction.Invoke(false); } }); }
public void Save (Schedule schedule) { if (NetworkStatusCheck.IsReachable ()) { //TestFlight.PassCheckpoint ("Started RemoteScheduledSessionsRepository.Save"); var client = new RestClient (); client.BaseUrl = "http://conference.apphb.com/api/schedule/"; var request = new RestRequest ("postedSession", Method.POST); request.AddObject (schedule); request.RequestFormat = DataFormat.Json; using (new NetworkIndicator()) { var response = client.Execute<Schedule> (request); } //TestFlight.PassCheckpoint ("Finished RemoteScheduledSessionsRepository.Save"); } else { } }
public void Insert(string message, string level) { Log log = new Log() { Message = message, Level = level }; log.Service = base.serviceName; // Identify client in log message RestClient client = new RestClient(RouteConfiguration.RouteDNS[RouteConfiguration.AvailableServices.LogService]); RestRequest request = new RestRequest("log/", Method.POST); request.AddObject(log); IRestResponse response = client.Execute(request); if (response.StatusCode == HttpStatusCode.InternalServerError) { throw new Exception("Remote Server Error"); } }
protected void generateKpiVentas_Click(object sender, EventArgs e) { string montoMeta = metaVentas.Text; string descipcion = descripcionVentasTotales.Text; KPI nuevoKpi = new KPI(descipcion, montoMeta); RestClient client = new RestClient(ConfigurationManager.AppSettings["endpoint"]); RestRequest request = new RestRequest("Kpis", Method.POST); request.RequestFormat = DataFormat.Json; request.AddObject(nuevoKpi); var response = client.Execute(request) as RestResponse; string json = response.Content; if (response.ResponseStatus != ResponseStatus.Error) { pnlMensajeExito.Visible = true; } else { pnlMensajeError.Visible = true; } }
public ActionResult Create(User collection) { try { // TODO: Add insert logic here var client = new RestClient("http://localhost:12932/"); var request = new RestRequest("api/Users/", Method.POST); var apiKey = Session["ApiKey"]; var UserId = Session["UserId"]; request.AddHeader("xcmps383authenticationkey", apiKey.ToString()); request.AddHeader("xcmps383authenticationid", UserId.ToString()); request.AddObject(collection); var queryResult = client.Execute(request); return RedirectToAction("Index"); } catch { return View(); } }
public RedirectToRouteResult AddMan(Manufacturer man) { var token = _sessionHelper.GetToken(); if (token == "SessionIsNull") return RedirectToAction("GoToErrorForm", "Cpu"); var clientMan = new RestClient(SiteConn.ManWebApiServer); var addMan = new RestRequest($"Man/AddMan", Method.POST) { RequestFormat = DataFormat.Json }; addMan.AddHeader("Authorization", token); addMan.AddHeader("Content-Type", "application/json"); addMan.AddObject(man); var responseMan = clientMan.Post(addMan); return RedirectToAction("List", "Man"); }
private static void AddProduct() { var client = new RestClient("http://*****:*****@"wnet\mhingley"; itemToAdd.Tagline = "Approved software store"; var request = new RestRequest("PostProduct", Method.POST); request.RequestFormat = DataFormat.Json; request.AddObject(itemToAdd); IRestResponse response = client.Execute(request); Console.WriteLine("Posting to AddProduct"); Console.WriteLine("response="); Console.WriteLine(response.Content); }
private long CreateOrder(long amount) { var cl = new RestClient(_BaseApiUrl); cl.Authenticator = new HttpBasicAuthenticator( _MerchantId.ToString(), _ApiKey); var req = new RestRequest(_PaymentsCreateOrderUrl, Method.POST); req.AddObject(new { Amount = 100, // Amount is in cents SourceCode = "Default" }); var res = cl.Execute<OrderResult>(req); if (res.Data != null && res.Data.ErrorCode == 0) { return res.Data.OrderCode; } return 0; }
public static void Login(string usrname, string passwd) { /* * Check if username was provided, * if not return an error */ if (usrname == String.Empty) { throw new InvalidOperationException("Username missing"); } /* * log into NewsBlur */ else { // Check for password, if not password provided, ommit it in the request AuthInfo info; if (passwd == String.Empty) { info = new AuthInfo { username = usrname }; } else { info = new AuthInfo { username = usrname, password = passwd }; } RestRequest request = new RestRequest("login", Method.POST); request.AddObject(info); client.ExecuteAsync(request, response => { Debug.WriteLine(response.Content); }); } }
public GetUserSessionByAccessTokenOutput GetUserSessionByAccessToken(string accessToken) { try { var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(accessToken).Payload.ToList(); var username = token.Where(a => a.Key == "unique_name").Select(b => b.Value).FirstOrDefault(); //string username = new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, object>(token.Payload).Items[1].Value; //var accessTokenObj = _CT.aToken.Deserialize(accessToken); GetUserSessionByAccessTokenInput input = new GetUserSessionByAccessTokenInput(); input.Username = username.ToString(); RestHTTP http = new RestHTTP(); RestSharp.RestRequest req = new RestSharp.RestRequest("api/accounts/GetUserSessionByAccessToken", RestSharp.Method.POST); req.AddHeader("Authorization", "Bearer " + input.AccessToken); req.AddObject(input); RestSharp.RestClient client = new RestSharp.RestClient(WebConfigurationManager.AppSettings["AuthServerAPI"]); var response = client.Execute <GetUserSessionByAccessTokenOutput>(req); if (response.StatusCode == System.Net.HttpStatusCode.OK) { GetUserSessionByAccessTokenOutput result = JsonConvert.DeserializeObject <GetUserSessionByAccessTokenOutput>(response.Content, new ClaimConverter()); result.AccessToken = accessToken; return(result); } else { return(null); } } catch (Exception ex) { throw new Exception(ex.Message); } }
public IRestResponse<TokenizeResult> Tokenize(string CardHolderName, string CardNumber, int CVV, int ExpiryMonth, int ExpiryYear) { var cl = new RestClient(_BaseApiUrl); _PaymentsTokenizeUrl = String.Format(_PaymentsTokenizeUrl, RestSharp.Contrib.HttpUtility.UrlEncode(_PublicKey)); var req = new RestRequest(_PaymentsTokenizeUrl, Method.POST); req.AddObject(new { CardHolderName = CardHolderName, Number = CardNumber, CVC = CVV, ExpirationDate = new DateTime(ExpiryYear, ExpiryMonth, 15, 0, 0 ,0, DateTimeKind.Utc).ToString("yyyy-MM-dd") }); return cl.Execute<TokenizeResult>(req); }
/// <summary> /// Authenticates using POST method /// </summary> /// <returns>Returns a valid Token value, if successfully authenticated, otherwise an empty string.</returns> public bool Authorize() { try { var authData = GetAuthData(); var request = new RestRequest("/RHS/Authorize/{data}", Method.POST); request.AddObject(authData); var response = client.Execute(request); Auth = JsonConvert.DeserializeObject<AuthResult>(response.Content);// deserializer.Deserialize<AuthResult>(response); Auth.IpInternal = authData.IpInternal; Auth.IpExternal = authData.IpExternal; Auth.HostName = authData.HostName; } catch { return false; } return Auth.IsAuthenticated; }
public Order Update(UpdateOrderRequest o) { var request = new RestRequest { Resource = _getPath, Method = Method.PUT }; request.AddParameter("orderId", o.id.ToString(), ParameterType.UrlSegment); request.AddObject(o); var response = Client.ExecuteWithErrorCheck<Order>(request); return response.Data; }
public ActionResult createSale(int id, string employee) { Mapper.CreateMap<SetCartDTO, GetCartDTO>(); Mapper.CreateMap<SetGameDTO, GetGameDTO>(); Mapper.CreateMap<SetGenreDTO, GetGenreDTO>(); Mapper.CreateMap<SetTagDTO, GetTagDTO>(); GetCartDTO sellCart = getSpecificSellCart(id); //use automapper to bind incoming to outgoing //SetCartDTO outgoingCart = Mapper.Map<SetCartDTO>(sellCart); List<SetGameDTO> cartGames = new List<SetGameDTO>(); SetCartDTO outgoingCart = new SetCartDTO(); //manualy parse to an SetCartDTO outgoingCart.User_Id = parseId(sellCart.URL); /* foreach (GetGameDTO game in sellCart.Games) { SetGameDTO tempGame = new SetGameDTO(); foreach (GetGenreDTO genre in game.Genres) { tempGame.Genres.Add(Mapper.Map<SetGenreDTO>(genre)); } foreach (GetTagDTO tag in game.Tags) { tempGame.Tags.Add(Mapper.Map<SetTagDTO>(tag)); } tempGame.GameName = game.GameName; tempGame.InventoryStock = game.InventoryStock; tempGame.Price = game.Price; tempGame.ReleaseDate = game.ReleaseDate; cartGames.Add(tempGame); } */ //outgoingCart.Games = cartGames; var request = new RestRequest("api/Sales", Method.POST); var apiKey = Session["ApiKey"]; var UserId = Session["UserId"]; request.AddHeader("xcmps383authenticationkey", apiKey.ToString()); request.AddHeader("xcmps383authenticationid", UserId.ToString()); request.AddObject(outgoingCart); var queryResult = client.Execute(request); statusCodeCheck(queryResult); if (queryResult.StatusCode != HttpStatusCode.Created) { return RedirectToAction("createSale", parseId(sellCart.URL)); } else if (queryResult.StatusCode == HttpStatusCode.Forbidden) { return RedirectToAction("Login", "User"); } return RedirectToAction("Index", "Home", ""); }
public ActionResult Edit(int id, SetGenreDTO collection) { if (!Session["Role"].Equals("Admin")) { return RedirectToAction("Index", "Home"); } try { // TODO: Add update logic here var request = new RestRequest("api/Genres/" + id, Method.PUT); var apiKey = Session["ApiKey"]; var UserId = Session["UserId"]; request.AddHeader("xcmps383authenticationkey", apiKey.ToString()); request.AddHeader("xcmps383authenticationid", UserId.ToString()); request.AddObject(collection); var queryResult = client.Execute(request); statusCodeCheck(queryResult); if (queryResult.StatusCode != HttpStatusCode.OK) { return View(); } else if (queryResult.StatusCode == HttpStatusCode.Forbidden) { return RedirectToAction("Login", "User"); } return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult EditUser(User user) { // get user to update db using api. var client = new RestClient(ServerBaseUrl + "UserRoles/UpdateUser"); RestRequest request = new RestRequest(Method.POST); request.AddObject(user); var response = client.Execute(request); return RedirectToAction("AllUsers"); }
/// <summary> /// The Wistia data API allows you to update a piece of media. /// </summary> /// <param name="media"></param> /// <returns></returns> public Media UpdateMedia(Media media) { var request = new RestRequest(); request.Resource = string.Format("medias/{0}.xml", media.Id); request.Method = Method.PUT; request.AddObject(media); return Execute<Media>(request); }