/// <summary> /// 组装普通文本请求参数。 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> public static string BuildQuery(IDictionary <string, string> parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator <KeyValuePair <string, string> > dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); postData.Append(HttpHelper.UrlEncode(value, Encoding.UTF8)); hasParam = true; } } return(postData.ToString()); }
/// <summary> /// ######### ######### ############ ########, ######### ####### /// </summary> /// <param name="rcptMergeVar">###### ######### ############ ########</param> /// <param name="bulkEmailRId">######## ############# ###### email ########</param> /// <param name="bulkEmailId">############# ###### email ########</param> /// <param name="emailAddress">Email ##### ##########</param> public void InitPersonalUnsubscribeMacros(rcpt_merge_var rcptMergeVar, int bulkEmailRId, Guid bulkEmailId, string emailAddress) { if (_isUsubscribeFromAllMailings) { return; } string bulkEmail = String.Format("{0:0000000000}", bulkEmailRId); foreach (string alias in UnsubscribeMacrosAliases) { rcptMergeVar.rcpt = emailAddress; string unsubscribeHash = MandrillUtilities.StringCrypto.EncryptString(emailAddress, bulkEmailId.ToString("N")); string unsubscribeKey = string.Concat(bulkEmail, unsubscribeHash); unsubscribeKey = HttpUtility.UrlEncode(unsubscribeKey); string unsubscribeLinkParameter = string.Format(UnsubscribeLinkParameterPattern, unsubscribeKey); string unsubscribeLink = !string.IsNullOrEmpty(_unsubscribeApplicationUrl) ? string.Concat(_unsubscribeApplicationUrl, unsubscribeLinkParameter) : string.Concat(string.Format(UnsubscribeLinkPattern, _applicationUrl), unsubscribeLinkParameter); var mergeVar = new merge_var() { name = alias, content = unsubscribeLink }; rcptMergeVar.vars.Add(mergeVar); } }
public ActionResult googleContacts() { var continueUrl = string.Concat(GeneralConstants.HTTP_HOST, "/callback?sd=", accountHostname, "&path=", HttpUtility.UrlEncode("/dashboard/contacts/import"), "&type=", ContactImportType.GOOGLE); var authsubUrl = AuthSubUtil.getRequestUrl(continueUrl, GoogleConstants.FEED_CONTACTS, false, false); return(Redirect(authsubUrl)); }
/// <summary> /// Similar to Get User but with authenticated user (token owner) as user id. /// <code>scope = identify</code> /// </summary> /// <param name="user">Id of the user.</param> /// <param name="gameMode"><see cref="GameMode"/>. User default mode will be used if not specified.</param> /// <returns></returns> public User GetUser(string user, GameMode?gameMode = null) { string route = $"/users/{HttpUtility.UrlEncode(user)}/{gameMode?.ToParamString()}"; var json = _httpClient.HttpGet(OsuClientV2.BaseUri + route); var obj = JsonConvert.DeserializeObject <User>(json); return(obj); }
public Beatmapset[] GetUserBeatmap(string user, UserBeatmapType type) { string route = $"/users/{HttpUtility.UrlEncode(user)}/beatmapsets/{type.ToParamString()}?limit=500&offset=0"; var json = _httpClient.HttpGet(OsuClientV2.BaseUri + route); var obj = JsonConvert.DeserializeObject <Beatmapset[]>(json); return(obj); }
public void UrlEncodeForForm_1() { Console.WriteLine(SymbolChars); // space and "#$%&'+,/:;<=>?@[\]^`{|}~ UrlEncodeTest(NetWebUtility.UrlEncode); // space and "#$%&'+,/:;<=>?@[\]^`{|}~ UrlEncodeTest(s => WebHttpUtility.UrlEncode(s).ToUpperInvariant()); // space and !"#$%&'()*+,/:;<=>?@[\]^`{|} UrlEncodeTest(UriHelper.UrlEncodeForForm); }
private void update_website(FinalPackageTestResultMessage message) { SecurityProtocol.set_protocol(); this.Log().Info(() => "Updating website for {0} v{1} with success '{2}' and results url: '{3}'".format_with(message.PackageId, message.PackageVersion, message.Success, message.ResultDetailsUrl)); try { var resultsUri = new Uri(message.ResultDetailsUrl); } catch (Exception ex) { Bootstrap.handle_exception(ex); return; } try { var url = string.Join("/", SERVICE_ENDPOINT, message.PackageId, message.PackageVersion); HttpClient client = _nugetService.get_client(_configurationSettings.PackagesUrl, url, "POST", "application/x-www-form-urlencoded"); StringBuilder postData = new StringBuilder(); postData.Append("apikey=" + HttpUtility.UrlEncode(_configurationSettings.PackagesApiKey)); postData.Append("&success=" + HttpUtility.UrlEncode(message.Success.to_string().to_lower())); postData.Append("&resultDetailsUrl=" + HttpUtility.UrlEncode(message.ResultDetailsUrl)); var form = postData.ToString(); var data = Encoding.ASCII.GetBytes(form); client.SendingRequest += (sender, e) => { SendingRequest(this, e); var request = (HttpWebRequest)e.Request; request.Timeout = 30000; request.Headers.Add(_nugetService.ApiKeyHeader, _configurationSettings.PackagesApiKey); request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } }; _nugetService.ensure_successful_response(client); } catch (Exception ex) { Bootstrap.handle_exception(ex); } this.Log().Info("Finished verification for {0} v{1}.".format_with(message.PackageId, message.PackageVersion)); // EventManager.publish(new WebsiteUpdateMessage()); }
/// <summary>获取App信息</summary> public static async Task <AppInfo?> GetAppInfo(this IAppClusterClient client, CancellationToken cancellationToken = default) { if (client == null) { throw new ArgumentNullException(nameof(client)); } #if NET40 var list = await client.Get <IList <AppInfo> >("apps?appIds=" + WebUtility.UrlEncode(client.AppId), cancellationToken).ConfigureAwait(false); #else var list = await client.Get <IReadOnlyList <AppInfo> >("apps?appIds=" + WebUtility.UrlEncode(client.AppId), cancellationToken).ConfigureAwait(false); #endif return(list?.FirstOrDefault()); }
public ActionResult blogger() { var viewdata = new NetworkViewModel(); viewdata.bloggerSessionKey = MASTERdomain.bloggerSessionKey; viewdata.blogList = MASTERdomain.googleBlogs.ToModel(); var continueUrl = string.Concat(GeneralConstants.HTTP_HOST, "/callback?sd=", accountHostname, "&path=", HttpUtility.UrlEncode("/dashboard/blogger/saveToken")); viewdata.requestUrl = AuthSubUtil.getRequestUrl(continueUrl, GoogleConstants.FEED_BLOGGER, false, true); return(View(viewdata)); }
/// <summary> /// This method encodes an url /// </summary> /// <param name="text"></param> /// <returns></returns> public static string UrlEncodeUTF8(string text) { if (text == null) { return(null); } if (text.Length == 0) { return(""); } // encode with url encoder var enc = HttpUtility.UrlEncode(text, Encoding.UTF8); // fix the missing space enc = enc.Replace("+", "%20"); // fix the exclamation point enc = enc.Replace("!", "%21"); // fix the quote enc = enc.Replace("'", "%27"); // fix the parentheses enc = enc.Replace("(", "%28"); enc = enc.Replace(")", "%29"); enc = enc.Replace("%2f", "/"); // uppercase the encoded stuff var enc2 = new StringBuilder(); for (var i = 0; i < enc.Length; i++) { // copy char enc2.Append(enc[i]); // upper stuff if (enc[i] == '%') { enc2.Append(char.ToUpper(enc[i + 1])); enc2.Append(char.ToUpper(enc[i + 2])); i += 2; } } return(enc2.ToString()); }
public static string Build(IReadOnlyCollection <KeyValuePair <string, string> > source) #endif { if (source == null || source.Count == 0) { return(""); } var sb = new StringBuilder(source.Count * 32); foreach (var kv in source) { sb.Append('&'); sb.Append(WebUtility.UrlEncode(kv.Key)); sb.Append('='); sb.Append(WebUtility.UrlEncode(kv.Value)); } return(sb.ToString(1, sb.Length - 1)); }
private void update_website(FinalResultMessage message) { SecurityProtocol.set_protocol(); if (string.IsNullOrWhiteSpace(_configurationSettings.PackagesApiKey)) { return; } this.Log().Info(() => "Updating website for {0} v{1} with cleanup ({2}).".format_with(message.PackageId, message.PackageVersion, message.Reject ? "rejecting stale package" : "sending reminder")); try { var url = string.Join("/", SERVICE_ENDPOINT, message.PackageId, message.PackageVersion); HttpClient client = _nugetService.get_client(_configurationSettings.PackagesUrl, url, "POST", "application/x-www-form-urlencoded"); var postData = new StringBuilder(); postData.Append("apikey=" + HttpUtility.UrlEncode(_configurationSettings.PackagesApiKey)); postData.Append("&reject=" + HttpUtility.UrlEncode(message.Reject.to_string().to_lower())); postData.Append("&cleanupComments=" + HttpUtility.UrlEncode(message.ResultMessage)); var form = postData.ToString(); var data = Encoding.ASCII.GetBytes(form); client.SendingRequest += (sender, e) => { SendingRequest(this, e); var request = (HttpWebRequest)e.Request; request.Timeout = 30000; request.Headers.Add(_nugetService.ApiKeyHeader, _configurationSettings.PackagesApiKey); request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } }; _nugetService.ensure_successful_response(client); } catch (Exception ex) { Bootstrap.handle_exception(ex); } }
public static Task <IReadOnlyList <AppInfo>?> GetAppsInfo(this IAppClusterClient client, IReadOnlyCollection <string>?appIds = null, CancellationToken cancellationToken = default) #endif { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (appIds == null || appIds.Count == 0) #if NET40 { return(client.Get <IList <AppInfo> >("apps", cancellationToken)); } return(client.Get <IList <AppInfo> >($"apps?appIds={WebUtility.UrlEncode(string.Join(",", appIds))}", cancellationToken)); #else { return(client.Get <IReadOnlyList <AppInfo> >("apps", cancellationToken)); } return(client.Get <IReadOnlyList <AppInfo> >($"apps?appIds={WebUtility.UrlEncode(string.Join(",", appIds))}", cancellationToken)); #endif }
/// <summary> /// Gets response content disposition header value. /// </summary> /// <param name="fileName">File name.</param> /// <returns>Content disposition header value.</returns> protected virtual string GetResponseContentDisposition(string fileName) { string processedFileName; HttpRequest request = CurrentContext.Request; string userAgent = (request.UserAgent ?? String.Empty).ToLowerInvariant(); if (userAgent.Contains("android")) { processedFileName = $"filename=\"{RemoveSpecialCharacters(fileName)}\""; } else if (userAgent.Contains("safari")) { processedFileName = $"filename*=UTF-8''{HttpUtility.UrlEncode(fileName)}"; } else { processedFileName = $"filename=\"{fileName}\"; filename*=UTF-8''{HttpUtility.UrlEncode(fileName)}"; } return($"attachment; {processedFileName}"); }
private void update_website(PackageValidationResultMessage message) { var failedRequired = message.ValidationResults.Any(r => r.Validated == false && r.ValidationLevel == ValidationLevelType.Requirement); this.Log().Info(() => "Updating website for {0} v{1} with results (package {2} requirements).".format_with(message.PackageId, message.PackageVersion, failedRequired ? "failed" : "passed")); try { var url = string.Join("/", SERVICE_ENDPOINT, message.PackageId, message.PackageVersion); HttpClient client = _nugetService.get_client(_configurationSettings.PackagesUrl, url, "POST", "application/x-www-form-urlencoded"); StringBuilder postData = new StringBuilder(); postData.Append("apikey=" + HttpUtility.UrlEncode(_configurationSettings.PackagesApiKey)); //postData.Append("&success=" + HttpUtility.UrlEncode(message.Success.to_string().to_lower())); //postData.Append("&resultDetailsUrl=" + HttpUtility.UrlEncode(message.ResultDetailsUrl)); var form = postData.ToString(); var data = Encoding.ASCII.GetBytes(form); client.SendingRequest += (sender, e) => { SendingRequest(this, e); var request = (HttpWebRequest)e.Request; request.Timeout = 30000; request.Headers.Add(_nugetService.ApiKeyHeader, _configurationSettings.PackagesApiKey); request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } }; _nugetService.ensure_successful_response(client); } catch (Exception ex) { Bootstrap.handle_exception(ex); } }
// trim(s) and strlen(s) built-in funcs; these are Format options public virtual string ToString(object o, string formatString, CultureInfo culture) { string s = (string)o; if (formatString == null) { return(s); } if (formatString.Equals("upper")) { return(s.ToUpper(culture)); } if (formatString.Equals("lower")) { return(s.ToLower(culture)); } if (formatString.Equals("cap")) { return(char.ToUpper(s[0], culture) + s.Substring(1)); } if (formatString.Equals("url-encode")) { return(HttpUtility.UrlEncode(s)); } if (formatString.Equals("xml-encode")) { return(SecurityElement.Escape(s)); } return(string.Format(formatString, s)); }
/// <summary>删除配置</summary> /// <returns>存在时删除后返回true,或者返回false</returns> public static Task <bool> RemoveItem(this INamespaceClient client, string key, string @operator, CancellationToken cancellationToken = default) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (@operator == null) { throw new ArgumentNullException(nameof(@operator)); } return(client.Delete($"envs/{client.Env}/apps/{client.AppId}/clusters/{client.Cluster}/namespaces/{client.Namespace}/items/{key}?operator={WebUtility.UrlEncode(@operator)}", cancellationToken)); }
public Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = "") { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return(paramList => { var ret = new HttpRequestMessage() { Method = restMethod.HttpMethod, }; foreach (var header in restMethod.Headers) { setHeader(ret, header.Key, header.Value); } string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary <string, string>(); for (int i = 0; i < paramList.Length; i++) { if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]), RegexOptions.IgnoreCase); continue; } if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } } continue; } if (restMethod.HeaderParameterMap.ContainsKey(i)) { setHeader(ret, restMethod.HeaderParameterMap[i], paramList[i]); } else { if (paramList[i] != null) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); } } } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach (var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = String.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }); }
/// <summary>回滚已发布配置接口</summary> public static Task <bool> Rollback(this INamespaceClient client, string @operator, int releaseId, CancellationToken cancellationToken = default) { if (client == null) { throw new ArgumentNullException(nameof(client)); } return(client.Put($"envs/{client.Env}/releases/{releaseId}/rollback?operator={WebUtility.UrlEncode(@operator)}", cancellationToken)); }
private static string CreateSiteID(string url) { return(HttpUtility.UrlEncode(url).Replace(".", "%2e").Replace("_", "%5f")); }
internal static string UrlEncode(this string value) => Utility.UrlEncode(value);
public Func <object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = "") { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return(paramList => { var ret = new HttpRequestMessage { Method = restMethod.HttpMethod, }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary <string, string>(); var headersToAdd = new Dictionary <string, string>(restMethod.Headers); for (int i = 0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]), RegexOptions.IgnoreCase); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; var httpContentParam = paramList[i] as HttpContent; if (httpContentParam != null) { ret.Content = httpContentParam; } else if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null ? paramList[i].ToString() : null; continue; } // ignore nulls if (paramList[i] == null) { continue; } // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; if (!restMethod.AttachmentNameMap.TryGetValue(i, out itemName)) { itemName = restMethod.QueryParameterMap[i]; } addMultipartItem(multiPartContent, itemName, paramList[i]); } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. foreach (var header in headersToAdd) { setHeader(ret, header.Key, header.Value); } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach (var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = String.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }); }
/// <summary> /// Converts a text string into a URL-encoded string. /// </summary> /// <param name="url">The text to URL-encode.</param> /// <returns>A URL-encoded string.</returns> public static string UrlEncode(string url) { return(HttpUtilityStd.UrlEncode(url)); }
/// <summary> /// URL编码 /// </summary> /// <param name="content"></param> /// <returns></returns> public static string UrlEncode(string content) { return(HttpHelper.UrlEncode(content)); }
Func <object[], HttpRequestMessage> buildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return(paramList => { // make sure we strip out any cancelation tokens if (paramsContainsCancellationToken) { paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); } var ret = new HttpRequestMessage { Method = restMethod.HttpMethod, }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary <string, string>(); var headersToAdd = new Dictionary <string, string>(restMethod.Headers); for (int i = 0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter .Format(paramList[i], restMethod.ParameterInfoMap[i]) .Replace("/", "%2F"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; var httpContentParam = paramList[i] as HttpContent; if (httpContentParam != null) { ret.Content = httpContentParam; } else if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null ? paramList[i].ToString() : null; continue; } // ignore nulls if (paramList[i] == null) { continue; } // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; string parameterName; Tuple <string, string> attachment; if (!restMethod.AttachmentNameMap.TryGetValue(i, out attachment)) { itemName = restMethod.QueryParameterMap[i]; parameterName = itemName; } else { itemName = attachment.Item1; parameterName = attachment.Item2; } // Check to see if it's an IEnumerable var itemValue = paramList[i]; var enumerable = itemValue as IEnumerable <object>; var typeIsCollection = false; if (enumerable != null) { Type tType = null; var eType = enumerable.GetType(); if (eType.GetTypeInfo().ContainsGenericParameters) { tType = eType.GenericTypeArguments[0]; } else if (eType.IsArray) { tType = eType.GetElementType(); } // check to see if it's one of the types we support for multipart: // FileInfo, Stream, string or byte[] if (tType == typeof(Stream) || tType == typeof(string) || tType == typeof(byte[]) #if !NETFX_CORE || tType == typeof(FileInfo) #endif ) { typeIsCollection = true; } } if (typeIsCollection) { foreach (var item in enumerable) { addMultipartItem(multiPartContent, itemName, parameterName, item); } } else { addMultipartItem(multiPartContent, itemName, parameterName, itemValue); } } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. foreach (var header in headersToAdd) { setHeader(ret, header.Key, header.Value); } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach (var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast <string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = String.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }); }
private static async Task <string> GetAccessToken(string AADDomain, bool useTenantAdmin = false) { await GetVariables(); AuthenticationResult token = null; if (!useTenantAdmin && ResourceTokenLookup.TryGetValue(GraphResourceId, out token) && token.ExpiresOn.UtcDateTime >= DateTime.UtcNow.AddMinutes(-5)) { //Return cached token for ADAL app-only tokens return(token.AccessToken); } var authenticationContext = new AuthenticationContext(ADALLogin + AADDomain); bool keepRetry = false; do { TimeSpan?delay = null; try { if (!useTenantAdmin) { var clientCredential = new ClientCredential(_appId, _appSecret); token = await authenticationContext.AcquireTokenAsync(GraphResourceId, clientCredential); } else { // Hack to get user token from a Web/API adal app - passing both username/password and client secret // Ref AADSTS70002 error Uri authUri = new Uri($"{ADALLogin}{ADALDomain}/oauth2/token"); var contentString = $"resource={HttpUtility.UrlEncode(GraphResourceId)}&client_id={_appId}&client_secret={_appSecret}&grant_type=password&username={HttpUtility.UrlEncode(_tenantAdmin)}&password={HttpUtility.UrlEncode(_tenantPassword)}&scope=openid"; var content = new StringContent(contentString, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpClient client = new HttpClient(); var response = await client.PostAsync(authUri, content); string responseMsg = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { JObject tokendata = JsonConvert.DeserializeObject <JObject>(responseMsg); return(tokendata["access_token"].ToString()); } throw new Exception(responseMsg); } } catch (Exception ex) { if (!(ex is AdalServiceException) && !(ex.InnerException is AdalServiceException)) { throw; } AdalServiceException serviceException; if (ex is AdalServiceException) { serviceException = (AdalServiceException)ex; } else { serviceException = (AdalServiceException)ex.InnerException; } if (serviceException.ErrorCode == "temporarily_unavailable") { RetryConditionHeaderValue retry = serviceException.Headers.RetryAfter; if (retry.Delta.HasValue) { delay = retry.Delta; } else if (retry.Date.HasValue) { delay = retry.Date.Value.Offset; } if (delay.HasValue) { Thread.Sleep((int)delay.Value.TotalSeconds); // sleep or other keepRetry = true; } } else { throw; } } } while (keepRetry); ResourceTokenLookup[GraphResourceId] = token; return(token.AccessToken); }
/// <summary> /// Builds markers uri parameter(s) /// </summary> /// <returns></returns> private string GetMarkersStr() { if (this.Markers.Count == 0) { return(null); } System.Text.StringBuilder sb = new System.Text.StringBuilder(200); string[] markerStrings = new string[this.Markers.Count]; int markerStringsIndex = 0; foreach (MapMarkers current in this.Markers) { //start with an empty stringbuilder. sb.Remove(0, sb.Length); //output the size parameter, if it was specified. if (current.MarkerSize != MarkerSizes.Unspecified) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } sb.AppendFormat("size:{0}", current.MarkerSize.ToString().ToLowerInvariant()); } //check for a color specified for the markers and add that style attribute if so if (current.Color.Equals(Color.Empty) == false) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } if (current.Color.IsNamedColor && Constants.IsExpectedNamedColor(current.Color.Name)) { sb.AppendFormat("color:{0}", current.Color.Name.ToLowerInvariant()); } else { sb.AppendFormat("color:0x{0:X6}", (current.Color.ToArgb() & 0x00FFFFFF)); } } //add a label, but if the MarkerSize is MarkerSizes.Tiny then you can't have a label. if (string.IsNullOrEmpty(current.Label) == false && current.MarkerSize != MarkerSizes.Tiny) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } sb.AppendFormat("label:{0}", current.Label); } //add a custom icon param if (string.IsNullOrEmpty(current.IconUrl) == false) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } sb.AppendFormat("icon:{0}", HttpUtility.UrlEncode(current.IconUrl)); if (current.Shadow != null) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } sb.AppendFormat("shadow:{0}", (current.Shadow == true ? "true" : "false")); } } //iterate the locations foreach (Location loc in current.Locations) { if (sb.Length > 0) { sb.Append(Constants.PIPE_URL_ENCODED); } sb.Append(loc.ToString()); } markerStrings[markerStringsIndex++] = "markers=" + sb.ToString(); } return(string.Join("&", markerStrings)); }