public HourlyWeatherResponse GetHourlyOpenWeatherMapWeather(decimal latitude, decimal longitude) { var request = new RestSharp.RestRequest("forecast", RestSharp.Method.GET); request.AddParameter("lat", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost); request.AddParameter("lon", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.GetOrPost); if (!string.IsNullOrEmpty(apiKey)) { //request.AddHeader("Authorization", string.Format("Bearer {0}", clientKey)); } var response = restClient.Execute<HourlyWeatherResponse>(request); if (response != null && response.Data != null) { return response.Data; } else { return null; } }
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; } }
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()); } } }
protected RestSharp.IRestResponse Delete(string url, string body, List<Header> headers) { if (headers == null) headers = new List<Header>(); RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(url, RestSharp.Method.DELETE); foreach (var header in headers) { request.AddParameter(header.Name, header.Value, RestSharp.ParameterType.HttpHeader); } request.AddBody(body); request.RequestFormat = RestSharp.DataFormat.Json; var response = client.Execute(request); return response; }
public RestSharp.IRestRequest ToRestRequest(string baseUrl, SDK.Http.IHttpRequest request) { var resourcePath = request.CanonicalUri.ToString().Replace(baseUrl, string.Empty); var method = this.ConvertMethod(request.Method); var restRequest = new RestSharp.RestRequest(resourcePath, method); restRequest.RequestFormat = RestSharp.DataFormat.Json; this.CopyHeaders(request.Headers, restRequest); if (request.HasBody) { restRequest.AddParameter(request.BodyContentType, request.Body, RestSharp.ParameterType.RequestBody); } return restRequest; }
//todo kick out RestSharp and make it truly async public static async Task<MangaResult> GetMangaQueryResultLink(string query) { try { RefreshAnilistToken(); var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); rq = new RestSharp.RestRequest("/manga/search/" + Uri.EscapeUriString(query)); rq.AddParameter("access_token", token); var smallObj = JArray.Parse(cl.Execute(rq).Content)[0]; rq = new RestSharp.RestRequest("manga/" + smallObj["id"]); rq.AddParameter("access_token", token); return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content)); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } }
public WeatherResponse GetForecastIOWeather(decimal latitude, decimal longitude, DateTime? time, string units, string[] excludes) { RestSharp.RestRequest request; if (time.HasValue) { request = new RestSharp.RestRequest("forecast/{apikey}/{latitude},{longitude},{time}", RestSharp.Method.GET); request.AddParameter("time", DateTimeToUnix(time.Value), RestSharp.ParameterType.UrlSegment); } else { request = new RestSharp.RestRequest("forecast/{apikey}/{latitude},{longitude}", RestSharp.Method.GET); } request.AddParameter("latitude", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.UrlSegment); request.AddParameter("longitude", longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), RestSharp.ParameterType.UrlSegment); request.AddParameter("apikey", _apiKey, RestSharp.ParameterType.UrlSegment); if (!string.IsNullOrEmpty(units)) { request.AddParameter("units", units, RestSharp.ParameterType.GetOrPost); } if (excludes != null && excludes.Length > 0) { request.AddParameter("exclude", string.Join(",", excludes), RestSharp.ParameterType.GetOrPost); } var response = _restClient.Execute<WeatherResponse>(request); return response.Data; }
public static async Task<AnimeResult> GetAnimeData(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); await RefreshAnilistToken(); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); var smallContent = ""; var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query)); rq.AddParameter("access_token", token); smallContent = cl.Execute(rq).Content; var smallObj = JArray.Parse(smallContent)[0]; rq = new RestSharp.RestRequest("/anime/" + smallObj["id"]); rq.AddParameter("access_token", token); var content = cl.Execute(rq).Content; return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content)); }
public WeatherData GetWorldWeatherOnlineWeather(decimal latitude, decimal longitude, int numberOfDays) { var request = new RestSharp.RestRequest("free/v1/weather.ashx", RestSharp.Method.GET); request.AddParameter("q", string.Format("{0},{1}", latitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo), longitude.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)), RestSharp.ParameterType.GetOrPost); request.AddParameter("format", "xml", RestSharp.ParameterType.GetOrPost); request.AddParameter("num_of_days", numberOfDays, RestSharp.ParameterType.GetOrPost); if (numberOfDays <= 0) { request.AddParameter("fx", "no", RestSharp.ParameterType.GetOrPost); } request.AddParameter("includeLocation", "yes", RestSharp.ParameterType.GetOrPost); request.AddParameter("key", clientKey, RestSharp.ParameterType.GetOrPost); var response = restClient.Execute<WeatherData>(request); if (response != null && response.Data != null) { return response.Data; } else { return null; } }
/// <summary> /// Add the given simulation to the running service. /// </summary> /// <param name="simulation">The simulation to add. Must not be null. </param> /// <returns>Created - the entry was added. Any other error indicates a failure. </returns> public HttpStatusCode Add(Simulation simulation) { if (null == simulation) throw new System.ArgumentNullException("simulation"); string path = string.Format("{0}", GetSimulationResource()); RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(path, RestSharp.Method.POST); request.AddParameter("application/json", JsonConvert.SerializeObject(simulation, JsonSerializerSettings), RestSharp.ParameterType.RequestBody); var response = client.Execute(request); return response.StatusCode; }
/// <summary> /// Delete the Simulation by name. This is case sensitive. /// </summary> /// <param name="name"></param> public HttpStatusCode DeleteByName(string name, bool removeImdb, bool retainSimulation) { string path = string.Format("{0}('{1}')", GetSimulationResource(), name); RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(path, RestSharp.Method.DELETE); if (removeImdb) { request.AddParameter("moksy-purgedata", "true", RestSharp.ParameterType.HttpHeader); } if (retainSimulation) { request.AddParameter("moksy-retainsimulation", retainSimulation.ToString(), RestSharp.ParameterType.HttpHeader); } var response = client.Execute(request); return response.StatusCode; }
public ILicenseResponse PerformAction(Consts.Action action, License license, RestSharp.Method httpMethod = RestSharp.Method.GET) { if (license == null) { throw new ArgumentNullException("license"); } if (action == Consts.Action.Unknown) { throw new ArgumentNullException("action"); } if (Configuration == null) { throw new NullReferenceException("Configuration property is null."); } if (string.IsNullOrWhiteSpace(Configuration.PostURL)) { throw new NullReferenceException("The PostURL of the specified configuration object is white space or null."); } if (action == Consts.Action.Create) { if (string.IsNullOrWhiteSpace(Configuration.SecretKey)) { throw new NullReferenceException("The SecretKey of the specified configuration object is an empty string or null."); } } if (action != Consts.Action.Create) { if (string.IsNullOrWhiteSpace(Configuration.ActivationKey)) { throw new NullReferenceException("the ActivationKey of the specified configuration object is white space or null."); } } var restClient = new RestSharp.RestClient(Configuration.PostURL); var restRequest = new RestSharp.RestRequest(); restRequest.Method = httpMethod; restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded"); if (action == Consts.Action.Unknown) { throw new UndefinedActionException("Undefined action."); } else { string description = Helper.DescriptionAttr <Consts.Action>(action); restRequest.AddParameter("slm_action", description); } switch (action) { case WordPressLicenseManagerNETClient.Consts.Action.Unknown: break; case WordPressLicenseManagerNETClient.Consts.Action.Activate: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add domain restRequest.AddParameter("registered_domain", license.RegisteredDomain); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Deactivate: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add domain restRequest.AddParameter("registered_domain", license.RegisteredDomain); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Check: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; case WordPressLicenseManagerNETClient.Consts.Action.Get: restRequest.AddParameter("secret_key", Configuration.ActivationKey); // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } break; case WordPressLicenseManagerNETClient.Consts.Action.Create: restRequest.AddParameter("secret_key", Configuration.SecretKey); restRequest.AddParameter("date_created", license.DateCreated.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_renewed", license.DateRenewed.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_expiry", license.DateExpired.ToString("yyyy-MM-dd")); // add license ID : update if provided, if not : create if (!string.IsNullOrWhiteSpace(license.Id)) { restRequest.AddParameter("id", license.Id); } // add product name if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } // add subscriber id if (string.IsNullOrWhiteSpace(license.SubscriberID) == false) { restRequest.AddParameter("subscr_id", license.SubscriberID); } // add mode if (string.IsNullOrWhiteSpace(license.Mode) == false) { restRequest.AddParameter("lic_mode", license.Mode); } // add software version if (string.IsNullOrWhiteSpace(license.Version) == false) { restRequest.AddParameter("version", license.Version); } // add ip address if (string.IsNullOrWhiteSpace(license.IpAddress) == false) { restRequest.AddParameter("ip_address", license.IpAddress); } // add registered domain if (string.IsNullOrWhiteSpace(license.RegisteredDomain) == false) { restRequest.AddParameter("registered_domain", license.RegisteredDomain); } // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } // add maximum number of domains allowed if (license.MaximumDomainAllowed >= 0) { restRequest.AddParameter("maximum_domained_allowed", license.MaximumDomainAllowed); } // add license key if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } else { throw new NewLicenseEmptyKeyException("Cannot create license with empty key."); } break; case WordPressLicenseManagerNETClient.Consts.Action.Update: restRequest.AddParameter("secret_key", Configuration.SecretKey); restRequest.AddParameter("date_created", license.DateCreated.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_renewed", license.DateRenewed.ToString("yyyy-MM-dd")); restRequest.AddParameter("date_expiry", license.DateExpired.ToString("yyyy-MM-dd")); // add license ID if (!string.IsNullOrWhiteSpace(license.Id)) { restRequest.AddParameter("id", license.Id); } // add product name if (string.IsNullOrWhiteSpace(license.ProductReference) == false) { restRequest.AddParameter("product_ref", license.ProductReference); } // add subscriber id if (string.IsNullOrWhiteSpace(license.SubscriberID) == false) { restRequest.AddParameter("subscr_id", license.SubscriberID); } // add mode if (string.IsNullOrWhiteSpace(license.Mode) == false) { restRequest.AddParameter("lic_mode", license.Mode); } // add software version if (string.IsNullOrWhiteSpace(license.Version) == false) { restRequest.AddParameter("version", license.Version); } // add ip address if (string.IsNullOrWhiteSpace(license.IpAddress) == false) { restRequest.AddParameter("ip_address", license.IpAddress); } // add registered domain if (string.IsNullOrWhiteSpace(license.RegisteredDomain) == false) { restRequest.AddParameter("registered_domain", license.RegisteredDomain); } // add first name if (string.IsNullOrWhiteSpace(license.FirstName) == false) { restRequest.AddParameter("first_name", license.FirstName); } // add last name if (string.IsNullOrWhiteSpace(license.LastName) == false) { restRequest.AddParameter("last_name", license.LastName); } // add company name if (string.IsNullOrWhiteSpace(license.CompanyName) == false) { restRequest.AddParameter("company_name", license.CompanyName); } // add email if (string.IsNullOrWhiteSpace(license.Email) == false) { restRequest.AddParameter("email", license.Email); } // add maximum number of domains allowed if (license.MaximumDomainAllowed >= 0) { restRequest.AddParameter("maximum_domained_allowed", license.MaximumDomainAllowed); } // add license key if (string.IsNullOrWhiteSpace(license.Key) == false) { restRequest.AddParameter("license_key", license.Key); } break; default: break; } var response = restClient.Execute(restRequest); var content = response.Content; var rootObject = new LicenseResponse(); if (response.StatusCode == HttpStatusCode.OK) { var responseRet = response.Content; // deserialize response var settings = new JsonSerializerSettings(); settings.MissingMemberHandling = MissingMemberHandling.Ignore; var format = "dd-MM-yyyy"; var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = format }; var converters = new List <JsonConverter>(); converters.Add(new AbstractConverter <LicenseResponse, ILicenseResponse>()); converters.Add(dateTimeConverter); settings.Converters = converters; var ret = JsonConvert.DeserializeObject(content, typeof(ILicenseResponse), settings) as ILicenseResponse; // update key property when checking license var concreteInstance = ret as LicenseResponse; concreteInstance.Raise(); return(concreteInstance as ILicenseResponse); } ; return(null); }
private void RefreshToken() { var cl = new RestSharp.RestClient("https://anilist.co/api"); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); rq.AddParameter("grant_type", "client_credentials"); rq.AddParameter("client_id", "kwoth-w0ki9"); rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"); token = JObject.Parse(cl.Execute(rq).Content)["access_token"].ToString(); }
public CommandResponse Hangup(string callId) { CommandResponse retVal = null; RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET); request.Resource = HANGUP_RESOURCE; request.AddParameter(HangupParams.CALL_ID, callId); try { RestSharp.RestResponse response = (RestSharp.RestResponse)restClient.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { retVal = JsonConvert.DeserializeObject<CommandResponse>(response.Content); } else { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = callId; retVal.status = -10; retVal.errorMsg = response.Content; } } catch (WebException exc) { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = callId; retVal.status = -20; retVal.errorMsg = exc.Message; } return retVal; }
/// <summary> /// Gets the best address for coordinates. /// </summary> /// <param name="coordinates">The coordinates.</param> /// <returns></returns> protected Address GetBestAddressForCoordinates(Coordinates coordinates) { Address address = GeoLookupCache.GetOrAdd(coordinates.ToString(), (key) => { var client = new RestSharp.RestClient("https://reverse.geocoder.api.here.com/6.2"); var req = new RestSharp.RestRequest("reversegeocode.json"); req.AddParameter("prox", coordinates.ToString()); req.AddParameter("mode", "retrieveAddresses"); req.AddParameter("maxresults", 1); req.AddParameter("app_id", Properties.Settings.Default.HereAppId); req.AddParameter("app_code", Properties.Settings.Default.HereAppCode); var resp = client.Execute <HereRestApi.ApiResponse <HereRestApi.LocationResult> >(req); lock ( GeoLookupCache ) { GeoLookupCount += 1; } if (!resp.Data.Response.View.Any() || !resp.Data.Response.View.First().Result.Any()) { return(new Address { Street1 = DataFaker.Address.StreetAddress(), City = DataFaker.Address.City(), State = DataFaker.Address.State(), County = DataFaker.Address.County(), PostalCode = DataFaker.Address.ZipCode(), Country = "US" }); } else { var location = resp.Data.Response.View.First().Result.First().Location; return(new Address { Street1 = $"{ location.Address.HouseNumber } { location.Address.Street }", City = location.Address.City, State = location.Address.State, County = location.Address.County, PostalCode = location.Address.PostalCode, Country = location.Address.Country.Substring(0, 2) }); } }); // // Save the cache every 100 lookups. That way, if there is a crash, we don't lose everything. // lock ( GeoLookupCache ) { if (GeoLookupCount > 100) { Support.SaveGeocodeCache(GeoLookupCache.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); GeoLookupCount = 0; } } return(address); }
string kokurl = "http://185.184.210.20:8080/api/";//main public string ServisIslem(string url, string istekler, bool isLogin = false, string Method = "POST", string ContentType = "application/json", bool UsePoll = false, bool localip = false, bool DontUseHostURL = false) { RestSharp.Method GelenMethod = RestSharp.Method.POST; if (UsePoll) { kokurl = "http://185.184.210.20:8080/services/pool/api/"; } if (localip) { kokurl = "http://192.168.1.38:8080/api/";//Lokal İP } 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; } RestSharp.RestClient client; client = new RestSharp.RestClient(kokurl + url); if (DontUseHostURL) { client = new RestSharp.RestClient(url); } client.Timeout = -1; var request = new RestSharp.RestRequest(GelenMethod); request.AddHeader("Content-Type", ContentType); if (!isLogin) { request.AddHeader("Authorization", "Bearer " + GetApiToken()); // request.AddParameter("Bearer", DataBase.MEMBER_DATA_GETIR()[0].API_TOKEN, RestSharp.ParameterType.Cookie); } 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"); } }
private static void CreateActivity(string token, string activityId, string nickname, string appId, string appAlias, string engine, string activityAlias) { Console.WriteLine($"Creating new activity, {activityId}."); var request = new RestSharp.RestRequest("/activities", RestSharp.Method.POST); request.AddHeader("Authorization", $"Bearer {token}"); request.AddHeader("Content-Type", "application/json"); var activity = new ActivityRequest() { Id = activityId, CommandLine = new[] { $"$(engine.path)\\\\revitcoreconsole.exe /i $(args[rvtFile].path) /al $(appbundles[{appId}].path)" }, Parameters = new ActivityParameters() { RvtFile = new Parameter() { Zip = false, OnDemand = false, Verb = "get", Description = "Input revit model.", Required = true, LocalName = "$(rvtFile)" }, Result = new Parameter() { Zip = false, OnDemand = false, Verb = "put", Description = "Results", Required = true, LocalName = "result.rvt" }, Execution = new Parameter() { Zip = true, OnDemand = false, Verb = "get", Description = " Hypar execution.", Required = true, LocalName = "execution.json" } }, Engine = engine, AppBundles = new[] { $"{nickname}.{appId}+{appAlias}" }, Description = "Convert Hypar Model to Revit." }; // RestSharp's serializer mangles the body. We need to send the pre-serialized body. var body = JsonConvert.SerializeObject(activity, Formatting.Indented); request.AddParameter("application/json", body, RestSharp.ParameterType.RequestBody); var response = _client.Execute(request); if (response.StatusCode == HttpStatusCode.Conflict) { Console.WriteLine($"The activity, {activityId}, already exists."); CreateNewActivityAlias(token, activityId, activityAlias, 1); } else if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine($"The activity, {activityId}, was created."); var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(response.Content); var version = Int32.Parse(data["version"].ToString()); CreateNewActivityAlias(token, activityId, activityAlias, version); } else { throw new Exception($"There was an error creating the activity: {response.StatusCode} - {response.Content}"); } }
/// <summary> /// Generate a call. /// </summary> /// <param name="destinationType">Type of destination can be one of the following: number – dial normal phone number, ip – dial to an external ip</param> /// <param name="destination">Destination number or ip destination</param> /// <param name="url">Url to send events to</param> /// <param name="appId">Application ID</param> /// <param name="fallbackUrl">Optional - Url to call in case ‘url’ fails</param> /// <param name="dialTimeout">Optional - Timeout for answer on this dial. Default: 30</param> /// <param name="callerIdNum">Optional - Caller ID number. Default: anonymous</param> /// <param name="callerIdName">Optional - Caller id name. Default: anonymous</param> /// <param name="delay">Optional - Delay in seconds before switch will originate the call. Default: none</param> /// <returns></returns> public CommandResponse Dial( eDialDestinationType destinationType, string destination, string url, int appId, string fallbackUrl, int?dialTimeout, string callerIdNum, string callerIdName, int?delay, string trunk, params CustomParam[] customParams) { RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET); request.Resource = DIAL_RESOURCE; request.AddParameter(DialParams.DEST_TYPE, destinationType.ToString()); request.AddParameter(DialParams.DEST, destination); url = Utils.AddCustomParamsToUrl(url, customParams); request.AddParameter(DialParams.URL, url); request.AddParameter(DialParams.APP_ID, appId); request.AddParameter(DialParams.TRUNK, trunk); if (!string.IsNullOrEmpty(fallbackUrl)) { fallbackUrl = Utils.AddCustomParamsToUrl(fallbackUrl, customParams); request.AddParameter(DialParams.FALLBACK_URL, fallbackUrl); } if (dialTimeout.HasValue) { request.AddParameter(DialParams.DIAL_TIMEOUT, dialTimeout.Value); } if (!string.IsNullOrEmpty(callerIdNum)) { request.AddParameter(DialParams.CALLER_ID_NUM, callerIdNum); } if (!string.IsNullOrEmpty(callerIdName)) { request.AddParameter(DialParams.CALLER_ID_NAME, callerIdName); } if (delay.HasValue) { request.AddParameter(DialParams.DELAY, delay.Value); } CommandResponse retVal = null; try { RestSharp.RestResponse response = (RestSharp.RestResponse)restClient.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { retVal = JsonConvert.DeserializeObject <CommandResponse>(response.Content); } else { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = null; retVal.errorMsg = response.Content; retVal.status = -10; } } catch (WebException exc) { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = null; retVal.errorMsg = exc.Message; retVal.status = -20; } return(retVal); }
private RestSharp.IRestRequest BuildRestSharpRequest(RestRequest restRequest) { var restSharpRequest = new RestSharp.RestRequest(restRequest.Resource); restSharpRequest.Method = (RestSharp.Method)Enum.Parse(typeof(RestSharp.Method), restRequest.Method.ToString()); restSharpRequest.RequestFormat = (RestSharp.DataFormat)Enum.Parse(typeof(RestSharp.DataFormat), restRequest.RequestFormat.ToString()); restSharpRequest.DateFormat = restRequest.DateFormat; //added by philip to force timeout within 15 seconds for connect restSharpRequest.Timeout = 15000; //TODO: solve this mapping //restSharpRequest.Credentials = restRequest.Credentials; if (restRequest.Body != null) { restSharpRequest.AddBody(restRequest.Body); } foreach (var item in restRequest.Cookies) { restSharpRequest.AddCookie(item.Key, item.Value); } foreach (var item in restRequest.Files) { if (!string.IsNullOrEmpty(item.Path)) { restSharpRequest.AddFile(item.Name, item.Path); } else { if (String.IsNullOrEmpty(item.ContentType)) { restSharpRequest.AddFile(item.Name, item.Bytes, item.FileName); } else { restSharpRequest.AddFile(item.Name, item.Bytes, item.FileName, item.ContentType); } } } foreach (var item in restRequest.Headers) { restSharpRequest.AddHeader(item.Key, item.Value); } foreach (var item in restRequest.UrlSegments) { restSharpRequest.AddUrlSegment(item.Key, item.Value); } foreach (var item in restRequest.Objects) { restSharpRequest.AddObject(item.Key, item.Value); } foreach (var item in restRequest.Parameters) { RestSharp.ParameterType t = (RestSharp.ParameterType)Enum.Parse(typeof(RestSharp.ParameterType), item.Type.ToString()); restSharpRequest.AddParameter( item.Name, item.Value, t ); } return(restSharpRequest); }
// Méthode qui va reporter les mails selectionnés public async void ReportSpams() { int reportsSent = 0; bool scanned = false; string hdrtest = ""; List<string> hdrReceived; Outlook.Explorer activeExplorer = this.Application.ActiveExplorer(); Outlook.Selection selection = activeExplorer.Selection; // Si il n'y a rien de selectionné... on n'a rien à faire if (selection.Count == 0) { MessageBox.Show("You have to select at least one message"); return; } foreach (object selected in selection) { scanned = false; Outlook.MailItem mailItem; // Il peut y avoir autre chose de seclectionné que des mails // donc si selected ce n'est pas un mailItem on ne le traite pas try { mailItem = (Outlook.MailItem)selected; } catch (InvalidCastException) { continue; } // new email Email mail = new Email(mailItem.Raw()); // check for Protecmail recieved header hdrReceived = mail.GetHeaders("received"); foreach(string hdrLine in hdrReceived) { int index = hdrLine.ToLower().IndexOf(".mxf.protecmail.com"); if (index > 0 ) { scanned = true; break; } } if (!scanned) { MessageBox.Show("Message with subject \"" + mail.GetHeader("subject") + "\" has not been scanned by Protecmail. If you think it should be, please contact our support: [email protected]", "Protecmail", MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } // white list hdrtest = mail.GetHeader("x-pm-wc"); if (hdrtest != "") { MessageBox.Show("Message with subject \"" + mail.GetHeader("subject") + "\" has been detected has spam but it's whitelisted by user. Checks your personals filter.", "Protecmail", MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } // not scanned hdrtest = mail.GetHeader("x-pm-scan"); if (hdrtest == "Not scanned. Disabled") { MessageBox.Show("Message with subject \"" + mail.GetHeader("subject") + "\" has not been scanned (disabled).", "Protecmail", MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } var request = new RestSharp.RestRequest("aj/report", RestSharp.Method.POST); request.AddParameter("text/plain", mail.Raw, RestSharp.ParameterType.RequestBody); //RestSharp.IRestResponse response = protecmailAPIClient.Execute(request); var response = await protecmailAPIClient.ExecuteTaskAsync(request); reportsSent++; } // retour client if (reportsSent == 1) { MessageBox.Show("Spam has been successfully reported to Protecmail"); } else if (reportsSent > 1) { MessageBox.Show("Spams has been successfully reported to Protecmail"); } }
/// <summary> /// Generate a call. /// </summary> /// <param name="destinationType">Type of destination can be one of the following: number – dial normal phone number, ip – dial to an external ip</param> /// <param name="destination">Destination number or ip destination</param> /// <param name="url">Url to send events to</param> /// <param name="appId">Application ID</param> /// <param name="fallbackUrl">Optional - Url to call in case ‘url’ fails</param> /// <param name="dialTimeout">Optional - Timeout for answer on this dial. Default: 30</param> /// <param name="callerIdNum">Optional - Caller ID number. Default: anonymous</param> /// <param name="callerIdName">Optional - Caller id name. Default: anonymous</param> /// <param name="delay">Optional - Delay in seconds before switch will originate the call. Default: none</param> /// <returns></returns> public CommandResponse Dial( eDialDestinationType destinationType, string destination, string url, int appId, string fallbackUrl, int? dialTimeout, string callerIdNum, string callerIdName, int? delay, string trunk, params CustomParam[] customParams) { RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET); request.Resource = DIAL_RESOURCE; request.AddParameter(DialParams.DEST_TYPE, destinationType.ToString()); request.AddParameter(DialParams.DEST, destination); url = Utils.AddCustomParamsToUrl(url, customParams); request.AddParameter(DialParams.URL, url); request.AddParameter(DialParams.APP_ID, appId); request.AddParameter(DialParams.TRUNK, trunk); if (!string.IsNullOrEmpty(fallbackUrl)) { fallbackUrl = Utils.AddCustomParamsToUrl(fallbackUrl, customParams); request.AddParameter(DialParams.FALLBACK_URL, fallbackUrl); } if (dialTimeout.HasValue) { request.AddParameter(DialParams.DIAL_TIMEOUT, dialTimeout.Value); } if (!string.IsNullOrEmpty(callerIdNum)) { request.AddParameter(DialParams.CALLER_ID_NUM, callerIdNum); } if (!string.IsNullOrEmpty(callerIdName)) { request.AddParameter(DialParams.CALLER_ID_NAME, callerIdName); } if (delay.HasValue) { request.AddParameter(DialParams.DELAY, delay.Value); } CommandResponse retVal = null; try { RestSharp.RestResponse response = (RestSharp.RestResponse)restClient.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { retVal = JsonConvert.DeserializeObject<CommandResponse>(response.Content); } else { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = null; retVal.errorMsg = response.Content; retVal.status = -10; } } catch (WebException exc) { //TODO: Add Log entry retVal = new CommandResponse(); retVal.callId = null; retVal.errorMsg = exc.Message; retVal.status = -20; } return retVal; }
/// <summary> /// 구매 확정을 위한 주문 내역 전송 /// </summary> /// <param name="aReceiptId"></param> /// <param name="aPurchaseList"></param> /// <returns></returns> public static DTOPurchasesResponse API_PostPurchaseSuccess(string aReceiptId, DTOPurchasesRequest aPurchasesRequest) { //================================================================================ // POST http://10.1.203.12:8080/api/caffe/purchases/purchase/receipt/{receipt_id} //================================================================================ //VOMenu menu = new VOMenu //{ // category = 100, // code = 1, // price = 1000, // type = "HOT", // size = "REGULAR", // count = 5 //}; //DTOPurchasesRequest obj = new DTOPurchasesRequest //{ // purchases = new List<VOMenu> // { // new VOMenu // { // category = 100, // code = 1, // price = 1000, // type = "HOT", // size = "REGULAR", // count = 5 // }, // new VOMenu // { // category = 200, // code = 8, // price = 1500, // type = "HOT", // size = "REGULAR", // count = 1 // }, // } //}; // //string json = JsonConvert.SerializeObject(aPurchasesRequest); RestSharp.RestClient client = new RestSharp.RestClient(URL_DCCAFFE); RestSharp.RestRequest request = new RestSharp.RestRequest(); request.AddHeader("Content-Type", "application/json;charset=UTF-8"); request.Method = RestSharp.Method.POST; request.RequestFormat = RestSharp.DataFormat.Json; request.Resource = URI_POST_PURCHASE; request.AddParameter("receipt_id", aReceiptId, RestSharp.ParameterType.UrlSegment); request.AddJsonBody(aPurchasesRequest); //---------------------------------------- var t1 = client.ExecuteTaskAsync(request); t1.Wait(); //---------------- // error handling if (t1.Result.ErrorException != null) { System.Diagnostics.Debug.WriteLine("[RESPONSE] " + t1.Result.Content); return(null); } string json = t1.Result.Content; //-------------- // debug output json = JsonFormatting(json); System.Diagnostics.Debug.WriteLine("[RESPONSE] " + json); //----------------------- // desirialized json data DTOPurchasesResponse dto = new DTOPurchasesResponse(); try { dto = JsonConvert.DeserializeObject <DTOPurchasesResponse>(json); dto.code = (int)t1.Result.StatusCode; } catch (Exception ex) { dto = null; System.Diagnostics.Debug.WriteLine("[ERROR] " + ex.Message); } return(dto); }
protected RestSharp.IRestResponse Put(string url, string json, IEnumerable<Header> headers) { RestSharp.IRestClient client = new RestSharp.RestClient(Root); RestSharp.IRestRequest request = new RestSharp.RestRequest(url, RestSharp.Method.PUT); request.AddParameter("application/json", json, RestSharp.ParameterType.RequestBody); foreach (var header in headers) { request.AddParameter(header.Name, header.Value, RestSharp.ParameterType.HttpHeader); } request.RequestFormat = RestSharp.DataFormat.Json; var response = client.Execute(request); return response; }
private async Task<AnimeResult> GetAnimeQueryResultLink(string query) { try { var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); RefreshAnilistToken(); rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query)); rq.AddParameter("access_token", token); var smallObj = JArray.Parse(cl.Execute(rq).Content)[0]; rq = new RestSharp.RestRequest("anime/" + smallObj["id"]); rq.AddParameter("access_token", token); return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content)); } catch (Exception) { return null; } }
private void RefreshAnilistToken() { try { var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); rq.AddParameter("grant_type", "client_credentials"); rq.AddParameter("client_id", "kwoth-w0ki9"); rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"); var exec = cl.Execute(rq); /* Console.WriteLine($"Server gave me content: { exec.Content }\n{ exec.ResponseStatus } -> {exec.ErrorMessage} "); Console.WriteLine($"Err exception: {exec.ErrorException}"); Console.WriteLine($"Inner: {exec.ErrorException.InnerException}"); */ token = JObject.Parse(exec.Content)["access_token"].ToString(); } catch (Exception ex) { Console.WriteLine($"Failed refreshing anilist token:\n {ex}"); } }
private static void RefreshAnilistToken() { try { var cl = new RestSharp.RestClient("http://anilist.co/api"); var rq = new RestSharp.RestRequest("/auth/access_token", RestSharp.Method.POST); rq.AddParameter("grant_type", "client_credentials"); rq.AddParameter("client_id", "kwoth-w0ki9"); rq.AddParameter("client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"); var exec = cl.Execute(rq); token = JObject.Parse(exec.Content)["access_token"].ToString(); } catch (Exception ex) { Console.WriteLine($"Failed refreshing anilist token:\n {ex}"); } }