protected async Task <Result <TOutbound> > Delete <TOutbound>(string id, string url = "", IDictionary <string, string> parameters = null) { HttpResponseMessage result = null; string requestUriString = string.Concat(_controller, "/", id, parameters?.ToQueryString() ?? ""); if (!string.IsNullOrEmpty(url)) { requestUriString = string.Concat(_controller, "/", url, "/", id, parameters?.ToQueryString() ?? ""); } result = await _client.DeleteAsync(new Uri(requestUriString)); if (result.IsSuccessStatusCode) { return(new Result <TOutbound> { Success = true //No Content }); } else { var error = new Result <TOutbound> { Error = result.StatusCode.ToString(), Message = result.ReasonPhrase, Success = false }; return(error); } }
protected async Task <Result <IList <TOutbound> > > GetList <TOutbound>(string url = "", IDictionary <string, string> parameters = null) { HttpResponseMessage result = null; string requestUriString = String.Concat(_controller, "/", parameters?.ToQueryString() ?? ""); if (!string.IsNullOrEmpty(url)) { requestUriString = String.Concat(_controller, "/", url, "/", parameters?.ToQueryString() ?? ""); } result = await _client.DeleteAsync(new Uri(requestUriString)); if (result.IsSuccessStatusCode) { return(new Result <IList <TOutbound> > { Success = true, Value = HttpHelper.DeserializeJsonString <IList <TOutbound> >(await result.Content.ReadAsStringAsync()) }); } else { var error = new Result <IList <TOutbound> > { Error = result.StatusCode.ToString(), Message = result.ReasonPhrase, Success = false }; return(error); } }
protected async Task <Result <IList <TOutbound> > > GetList <TOutbound>(String controller, IDictionary <String, String> parameters = null) { HttpResponseMessage result = null; if (parameters == null) { result = await _client.GetAsync(controller); } else { result = await _client.GetAsync(controller + "/" + parameters.ToQueryString()); } if (result.IsSuccessStatusCode) { return(new Result <IList <TOutbound> >() { Success = true, Value = JsonConvert.DeserializeObject <IList <TOutbound> >(await result.Content.ReadAsStringAsync()) }); } else { var error = new Result <IList <TOutbound> >() { Error = result.StatusCode.ToString(), Message = result.ReasonPhrase, Success = false }; return(error); } }
/// <summary> /// Convert dictionary to querystring. /// </summary> /// <param name="dict">Dictionary</param> /// <param name="configure">Configuration function.</param> /// <returns>Returns querystring.</returns> public static string ToQueryString<TKey, TValue>(this IDictionary<TKey, TValue> dict, Action<QueryStringOptions> configure) { if (configure == null) throw new ArgumentNullException(nameof(configure)); var opts = new QueryStringOptions(); configure(opts); return dict.ToQueryString(opts); }
public string GetLoginUrl(string redirect, IDictionary<string, object> parameters) { if (parameters != null) return client.GetAuthenticateUrl(redirect) + parameters.ToQueryString(); return client.GetAuthenticateUrl(redirect); }
public string GetLoginUrl(string redirect, IDictionary<string, object> parameters) { if (parameters != null) return client.GetAuthorizationUri(client.GetRequestToken(redirect + parameters.ToQueryString())).ToString(); return client.GetAuthorizationUri(client.GetRequestToken(redirect)).ToString(); }
/// <summary> /// Unpins the specified recent history record. /// </summary> /// <param name="historyType">The history type.</param> /// <param name="values">The values necessary for loading the object as a dictionary of key value pairs.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="values" /> is <c>null</c> or empty.</exception> public void Unpin(HistoryType historyType, IDictionary <string, object> values) { if (values == null || !values.Any()) { throw new ArgumentNullException("values"); } var queryStringValues = values.ToQueryString(true); var sqlParameters = new List <SqlParameter>(); sqlParameters.Add(new SqlParameter { ParameterName = "@return_value", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.ReturnValue }); sqlParameters.Add(new SqlParameter { ParameterName = "@HistoryType_RHC", SqlDbType = SqlDbType.VarChar, Value = historyType.ToString() }); sqlParameters.Add(new SqlParameter { ParameterName = "@ObjectValues", SqlDbType = SqlDbType.VarChar, Value = queryStringValues }); sqlParameters.Add(new SqlParameter { ParameterName = "@IsPinned", SqlDbType = SqlDbType.Bit, Value = false }); sqlParameters.Add(new SqlParameter { ParameterName = "@UserID", SqlDbType = SqlDbType.VarChar, Value = UserService.Username }); SqlService.ExecuteNonQuery(connectionName, "RecentHistoryUpdate", sqlParameters); // Data changed so remove all variations of history // Note: Changed to explicitly set key models instead of going by key name while non-cluster safe keysInUse process is still in place. CacheService.Remove(new KeyModel(CacheType.User, "History").Add("Single").Add(historyType).Add(queryStringValues)); CacheService.Remove(new KeyModel(CacheType.User, "History").Add("All").Add(historyType)); }
public static string AddQueryString(this string routeName, IDictionary <string, string> parameters) { if (parameters == null || parameters.Count == 0) { return(routeName); } return($"{routeName}?{parameters.ToQueryString()}"); }
public IObservable <string> GetUri(string path, IDictionary <string, string> parameters) => parameters .ToQueryString() .Select(q => new UriBuilder("https://medium.com") { Path = path, Query = q }.ToString());
public static string AddQueryString(string uri, IDictionary <string, string> queryString) { #if NET45 return(uri + (queryString.Any() ? "?" + queryString.ToQueryString() : string.Empty)); #else return(Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(uri, queryString)); #endif }
/// <summary> /// Create HttpRequest with specific Request Method /// </summary> /// <param name="requestUrl">requestUrl</param> /// <param name="queryDictionary">queryDictionary</param> /// <param name="method">method</param> public WebRequestHttpRequester(string requestUrl, IDictionary <string, string>?queryDictionary, HttpMethod method) { _requestUrl = $"{requestUrl}{(requestUrl.Contains("?") ? "&" : "?")}{queryDictionary.ToQueryString()}"; _request = WebRequest.CreateHttp(requestUrl); _request.UserAgent = HttpHelper.GetUserAgent(); _request.Method = method.Method; }
public static Uri BuildRequestUri(string host, string apiSubPath, IDictionary <string, string> queryParameters = null) { return(new UriBuilder(host) { Path = apiSubPath, Query = queryParameters.ToQueryString() }.Uri); }
public Request(RequestMethod method, string path, IDictionary <string, string> parameters) { _method = method; _uri = new UriBuilder(scheme, host) { Path = path, Query = parameters?.ToQueryString() }.Uri; }
/// <summary> /// Gets the recent history item for a specified history type and object ID /// </summary> /// <param name="historyType">The history type.</param> /// <param name="values">The values necessary for loading the object as a dictionary of key value pairs.</param> /// <returns>Returns <see cref="IEnumerable{HistoryModel}"/> for a single matching recent history record. If no matching record found returns null.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="values"/> is <c>null</c> or empty.</exception> public HistoryModel Get(HistoryType historyType, IDictionary <string, object> values) { if (values == null || !values.Any()) { throw new ArgumentNullException("values"); } var queryStringValues = values.ToQueryString(true); var key = new KeyModel(CacheType.User, "History").Add("Single").Add(historyType).Add(queryStringValues); HistoryModel data; if (!CacheService.TryGet(key, out data)) { var sqlParameters = new List <SqlParameter>(); sqlParameters.Add(new SqlParameter { ParameterName = "@return_value", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.ReturnValue }); sqlParameters.Add(new SqlParameter { ParameterName = "@HistoryType_RHC", SqlDbType = SqlDbType.VarChar, Value = historyType.ToString() }); sqlParameters.Add(new SqlParameter { ParameterName = "@ObjectValues", SqlDbType = SqlDbType.VarChar, Value = queryStringValues }); sqlParameters.Add(new SqlParameter { ParameterName = "@UserID", SqlDbType = SqlDbType.VarChar, Value = UserService.Username }); data = SqlService.Execute <HistoryModel>(connectionName, "RecentHistoryGetSingle", sqlParameters, reader => { var model = new HistoryModel(); model.HistoryType = historyType; string vals = (reader[2] as string); if (!string.IsNullOrEmpty(vals) && vals.IndexOf('=') >= 0) { model.Values = new Dictionary <string, object>(); var split = vals.Split(new char[] { '=' }, StringSplitOptions.None); model.Values.Add(split[0], split[1]); } model.DisplayName = reader[3] as string; model.IsPinned = reader.GetBoolean(4); model.DateAccessed = reader.GetDateTime(5); model.Username = reader[6] as string; return(model); } ).FirstOrDefault(); if (data != null) { // Successful so store in cache CacheService.Set(key, data); } } return(data); }
public static Uri SetQuery(this Uri uri, IDictionary <string, string> query) { var queryString = query.ToQueryString(); var uriWithQueryParam = new UriBuilder(uri) { Query = queryString }; return(uriWithQueryParam.Uri); }
/// <summary> /// Builds a ZAP API request url. /// </summary> /// <param name="dataType">The data type of the request.</param> /// <param name="component">The component the API call resides in.</param> /// <param name="callType">The call type of the request.</param> /// <param name="method">The method name of the API call.</param> /// <param name="parameters">Optional parameters to send to the API method.</param> /// <returns>ZAP API request url.</returns> public static string BuildRequestUrl(DataType dataType, string component, CallType callType, string method, IDictionary <string, object> parameters) { var urlPath = $"http://zap/{dataType.ToString().ToLower()}/{component}/{callType.ToString().ToLower()}/{method}/"; if (parameters != null && parameters.Any()) { var queryString = parameters.ToQueryString(); urlPath = $"{urlPath}?{queryString}"; } return(urlPath); }
public async Task <T> GetAsync <T>(string relativeResource, IDictionary <string, string> query = null, Func <string, T> parser = null) { if (query == null) { return(await GetAsync <T> (relativeResource, string.Empty, parser)); } else { return(await GetAsync <T> (relativeResource, query.ToQueryString(), parser)); } }
/// <summary> /// Builds the request URL. /// </summary> /// <param name="url">The URL.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> protected virtual string BuildRequestUrl(string url, IDictionary <string, string> parameters) { foreach (var p in Parameters.Where(p => !parameters.ContainsKey(p.Key))) { parameters.Add(p.Key, p.Value); } parameters.Add("url", url); return(ApiEndpoint + parameters.ToQueryString()); }
public async Task DeleteAsync(string relativeResource, IDictionary <string, string> query = null) { if (query == null) { await DeleteAsync(relativeResource, string.Empty); } else { await DeleteAsync(relativeResource, query.ToQueryString()); } }
public async Task <T> DeleteAsync <T>(string relativeResource, IDictionary <string, string> query = null) { if (query == null) { return(await DeleteAsync <T> (relativeResource, string.Empty)); } else { return(await DeleteAsync <T> (relativeResource, query.ToQueryString())); } }
private static RequestPayload CheckForRequestPayload(RequestData requestData, IDictionary<string,string> requestParameters) { var shouldHaveRequestBody = requestData.HttpMethod.ShouldHaveRequestBody(); var hasSuppliedARequestPayload = requestData.Payload != null; if (shouldHaveRequestBody && hasSuppliedARequestPayload) { return requestData.Payload; } return new RequestPayload(FormUrlEncoded, requestParameters.ToQueryString()); }
protected async Task <Result <TOutbound> > Get <TOutbound>(string id, string url = "", IDictionary <string, string> parameters = null) { HttpResponseMessage result = null; string requestUriString = _controller; if (!string.IsNullOrEmpty(url)) { requestUriString = string.Concat(requestUriString, "/", url); } if (!string.IsNullOrEmpty(id)) { requestUriString = string.Concat(requestUriString, "/", id); } if (parameters != null) { requestUriString = string.Concat(requestUriString, parameters.ToQueryString()); } try { result = await _client.GetAsync(requestUriString); } catch (Exception e) { DebugHelper.Log(e); } if (result.IsSuccessStatusCode) { return(new Result <TOutbound> { Success = true, Value = HttpHelper.DeserializeJsonString <TOutbound>(await result.Content.ReadAsStringAsync()) }); } else { var error = new Result <TOutbound> { Error = result.StatusCode.ToString(), Message = result.ReasonPhrase, Success = false }; return(error); } }
/// <summary> /// Sends an API query to Ontraport. /// </summary> /// <typeparam name="T">The expected response data type. Set to JObject to parse manually. Set to Object to discard output.</typeparam> /// <param name="endpoint">The URL endpoint, excluding that goes after https://api.ontraport.com/1/ </param> /// <param name="method">The web request method.</param> /// <param name="encodeJson">True to encode the request as Json, false to encode as URL query.</param> /// <param name="values">Values set by the method type.</param> /// <param name="valuesOptional">Optional values set by the caller.</param> /// <returns>An ApiResponse of the expected type.</returns> protected async Task <T> RequestAsync <T>(string endpoint, HttpMethod method, bool encodeJson, IDictionary <string, object> values = null) where T : class { values = values ?? new Dictionary <string, object>(); // Serialize request. var content = encodeJson ? JsonConvert.SerializeObject(values, Formatting.None) : values.ToQueryString(); var requestUrl = endpoint; if (!encodeJson && !string.IsNullOrEmpty(content)) { requestUrl += "?" + content; content = ""; } var response = await _httpClient.SendAsync(new HttpRequestMessage(method, requestUrl) { Content = new StringContent(content, Encoding.UTF8, encodeJson ? ContentJson : ContentUrl) }); response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); response.Content?.Dispose(); if (typeof(T) == typeof(object)) { return(new object() as T); } if (typeof(T) == typeof(JObject)) { // Return JSON manual parser. return(JObject.Parse(responseText) as T); } else { // Parse response. var result = JsonConvert.DeserializeObject <ApiResponse <T> >(responseText); if (result.Code != 0) { throw new WebException($"The remote server returned an error: ({result.Code})"); } return(result.Data); } }
public void Write(IOAuthMessage message, IDictionary<string, object> parameters) { if (message == null) throw new ArgumentNullException("message"); if (parameters == null) message.Body = string.Empty; else { var body = parameters.ToQueryString(); if (body.StartsWith("?")) body = body.Substring(1); message.Body = body; } }
public async Task <string> AuthorizedQueryAsync(string apiName, IDictionary <string, string> req) { req.AddNonceParameter(); var message = req.ToQueryString(); var sign = Sign(_secret, message); var content = new FormUrlEncodedContent(req); content.Headers.Add("Sign", sign); content.Headers.Add("Key", _key); var response = await _httpClient.PostAsync(apiName, content); return(await response.Content.ReadAsStringAsync()); }
public string ApiQuery(string apiName, IDictionary <string, string> req) { using var wb = new WebClient(); req.AddNonceParameter(); var message = req.ToQueryString(); var sign = Sign(_secret, message); wb.Headers.Add("Sign", sign); wb.Headers.Add("Key", _key); var data = req.ToNameValueCollection(); var response = wb.UploadValues($"{_url}/{apiName}", HttpMethod.Post.ToString(), data); return(Encoding.UTF8.GetString(response)); }
private static RequestPayload CheckForRequestPayload(RequestData requestData, IDictionary <string, string> requestParameters) { var shouldHaveRequestBody = requestData.HttpMethod.ShouldHaveRequestBody(); var hasSuppliedParameters = requestParameters.Count > 0; var hasSuppliedARequestPayload = requestData.Payload != null; if (shouldHaveRequestBody && hasSuppliedParameters) { return(new RequestPayload("application/x-www-form-urlencoded", requestParameters.ToQueryString())); } if (shouldHaveRequestBody && hasSuppliedARequestPayload) { return(requestData.Payload); } return(new RequestPayload("application/x-www-form-urlencoded", "")); }
private static RequestPayload CheckForRequestPayload(RequestData requestData, IDictionary<string,string> requestParameters) { var shouldHaveRequestBody = requestData.HttpMethod.ShouldHaveRequestBody(); var hasSuppliedParameters = requestParameters.Count > 0; var hasSuppliedARequestPayload = requestData.Payload != null; if (shouldHaveRequestBody && hasSuppliedParameters) { return new RequestPayload("application/x-www-form-urlencoded", requestParameters.ToQueryString()); } if (shouldHaveRequestBody && hasSuppliedARequestPayload) { return requestData.Payload; } return new RequestPayload("application/x-www-form-urlencoded", ""); }
public static void SubmitForm(string url, IDictionary <string, string> fields, string action = "submitting form") { HttpWebRequest request; HttpWebResponse response; try { request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookies ?? new CookieContainer(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII)) { writer.Write(fields.ToQueryString()); } response = (HttpWebResponse)request.GetResponse(); ConnectionStatus = response.StatusCode; Log.Write("Connection status to {0} is {1} {2}: {3}".F(response.ResponseUri, (int)response.StatusCode, response.StatusCode, response.StatusDescription)); if (response.Cookies != null) { Log.Write("Cookies exist."); } else { Log.Write("Cookies do not exist."); } cookies = request.CookieContainer; StreamReader responseReader = new StreamReader(response.GetResponseStream()); string fullResponse = responseReader.ReadToEnd(); response.Close(); } catch (WebException ex) { Log.Write("Error while {0}:".F(action)); Log.Write(ex.ToString()); throw; } }
private async Task <string> DoRequest(string url, HttpMethod method, IDictionary <string, string> urlParams = null, object bodyObject = null, IDictionary <string, string> headers = null) { string fullRequestUrl = string.Empty; HttpResponseMessage response = null; if (headers == null) { headers = new Dictionary <string, string>(); } if (this.Credentials != null) { headers.Add("Authorization", this.AuthHeader); } headers.Add("Accept", "application/json"); fullRequestUrl = string.Format("{0}{1}{2}", this.Host.ToString(), url, urlParams?.ToQueryString()); using (var request = new HttpRequestMessage(method, fullRequestUrl)) { request.AddHeaders(headers); if (bodyObject != null) { request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(bodyObject), System.Text.Encoding.UTF8, "application/json"); } response = await this.Client.SendAsync(request).ConfigureAwait(false); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (!response.IsSuccessStatusCode) { var errDesc = response.ReasonPhrase; if (!string.IsNullOrEmpty(content)) { errDesc += " - " + content; } throw new HttpRequestException(string.Format("RestfulService: Error sending request to web service URL {0}. Reason: {1}", fullRequestUrl, errDesc)); } return(content); }
/* TODO (andgein): process `meta` dictionary in response, process paginated response */ private async Task <List <TObject> > GetList <TObject>(IDictionary <string, string> parameters = null, string additional = "") where TObject : StepikApiObject { var apiEndpoint = typeof(TObject).GetApiEndpoint(); var url = string.IsNullOrEmpty(additional) ? apiEndpoint : $"{apiEndpoint}/{additional}"; if (parameters != null) { var builder = new UriBuilder(apiBaseUrl + url) { Query = parameters.ToQueryString() }; url = builder.ToString(); } var response = await MakeRequest(HttpMethod.Get, url); /* JSON in response always contains key with the same name as an API endpoint*/ return(ExtractOneJsonField <List <TObject> >(response, apiEndpoint)); }
public void Write(IOAuthMessage message, IDictionary <string, object> parameters) { if (message == null) { throw new ArgumentNullException("message"); } if (parameters == null) { message.Body = string.Empty; } else { var body = parameters.ToQueryString(); if (body.StartsWith("?")) { body = body.Substring(1); } message.Body = body; } }
public async Task <TResult> AuthorizedQueryAsync <TResult>( string apiName, IDictionary <string, string> req, JsonSerializerOptions jsonSerializerOptions = null) { req.AddNonceParameter(); var message = req.ToQueryString(); var sign = Sign(_secret, message); var content = new FormUrlEncodedContent(req); content.Headers.Add("Sign", sign); content.Headers.Add("Key", _key); var response = await _httpClient.PostAsync(apiName, content); await using var responseStream = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync <TResult>(responseStream, jsonSerializerOptions); return(result); }
/// <summary> /// Gets the query string. /// </summary> /// <param name="urlEncodeParams">if set to <c>true</c> [URL encode parameters].</param> /// <param name="includeEmptyValues">if set to <c>true</c> [include empty values].</param> private void GetQueryString(bool urlEncodeParams = false, bool includeEmptyValues = true) { base.Query = _queryString.ToQueryString(urlEncodeParams, includeEmptyValues); }
public HttpRequestItem(HttpMethodType method, string rawUrl, IDictionary<string, string> queryValues) : this(method, rawUrl) { _rawData.Append(queryValues.ToQueryString()); }
public static string ToQueryString(this IDictionary <string, string> dict) { return(dict == null ? string.Empty : dict.ToQueryString(Encoding.Default)); }