public HammockHttpClient(Uri baseUri, string username, string password) { this.client = new RestClient { Authority = baseUri.ToString() }; client.AddHeader("Accept", "application/json"); client.AddHeader("Content-Type", "application/json; charset=utf-8"); client.ServicePoint = System.Net.ServicePointManager.FindServicePoint(baseUri); client.ServicePoint.SetTcpKeepAlive(true, 300, 30); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { var credentials = username + ":" + password; var base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); client.AddHeader("Authorization", "Basic " + base64Credentials); } client.RetryPolicy = new RetryPolicy { RetryConditions = { new Hammock.Retries.NetworkError(), new Hammock.Retries.Timeout(), new Hammock.Retries.ConnectionClosed() }, RetryCount = 3 }; client.BeforeRetry += new EventHandler<RetryEventArgs>(client_BeforeRetry); }
/// <summary> /// Initializes a new instance of the <see cref="Silanis.ESL.SDK.PackageService"/> class. /// </summary> /// <param name="apiToken">API token.</param> /// <param name="baseUrl">Base URL.</param> public PackageService (RestClient restClient, string baseUrl) { this.restClient = restClient; template = new UrlTemplate (baseUrl); settings = new JsonSerializerSettings (); settings.NullValueHandling = NullValueHandling.Ignore; }
/// <summary> /// Retrieves a new token from Webtrends auth service /// </summary> public string Execute() { var builder = new JWTBuilder(); var header = new JWTHeader { Type = "JWT", Algorithm = "HS256" }; var claimSet = new JWTClaimSet { Issuer = clientId, Principal = clientId, Audience = audience, Expiration = DateTime.Now.ToUniversalTime().AddSeconds(30), Scope = scope }; string assertion = builder.BuildAssertion(header, claimSet, clientSecret); var client = new RestClient(authUrl); var request = new RestRequest("token/", Method.POST); request.AddParameter("client_id", clientId); request.AddParameter("client_assertion", assertion); request.AddParameter("grant_type", "client_credentials"); request.AddParameter("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); var response = client.Execute(request).Content; return (string)JObject.Parse(response)["access_token"]; }
public void Can_Perform_GET_Async() { const string baseUrl = "http://localhost:8084/"; const string val = "Basic async test"; var resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl, Handlers.EchoValue(val))) { var client = new RestClient(baseUrl); var request = new RestRequest(""); IRestResponse response = null; client.ExecuteAsync(request, (resp, asyncHandle) => { response = resp; resetEvent.Set(); }); resetEvent.WaitOne(); Assert.NotNull(response.Content); Assert.Equal(val, response.Content); } }
private void GetTwitterToken() { var credentials = new OAuthCredentials { Type = OAuthType.RequestToken, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = Constants.ConsumerKey, ConsumerSecret = Constants.ConsumerKeySecret, Version = Constants.OAuthVersion, CallbackUrl = Constants.CallbackUri }; var client = new RestClient { Authority = "https://api.twitter.com/oauth", Credentials = credentials, HasElevatedPermissions = true, SilverlightAcceptEncodingHeader = "gizp", DecompressionMethods = DecompressionMethods.GZip, }; var request = new RestRequest { Path = "/request_token" }; client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted)); }
private static string RetrieveTweets(string sinceId) { BasicAuthCredentials credentials = new BasicAuthCredentials { Username = WebConfigurationManager.AppSettings["ScreenName"], Password = WebConfigurationManager.AppSettings["SuperTweetPassword"] }; RestClient client = new RestClient { Authority = "http://api.supertweet.net", VersionPath = "1" }; string possibleSinceId = string.IsNullOrWhiteSpace(sinceId) ? "": string.Format("&since_id={0}", sinceId) ; RestRequest request = new RestRequest { Credentials = credentials, Path = string.Format("statuses/home_timeline.json?count=200&include_entities=false{0}", possibleSinceId) }; RestResponse response = client.Request(request); var content = response.Content; return content; }
public static RestRequest DelegateWith(RestClient client, RestRequest request) { if(request == null) { throw new ArgumentNullException("request"); } if(!request.Method.HasValue) { throw new ArgumentException("Request must specify a web method."); } var method = request.Method.Value; var credentials = (OAuthCredentials)request.Credentials; var url = request.BuildEndpoint(client).ToString(); var workflow = new OAuthWorkflow(credentials); var uri = new Uri(client.Authority); var realm = uri.Host; var enableTrace = client.TraceEnabled || request.TraceEnabled; var info = workflow.BuildProtectedResourceInfo(method, request.GetAllHeaders(), url); var query = credentials.GetQueryFor(url, request, info, method, enableTrace); ((OAuthWebQuery) query).Realm = realm; var auth = query.GetAuthorizationContent(); var echo = new RestRequest(); echo.AddHeader("X-Auth-Service-Provider", url); echo.AddHeader("X-Verify-Credentials-Authorization", auth); return echo; }
public static void GetFriends(EventHandler<FriendsListEventArgs> callback) { var serializer = new Hammock.Serialization.HammockDataContractJsonSerializer(); RestClient client = new RestClient { Authority = baseUrl, Timeout = new TimeSpan(0, 0, 0, _timeOut), Serializer = serializer, Deserializer = serializer }; RestRequest request = new RestRequest { Path = "GetFriends" + "?timestamp=" + DateTime.Now.Ticks.ToString(), Timeout = new TimeSpan(0, 0, 0, _timeOut) }; friendscallback = callback; try { client.BeginRequest(request, new RestCallback<List<Friend>>(GetFriendsCallback)); } catch (Exception ex) { friendscallback.Invoke(null, new FriendsListEventArgs() { Friends = null, Error = new WebException("Communication Error!", ex) }); } }
public DropboxFileSystem (Session session) { this.session = session; sharedClient = new RestClient (session); UserId = session.UserIds.FirstOrDefault () ?? "Unknown"; FileExtensions = new System.Collections.ObjectModel.Collection<string> (); }
public ActionResult Index() { var restConfig = RestConfig.Current; if (string.IsNullOrEmpty(restConfig.UserId)) return RedirectToAction("Authorize"); var client = new RestClient {Authority = restConfig.BaseUrl}; var request = new RestRequest { Path = string.Format("users/{0}/queues/instant", restConfig.UserId), Credentials = OAuthCredentials.ForProtectedResource( restConfig.OAuthKey, restConfig.OAuthSharedSecret, restConfig.OAuthToken, restConfig.OAuthTokenSecret) }; var response = client.Request(request); if (response.StatusCode == HttpStatusCode.OK) { var xml = XDocument.Parse(response.Content); var items = from i in xml.Descendants("queue_item") select new Movie { Title = (string) i.Descendants("title").Attributes("regular").FirstOrDefault(), Thumbnail = (string)i.Descendants("box_art").Attributes("small").FirstOrDefault(), ReleaseYear = (string)i.Descendants("release_year").FirstOrDefault(), Link = (string)i.Descendants("link").Where(x => (string) x.Attribute("rel") == "alternate").Attributes("href").FirstOrDefault() }; var model = new {Response = response, Items = items}.ToExpando(); return View(model); } return View(new {Response = response, Items = (object) null}.ToExpando()); }
public ActionResult Details(string code) { RestClient<Product> productsRestClient = new RestClient<Product>("http://localhost:3001/"); var product = productsRestClient.Get("products/code/" + code).Result; // TODO: Fix this in EF product.Supplier = new Supplier { Id = product.SupplierId, Name = "My Supplier" }; var productViewModel = new ProductViewModel() { Id = product.Id, Code = product.Code, Name = product.DisplayName, Price = product.UnitPrice, SupplierName = product.Supplier.Name }; ProductViewModel another = Mapper.Map<ProductViewModel>(product); return View(another); }
public RestResponse GetFavorites(string user, int page, int pageSize) { // Documentation for GET /favorites // https://dev.twitter.com/docs/api/1/get/favorites // Create the REST Client var client = new RestClient {Authority = "http://api.twitter.com/1"}; // Create the REST Request var request = new RestRequest {Path = "favorites.json", Method = WebMethod.Get}; request.AddParameter("id", user); request.AddParameter("page", page.ToString()); request.AddParameter("count", pageSize.ToString()); // Set API authentication tokens var appSettings = ConfigurationManager.AppSettings; request.Credentials = OAuthCredentials.ForProtectedResource( appSettings["ConsumerKey"], appSettings["ConsumerSecret"], appSettings["Token"], appSettings["TokenSecret"]); // Make request var response = client.Request(request); return response; }
private void ApplicationBarIconButton_Click(object sender, EventArgs e) { RestClient client2 = new RestClient { Authority = "https://graph.facebook.com/", }; RestRequest request2 = new RestRequest { Path = "/me/feed?message=" + WatermarkTB.Text }; if (imgstream != null) { string albumId = (string)settings["facebook_photo"]; request2 = new RestRequest { Path = albumId + "/photos?message=" + WatermarkTB.Text }; request2.AddFile("photo", "image.jpg", imgstream); } request2.AddField("access_token", (string)settings["facebook_token"]); var callback = new RestCallback( (restRequest, restResponse, userState) => { // Callback when signalled } ); client2.BeginRequest(request2, callback); MessageBox.Show("Share successfully.", "Thanks", MessageBoxButton.OK); this.NavigationService.GoBack(); }
public void MultipartFormData_WithParameterAndFile() { const string baseUrl = "http://localhost:8888/"; using (SimpleServer.Create(baseUrl, EchoHandler)) { RestClient client = new RestClient(baseUrl); RestRequest request = new RestRequest("/", Method.POST) { AlwaysMultipartFormData = true }; DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetCurrentDirectory()) .Parent; if (directoryInfo != null) { string path = Path.Combine(directoryInfo.FullName, "Assets\\TestFile.txt"); request.AddFile("fileName", path); } request.AddParameter("controlName", "test", "application/json", ParameterType.RequestBody); IRestResponse response = client.Execute(request); Assert.AreEqual(this.expectedFileAndBodyRequestContent, response.Content); } }
public void Handles_Non_Existent_Domain() { var client = new RestClient("http://nonexistantdomainimguessing.org"); var request = new RestRequest("foo"); var response = client.Execute(request); Assert.Equal(ResponseStatus.Error, response.ResponseStatus); }
public TraktService(string client, string secret) { RestClient = new RestClient("https://api.trakt.tv"); this.Client = client; this.Secret = secret; }
public void fetchXml() { User = usernamBox.Text.Replace(" ", "").Replace("/", "").Replace(".", ""); URL = new Uri("http://" + User + ".tumblr.com/api/read/json"); int max = 0; var client = new RestClient(); client.Authority = URL.ToString(); var request = new RestRequest(); request.AddParameter("type", "photo"); request.AddParameter("num", "50"); request.AddParameter("filter", "text"); var r1 = client.Request(request); var t = r1.Content.ToString().Replace("var tumblr_api_read = ", ""); var firstResponse = JsonParser.FromJson(t); max = Convert.ToInt32(firstResponse["posts-total"]); // to eventually make each fetch a separate request for (int i = 0; i < max; i += 51) { if (i != 0) { request.AddParameter("start", i.ToString()); } var r2 = client.Request(request); var t2 = r2.Content.ToString().Replace("var tumblr_api_read = ", ""); var Response = JsonParser.FromJson(t2); getUrls(Response.ToDictionary(x => x.Key, x => x.Value)); } }
// throws Exception public int getNumberOfAvailableUpdates() { string jsonStr = new RestClient().getMethod(server, "/patches.json"); JSONArray updates = new JSONArray(jsonStr); return updates.Length(); }
public TwitterHelper() { _twitterSettings = Helper.LoadSetting<TwitterAccess>(Constants.TwitterAccess); if (_twitterSettings == null || String.IsNullOrEmpty(_twitterSettings.AccessToken) || String.IsNullOrEmpty(_twitterSettings.AccessTokenSecret)) { return; } _authorized = true; _credentials = new OAuthCredentials { Type = OAuthType.ProtectedResource, SignatureMethod = OAuthSignatureMethod.HmacSha1, ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, ConsumerKey = TwitterSettings.ConsumerKey, ConsumerSecret = TwitterSettings.ConsumerKeySecret, Token = _twitterSettings.AccessToken, TokenSecret = _twitterSettings.AccessTokenSecret, Version = TwitterSettings.OAuthVersion, }; _client = new RestClient { Authority = "http://api.twitter.com", HasElevatedPermissions = true }; }
public async Task TestMultipleRequests(Type factoryType) { using (var client = new RestClient("http://httpbin.org/") { HttpClientFactory = CreateClientFactory(factoryType, false), }) { { var request = new RestRequest("post", Method.POST); request.AddParameter("param1", "param1"); var response = await client.Execute<HttpBinResponse>(request); Assert.NotNull(response.Data); Assert.NotNull(response.Data.Form); Assert.True(response.Data.Form.ContainsKey("param1")); Assert.Equal("param1", response.Data.Form["param1"]); } { var request = new RestRequest("post", Method.POST); request.AddParameter("param1", "param1+"); var response = await client.Execute<HttpBinResponse>(request); Assert.NotNull(response.Data); Assert.NotNull(response.Data.Form); Assert.True(response.Data.Form.ContainsKey("param1")); Assert.Equal("param1+", response.Data.Form["param1"]); } } }
public void Handles_Server_Timeout_Error_Async() { const string baseUrl = "http://localhost:8888/"; ManualResetEvent resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl, TimeoutHandler)) { RestClient client = new RestClient(baseUrl); RestRequest request = new RestRequest("404") { Timeout = 500 }; IRestResponse response = null; client.ExecuteAsync(request, responseCb => { response = responseCb; resetEvent.Set(); }); resetEvent.WaitOne(); Assert.NotNull(response); Assert.AreEqual(response.ResponseStatus, ResponseStatus.TimedOut); Assert.NotNull(response.ErrorException); Assert.IsInstanceOf<WebException>(response.ErrorException); Assert.AreEqual(response.ErrorException.Message, "The request timed-out."); } }
private async Task Authenticate() { var client = new RestClient { BaseUrl = "https://datamarket.accesscontrol.windows.net", UserAgent = UserAgent, }; var request = new RestRequest("v2/OAuth2-13", HttpMethod.Post) { ContentType = ContentTypes.FormUrlEncoded, ReturnRawString = true, }; request.AddParameter("client_id", ClientId); request.AddParameter("client_secret", ClientSecret); request.AddParameter("scope", "http://music.xboxlive.com"); request.AddParameter("grant_type", "client_credentials"); var result = await client.ExecuteAsync<string>(request); TokenResponse = JsonConvert.DeserializeObject<TokenResult>(result); if (TokenResponse != null) { TokenResponse.TimeStamp = DateTime.Now; } }
public Uri BuildEndpoint(RestClient client) { var sb = new StringBuilder(); var path = Path.IsNullOrBlank() ? client.Path.IsNullOrBlank() ? "" : client.Path : Path; var versionPath = VersionPath.IsNullOrBlank() ? client.VersionPath.IsNullOrBlank() ? "" : client.VersionPath : VersionPath; var skipAuthority = client.Authority.IsNullOrBlank(); sb.Append(skipAuthority ? "" : client.Authority); sb.Append(skipAuthority ? "" : client.Authority.EndsWith("/") ? "" : "/"); sb.Append(skipAuthority ? "" : versionPath.IsNullOrBlank() ? "" : versionPath); if (!skipAuthority && !versionPath.IsNullOrBlank()) { sb.Append(versionPath.EndsWith("/") ? "" : "/"); } sb.Append(path.IsNullOrBlank() ? "" : path.StartsWith("/") ? path.Substring(1) : path); Uri uri; Uri.TryCreate(sb.ToString(), UriKind.RelativeOrAbsolute, out uri); // [DC]: If the path came in with parameters attached, we should scrub those WebParameterCollection parameters; uri = uri.UriMinusQuery(out parameters); foreach (var parameter in parameters) { Parameters.Add(parameter); } return uri; }
public PubMedPublicationIdsResult GetPublicationsIds(PubMedQueryFilter filter) { var restClient = new RestClient(ServiceURLs.ESearchBaseURL); var restRequest = new RestRequest(); restRequest.AddParameter("db", databaseName, ParameterType.QueryString); restRequest.AddParameter("retmode", "json", ParameterType.QueryString); restRequest.AddParameter("retstart", (filter.Skip * filter.Take), ParameterType.QueryString); restRequest.AddParameter("term", filter.Query, ParameterType.QueryString); restRequest.AddParameter("retmax", filter.Take, ParameterType.QueryString); if (filter.RelDate != DateTime.MinValue) { var pmDate = PubMedDateOperations.DatetimeToPubMedDate(filter.RelDate); restRequest.AddParameter("reldate", pmDate, ParameterType.QueryString); } var waitTime = PubMedThrottler.GetWaitTime(); Thread.Sleep(waitTime); var response = restClient.Execute<PubMedResponse>(restRequest).Result; if (response.Data == null) throw new Exception("No Response From The Server"); var result = new PubMedPublicationIdsResult(); result.PubMedIdCollection = new List<string>(); response.Data.esearchresult.idlist.ForEach(r => result.PubMedIdCollection.Add(r)); return result; }
public void Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler() { const string baseUrl = "http://localhost:8080/"; const string ExceptionMessage = "Thrown from OnBeforeDeserialization"; using (SimpleServer.Create(baseUrl, Handlers.Generic<ResponseHandler>())) { var client = new RestClient(baseUrl); var request = new RestRequest("success"); request.OnBeforeDeserialization += response => { throw new Exception(ExceptionMessage); }; var task = client.ExecuteTaskAsync<Response>(request); try { // In the broken version of the code, an exception thrown in OnBeforeDeserialization causes the task to // never complete. In order to test that condition, we'll wait for 5 seconds for the task to complete. // Since we're connecting to a local server, if the task hasn't completed in 5 seconds, it's safe to assume // that it will never complete. Assert.True(task.Wait(TimeSpan.FromSeconds(5)), "It looks like the async task is stuck and is never going to complete."); } catch (AggregateException e) { Assert.Equal(1, e.InnerExceptions.Count); Assert.Equal(ExceptionMessage, e.InnerExceptions.First().Message); return; } Assert.True(false, "The exception thrown from OnBeforeDeserialization should have bubbled up."); } }
public string BuildEndpoint(RestClient client) { var sb = new StringBuilder(); var path = Path.IsNullOrBlank() ? client.Path.IsNullOrBlank() ? "" : client.Path : Path; var versionPath = VersionPath.IsNullOrBlank() ? client.VersionPath.IsNullOrBlank() ? "" : client.VersionPath : VersionPath; var skipAuthority = client.Authority.IsNullOrBlank(); sb.Append(skipAuthority ? "" : client.Authority); sb.Append(skipAuthority ? "" : client.Authority.EndsWith("/") ? "" : "/"); sb.Append(skipAuthority ? "" : versionPath.IsNullOrBlank() ? "" : versionPath); if (!skipAuthority && !versionPath.IsNullOrBlank()) { sb.Append(versionPath.EndsWith("/") ? "" : "/"); } sb.Append(path.IsNullOrBlank() ? "" : path.StartsWith("/") ? path.Substring(1) : path); var queryStringHandling = QueryHandling ?? client.QueryHandling ?? Hammock.QueryHandling.None; switch (queryStringHandling) { case Hammock.QueryHandling.AppendToParameters: return WebExtensions.UriMinusQuery(sb.ToString(), Parameters); default: return sb.ToString(); } }
public IRestClient CreateClient() { var client = new RestClient(); client.HttpClientFactory = this.GetHttpClientFactory(); client.IgnoreResponseStatusCode = true; return client; }
public void Handles_GET_Request_404_Error() { var client = new RestClient(BaseUrl); var request = new RestRequest("StatusCode/404"); var response = client.Execute(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public void Handles_Default_Root_Element_On_No_Error() { Uri baseUrl = new Uri("http://localhost:8888/"); using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.Generic<ResponseHandler>())) { RestClient client = new RestClient(baseUrl); RestRequest request = new RestRequest("success") { RootElement = "Success" }; request.OnBeforeDeserialization = resp => { if (resp.StatusCode == HttpStatusCode.NotFound) { request.RootElement = "Error"; } }; IRestResponse<Response> response = client.Execute<Response>(request); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("Works!", response.Data.Message); } }
public void Writes_Response_To_Stream() { const string baseUrl = "http://localhost:8888/"; using (SimpleServer.Create(baseUrl, Handlers.FileHandler)) { string tempFile = Path.GetTempFileName(); using (var writer = File.OpenWrite(tempFile)) { var client = new RestClient(baseUrl); var request = new RestRequest("Assets/Koala.jpg"); request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer); var response = client.DownloadData(request); Assert.Null(response); } var fromTemp = File.ReadAllBytes(tempFile); var expected = File.ReadAllBytes(Environment.CurrentDirectory + "\\Assets\\Koala.jpg"); Assert.Equal(expected, fromTemp); } }
public SOQueryFacade() { restClient = new RestClient(serviceBaseUrl); }
public void toUpdate_Click(object sender, EventArgs e) { try { string user_id = searchCatName.Text; int id = Convert.ToInt16(user_id); string name = Login.log; string pas = Login.pass; string url = Login.url; string resName = Login.resource; var client = new RestClient(url) { Authenticator = new HttpBasicAuthenticator(name, pas) }; var request = new RestRequest("/{resource}/{id}", Method.GET) { RequestFormat = DataFormat.Json }; request.AddUrlSegment("resource", resName); request.AddUrlSegment("id", id); var execute = client.Execute(request); IRestResponse response = execute; HttpStatusCode statusCode = response.StatusCode; var content = execute.Content; if (response.IsSuccessful == true) { content = JToken.Parse(content).ToString(Formatting.Indented); JObject json = JObject.Parse(content); var update_ok = new UPDATE_OK(); update_ok.currentIdLabel.Text = user_id; update_ok.contentTextBox.Text = content; update_ok.Show(); Close(); } else if (statusCode == HttpStatusCode.BadRequest) { MessageBox.Show("Bad request exception." + "\nFill NAME,PARENT ID and ORDERING ID at least to update category.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if ((int)statusCode == 401) { MessageBox.Show("Authorization error. Go back to LOGin window and enter proper login and password.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if ((int)statusCode == 404) { MessageBox.Show("Bad request error.Check if this id exist.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Error occured.\nError code: " + (int)statusCode); } } catch (FormatException) { MessageBox.Show("Put integer number(id) you want to see or CLOSE update window.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (JsonReaderException) { MessageBox.Show("Chech URL you put while logging in.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static IAuthenticated Authenticate(RestClient restClient, string tenantId) { return(CreateAuthenticated(restClient, tenantId)); }
private static Authenticated CreateAuthenticated(RestClient restClient, string tenantId) { return(new Authenticated(restClient, tenantId)); }
/// <summary> /// Create filter and fetch record from rest client api /// </summary> /// <param name="search"></param> /// <returns></returns> public BeerList FetchBeerList(SearchGrid search) { try { StringBuilder sbQuery = new StringBuilder(); sbQuery.Append("&sort=" + search.sord.ToUpper()); sbQuery.Append("&order=" + search.sidx); sbQuery.Append("&p=" + search.page); if (search.filters != null && search.filters != "") { var filterresult = JsonConvert.DeserializeObject <Class.Filter>(search.filters); foreach (var rule in filterresult.rules) { if (rule.field == "name") { sbQuery.Append("&name=" + rule.data); } if (rule.field == "description") { sbQuery.Append("&description=" + rule.data); } if (rule.field == "description") { sbQuery.Append("&abv=" + rule.data); } if (rule.field == "abv") { sbQuery.Append("&abv=" + rule.data); } if (rule.field == "ibu") { sbQuery.Append("&ibu=" + rule.data); } if (rule.field == "glasswareId") { sbQuery.Append("&glasswareId=" + rule.data); } if (rule.field == "srmId") { sbQuery.Append("&srmId=" + rule.data); } if (rule.field == "availableId") { sbQuery.Append("&availableId=" + rule.data); } if (rule.field == "styleId") { sbQuery.Append("&styleId=" + rule.data); } if (rule.field == "isOrganic") { sbQuery.Append("&isOrganic=" + rule.data); } if (rule.field == "status") { sbQuery.Append("&status=" + rule.data); } if (rule.field == "createDate") { sbQuery.Append("&createDate=" + rule.data); } if (rule.field == "updateDate") { sbQuery.Append("&updateDate=" + rule.data); } if (rule.field == "random") { sbQuery.Append("&random=" + rule.data); } } } BeerList obj = new BeerList(); RestClient rc = new RestClient(); obj = rc.getResultBeerList(sbQuery.ToString()); return(obj); } catch (Exception ex) { throw ex; } }
public ProductResponse RetrieveProduct(long id) { var path = "/craftlink/v1/products/" + id; return RestClient.Get<ProductResponse>(RequestOptions.BaseUrl + path, CreateHeaders(path, RequestOptions)); }
private async Task <ApiResponse <T> > Exec <T>(RestRequest req, IReadableConfiguration configuration) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler(existingDeserializer, "application/json", "text/json", "text/x-json", "text/javascript", "*+json"); } else { var codec = new CustomJsonCodec(configuration); client.AddHandler(codec, "application/json", "text/json", "text/x-json", "text/javascript", "*+json"); } client.AddHandler(new XmlDeserializer(), "application/xml", "text/xml", "*+xml", "*"); client.Timeout = configuration.Timeout; if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } InterceptRequest(req); var response = await client.ExecuteTaskAsync <T>(req); InterceptResponse(req, response); var result = toApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) { result.Cookies = new List <Cookie>(); } foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return(result); }
public Weather(string station) { client = new RestClient("https://api.weather.gov"); this.station = station; }
public void sendUpdateSMS(SimulTrips trip, string actualStartTime) { string message = "START " + trip.route_id.Substring(3, trip.route_id.Length - 3); if (trip.direction_id == 0) { if (trip.route_id == "ROULRT2") { message += " EB"; } else { message += " NB"; } } else { if (trip.route_id == "ROULRT2") { message += " WB"; } else { message += " SB"; } } message += " " + trip.start_time.ToString(@"hhmm"); message += actualStartTime; _inboundSMSMessage sms = new _inboundSMSMessage(); sms.dateTime = "Fri Nov 22 2013 12:12:13 GMT+0000 (UTC)"; sms.message = message; sms.destinationAddress = ""; sms.senderAddress = "tel:+639170000000"; List <_inboundSMSMessage> smss = new List <_inboundSMSMessage>(); smss.Add(sms); _inboundSMSMessageList smsList = new _inboundSMSMessageList(); smsList.inboundSMSMessage = smss; smsList.numberOfMessagesInThisBatch = "1"; globe_sms_mo sms_mo = new globe_sms_mo(); sms_mo.inboundSMSMessageList = smsList; string jsonData = JsonConvert.SerializeObject(sms_mo); var client = new RestClient("https://komyutersms.azurewebsites.net/api/SMSIncoming"); //var client = new RestClient("https://localhost:44358/api/SMSIncoming"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", jsonData, ParameterType.RequestBody); IRestResponse response = client.Execute(request); }
public Index(Restapi.Glip.Chats.Index parent) { this.parent = parent; this.rc = parent.rc; }
public MetadataService() { _client = new RestClient(Environment.GetEnvironmentVariable("URL_INTERNAL_METADATA")); _cache = new CacheServices(); }
public LcContent() { restClient = new RestClient("https://api.github.com"); pagesOwnerRepo = ConfigurationManager.AppSettings["pagesOwnerRepo"]; }
public SOQueryFacade(IPage page) { restClient = new RestClient(serviceBaseUrl, page); }
public APIRestClient() { client = new RestClient(); client.UseSystemTextJson(); }
public void import() { string filePath = openFileDialog1.FileName; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath); Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange; List <Excel> listEx = new List <Excel>(); int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; for (int i = 2; i <= rowCount; i++) { Excel excel = new Excel(); if (xlRange.Cells[i, 2].Value2 == null) { excel.Title = ""; } else { excel.Title = xlRange.Cells[i, 2].Value2.ToString(); } if (xlRange.Cells[i, 3].Value2 == null) { excel.DocumentType = ""; } else { excel.DocumentType = xlRange.Cells[i, 3].Value2.ToString(); } if (xlRange.Cells[i, 4].Value2 == null) { excel.LocationID = ""; } else { excel.LocationID = xlRange.Cells[i, 4].Value2.ToString(); } if (xlRange.Cells[i, 5].Value2 == null) { excel.Creator = ""; } else { excel.Creator = xlRange.Cells[i, 5].Value2.ToString(); } if (xlRange.Cells[i, 6].Value2 == null) { excel.Date = ""; } else { excel.Date = xlRange.Cells[i, 6].Value2.ToString(); } if (xlRange.Cells[i, 7].Value2 == null) { excel.Description = ""; } else { excel.Description = xlRange.Cells[i, 7].Value2.ToString(); } listEx.Add(excel); } var client = new RestClient("https://api.kho.dulieutnmt.vn:8443/api/v1.0/document/"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", listEx, ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); }
public APIRestClient(string url) { client = new RestClient(url); client.UseSystemTextJson(); }
public void SetUpServiceObject() { Client = CreateClient.GetNewClient(BASE_URL); }
private async Task HourlyMessage() { var time = DateTime.UtcNow.AddHours(-3); if (time.Minute != 0) { return; } if (time.Hour == 0) { this._audioService.PlaySoundByNameOnAllMostPopulatedAudioChannels("meianoite").CAwait(); return; } foreach (var guild in this._discord.Guilds) { try { string title = time.ToString("h tt", CultureInfo.InvariantCulture); string msg = null; switch (time.Hour) { case 0: title = "Meia noite, vão dormi"; msg = $"Horário oficial do óleo de macaco"; break; case 12: title = "Meio dia"; msg = $"Hora de comer *nhon nhon nhon*"; break; } var json = await JsonCache.LoadValueAsync($"GuildSettings/{guild.Id}", "channelHourlyMessage"); if (json == null) { continue; } var channel = guild.GetTextChannel(Convert.ToUInt64(json.Value)); if (channel == null) { continue; } if (channel.CachedMessages.Count <= 0) { return; } var lastUserMsg = channel.CachedMessages.OrderBy(m => m.Timestamp).Last() as IUserMessage; bool lastMsgIsFromThisBot = lastUserMsg != null && lastUserMsg.Author.Id == this._discord.CurrentUser.Id; // motivation phrase if (string.IsNullOrEmpty(msg)) { msg = await this.GetRandomMotivationPhrase(); } msg = string.IsNullOrEmpty(msg) ? "Hora agora" : $"*\"{msg}\"*"; var embed = new EmbedBuilder { Title = title, Description = msg }; RestUserMessage msgSend = null; if (lastMsgIsFromThisBot) { if (lastUserMsg.MentionedUserIds.Count <= 0) { await lastUserMsg.ModifyAsync(p => p.Embed = embed.Build() ); } } else { msgSend = await channel.SendMessageAsync(string.Empty, false, embed.Build()); } // get random photo try { var client = new RestClient("https://picsum.photos/96"); var request = new RestRequest(Method.GET); var timeline = await client.ExecuteAsync(request); if (!string.IsNullOrEmpty(timeline.ResponseUri.OriginalString)) { embed.ThumbnailUrl = timeline.ResponseUri.OriginalString; await msgSend.ModifyAsync(p => p.Embed = embed.Build()); } } catch (Exception e) { await this._log.Error(e.ToString()); } } catch (Exception e) { await this._log.Error(e.ToString()); continue; } } }
public JiraClient(RestClient client) { Client = client; }
public JiraClient(String url) { Client = new RestClient(url); }
public GraphQLClient(string GraphQLApiUrl, Form1 f1) { _client = new RestClient(GraphQLApiUrl); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; }
/// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> public ApiClient() { Configuration = Onboard.Api.Client.CSharp.Client.Configuration.Default; RestClient = new RestClient("https://solab.azure-api.net/onboard"); RestClient.IgnoreResponseStatusCode = true; }
static void Main() { Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; string StartTime = DateTime.Now.ToString("MM.dd.yyyy H.mm"); if (File.Exists("./Proxies.txt")) { if (!Directory.Exists("Old")) { Directory.CreateDirectory("Old"); } Directory.CreateDirectory($"./Old/{StartTime}"); try { File.Move("./Proxies.txt", $"./Old/{StartTime}/Proxies.txt"); } catch { File.Delete("./Proxies.txt"); } } Console.WriteLine("Scraping Proxies from free-proxy-list.net"); var client1 = new RestClient("https://free-proxy-list.net/anonymous-proxy.html"); var request1 = new RestRequest(Method.GET); request1.AddCookie("__cfduid", "ddf3400da018be098cb3feaa97f6d5cd31594606537"); IRestResponse response1 = client1.Execute(request1); string response1String = response1.Content; MatchCollection matches1 = Regex.Matches(response1String, "(?<=\n)([0-9].*?)(?=\n)"); foreach (Match match in matches1) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches1.Count} proxies from free-proxy-list.net"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from spys.me"); var client2 = new RestClient("http://spys.me/proxy.txt"); var request2 = new RestRequest(Method.GET); IRestResponse response2 = client2.Execute(request2); string response2String = response2.Content; MatchCollection matches2 = Regex.Matches(response2String, "(?<=\n)([0-9].*?)(?= )"); foreach (Match match in matches2) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches2.Count} proxies from spys.me"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from proxy-daily.com"); var client3 = new RestClient("https://proxy-daily.com/"); var request3 = new RestRequest(Method.GET); request3.AddCookie("__cfduid", "d9c1055d453083cff27ce1e2ea5540a901594610222"); IRestResponse response3 = client3.Execute(request3); string response3String = response3.Content; MatchCollection matches3 = Regex.Matches(response3String, "(?<=\n)([0-9].*?)(?=\n)"); foreach (Match match in matches3) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches3.Count} proxies from proxy-daily.com"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from checkerproxy.net"); string urlDate = DateTime.Today.ToString("yyyy-MM-dd"); var client4 = new RestClient($"https://checkerproxy.net/api/archive/{urlDate}"); var request4 = new RestRequest(Method.GET); request4.AddCookie("__cfduid", "de8719ba619e8722ea01c3a398372d8a61594610838"); IRestResponse response4 = client4.Execute(request4); string response4String = response4.Content; MatchCollection matches4 = Regex.Matches(response4String, "(?<=\"addr\":\")([0-9].*?)(?=\")"); foreach (Match match in matches4) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches4.Count} proxies from checkerproxy.net"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from sslproxies.org"); var client5 = new RestClient("https://www.sslproxies.org/"); var request5 = new RestRequest(Method.GET); request5.AddCookie("__cfduid", "ddf3400da018be098cb3feaa97f6d5cd31594606537"); IRestResponse response5 = client5.Execute(request5); string response5String = response5.Content; MatchCollection matches5 = Regex.Matches(response5String, "(?<=\n)([0-9].*?)(?=\n)"); foreach (Match match in matches5) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches5.Count} proxies from sslproxies.org"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from socks-proxy.net"); var client6 = new RestClient("https://socks-proxy.net/"); var request6 = new RestRequest(Method.GET); request6.AddCookie("__cfduid", "ddf3400da018be098cb3feaa97f6d5cd31594606537"); IRestResponse response6 = client6.Execute(request6); string response6String = response6.Content; MatchCollection matches6 = Regex.Matches(response6String, "(?<=\n)([0-9].*?)(?=\n)"); foreach (Match match in matches6) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches6.Count} proxies from socks-proxy.net"); Thread.Sleep(400); for (int i = 1; i < 11; i++) { Console.WriteLine($"Scraping Proxies from proxy-list.org, page {i}"); var client7 = new RestClient($"https://proxy-list.org/english/index.php?p={i}"); var request7 = new RestRequest(Method.GET); request7.AddCookie("__cfduid", "ddf3400da018be098cb3feaa97f7d5cd31594707537"); IRestResponse response7 = client7.Execute(request7); string response7String = response7.Content; MatchCollection matches7 = Regex.Matches(response7String, @"(?<=text/javascript\"">Proxy\(')(.*?)(?=')"); foreach (Match match in matches7) { string matchDecoded = Base64Decode(match.Value); writeToText(matchDecoded); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches7.Count} proxies from proxy-list.org, page {i}"); Thread.Sleep(400); } Console.WriteLine("Scraping Proxies from 89ip.cn"); var client8 = new RestClient("http://www.89ip.cn/tqdl.html?num=9999&address=&kill_address=&port=&kill_port=&isp="); var request8 = new RestRequest(Method.GET); request8.AddCookie("waf_cookie", "8b129353-25dd-4dfe06bdf3efa6ba2421869d8a83de34e5af"); IRestResponse response8 = client8.Execute(request8); string response8String = response8.Content; MatchCollection matches8 = Regex.Matches(response8String, "(?<=<br>)([0-9].*?)(?=<br>)"); foreach (Match match in matches8) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches8.Count} proxies from 89ip.cn"); Thread.Sleep(400); Console.WriteLine("Scraping Proxies from proxyscrape.com"); var client9 = new RestClient("https://api.proxyscrape.com/?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all"); var request9 = new RestRequest(Method.GET); IRestResponse response9 = client9.Execute(request9); string response9String = response9.Content; MatchCollection matches9 = Regex.Matches(response9String, "(?<=\n)([0-9].*?)(?=\n)"); foreach (Match match in matches9) { //Console.WriteLine(match.Value); writeToText(match.ToString()); Interlocked.Increment(ref Scraped); Console.Title = $"rondProxy | Proxy Scraper | Scraped: {Scraped}"; } Thread.Sleep(400); Console.WriteLine($"Scraped {matches9.Count} proxies from proxyscrape.com"); Thread.Sleep(400); Console.WriteLine("Done Scraping."); Thread.Sleep(-1); }
public async Task <bool> SendProgramAsync(int boardId, bool isMultiple) { ThisBoard = await _context.Boards .Include(b => b.Display) .AsNoTracking() .FirstOrDefaultAsync(m => m.ID == boardId); string c4_IPAddress = ThisBoard.Display.C4_IP; string vsnFilename = "board" + boardId.ToString() + ".vsn"; Client = new RestClient("http://" + c4_IPAddress + "/api/program/" + vsnFilename); Client.Timeout = -1; Request = new RestRequest(Method.POST); Request.AddHeader("Content-Type", "multipart/form-data;bounda6ry=;"); //Manage post directory and the program (+files) to be sent string postDirectory; string defaultDirectory = Directory.GetCurrentDirectory(); this.logger.LogDebug("Current Directory: " + defaultDirectory); if (!isMultiple) { postDirectory = UploadsFolder.GetUploadsSubPath(UploadsFolder.TempFolderSingle); } else { postDirectory = UploadsFolder.GetUploadsSubPath(UploadsFolder.TempFolderMultiple); } Directory.SetCurrentDirectory(postDirectory); this.logger.LogDebug("New Directory: " + postDirectory); List <string> filenameList = GetAllFilenames(postDirectory); int key = 0; foreach (var file in filenameList) { Request.AddFile("f" + key.ToString(), file); key++; } Response = Client.Execute(Request); /*string content = response.Content; * string contentType = response.ContentType; * IList<Parameter> headers = response.Headers; * string errorMessage = response.ErrorMessage; * Exception errorException = response.ErrorException;*/ NumericStatusCode = (int)Response.StatusCode; //Reset default directory after request execution Directory.SetCurrentDirectory(defaultDirectory); this.logger.LogDebug("Directory is reset to " + Directory.GetCurrentDirectory()); if (Response.IsSuccessful || Response.ResponseStatus.ToString() == "Completed") { if (NumericStatusCode == 200) { return(true); } else { return(false); } } else { return(false); } }
private static void SetCookie(RestClient client, string domain, string cookieHeader) { client.CookieContainer.SetCookies(new Uri(domain), cookieHeader); }
public void DeleteProduct(long id) { var path = "/craftlink/v1/products/" + id; RestClient.Delete<object>(RequestOptions.BaseUrl + path, CreateHeaders(path, RequestOptions)); }
/// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default configuration. /// </summary> public ApiClient() { Configuration = Org.OpenAPITools.Client.Configuration.Default; RestClient = new RestClient("http://petstore.swagger.io:80/v2"); }
/// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class /// with default base path (http://petstore.swagger.io:80/v2). /// </summary> /// <param name="config">An instance of Configuration.</param> public ApiClient(Configuration config) { Configuration = config ?? Org.OpenAPITools.Client.Configuration.Default; RestClient = new RestClient(Configuration.BasePath); }
/// <summary> /// List code packages /// </summary> /// <param name="filter"> </param> /// <remarks> /// http://dev.iron.io/worker/reference/api/#list_code_packages /// </remarks> public CodeInfoCollection Codes(PagingFilter filter = null) { return(RestClient.Get <CodeInfoCollection>(_config, string.Format("{0}/codes", EndPoint), filter).Result); }
public ProductResponse UpdateProduct(long id, UpdateProductRequest updateProductRequest) { var path = "/craftlink/v1/products/" + id; return RestClient.Put<ProductResponse>(RequestOptions.BaseUrl + path, CreateHeaders(updateProductRequest, path, RequestOptions), updateProductRequest); }