Here are the examples of the csharp api System.Uri.EscapeDataString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2209 Examples
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static Uri AddQueryParameters(Uri uri, IEnumerable<KeyValuePair<string, string>> parameters)
{
var builder = new StringBuilder();
foreach (var param in parameters)
{
if (builder.Length > 0)
builder.Append('&');
builder.Append(Uri.EscapeDataString(param.Key));
builder.Append('=');
builder.Append(Uri.EscapeDataString(param.Value));
}
return AddQueryValue(uri, builder.ToString());
}
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static string FormatUriParams(NameValueCollection parameters)
{
if (parameters == null || parameters.Count == 0)
return "";
var result = new StringBuilder();
foreach (var key in parameters.AllKeys)
{
var value = parameters[key];
if (value == null)
continue;
result.AppendFormat("&{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
}
if (result.Length == 0)
return "";
return result.ToString(1, result.Length - 1);
}
19
View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
protected AuthenticationHeaderValue GetAuthorizationHeader(string uri, HttpMethod method)
{
string nonce = DateTime.Now.Ticks.ToString();
string timestamp = DateTime.Now.ToUnixTimestamp().ToString();
List<string> authParams = new List<string>();
authParams.Add("oauth_consumer_key=" + ConsumerKey);
authParams.Add("oauth_nonce=" + nonce);
authParams.Add("oauth_signature_method=HMAC-SHA1");
authParams.Add("oauth_timestamp=" + timestamp);
authParams.Add("oauth_token=" + AccessToken);
authParams.Add("oauth_version=1.0");
SplitUri(uri, out string url, out string[] queryParams);
List<string> requestParams = new List<string>(authParams);
requestParams.AddRange(queryParams);
requestParams.Sort();
string signatureBaseString = string.Join("&", requestParams);
signatureBaseString = string.Concat(method.Method.ToUpper(), "&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(signatureBaseString));
string signature = GetSignature(signatureBaseString);
string hv = string.Join(", ", authParams.Select(x => x.Replace("=", " = \"") + '"'));
hv += $", oauth_signature=\"{Uri.EscapeDataString(signature)}\"";
return new AuthenticationHeaderValue("OAuth", hv);
}
19
View Source File : BaseApiClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
protected string GetSignature(string signatureBaseString)
{
byte[] key = Encoding.ASCII.GetBytes(string.Concat(Uri.EscapeDataString(ConsumerSecret), "&", Uri.EscapeDataString(AccessTokenSecret)));
string signature;
using (HMACSHA1 hasher = new HMACSHA1(key))
{
signature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString)));
}
return signature;
}
19
View Source File : TweetClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
public async Task<Tweet> TweetAsync(string text)
{
return await PostAsync<Tweet>(null, ApiUri + $"update.json?status={Uri.EscapeDataString(text)}");
}
19
View Source File : TweetClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
public async Task<Tweet> QuoteAsync(long tweetId, string text)
{
Tweet tweet = await GetTweetAsync(tweetId);
return await PostAsync<Tweet>(null, ApiUri + $"update.json?status=" +
$"{Uri.EscapeDataString(text + $" https://twitter.com/{tweet.Creator.ScreenName}/status/{tweetId}")}");
}
19
View Source File : TweetClient.cs
License : MIT License
Project Creator : 4egod
License : MIT License
Project Creator : 4egod
public async Task<Tweet> CommentAsync(long tweetId, string text)
{
Tweet tweet = await GetTweetAsync(tweetId);
return await PostAsync<Tweet>(null, ApiUri + $"update.json?status={Uri.EscapeDataString(text + " @4egod")}" +
$"&in_reply_to_status_id={tweetId}");
}
19
View Source File : ExceptionView.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void EmailSupport_Click(object sender, RoutedEventArgs e)
{
string email = "mailto:[email protected]?subject=Unhandled%20Exception&body=" + Uri.EscapeDataString(FormatEmail());
try
{
Process.Start(email);
}
catch (Exception)
{
MessageBox.Show(
"We have not detected an email client on your PC!\r\nPlease email [email protected] with the exception message.");
}
}
19
View Source File : BaseRecordApiService.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public virtual async Task<bool> Delete(string id, CancellationToken cancellationToken = default)
{
SetHeader();
using var responseMessage = await HttpClient.DeleteAsync($"{PrepUrl}/{Uri.EscapeDataString(id)}", cancellationToken).ConfigureAwait(false);
if (!responseMessage.IsSuccessStatusCode)
return false;
return await responseMessage.Content.ReadFromJsonAsync<bool>(cancellationToken: cancellationToken).ConfigureAwait(false);
}
19
View Source File : BaseRecordApiService.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public virtual async Task<bool> Exists(string id, CancellationToken cancellationToken = default)
{
SetHeader();
using var responseMessage = await HttpClient.GetAsync($"{PrepUrl}/{Uri.EscapeDataString(id)}", cancellationToken).ConfigureAwait(false);
return responseMessage.IsSuccessStatusCode;
}
19
View Source File : BaseRecordApiService.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public virtual async Task<T?> Get(string id, CancellationToken cancellationToken = default)
{
SetHeader();
using var responseMessage = await HttpClient.GetAsync($"{PrepUrl}/{Uri.EscapeDataString(id)}", cancellationToken).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
var result = await responseMessage.Content.ReadFromJsonAsync<T>(cancellationToken: cancellationToken).ConfigureAwait(false);
if (result is not null)
result = result with { Id = id };
return result;
}
19
View Source File : BaseRecordApiService.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public virtual async Task<bool> Update(T value, CancellationToken cancellationToken = default)
{
SetHeader();
using var responseMessage = await HttpClient.PutAsJsonAsync($"{PrepUrl}/{Uri.EscapeDataString(value.Id)}", value, cancellationToken).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();
return await responseMessage.Content.ReadFromJsonAsync<bool>(cancellationToken: cancellationToken).ConfigureAwait(false);
}
19
View Source File : ClientUriGenerator.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public string Post(Post post) => $"{BaseAddress}/posts/{Uri.EscapeDataString(post.Id)}";
19
View Source File : ClientUriGenerator.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public string Search(string query = "") => $"{BaseAddress}/search/{Uri.EscapeDataString(query)}";
19
View Source File : ClientUriGenerator.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public string Category(Category category) => $"{BaseAddress}/categories/{Uri.EscapeDataString(category.ToString())}";
19
View Source File : ClientUriGenerator.cs
License : Apache License 2.0
Project Creator : acblog
License : Apache License 2.0
Project Creator : acblog
public string Keyword(Keyword keyword) => $"{BaseAddress}/keywords/{Uri.EscapeDataString(keyword.ToString())}";
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static void AppendSingleQueryValue(StringBuilder builder, String name, String value)
{
if (builder.Length > 0)
{
builder.Append("&");
}
builder.Append(Uri.EscapeDataString(name));
builder.Append("=");
builder.Append(Uri.EscapeDataString(value));
}
19
View Source File : ValueEncoders.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static String UriDataEscape(
String value,
Int32 maxSegmentSize)
{
if (value.Length <= maxSegmentSize)
{
return Uri.EscapeDataString(value);
}
// Workaround size limitation in Uri.EscapeDataString
var result = new StringBuilder();
var i = 0;
do
{
var length = Math.Min(value.Length - i, maxSegmentSize);
if (Char.IsHighSurrogate(value[i + length - 1]) && length > 1)
{
length--;
}
result.Append(Uri.EscapeDataString(value.Substring(i, length)));
i += length;
}
while (i < value.Length);
return result.ToString();
}
19
View Source File : UrlUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri GetCredentialEmbeddedUrl(Uri baseUrl, string username, string preplacedword)
{
ArgUtil.NotNull(baseUrl, nameof(baseUrl));
// return baseurl when there is no username and preplacedword
if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(preplacedword))
{
return baseUrl;
}
UriBuilder credUri = new UriBuilder(baseUrl);
// ensure we have a username, uribuild will throw if username is empty but preplacedword is not.
if (string.IsNullOrEmpty(username))
{
username = "emptyusername";
}
// escape chars in username for uri
credUri.UserName = Uri.EscapeDataString(username);
// escape chars in preplacedword for uri
if (!string.IsNullOrEmpty(preplacedword))
{
credUri.Preplacedword = Uri.EscapeDataString(preplacedword);
}
return credUri.Uri;
}
19
View Source File : VssHttpUriUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[EditorBrowsable(EditorBrowsableState.Never)]
public static String ReplaceRouteValues(
String routeTemplate,
Dictionary<String, Object> routeValues,
RouteReplacementOptions routeReplacementOptions)
{
StringBuilder sbResult = new StringBuilder();
StringBuilder sbCurrentPathPart = new StringBuilder();
int paramStart = -1, paramLength = 0;
bool insideParam = false;
HashSet<string> unusedValues = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> caseIncensitiveRouteValues = new Dictionary<string, object>(routeValues, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < routeTemplate.Length; i++)
{
char c = routeTemplate[i];
if (insideParam)
{
if (c == '}')
{
insideParam = false;
String paramName = routeTemplate.Substring(paramStart, paramLength);
paramLength = 0;
if (paramName.StartsWith("*"))
{
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.WildcardAsQueryParams))
{
continue;
}
// wildcard route
paramName = paramName.Substring(1);
}
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue))
{
if (paramValue != null)
{
sbCurrentPathPart.Append(paramValue.ToString());
unusedValues.Remove(paramName);
}
}
else if (routeReplacementOptions.HasFlag(RouteReplacementOptions.RequireExplicitRouteParams))
{
throw new ArgumentException("Missing route param " + paramName);
}
}
else
{
paramLength++;
}
}
else
{
if (c == '/')
{
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
sbCurrentPathPart.Clear();
}
}
else if (c == '{')
{
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '{')
{
// Escaped '{'
sbCurrentPathPart.Append(c);
i++;
}
else
{
insideParam = true;
paramStart = i + 1;
}
}
else if (c == '}')
{
sbCurrentPathPart.Append(c);
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '}')
{
// Escaped '}'
i++;
}
}
else
{
sbCurrentPathPart.Append(c);
}
}
}
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.EscapeUri))
{
sbResult = new StringBuilder(Uri.EscapeUriString(sbResult.ToString()));
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.AppendUnusedAsQueryParams) && unusedValues.Count > 0)
{
bool isFirst = true;
foreach (String paramName in unusedValues)
{
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue) && paramValue != null)
{
sbResult.Append(isFirst ? '?' : '&');
isFirst = false;
sbResult.Append(Uri.EscapeDataString(paramName));
sbResult.Append('=');
sbResult.Append(Uri.EscapeDataString(paramValue.ToString()));
}
}
}
return sbResult.ToString();
}
19
View Source File : GrandIdApiClient.cs
License : MIT License
Project Creator : ActiveLogin
License : MIT License
Project Creator : ActiveLogin
private static string GetUrl(string baseUrl, Dictionary<string, string?> queryStringParams)
{
if (!queryStringParams.Any())
{
return baseUrl;
}
var queryString = string.Join("&", queryStringParams.Select(x => $"{x.Key}={Uri.EscapeDataString(x.Value ?? string.Empty)}"));
return $"{baseUrl}?{queryString}";
}
19
View Source File : ODataQueryOptionExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static Uri GetNextPageLink(Uri requestUri, IEnumerable<KeyValuePair<string, string>> queryParameters, int pageSize)
{
var stringBuilder = new StringBuilder();
var num = pageSize;
foreach (var keyValuePair in queryParameters)
{
var key = keyValuePair.Key;
var str1 = keyValuePair.Value;
switch (key)
{
case "$top":
int result1;
if (int.TryParse(str1, out result1))
{
str1 = (result1 - pageSize).ToString(CultureInfo.InvariantCulture);
}
break;
case "$skip":
int result2;
if (int.TryParse(str1, out result2))
{
num += result2;
}
continue;
}
var str2 = key.Length <= 0 || (int)key[0] != 36 ? Uri.EscapeDataString(key) : string.Format("${0}", Uri.EscapeDataString(key.Substring(1)));
var str3 = Uri.EscapeDataString(str1);
stringBuilder.Append(str2);
stringBuilder.Append('=');
stringBuilder.Append(str3);
stringBuilder.Append('&');
}
stringBuilder.AppendFormat("$skip={0}", num);
return new UriBuilder(requestUri)
{
Query = stringBuilder.ToString()
}.Uri;
}
19
View Source File : PackageRepositoryHelpers.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string PackageInstallUrl(this HtmlHelper html, UrlHelper url, string packageUniqueName)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href)
{
Fragment = packageUniqueName
};
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
View Source File : PackageRepositoryHelpers.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string PackageRepositoryInstallUrl(this HtmlHelper html, UrlHelper url)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href);
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
View Source File : PackageRepositoryHelpers.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string PackageInstallUrl(this HtmlHelper html, UrlHelper url, string packageUniqueName)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href)
{
Fragment = packageUniqueName
};
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
View Source File : PackageRepositoryHelpers.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string PackageRepositoryInstallUrl(this HtmlHelper html, UrlHelper url)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href);
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
View Source File : AuthenticationValues.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public virtual void SetAuthParameters(string user, string token)
{
this.AuthParameters = "username=" + Uri.EscapeDataString(user) + "&token=" + Uri.EscapeDataString(token);
}
19
View Source File : CookieService.cs
License : MIT License
Project Creator : agc93
License : MIT License
Project Creator : agc93
public Dictionary<string, string> GetCookies() {
if (Path.HasExtension(_config.Cookies) && File.Exists(_config.Cookies)) {
var ckTxt = File.ReadAllLines(Path.GetFullPath(_config.Cookies));
var ckSet = ParseCookiesTxt(ckTxt);
return ckSet;
} else if (_config.Cookies.StartsWith("{") || _config.Cookies.StartsWith("%7B")) {
//almost certainly a raw sid, we'll replacedume it is
var raw = Uri.UnescapeDataString(_config.Cookies);
return new Dictionary<string, string> {["sid"] = Uri.EscapeDataString(raw)};
} else {
if (_config.Cookies.Contains('\n')) {
var ckSet = ParseCookiesTxt(_config.Cookies.Split('\n'));
return ckSet;
} else {
return _config.Cookies.Split(';').Select(s => s.Trim(' ')).ToDictionary(s => s.Split('=').First(), s => s.Split('=').Last());
}
}
}
19
View Source File : QueryUriBuilder.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public Uri Build()
{
return new UriBuilder(this.SourceUri)
{
Query = string.Join("&", this._queryParams.Select(e => Uri.EscapeDataString(e.Key) + '=' + Uri.EscapeDataString(e.Value)))
}.Uri;
}
19
View Source File : StringOperation.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public static string ToUrlEncoded(this string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return string.Empty;
}
return Uri.EscapeDataString(input);
}
19
View Source File : BlazorGridRequest.cs
License : MIT License
Project Creator : Akinzekeel
License : MIT License
Project Creator : Akinzekeel
public string ToQueryString()
{
var dic = ToDictionary();
var values = dic.Select(x =>
{
var v = x.Value?.ToString();
if (!string.IsNullOrEmpty(v))
v = Uri.EscapeDataString(v);
return x.Key + '=' + v;
});
return string.Join("&", values);
}
19
View Source File : Auth.cs
License : MIT License
Project Creator : AlaricGilbert
License : MIT License
Project Creator : AlaricGilbert
public static async Task Login(string username, string preplacedword)
{
string url = "https://preplacedport.bilibili.com/api/v3/oauth2/login";
var pwd = Uri.EscapeDataString(await EncryptPreplacedword(preplacedword));
string data = $"username={Uri.EscapeDataString(username)}&preplacedword={pwd}&gee_type=10&appkey={Common.AppKey}&mobi_app=android&platform=android&ts={Common.TimeSpan}";
data += "&sign=" + Common.GetSign(data);
using (HttpClient hc = new HttpClient())
{
hc.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 BiliDroid/5.44.2 ([email protected])");
hc.DefaultRequestHeaders.Add("referer", "https://www.bilibili.com/");
var response = await hc.PostAsync(url, new StringContent(data,Encoding.UTF8, "application/x-www-form-urlencoded"));
var result = await response.Content.ReadreplacedtringAsync();
var model = JsonConvert.DeserializeObject<AuthModelV3>(result);
Account.AccessKey = model.data.token_info.access_token;
Account.AuthResultCode = model.code;
await FreshSSO();
}
}
19
View Source File : Resource.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
protected static String EncodeQueryString(IEnumerable<KeyValuePair<string, string>> values)
{
if (values != null)
{
// we are seeing super weird crashes on some iOS devices:
// see 'ForwardGeocodeResource' for more details
var encodedValues = from p in values
#if UNITY_IOS
#if UNITY_2017_1_OR_NEWER
let k = UnityEngine.Networking.UnityWebRequest.EscapeURL(p.Key.Trim())
let v = UnityEngine.Networking.UnityWebRequest.EscapeURL(p.Value)
#else
let k = WWW.EscapeURL(p.Key.Trim())
let v = WWW.EscapeURL(p.Value)
#endif
#else
let k = Uri.EscapeDataString(p.Key.Trim())
let v = Uri.EscapeDataString(p.Value)
#endif
orderby k
select string.IsNullOrEmpty(v) ? k : string.Format("{0}={1}", k, v);
if (encodedValues.Count() == 0)
{
return string.Empty;
}
else
{
return "?" + string.Join(
"&", encodedValues.ToArray());
}
}
return string.Empty;
}
19
View Source File : ForwardGeocodeResource.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public override string GetUrl()
{
Dictionary<string, string> opts = new Dictionary<string, string>();
if (this.Autocomplete != null)
{
opts.Add("autocomplete", this.Autocomplete.ToString().ToLower());
}
if (this.Bbox != null)
{
var nonNullableBbox = (Vector2dBounds)this.Bbox;
opts.Add("bbox", nonNullableBbox.ToString());
}
if (this.Country != null)
{
opts.Add("country", ForwardGeocodeResource.GetUrlQueryFromArray<string>(this.Country));
}
if (this.Proximity != null)
{
var nonNullableProx = (Vector2d)this.Proximity;
opts.Add("proximity", nonNullableProx.ToString());
}
if (this.Types != null)
{
opts.Add("types", GetUrlQueryFromArray(this.Types));
}
// !!!!!!!!!! HACK !!!!!!!
// we are seeing super weird behaviour on some iOS devices:
// crashes with properly escaped whitespaces %20 and commas %2C - and other special characters
// 'NSAllowsArbitraryLoads' and 'NSURLConnection finished with error - code - 1002'
// Use 'CFNETWORK_DIAGNOSTICS=1' in XCode to get more details https://stackoverflow.com/a/46748461
// trying to get rid of at least the most common characters - other will still crash
#if UNITY_IOS
Query = Query
.Replace(",", " ")
.Replace(".", " ")
.Replace("-", " ");
#endif
return
Constants.BaseAPI +
ApiEndpoint +
Mode +
#if UNITY_IOS
#if UNITY_2017_1_OR_NEWER
UnityEngine.Networking.UnityWebRequest.EscapeURL(Query) +
#else
WWW.EscapeURL(Query) +
#endif
#else
Uri.EscapeDataString(Query) +
#endif
".json" +
EncodeQueryString(opts);
}
19
View Source File : MKMAuth.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public string GetAuthorizationHeader(string method, string url)
{
var uri = new Uri(url);
var baseUri = uri.GetLeftPart(UriPartial.Path);
//MessageBox.Show(baseUri);
Dictionary<string, string> headerParams = new Dictionary<string, string>(configHeaderParams)
{
{ "realm", baseUri }
};
/// Start composing the base string from the method and request URI
var baseString = method.ToUpper()
+ "&"
+ Uri.EscapeDataString(baseUri)
+ "&";
var index = url.IndexOf("?");
if (index > 0)
{
var urlParams = url.Substring(index).Remove(0, 1);
var args = ParseQueryString(urlParams);
foreach (var k in args)
{
headerParams.Add(k.Key, k.Value);
}
}
/// Gather, encode, and sort the base string parameters
var encodedParams = new SortedDictionary<string, string>();
foreach (var parameter in headerParams)
{
if (false == parameter.Key.Equals("realm"))
{
encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value));
}
}
/// Expand the base string by the encoded parameter=value pairs
var paramStrings = new List<string>();
foreach (var parameter in encodedParams)
{
paramStrings.Add(parameter.Key + "=" + parameter.Value);
}
var paramString = Uri.EscapeDataString(string.Join<string>("&", paramStrings));
baseString += paramString;
/// Create the OAuth signature
var signatureKey = Uri.EscapeDataString(appSecret) + "&" + Uri.EscapeDataString(accessSecret);
var hasher = HMAC.Create();
hasher.Key = Encoding.UTF8.GetBytes(signatureKey);
var rawSignature = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString));
var oAuthSignature = Convert.ToBase64String(rawSignature);
/// Include the OAuth signature parameter in the header parameters array
headerParams.Add("oauth_signature", oAuthSignature);
/// Construct the header string
var headerParamStrings = new List<string>();
foreach (var parameter in headerParams)
{
headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\"");
}
var authHeader = "OAuth " + string.Join<string>(", ", headerParamStrings);
return authHeader;
}
19
View Source File : ReportForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=hardware&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the hardware report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
View Source File : CrashForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
try {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=crash&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the crash report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} catch {
}
}
19
View Source File : ReportForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=hardware&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the hardware report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
View Source File : CrashForm.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void sendButton_Click(object sender, EventArgs e) {
try {
Version version = typeof(CrashForm).replacedembly.GetName().Version;
WebRequest request = WebRequest.Create(
"http://openhardwaremonitor.org/report.php");
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/x-www-form-urlencoded";
string report =
"type=crash&" +
"version=" + Uri.EscapeDataString(version.ToString()) + "&" +
"report=" + Uri.EscapeDataString(reportTextBox.Text) + "&" +
"comment=" + Uri.EscapeDataString(commentTextBox.Text) + "&" +
"email=" + Uri.EscapeDataString(emailTextBox.Text);
byte[] byteArray = Encoding.UTF8.GetBytes(report);
request.ContentLength = byteArray.Length;
try {
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Close();
} catch (WebException) {
MessageBox.Show("Sending the crash report failed.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} catch {
}
}
19
View Source File : GetRequest.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public GetRequest AddParam(string property, string value)
{
if ((property != null) && (value != null))
{
_params.Add(Uri.EscapeDataString(property), Uri.EscapeDataString(value));
}
return this;
}
19
View Source File : RestRequestBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public RestRequestBuilder AddParam(string property, string value)
{
if ((property != null) && (value != null))
{
_params.Add(Uri.EscapeDataString(property), Uri.EscapeDataString(value));
}
return this;
}
19
View Source File : PrivateUrlBuilder.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string Build(string method, string path, DateTime utcDateTime, GetRequest request)
{
string strDateTime = utcDateTime.ToString("s");
var req = new GetRequest(request)
.AddParam(_aKKey, _aKValue)
.AddParam(_sMKey, _sMVaue)
.AddParam(_sVKey, _sVValue)
.AddParam(_tKey, strDateTime);
string signature = _signer.Sign(method, _host, path, req.BuildParams());
string url = $"https://{_host}{path}?{req.BuildParams()}&Signature={Uri.EscapeDataString(signature)}";
return url;
}
19
View Source File : StsTokenAccessTest.cs
License : MIT License
Project Creator : aliyun
License : MIT License
Project Creator : aliyun
[Fact]
public async Task TestStsTokenAccess()
{
var query = new Dictionary<String, String>
{
{"Action", "replacedumeRole"},
{"RoleArn", replacedumerRoleArn},
{"RoleSessionName", "foo"},
{"Format", "JSON"},
{"Version", "2015-04-01"},
{"AccessKeyId", AccessKeyId},
{"SignatureMethod", "HMAC-SHA1"},
{"SignatureVersion", "1.0"},
{"SignatureNonce", Guid.NewGuid().ToString()},
{"Timestamp", DateTimeOffset.UtcNow.ToString("yyyy-MM-dd\\Thh:mm:ss\\Z")},
};
var canonicalizedQueryString = String.Join("&", query
.Select(x => $"{x.Key}={Uri.EscapeDataString(x.Value)}")
.OrderBy(x => x));
var signSource = $"GET&%2F&{Uri.EscapeDataString(canonicalizedQueryString)}";
var hash = new HMACSHA1(Encoding.UTF8.GetBytes(AccessKey + "&")).ComputeHash(Encoding.UTF8.GetBytes(signSource));
var signature = Convert.ToBase64String(hash);
var httpClient = new HttpClient()
{
BaseAddress = new Uri("https://sts.aliyuncs.com"),
};
var response = await httpClient.GetAsync("/?" + $"{canonicalizedQueryString}&Signature={signature}");
this.output.WriteLine(await response.Content.ReadreplacedtringAsync());
}
19
View Source File : AppBase.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private string GetValidFileName(string fileName)
{
fileName = Uri.EscapeDataString(fileName.AsFileName(false));
return fileName;
}
19
View Source File : ApiClient.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
19
View Source File : AnkhErrorMessage.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public static void SendByMail(string recipient, string subject, Exception ex,
replacedembly replacedembly, StringDictionary additionalInfo)
{
string attributes = GetAttributes(additionalInfo);
StringBuilder msg = new StringBuilder();
msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
msg.AppendLine();
msg.AppendLine(GetMessage(ex));
msg.AppendLine();
msg.AppendLine(GetAttributes(additionalInfo));
msg.AppendLine();
msg.AppendLine("[ Please send this as plain text to allow automatic pre-processing ]");
msg.AppendLine();
string command = string.Format("mailto:{0}?subject={1}&body={2}",
recipient,
Uri.EscapeDataString(subject),
Uri.EscapeDataString(msg.ToString()));
Debug.WriteLine(command);
Process p = new Process();
p.StartInfo.FileName = command;
p.StartInfo.UseShellExecute = true;
p.Start();
}
19
View Source File : AnkhErrorMessage.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private static string GetAttributes(StringDictionary additionalInfo)
{
if (additionalInfo == null)
return "";
StringBuilder builder = new StringBuilder();
foreach (DictionaryEntry de in additionalInfo)
{
builder.AppendFormat("{0}={1}", (string)de.Key, Uri.EscapeDataString((string)de.Value));
builder.AppendLine();
}
return builder.ToString();
}
19
View Source File : SolutionSettings.Commit.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public Uri GetIssueTrackerUri(string issueId)
{
if (issueId == null)
throw new ArgumentNullException("issueId");
if (string.IsNullOrEmpty(issueId))
return null;
RefreshIfDirty();
SettingsCache cache = _cache;
if (cache == null || cache.BugTrackUrl == null)
return null;
string url = cache.BugTrackUrl.Replace("%BUGID%", Uri.EscapeDataString(issueId));
if (url.StartsWith("^/"))
{
Uri repositoryRoot = RepositoryRoot;
if (repositoryRoot == null)
return null;
url = repositoryRoot.AbsoluteUri + url.Substring(2);
}
Uri result;
if (Uri.TryCreate(url, UriKind.Absolute, out result))
return result;
return null;
}
19
View Source File : SolutionSettings.Commit.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public Uri GetRevisionUri(string revisionText)
{
if (revisionText == null)
throw new ArgumentNullException("revisionText");
if (string.IsNullOrEmpty(revisionText))
return null;
RefreshIfDirty();
SettingsCache cache = _cache;
if (cache == null || cache.RevisionUrl == null)
return null;
string url = cache.RevisionUrl.Replace("%REVISION%", Uri.EscapeDataString(revisionText));
if (url.StartsWith("^/"))
{
Uri repositoryRoot = RepositoryRoot;
if (repositoryRoot == null)
return null;
url = repositoryRoot.AbsoluteUri + url.Substring(2);
}
Uri result;
if (Uri.TryCreate(url, UriKind.Absolute, out result))
return result;
return null;
}
19
View Source File : HotReloadClientsHolder.cs
License : MIT License
Project Creator : AndreiMisiukevich
License : MIT License
Project Creator : AndreiMisiukevich
internal async Task UpdateResourceAsync(string pathString, string contentString)
{
var escapedFilePath = Uri.EscapeDataString(pathString);
var data = Encoding.UTF8.GetBytes(contentString);
using (var content = new ByteArrayContent(data))
{
var sendTasks = _addresses
.Select(addr => _client.PostAsync($"{addr}/reload?path={escapedFilePath}", content)).ToArray();
await Task.WhenAll(sendTasks).ConfigureAwait(false);
}
}
See More Examples