public ActionResult Index(string projectName, string gitUrl) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Projects/" + projectName + "/" + gitUrl; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); return Redirect("/Projects/" + projectName); }
public ActionResult Index(string projectName, string applicationName, string clusterName, Dictionary<string, string> config) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); if (config.ContainsKey("controller")) return RedirectToAction("Index"); var url = hostName + "/api/Clusters/" + projectName + "/" + applicationName + "/" + clusterName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.PUT); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); request.AddBody(JsonConvert.SerializeObject(config)); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } return RedirectToAction("Index"); }
public static string UpdateCustomer() { var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Customer/1047/update") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); request.AddParameter("application/json", "{" + "\"CustomerID\": 1047,\n" + "\"Email\": \"[email protected]\",\n" + "\"ShippingAddress\": \"Calle Max Henriquez Ureña No. 6\",\n" + "\"BillingAddress\": \"Calle 1 No 10, Piantini\",\n" + "\"FirstName\": \"Emmanuel\",\n" + "\"LastName\": \"De los Santos\",\n" + "\"DocumentTypeId\": 2,\n" + "\"DocNumber\": \"00114918123\",\n" + "\"PhoneNumber\": \"8096043111\" ,\n" + "\"Enable\": true }" , RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
private static AppBundleResponse UpdateAppBundle(string token, string appId) { Console.WriteLine($"Updating app {appId}."); var request = new RestSharp.RestRequest($"/appbundles/{appId}/versions", RestSharp.Method.POST); request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Content-Type", "application/json"); request.RequestFormat = RestSharp.DataFormat.Json; var body = new NewAppBundleRequest() { Id = null, Engine = "Autodesk.Revit+2019", Description = "Convert Hypar Models to Revit." }; request.AddBody(body); var response = _client.Execute(request); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"There was an error creating a new app bundle: {response.StatusCode} - {response.Content}"); } var newVersionResponse = JsonConvert.DeserializeObject <AppBundleResponse>(response.Content); return(newVersionResponse); }
public ActionResult Index(string projectName, string applicationName, string clusterName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var newCluster = new Elders.Pandora.Box.Cluster(clusterName, new Dictionary<string, string>()); var url = hostName + "/api/Clusters/" + projectName + "/" + applicationName + "/" + clusterName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); request.AddBody(JsonConvert.SerializeObject(new Dictionary<string, string>())); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } Elders.Pandora.Server.UI.ViewModels.User.GiveAccess(User, projectName, applicationName, clusterName, Access.WriteAccess); var config = GetConfig(projectName, applicationName); config.Clusters.Add(new Configuration.ClusterDTO(new Cluster(newCluster.Name, Access.WriteAccess), newCluster.AsDictionary())); return View(config); }
public async Task <TrustedPublisher> GetTrustedPublisher(string url) { client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl")); RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-trustedpublisher-func/GetTrustedPublisher", RestSharp.Method.POST); restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey")); restRequest.AddHeader("Content-Type", "application/json"); TrustedPublisherRequest publisherRequest = new TrustedPublisherRequest() { Url = url }; restRequest.AddJsonBody(publisherRequest); try { var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false); return(JsonConvert.DeserializeObject <TrustedPublisher>(response.Content)); } catch (Exception) { return(new TrustedPublisher() { Reason = "Konnte leider nicht validiert werden" }); } }
//public string PrivateAccountKey ="PrivateAccountKey"; public static string PostPurchase() { var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Purchase") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); request.AddParameter("application/json", "{" + "\"TrxToken\": \"CT__6NBt_OO5gfCg7RUCF_xdtRuaohj8YOAjLqkyXVed23g_\",\n" + "\"Order\": \"000001\",\n" + "\"Amount\": 13000,\n" + "\"Tip\": 000,\n" + "\"Currency\": \"DOP\",\n" + "\"Capture\": true,\n" + "\"CustomerIP\": \"100.0.0.2\",\n" + "\"DataDo\": { \"Tax\": 000,\n \"Invoice\": \"000001\",\n }" + "}", RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
public async Task <List <Models.SearchResponse> > GetFakeNewsDb(string message) { try { client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl")); RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-factsearch-fa/Search", RestSharp.Method.POST); restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey")); restRequest.AddHeader("Content-Type", "application/json"); Models.Request requestObject = new Models.Request { text = message }; restRequest.AddJsonBody(requestObject); var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false); return(JsonConvert.DeserializeObject <List <Models.SearchResponse> >(response.Content)); } catch (Exception ex) { throw; } }
public string delete(string url, bool requestId) { string time = this.srvrTime(); var client = new RestSharp.RestClient(this.urlRoot); var request = new RestSharp.RestRequest(url); string nonce = Guid.NewGuid().ToString(); string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "DELETE", getPath(url), getQuery(url), null); request.AddHeader("X-Time", time); request.AddHeader("X-Nonce", nonce); request.AddHeader("X-Auth", this.apiKey + ":" + digest); request.AddHeader("X-Organization-Id", this.orgId); if (requestId) { request.AddHeader("X-Request-Id", Guid.NewGuid().ToString()); } var response = client.Execute(request, RestSharp.Method.DELETE); Console.ForegroundColor = ConsoleColor.DarkGray; Console.Out.WriteLine("res: [" + response.Content + "]"); if (response.StatusCode != HttpStatusCode.OK) { return("{error_id: -1}"); } return(response.Content); }
private static void CreateNewActivityAlias(string token, string activityId, string activityAlias, int version) { Console.WriteLine($"Creating new activity alias for activity, {activityId}."); var request = new RestSharp.RestRequest($"/activities/{activityId}/aliases", RestSharp.Method.POST); request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Content-Type", "application/json"); request.RequestFormat = RestSharp.DataFormat.Json; var data = new Dictionary <string, object>() { { "version", 1 }, { "id", activityAlias } }; request.AddBody(data); var response = _client.Execute(request); if (response.StatusCode == HttpStatusCode.Conflict) { Console.WriteLine($"The alias, {activityAlias}, already exists."); } else if (response.StatusCode != HttpStatusCode.OK) { throw new Exception($"There was an error creating the activity alias: {response.StatusCode} - {response.Content}"); } }
private static void CreateNickname(string nickname, string token) { Console.WriteLine($"Getting the existing app nickname."); var request = new RestSharp.RestRequest("/forgeapps/me", RestSharp.Method.GET); request.AddHeader("Authorization", $"Bearer {token}"); var response = _client.Execute(request); if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine($"The forge app has the nickname: {response.Content}"); } Console.WriteLine($"Creating the nickname '{nickname}'."); request = new RestSharp.RestRequest("/forgeapps/me", RestSharp.Method.PATCH); request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Content-Type", "application/json"); var body = new Dictionary <string, string>() { { "nickname", nickname } }; request.RequestFormat = RestSharp.DataFormat.Json; request.AddBody(body); response = _client.Execute(request); if (response.StatusCode == HttpStatusCode.NoContent) { Console.WriteLine("Nickname successfully updated."); } else { throw new Exception($"There was an error creating the nickname: {response.StatusCode} - {response.Content}"); } }
/// <summary> /// Ejecuta la llamada al servicio REST con RestSharp /// </summary> /// <typeparam name="T">Tipo de dato del objeto de retorno</typeparam> /// <param name="uri">url del endpoint del servicio rest</param> /// <param name="httpMethod">Método HTTP</param> /// <param name="objJsonBody">Objeto request body</param> /// <returns>Interface IRestResponse<T></returns> public static RestSharp.IRestResponse<T> Execute<T>(string uri, RestSharp.Method httpMethod, object objJsonBody = null, string authorizationHeader = null) where T : new() { var client = new RestSharp.RestClient(uri); var request = new RestSharp.RestRequest(httpMethod); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/json"); if (!string.IsNullOrEmpty(authorizationHeader)) { request.AddHeader("Authorization", authorizationHeader); } if (objJsonBody != null) request.AddParameter("application/json", objJsonBody, RestSharp.ParameterType.RequestBody); //request.AddJsonBody(objJsonBody); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; RestSharp.IRestResponse<T> response = null; for (int i = 0; i < 2; i++) { response = client.Execute<T>(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) break; else if (response.StatusCode == HttpStatusCode.RequestTimeout || (int)response.StatusCode > 500) Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["timer_web_api"])); } return response; }
public string GetKB(string question) { string qnamakerUriBase = $"https://{ConfigurationManager.AppSettings["QnAApiHostName"]}/qnamaker/v1.0"; string apiApppId = ConfigurationManager.AppSettings["QnAKnowledgebaseId"]; string apiKey = ConfigurationManager.AppSettings["QnASubscriptionKey"]; string body = $"{{\"question\" : \"{question}\"}}"; qnamakerUriBase += $"/knowledgebases/{apiApppId}/generateAnswer"; RestSharp.RestClient client = new RestSharp.RestClient(qnamakerUriBase) { Encoding = System.Text.Encoding.UTF8, }; RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST); // Add Header request.AddHeader("Content-Type", "application/json"); request.AddHeader("Ocp-Apim-Subscription-Key", apiKey); request.AddHeader("cache-control", "no-cache"); // Add Body request.AddParameter("undefined", body, RestSharp.ParameterType.RequestBody); // Send the Post Request RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
private static void UpdateUserAccess(User user, string projectName, string applicationName, string cluster, Access access) { user.Access.AddRule(new AccessRules { Project = projectName, Application = applicationName, Cluster = cluster, Access = access }); var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Users/" + ClaimsPrincipal.Current.Id(); var restClient = new RestSharp.RestClient(url); var editRequest = new RestSharp.RestRequest(); editRequest.Method = RestSharp.Method.PUT; editRequest.RequestFormat = RestSharp.DataFormat.Json; editRequest.AddHeader("Content-Type", "application/json;charset=utf-8"); editRequest.AddHeader("Authorization", "Bearer " + ClaimsPrincipal.Current.IdToken()); editRequest.AddBody(user); var editResult = restClient.Execute(editRequest); }
public object PostRest(IConfiguration _config, string Method, string Inst, string Type, string entity, out string Error) { object obj = new object(); Error = string.Empty; try { var client = new RestSharp.RestClient(_config.GetConnectionString("UrlConnectEpicor") + Method + Inst); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("authorization", "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", _config["UserEpicor"], _config["PassEpicor"])))); request.AddHeader("content-type", "application/json"); request.AddParameter("application/json", entity, RestSharp.ParameterType.RequestBody); var response = client.Execute(request); if (response.StatusCode.ToString() != "OK") { Error = response.Content; } obj = JObject.Parse(response.Content).SelectToken(Type, false); } catch (Exception ex) { Error = ex.Message; } return(obj); }
public async Task <ScraperResponse> GetWebScraperResult(string url) { client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl")); RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-webscraper-func/WebScraperFunc", RestSharp.Method.POST); restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey")); restRequest.AddHeader("Content-Type", "application/json"); ScraperRequest requestObject = new ScraperRequest() { url = url }; restRequest.AddJsonBody(requestObject); try { var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false); return(JsonConvert.DeserializeObject <ScraperResponse>(response.Content)); } catch (Exception) { throw; } }
private void web1_Navigating(object sender, NavigatingCancelEventArgs e) { GTMAccessToken _gtmAccessToken = null; if (e.Uri.Query.ToLower().IndexOf("code") != -1 ) { //get the "code" from GTM string _code = e.Uri.Query.Replace("?code=", ""); e.Cancel = true; var _rc = new RestSharp.RestClient(@"https://api.citrixonline.com"); RestSharp.RestRequest _gtmTokenCodeReq = new RestSharp.RestRequest("/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id={api_key}", RestSharp.Method.GET); _gtmTokenCodeReq.AddUrlSegment("responseKey", _code); _gtmTokenCodeReq.AddUrlSegment("api_key", this.gtmAPIKey.Text); var _gtmTokenCodeResp = _rc.Execute(_gtmTokenCodeReq); if (_gtmTokenCodeResp.StatusCode == System.Net.HttpStatusCode.OK) { var jsonCode = _gtmTokenCodeResp.Content; _gtmAccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<GTMAccessToken>(jsonCode); } //now we have the token. Create a meeting var _gtmMeetingReq = new RestSharp.RestRequest(@"/G2M/rest/meetings", RestSharp.Method.POST); _gtmMeetingReq.AddHeader("Accept", "application/json"); _gtmMeetingReq.AddHeader("Content-type", "application/json"); _gtmMeetingReq.AddHeader("Authorization", string.Format("OAuth oauth_token={0}", _gtmAccessToken.access_token)); //creating the meeting request json for the request. Newtonsoft.Json.Linq.JObject _meetingRequestJson = new Newtonsoft.Json.Linq.JObject(); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("subject", "Immediate Meeting")); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("starttime", DateTime.UtcNow.AddSeconds(30).ToString("s"))); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("endtime", DateTime.UtcNow.AddHours(1).AddSeconds(30).ToString("s"))); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("passwordrequired", "false")); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("conferencecallinfo", "Hybrid")); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("timezonekey", "")); _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("meetingtype", "Immediate")); //converting the jobject back to string for use within the request string gtmJSON = Newtonsoft.Json.JsonConvert.SerializeObject(_meetingRequestJson); _gtmMeetingReq.AddParameter("text/json", gtmJSON, RestSharp.ParameterType.RequestBody); var _responseMeetingRequest = _rc.Execute(_gtmMeetingReq); if (_responseMeetingRequest.StatusCode == System.Net.HttpStatusCode.Created) { // meeting created to add a message, format it and add it to the list string _meetingResponseJson = _responseMeetingRequest.Content; Newtonsoft.Json.Linq.JArray _meetingResponse = Newtonsoft.Json.Linq.JArray.Parse(_meetingResponseJson); var _gtmMeetingObject = _meetingResponse[0]; MessageBox.Show(_gtmMeetingObject["joinURL"].ToString()); } } }
public async Task ReportMessage(Models.ReportDetails details) { client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl")); RestSharp.RestRequest restRequest = new RestSharp.RestRequest("we-fakenews-func/Insert", RestSharp.Method.POST); restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey")); restRequest.AddHeader("Content-Type", "application/json"); restRequest.AddJsonBody(details); await client.ExecuteAsync(restRequest).ConfigureAwait(false); }
public RestSharp.RestRequest CreateRequest(string resource, RestSharp.Method method) { var request = new RestSharp.RestRequest(resource, method); request.RequestFormat = RestSharp.DataFormat.Json; request.XmlSerializer.DateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; request.JsonSerializer.DateFormat = "yyyy-MM-ddTHH:mm:ss.fff"; request.AddHeader("apikey", GlobalConfiguration.Configuration.ApiKey); request.AddHeader("Accept", "application/json, text/json, text/x-json"); request.Timeout = 1000 * 30; return(request); }
public JsonResult TesteAPI() { var client = new RestSharp.RestClient("https://api-movida.loyaltysci.com/loyalty-api-external/webresources/v0/member/by-email/[email protected]"); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Postman-Token", "1032995c-606a-42ed-a687-1f3e50c87e60"); request.AddHeader("Cache-Control", "no-cache"); request.AddHeader("authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJIdktRbzJRaGg5cWQ2TWVmaHp4UWw1d1FTdEtaVlFWZGlhS0RnRC1GekswIn0.eyJqdGkiOiIxZWYzYTU3YS00MzE2LTQxYWYtYWQ3ZS0yY2RkMDZjNzc5MjMiLCJleHAiOjE1Mzc0MTM0NDgsIm5iZiI6MCwiaWF0IjoxNTM3Mzc3NDQ4LCJpc3MiOiJodHRwczovL2lkcC1tb3ZpZGEubG95YWx0eXNjaS5jb20vYXV0aC9yZWFsbXMvTG95YWx0eS1leHRlcm5vIiwiYXVkIjoibG95YWx0eS1hcGktZXh0ZXJuYWwiLCJzdWIiOiJhYWRkNDc4My0xM2FiLTRkOTgtYWJmOS0xOTg2Yzc0MzQzYzIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJsb3lhbHR5LWFwaS1leHRlcm5hbCIsImF1dGhfdGltZSI6MCwic2Vzc2lvbl9zdGF0ZSI6ImUzNTY1ZWUwLWU4YjYtNDdiMy05MTZmLTA0MGE3NzM4OTE0MiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiKiJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiY2xpZW50IiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJyZWFsbS1tYW5hZ2VtZW50Ijp7InJvbGVzIjpbInZpZXctaWRlbnRpdHktcHJvdmlkZXJzIiwidmlldy1yZWFsbSIsIm1hbmFnZS1pZGVudGl0eS1wcm92aWRlcnMiLCJpbXBlcnNvbmF0aW9uIiwicmVhbG0tYWRtaW4iLCJjcmVhdGUtY2xpZW50IiwibWFuYWdlLXVzZXJzIiwicXVlcnktcmVhbG1zIiwidmlldy1hdXRob3JpemF0aW9uIiwicXVlcnktY2xpZW50cyIsInF1ZXJ5LXVzZXJzIiwibWFuYWdlLWV2ZW50cyIsIm1hbmFnZS1yZWFsbSIsInZpZXctZXZlbnRzIiwidmlldy11c2VycyIsInZpZXctY2xpZW50cyIsIm1hbmFnZS1hdXRob3JpemF0aW9uIiwibWFuYWdlLWNsaWVudHMiLCJxdWVyeS1ncm91cHMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJ2aWV3LXByb2ZpbGUiXX19LCJjbGllbnRIb3N0IjoiMTg5LjIwMS4xOTYuMTQ1IiwiY2xpZW50SWQiOiJsb3lhbHR5LWFwaS1leHRlcm5hbCIsInByZWZlcnJlZF91c2VybmFtZSI6InNlcnZpY2UtYWNjb3VudC1sb3lhbHR5LWFwaS1leHRlcm5hbCIsImNsaWVudEFkZHJlc3MiOiIxODkuMjAxLjE5Ni4xNDUiLCJlbWFpbCI6InNlcnZpY2UtYWNjb3VudC1sb3lhbHR5LWFwaS1leHRlcm5hbEBwbGFjZWhvbGRlci5vcmcifQ.BVEf7Ve2zODBgEUyjWZg4PSefhNNJfowUM8-WkEPAnT_YRY7tKQkqRkVqpjW5eKHSzERBeWJeLhwNw6wmP34Cj23u_kQkjEX7rzKVhvCXUjuMsSY_Lny61npmmd0suqAXT5Jin03_h4ab7XvOtjb-2_LY4bRG1ZuPCuAei1wcWJ0hoCk3rD3-1sCbc1Wl_4b0DorygxbkWjbX-Nmrb5VXMtayHrdZazfk9pjocGzb7-0hZY8mCYrr3kErwd6EgNGAJm6l3PJLovAB1J4wYxgnK0btzYREXroAiryt59hvCHoK2AXKsFftgk5uvxPKG-HfnC-KG4VoT9tlcNTCROk8w"); RestSharp.IRestResponse response = client.Execute(request); return(Json(response.Content, JsonRequestBehavior.AllowGet)); }
public string ServisIslem(string url, string istekler, bool isLogin = false, string Method = "POST", string ContentType = "application/json") { RestSharp.Method GelenMethod = RestSharp.Method.POST; switch (Method) { case "POST": GelenMethod = RestSharp.Method.POST; break; case "PUT": GelenMethod = RestSharp.Method.PUT; break; case "DELETE": GelenMethod = RestSharp.Method.DELETE; break; default: break; } var client = new RestSharp.RestClient(kokurl + url); client.Timeout = -1; var request = new RestSharp.RestRequest(GelenMethod); request.AddHeader("Content-Type", ContentType); if (!isLogin) { request.AddHeader("Authorization", "Bearer " + GetApiToken()); } request.AddParameter(ContentType, istekler, RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { return(response.Content); } else { return("Hata"); } }
void OrnekCalismaTestDummy() { var icon = BitmapFactory.DecodeResource(Resources, Resource.Mipmap.aaestro); var ms = new MemoryStream(); icon.Compress(Bitmap.CompressFormat.Png, 0, ms); byte[] mediabyte = ms.ToArray(); var MeID = DataBase.MEMBER_DATA_GETIR()[0]; var client = new RestSharp.RestClient("http://31.169.67.210:8080/api/examples"); client.Timeout = -1; var request = new RestSharp.RestRequest(RestSharp.Method.POST); // request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"); request.AddHeader("Accept", "*/*"); //request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("Authorization", "Bearer " + MeID.API_TOKEN); request.AddParameter("text", "ddddddddd"); request.AddFile("afterImagePath", mediabyte, "sosi_media_file.png"); request.AddFile("beforeImagePath", mediabyte, "sosi_media_file1.png"); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { var jsonobj = response.Content; //var Icerik = Newtonsoft.Json.JsonConvert.DeserializeObject<MediaUploadDTO>(jsonobj.ToString()); //if (Icerik != null) //{ // return Icerik.beforeMediaPath; //} //else //{ // return ""; //} } else { //return ""; } }
public string OkuGetir(string url, bool DontUseHostURL = false, bool isLogin = false, bool UsePoll = false, bool DontUseSize = false) { if (UsePoll) { kokurl = "http://185.184.210.20:8080/services/pool/api/"; } RestSharp.RestClient client; if (DontUseHostURL) { client = new RestSharp.RestClient(url); } else { if (!DontUseSize) { client = new RestSharp.RestClient(kokurl + url + "?size=100000"); } else { client = new RestSharp.RestClient(kokurl + url); } } client.Timeout = -1; var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Content-Type", "application/json"); if (!isLogin) { request.AddHeader("Authorization", "Bearer " + GetApiToken()); // request.AddParameter("Bearer", DataBase.MEMBER_DATA_GETIR()[0].API_TOKEN,RestSharp.ParameterType.Cookie); } RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { return(response.Content); } else { return(null); } }
public static string PurchaseRefund() { var client = new RestSharp.RestClient( "https://lab.cardnet.com.do/servicios/tokens/v1/api/Purchase/12511/refund") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
public static string GetPurchaseList() { var client = new RestSharp.RestClient( "https://lab.cardnet.com.do/servicios/tokens/v1/api/Purchase?CustomerID=100&From=20180525&To=20191225&Authorize=false") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
string OnceLogoyuYule() { var MeID = DataBase.MEMBER_DATA_GETIR()[0]; var client = new RestSharp.RestClient("http://31.169.67.210:8080/api/template-medias"); client.Timeout = -1; byte[] mediabyte = ConvertImageToByte(((LogoFragment)fragments[3]).GetCompanyLogoPath()); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"); request.AddHeader("Accept", "*/*"); request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("Authorization", "Bearer " + MeID.API_TOKEN); request.AddParameter("mediaCount", 0); request.AddParameter("postText", ""); request.AddParameter("templateId", "0"); request.AddParameter("video", false); request.AddParameter("userId", MeID.id); request.AddParameter("processed", false); request.AddParameter("type", "POST"); request.AddFile("photo", mediabyte, "sosi_media_file.png"); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { var jsonobj = response.Content; var Icerik = Newtonsoft.Json.JsonConvert.DeserializeObject <MediaUploadDTO>(jsonobj.ToString()); if (Icerik != null) { return(Icerik.beforeMediaPath); } else { return(""); } } else { return(""); } }
void UploadWebService(MediaUploadDTO MediaUploadDTO1, byte[] mediabyte, YUKLENECEK_SABLON GuncellenecekSablon, int count) { string jsonString = JsonConvert.SerializeObject(MediaUploadDTO1); string uzanti = ".png"; if (MediaUploadDTO1.video) { uzanti = ".mp4"; } var client = new RestSharp.RestClient("http://31.169.67.210:8080/api/template-medias"); client.Timeout = -1; var request = new RestSharp.RestRequest(RestSharp.Method.POST); //request.Accept = "*/*"; //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"; //client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"; request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"); request.AddHeader("Accept", "*/*"); request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("Authorization", "Bearer " + MeId.API_TOKEN); request.AddParameter("mediaCount", MediaUploadDTO1.mediaCount); request.AddParameter("postText", MediaUploadDTO1.postText); request.AddParameter("templateId", MediaUploadDTO1.templateId); request.AddParameter("video", MediaUploadDTO1.video); request.AddParameter("userId", MeId.id); request.AddParameter("processed", false); request.AddParameter("type", "POST"); request.AddFile("photo", mediabyte, "sosi_media_file" + uzanti); RestSharp.IRestResponse response = client.Execute(request); if (response.StatusCode != HttpStatusCode.Unauthorized && response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.BadRequest && response.StatusCode != HttpStatusCode.Forbidden && response.StatusCode != HttpStatusCode.MethodNotAllowed && response.StatusCode != HttpStatusCode.NotAcceptable && response.StatusCode != HttpStatusCode.RequestTimeout && response.StatusCode != HttpStatusCode.NotFound) { GuncellenecekSablon.isUploaded = true; DataBase.YUKLENECEK_SABLON_Guncelle(GuncellenecekSablon); GleenBase2.RunOnUiThread(delegate() { MedyaUploadServiceDialogFragment1.UploadProgress(count + 1); }); } }
PagedResult <TVShow> ITVShowsStore.ListPopular(int page) { var client = new RestSharp.RestClient("https://api.themoviedb.org/3"); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestSharp.RestRequest("tv/popular"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; request.AddHeader("Accept", "application/json"); request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0"); request.AddParameter("language", "en"); request.AddParameter("page", page); request.JsonSerializer = new NewtonsoftJsonSerializer(); var response = client.ExecuteAsGet <PagedResult <TVShowResponse> >(request, "GET"); return(new PagedResult <TVShow> { Results = from showResponse in response.Data.Results select new TVShow { Id = showResponse.Id, Genres = String.Join(", ", from genreId in showResponse.GenreIds select GetGenreById(genreId).Name), Name = showResponse.Name, Overview = showResponse.Overview, PosterThumb = "https://image.tmdb.org/t/p/w92" + showResponse.PosterPath, PosterImage = "https://image.tmdb.org/t/p/w300" + showResponse.PosterPath, Popularity = showResponse.Popularity, VoteAverage = showResponse.VoteAverage }, TotalPages = response.Data.TotalPages, Page = response.Data.Page, TotalResults = response.Data.TotalResults }); }
public static string PaymentProfileDelete() { var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Customer/100/PaymentProfileDelete") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); request.AddParameter("application/json", "{ \"PaymentProfileId\": \"1915\"}", RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
string GetWeiXinToken(string originalId) { int platform = -1; Flatform.TryGetValue(originalId, out platform); var client = new RestSharp.RestClient(WeiXinApi); var request = new RestSharp.RestRequest("packet/test?platform=" + platform, RestSharp.Method.GET); request.AddHeader("access_token", "access_token"); var response = client.Execute(request); if (response.IsSuccessful) { try { var model = JsonConvert.DeserializeObject <WeixinApiResponse>(response.Content); if (model != null) { return(model.access_token); } } catch (Exception e) { Logger.Error("GetWeiXinToken", e); } } return(string.Empty); }
public IActionResult GetClientComputerName(string ip) { try { Config config = ConfigJSON.Read(); string url = "http://" + ip + ":" + config.ClientPort + "/POSClient/GetComputerName"; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Access-Control-Allow-Origin", "*"); RestSharp.IRestResponse response = client.Execute(request); string pcName = response.Content.Replace("\"", ""); int terminalId = 0; //check if terminal is assigned TerminalMapping terminalMapping = _context.TerminalMapping.FirstOrDefault(x => x.PCName == pcName); Terminal terminal = new Terminal(); if (terminalMapping != null) { terminal = _context.Terminal.FirstOrDefault(x => x.Id == terminalMapping.TerminalId); } return(Ok(new { pcName = pcName, terminalId = terminalMapping.TerminalId.ToString(), terminalName = terminal?.Name })); } catch (Exception ex) { return(StatusCode(500)); } }
/// <summary> /// Converts a REST request into a Restsharp request. /// </summary> protected RestSharp.IRestRequest ToRestSharpClient(IRestRequest request) { var rsRequest = new RestSharp.RestRequest(request.Resource, (RestSharp.Method)request.Method); if (request.Timeout.HasValue) { rsRequest.Timeout = request.Timeout.Value; } foreach (var header in request.Headers) { rsRequest.AddHeader(header.Name, header.Value); } if (request.Body.HasValue) { var contentTypes = new Dictionary <SerializerFormat, string> { { SerializerFormat.Json, "application/json" }, { SerializerFormat.Xml, "text/xml" }, }; rsRequest.AddParameter( contentTypes[request.Body.Value.Format], request.Body.Value.Content, RestSharp.ParameterType.RequestBody); } return(rsRequest); }
private string Upload(byte[] bytes, string fileName) { var campaignApiUrl = _siteSettingsService.GetSettingsOrDefault().CampaignApiUrl; var campaignAuthCode = _siteSettingsService.GetSettingsOrDefault().CampaignTransactionalAuthorizationCode; if (string.IsNullOrEmpty(campaignApiUrl) || string.IsNullOrEmpty(campaignAuthCode)) { Log.Error($"Error uploading file to Campaign. Campaign settings are missing."); return(null); } //using RestSharp for the assistance with the image post var restClient = new RestSharp.RestClient(campaignApiUrl.Trim('/')); var request = new RestSharp.RestRequest($"{campaignAuthCode.Trim()}/uploadpersonalizedattachments", RestSharp.Method.POST) { AlwaysMultipartFormData = true }; request.AddHeader("Content-Type", "multipart/form-data"); request.AddFile(MessageArgument.AttachmentFile.Value, bytes, fileName, System.Web.MimeMapping.GetMimeMapping(fileName)); var restResponse = restClient.Execute(request); if (!restResponse.Content.ToLower().StartsWith("ok")) { Log.Error($"Error uploading attachment to Campaign. Campaign message: {restResponse.Content}. Filename: {fileName}"); return(string.Empty); } return(restResponse.Content.Replace("ok:", "").Trim()); //return the attachment token value wich will be sent with a message as an additional argument }
private IDictionary <long, Genre> ListGenres() { var client = new RestSharp.RestClient("https://api.themoviedb.org/3"); IDictionary <long, Genre> dict = new Dictionary <long, Genre>(); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestSharp.RestRequest("genre/tv/list"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; request.AddHeader("Accept", "application/json"); request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0"); request.JsonSerializer = new NewtonsoftJsonSerializer(); var response = client.ExecuteAsGet <GenreResponse>(request, "GET"); response.Data.Genres.ForEach((Genre obj) => dict.Add(obj.Id, obj)); request = new RestSharp.RestRequest("genre/movie/list"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; request.AddHeader("Accept", "application/json"); request.AddParameter("api_key", "ad332258020257fb88e2cc468225dcb0"); request.JsonSerializer = new NewtonsoftJsonSerializer(); response = client.ExecuteAsGet <GenreResponse>(request, "GET"); response.Data.Genres.ForEach((Genre obj) => { if (!dict.ContainsKey(obj.Id)) { dict.Add(obj.Id, obj); } }); return(dict); }
public static async Task <string> GetTwitter([ActivityTrigger] string request, ILogger log) { client = new RestSharp.RestClient("https://we-factsearch-fa.azurewebsites.net"); RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/api/SearchTwitter", RestSharp.Method.POST); restRequest.AddHeader("Content-Type", "application/json"); Model.RootObject requestData = JsonConvert.DeserializeObject <Model.RootObject>(request); string query = string.Empty; foreach (var item in requestData.documents[0].keyPhrases) { query += item + " "; } Model.SearchQuery searchQuery = new Model.SearchQuery() { query = query }; restRequest.AddJsonBody(searchQuery); var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false); return(response.Content); }
private static User GetUser() { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Users/" + ClaimsPrincipal.Current.Id(); var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.GET; request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json;charset=utf-8"); request.AddHeader("Authorization", "Bearer " + ClaimsPrincipal.Current.Token()); var result = restClient.Execute(request); return JsonConvert.DeserializeObject<User>(result.Content); }
//[ResourceAuthorize(Resources.Actions.Manage, Resources.Users)] public ActionResult Edit(string userId, AccessRules[] access) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Users/" + userId; var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.PUT; request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json;charset=utf-8"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var securityAccess = new SecurityAccess(); if (access == null) access = new AccessRules[] { }; foreach (var rule in access) { securityAccess.AddRule(rule); } var user = GetUser(userId); user.Access = securityAccess; request.AddBody(user); var result = restClient.Execute(request); if (result.StatusCode == System.Net.HttpStatusCode.OK) { var identity = (User.Identity as ClaimsIdentity); var role = identity.Claims.SingleOrDefault(x => x.Type == "SecurityAccess"); if (role != null) identity.RemoveClaim(role); identity.AddClaim(new Claim("SecurityAccess", JsonConvert.SerializeObject(securityAccess, Formatting.Indented))); } return RedirectToAction("Edit"); }
//[ResourceAuthorize(Resources.Actions.Read, Resources.Users)] public ActionResult Index(int count = 0, int start = 0, string filter = null) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Users"; var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.GET; request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json;charset=utf-8"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var result = restClient.Execute<List<User>>(request); foreach (var user in result.Data) { GetUserInfo(user); } return View(result.Data); }
public List<WeatherPoint> GetMetwitWeather(decimal latitude, decimal longitude) { var request = new RestSharp.RestRequest("v2/weather", RestSharp.Method.GET); request.AddParameter("location_lat", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost); request.AddParameter("location_lng", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost); if (!string.IsNullOrEmpty(clientKey)) { request.AddHeader("Authorization", string.Format("Bearer {0}", clientKey)); } var response = restClient.Execute<WeatherResponse>(request); if (response != null && response.Data != null) { return response.Data.Objects; } else { return null; } }
public static async Task<string> ExecuteReport() { var sf_client = new Salesforce.Common.AuthenticationClient(); sf_client.ApiVersion = "v34.0"; await sf_client.UsernamePasswordAsync(consumerKey, consumerSecret, username, password + usertoken, url); string reportUrl = "/services/data/" + sf_client.ApiVersion + "/analytics/reports/" + reportId; var client = new RestSharp.RestClient(sf_client.InstanceUrl); var request = new RestSharp.RestRequest(reportUrl, RestSharp.Method.GET); request.AddHeader("Authorization", "Bearer " + sf_client.AccessToken); var restResponse = client.Execute(request); var reportData = restResponse.Content; return reportData; }
public ActionResult Index() { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Projects"; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } var projects = JsonConvert.DeserializeObject<List<string>>(response.Content); return View(projects); }
public ActionResult Applications(string projectName, string applicationName, string fileName, string config) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Jars/" + projectName + "/" + applicationName + "/" + fileName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); if (!string.IsNullOrWhiteSpace(config)) { try { var jar = JsonConvert.DeserializeObject<Jar>(config); var box = Box.Box.Mistranslate(jar); } catch (Exception) { var jar = new Jar(); jar.Name = applicationName; config = JsonConvert.SerializeObject(jar); } } else { var jar = new Jar(); jar.Name = applicationName; config = JsonConvert.SerializeObject(jar); } request.AddBody(config); var response = client.Execute(request); Elders.Pandora.Server.UI.ViewModels.User.GiveAccess(User, projectName, applicationName, "Defaults", Access.WriteAccess); return Redirect("/Projects/" + projectName + "/" + applicationName + "/Clusters"); }
private User GetUser(ClaimsIdentity args) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var claims = args.Claims; var userId = claims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value; string token = claims.Where(x => x.Type == "id_token").FirstOrDefault().Value; var url = hostName + "/api/Users/" + userId; var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.GET; request.AddHeader("Authorization", "Bearer " + token); var result = restClient.Execute(request); User user = null; if (string.IsNullOrWhiteSpace(result.Content) || result.Content.ToLowerInvariant() == "null") { user = new User(); user.Id = userId; user.Access = new SecurityAccess(); CreateUser(user, token); } else { user = JsonConvert.DeserializeObject<User>(result.Content); } return user; }
public ActionResult Update(string projectName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Projects/Update/" + projectName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } return RedirectToAction("Index"); }
private void GetUserInfo(User user) { var url = "https://www.googleapis.com/plus/v1/people/" + user.Id; var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.GET; request.AddHeader("Authorization", "Bearer " + User.AccessToken()); var result = restClient.Execute<GoogleUserInfo>(request); var info = result.Data; if (info != null) { user.AvatarUrl = info.Image.Url; user.FullName = info.DisplayName; user.FirstName = info.Name.GivenName; user.LastName = info.Name.FamilyName; if (info.Organizations != null) { var organization = info.Organizations.FirstOrDefault(x => x.Primay == true); if (organization == null) organization = info.Organizations.FirstOrDefault(); if (organization != null) user.Organization = organization.Name; } } }
public ActionResult OpenJson(string projectName, string applicationName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Jars/" + projectName + "/" + applicationName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); var config = JsonConvert.DeserializeObject<dynamic>(response.Content); return View("_ApplicationJsonView", model: JsonConvert.SerializeObject(config, Formatting.Indented)); }
private List<Jar> GetJars(string projectName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Jars/" + projectName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } return JsonConvert.DeserializeObject<List<Jar>>(response.Content); }
public FileResult DownloadJson(string projectName, string applicationName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Jars/" + projectName + "/" + applicationName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); string fileName = applicationName + ".json"; byte[] bytes = new byte[response.Content.Length * sizeof(char)]; Buffer.BlockCopy(response.Content.ToCharArray(), 0, bytes, 0, bytes.Length); return File(bytes, MimeMapping.GetMimeMapping(fileName), fileName); }
private void CreateUser(User user, string token) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var url = hostName + "/api/Users/" + user.Id; var restClient = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(); request.Method = RestSharp.Method.POST; request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json;charset=utf-8"); request.AddHeader("Authorization", "Bearer " + token); request.AddBody(user); restClient.Execute(request); }
protected RestSharp.IRestResponse Get(string url, IEnumerable<Header> headers) { RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(url); foreach (var h in headers) { request.AddHeader(h.Name, h.Value); } var response = client.Execute(request); return response; }
/// <summary> /// Terminate the running proxy. /// </summary> public void Exit() { try { var all = GetAll(); // If we get to here, the proxy is running; we need to bail out. RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(GetSimulationResource(), RestSharp.Method.DELETE); request.AddHeader("moksy-exit", "true"); var response = client.Execute(request); // The response will not return; the service will bail out. } catch (System.Net.WebException) { // The service is not running - return. return; } }
public ActionResult Index(string projectName, string applicationName) { var hostName = ApplicationConfiguration.Get("pandora_api_url"); var breadcrumbs = new List<KeyValuePair<string, string>>(); breadcrumbs.Add(new KeyValuePair<string, string>("Projects", "/Projects")); breadcrumbs.Add(new KeyValuePair<string, string>(projectName, "/Projects/" + projectName)); ViewBag.Breadcrumbs = breadcrumbs; var url = hostName + "/api/Jars/" + projectName + "/" + applicationName; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.RequestFormat = RestSharp.DataFormat.Json; request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Bearer " + User.IdToken()); var response = client.Execute(request); if (!string.IsNullOrWhiteSpace(response.ErrorMessage)) { throw response.ErrorException; } var config = JsonConvert.DeserializeObject<Configuration>(response.Content); return View(config); }