Here are the examples of the csharp api System.Net.WebUtility.UrlEncode(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
538 Examples
19
View Source File : GraphApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<PutEdgeDefinitionResponse> PutEdgeDefinitionAsync(
string graphName,
string collectionName,
PutEdgeDefinitionBody body,
PutEdgeDefinitionQuery query = null)
{
string uriString = _graphApiPath + "/" +
WebUtility.UrlEncode(graphName) + "/edge/" +
WebUtility.UrlEncode(collectionName);
if (query != null)
{
uriString += "?" + query.ToQueryString();
}
var content = GetContent(body, new ApiClientSerializationOptions(true, true));
using (var response = await _transport.PutAsync(uriString, content).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<PutEdgeDefinitionResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : GraphApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual Task<PatchEdgeResponse<U>> PatchEdgeAsync<T, U>(
string graphName,
string collectionName,
string edgeKey,
T edge,
PatchEdgeQuery query = null)
{
return PatchEdgeAsync<T, U>(
graphName,
WebUtility.UrlEncode(collectionName) + "/" + WebUtility.UrlEncode(edgeKey),
edge,
query);
}
19
View Source File : GraphApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<PatchEdgeResponse<U>> PatchEdgeAsync<T, U>(
string graphName,
string doreplacedentId,
T edge,
PatchEdgeQuery query = null)
{
ValidateDoreplacedentId(doreplacedentId);
string uri = _graphApiPath + "/" + WebUtility.UrlEncode(graphName) +
"/edge/" + doreplacedentId;
if (query != null)
{
uri += "?" + query.ToQueryString();
}
var content = GetContent(edge, new ApiClientSerializationOptions(true, true));
using (var response = await _transport.PatchAsync(uri, content).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<PatchEdgeResponse<U>>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : GraphApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual Task<PutVertexResponse<T>> PutVertexAsync<T>(
string graphName,
string collectionName,
string key,
T vertex,
PutVertexQuery query = null)
{
return PutVertexAsync<T>(
graphName,
WebUtility.UrlEncode(collectionName) + "/" + WebUtility.UrlEncode(key),
vertex,
query);
}
19
View Source File : GraphApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<PutVertexResponse<T>> PutVertexAsync<T>(
string graphName,
string doreplacedentId,
T vertex,
PutVertexQuery query = null)
{
ValidateDoreplacedentId(doreplacedentId);
string uri = _graphApiPath + "/" + WebUtility.UrlEncode(graphName) +
"/vertex/" + doreplacedentId;
if (query != null)
{
uri += "?" + query.ToQueryString();
}
var content = GetContent(vertex, new ApiClientSerializationOptions(true, true));
using (var response = await _transport.PutAsync(uri, content).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<PutVertexResponse<T>>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<DeleteUserResponse> DeleteUserAsync(string username)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username);
using (var response = await _client.DeleteAsync(uri).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<DeleteUserResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<PutAccessLevelResponse> PutDatabaseAccessLevelAsync(
string username,
string dbName,
PutAccessLevelBody body)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username)
+ "/database/" + WebUtility.UrlEncode(dbName);
var content = GetContent(body, new ApiClientSerializationOptions(true, true));
using (var response = await _client.PutAsync(uri, content).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<PutAccessLevelResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<GetAccessLevelResponse> GetDatabaseAccessLevelAsync(
string username,
string dbName)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username)
+ "/database/" + WebUtility.UrlEncode(dbName);
using (var response = await _client.GetAsync(uri).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<GetAccessLevelResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<DeleteAccessLevelResponse> DeleteDatabaseAccessLevelAsync(
string username,
string dbName)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username)
+ "/database/" + WebUtility.UrlEncode(dbName);
using (var response = await _client.DeleteAsync(uri).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<DeleteAccessLevelResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<GetAccessibleDatabasesResponse> GetAccessibleDatabasesAsync(
string username,
GetAccessibleDatabasesQuery query = null)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username) + "/database";
if (query != null)
{
uri += '?' + query.ToQueryString();
}
using (var response = await _client.GetAsync(uri).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<GetAccessibleDatabasesResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<PutAccessLevelResponse> PutCollectionAccessLevelAsync(
string username,
string dbName,
string collectionName,
PutAccessLevelBody body)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username)
+ "/database/" + WebUtility.UrlEncode(dbName) + "/" +
WebUtility.UrlEncode(collectionName);
var content = GetContent(body, new ApiClientSerializationOptions(true, true));
using (var response = await _client.PutAsync(uri, content).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<PutAccessLevelResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : UserApiClient.cs
License : Apache License 2.0
Project Creator : Actify-Inc
License : Apache License 2.0
Project Creator : Actify-Inc
public virtual async Task<GetAccessLevelResponse> GetCollectionAccessLevelAsync(
string username,
string dbName,
string collectionName)
{
string uri = _userApiPath + "/" + WebUtility.UrlEncode(username)
+ "/database/" + WebUtility.UrlEncode(dbName) + "/" +
WebUtility.UrlEncode(collectionName);
using (var response = await _client.GetAsync(uri).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
return DeserializeJsonFromStream<GetAccessLevelResponse>(stream);
}
throw await GetApiErrorException(response).ConfigureAwait(false);
}
}
19
View Source File : StringFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string UrlEscape(string input)
{
return input == null ? null : WebUtility.UrlEncode(input);
}
19
View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendFormat("{0}:{1}", Host, Port);
var args = new List<string>();
if (Client != null)
args.Add("Client=" + Client);
if (Preplacedword != null)
args.Add("Preplacedword=" + System.Net.WebUtility.UrlEncode(Preplacedword));
if (Db != RedisConfig.DefaultDb)
args.Add("Db=" + Db);
if (Ssl)
args.Add("Ssl=true");
if (ConnectTimeout != RedisConfig.DefaultConnectTimeout)
args.Add("ConnectTimeout=" + ConnectTimeout);
if (SendTimeout != RedisConfig.DefaultSendTimeout)
args.Add("SendTimeout=" + SendTimeout);
if (ReceiveTimeout != RedisConfig.DefaultReceiveTimeout)
args.Add("ReceiveTimeout=" + ReceiveTimeout);
if (RetryTimeout != RedisConfig.DefaultRetryTimeout)
args.Add("RetryTimeout=" + RetryTimeout);
if (IdleTimeOutSecs != RedisConfig.DefaultIdleTimeOutSecs)
args.Add("IdleTimeOutSecs=" + IdleTimeOutSecs);
if (NamespacePrefix != null)
args.Add("NamespacePrefix=" + System.Net.WebUtility.UrlEncode(NamespacePrefix));
if (args.Count > 0)
sb.Append("?").Append(string.Join("&", args));
return sb.ToString();
}
19
View Source File : LavalinkRestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public Task<LavalinkTrack> DecodeTrackAsync(string trackString)
{
var str = WebUtility.UrlEncode(trackString);
var decodeTrackUri = new Uri($"{this.RestEndpoint.ToHttpString()}{Endpoints.DECODE_TRACK}?track={str}");
return this.InternalDecodeTrackAsync(decodeTrackUri);
}
19
View Source File : LavalinkRestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public Task<LavalinkLoadResult> GetTracksAsync(Uri uri)
{
var str = WebUtility.UrlEncode(uri.ToString());
var tracksUri = new Uri($"{this.RestEndpoint.ToHttpString()}{Endpoints.LOAD_TRACKS}?identifier={str}");
return this.InternalResolveTracksAsync(tracksUri);
}
19
View Source File : LavalinkRestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public Task<LavalinkLoadResult> GetTracksAsync(FileInfo file)
{
var str = WebUtility.UrlEncode(file.FullName);
var tracksUri = new Uri($"{this.RestEndpoint.ToHttpString()}{Endpoints.LOAD_TRACKS}?identifier={str}");
return this.InternalResolveTracksAsync(tracksUri);
}
19
View Source File : SmsBaoSmsSender.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public async Task<bool> SendAsync(SmsMessage smsMessage)
{
var client = _clientFactory.CreateClient();
const string requestUriFormat = "https://api.smsbao.com/sms?u={0}&p={1}&m={2}&c={3}";
// 如果需要 %20 转 + , 则用 Uri.EscapeDataString(someString);
var urlEncodedMessage = WebUtility.UrlEncode(smsMessage.Text);
var requestUri = String.Format(requestUriFormat, _smsBaoSmsSettings.Username, _smsBaoSmsSettings.Preplacedword, smsMessage.PhoneNumber, urlEncodedMessage);
try
{
var sendResult = await client.GetStringAsync(requestUri);
var result = sendResult == "0";
if (!result)
{
_logger.LogError("SmsBaoSmsSender 发送短信失败:手机号:{0} 内容:{1} 错误号:{2} 错误消息:{3}", smsMessage.PhoneNumber, smsMessage.Text, sendResult, GetErrorMesssage(sendResult));
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "SmsBao");
return false;
}
}
19
View Source File : LinkAttachmentBaseViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
protected async Task LoadGroupMeInfoAsync()
{
try
{
const string GROUPME_INLINE_URL = "https://inline-downloader.groupme.com/info?url=";
var data = await this.ImageDownloader.DownloadStringDataAsync($"{GROUPME_INLINE_URL}{WebUtility.UrlEncode(this.Url)}");
var results = JsonConvert.DeserializeObject<GroupMeInlineDownloaderInfo>(data);
this.LinkInfo = results;
this.MetadataDownloadCompleted();
}
catch (Exception)
{
this.OnPropertyChanged(string.Empty);
}
}
19
View Source File : LinkAttachmentBaseViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
protected async Task LoadGroupMeInfoAsync()
{
try
{
const string GROUPME_INLINE_URL = "https://inline-downloader.groupme.com/info?url=";
var data = await this.ImageDownloader.DownloadStringDataAsync($"{GROUPME_INLINE_URL}{WebUtility.UrlEncode(this.Url)}");
var results = JsonConvert.DeserializeObject<GroupMeInlineDownloaderInfo>(data);
this.LinkInfo = results;
this.MetadataDownloadCompleted();
}
catch (Exception)
{
this.RaisePropertyChanged(string.Empty);
}
}
19
View Source File : ServerSms.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private string _urlencode(string str) {
if (SmscPost) return str;
return WebUtility.UrlEncode(str);
}
19
View Source File : CollectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static string ToQueryString(this NameValueCollection source)
{
if (source == null)
{
return null;
}
var sb = new StringBuilder(1024);
foreach (var key in source.AllKeys)
{
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
sb.Append("&");
sb.Append(WebUtility.UrlEncode(key));
sb.Append("=");
var val = source.Get(key);
if (val != null)
{
sb.Append(WebUtility.UrlEncode(val));
}
}
return sb.Length > 0 ? sb.ToString(1, sb.Length - 1) : "";
}
19
View Source File : OneDriveClient.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public async Task<string?> LoginAsync(bool interactive)
{
try
{
return await LoginCoreAsync();
}
catch (Exception e)
{
_logger.LogError(e, "failed to login One Drive");
if (interactive)
{
throw;
}
}
return default;
async Task<string?> LoginCoreAsync()
{
var options = _oneDriveOAuthOptions.Value;
var redirectUrl = await _idenreplacedyApi.GetRedirectURL("");
if (_authUrl == null)
{
_authUrl = options.Authority;
var clientId = options.Type == OAuth2ClientType.Dev
? options.DevClientId
: options.ClientId;
_authUrl += $"?client_id={clientId}";
_authUrl += "&response_type=token";
_authUrl += $"&redirect_uri={WebUtility.UrlEncode(redirectUrl)}";
_authUrl += $"&scope={WebUtility.UrlEncode(string.Join(" ", options.DefaultScopes))}";
}
var callbackUrl = await _idenreplacedyApi.LaunchWebAuthFlow(new LaunchWebAuthFlowDetails
{
Interactive = interactive,
Url = new HttpURL(_authUrl)
});
var token = callbackUrl.Split("#")[1].Split("&")[0].Split("=")[1];
LoadToken(token);
_logger.LogInformation("OneDrive login success");
return token;
}
}
19
View Source File : OneDriveClient.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public async Task<string?> LoginAsync(bool interactive)
{
try
{
return await LoginCoreAsync();
}
catch (Exception e)
{
_logger.LogError(e, "failed to login One Drive");
if (interactive)
{
throw;
}
}
return default;
async Task<string?> LoginCoreAsync()
{
var options = _oneDriveOAuthOptions.Value;
var redirectUrl = await _idenreplacedyApi.GetRedirectURL("");
if (_authUrl == null)
{
_authUrl = options.Authority;
var clientId = options.Type == OAuth2ClientType.Dev
? options.DevClientId
: options.ClientId;
_authUrl += $"?client_id={clientId}";
_authUrl += "&response_type=token";
_authUrl += $"&redirect_uri={WebUtility.UrlEncode(redirectUrl)}";
_authUrl += $"&scope={WebUtility.UrlEncode(string.Join(" ", options.DefaultScopes))}";
}
var callbackUrl = await _idenreplacedyApi.LaunchWebAuthFlow(new LaunchWebAuthFlowDetails
{
Interactive = interactive,
Url = new HttpURL(_authUrl)
});
var token = callbackUrl.Split("#")[1].Split("&")[0].Split("=")[1];
LoadToken(token);
_logger.LogInformation("OneDrive login success");
return token;
}
}
19
View Source File : GoogleDriveClient.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public async Task<string?> LoginAsync(bool interactive)
{
try
{
return await LoginCoreAsync();
}
catch (Exception e)
{
_logger.LogError(e, "failed to login Google Drive");
if (interactive)
{
throw;
}
}
return default;
async Task<string?> LoginCoreAsync()
{
var options = _googleDriveOauthOptions.Value;
var redirectUrl = await _idenreplacedyApi.GetRedirectURL("");
if (_authUrl == null)
{
_authUrl = "https://accounts.google.com/o/oauth2/auth";
var clientId = options.Type == OAuth2ClientType.Dev
? options.DevClientId
: options.ClientId;
_authUrl += $"?client_id={clientId}";
_authUrl += "&response_type=token";
_authUrl += $"&redirect_uri={WebUtility.UrlEncode(redirectUrl)}";
_authUrl += $"&scope={WebUtility.UrlEncode(string.Join(" ", options.Scopes))}";
}
var callbackUrl = await _idenreplacedyApi.LaunchWebAuthFlow(new LaunchWebAuthFlowDetails
{
Interactive = interactive,
Url = new HttpURL(_authUrl)
});
var token = callbackUrl.Split("#")[1].Split("&")[0].Split("=")[1];
LoadToken(token);
_logger.LogInformation("Google Drive login success");
return token;
}
}
19
View Source File : GoogleDriveClient.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public async Task<string?> LoginAsync(bool interactive)
{
try
{
return await LoginCoreAsync();
}
catch (Exception e)
{
_logger.LogError(e, "failed to login Google Drive");
if (interactive)
{
throw;
}
}
return default;
async Task<string?> LoginCoreAsync()
{
var options = _googleDriveOauthOptions.Value;
var redirectUrl = await _idenreplacedyApi.GetRedirectURL("");
if (_authUrl == null)
{
_authUrl = "https://accounts.google.com/o/oauth2/auth";
var clientId = options.Type == OAuth2ClientType.Dev
? options.DevClientId
: options.ClientId;
_authUrl += $"?client_id={clientId}";
_authUrl += "&response_type=token";
_authUrl += $"&redirect_uri={WebUtility.UrlEncode(redirectUrl)}";
_authUrl += $"&scope={WebUtility.UrlEncode(string.Join(" ", options.Scopes))}";
}
var callbackUrl = await _idenreplacedyApi.LaunchWebAuthFlow(new LaunchWebAuthFlowDetails
{
Interactive = interactive,
Url = new HttpURL(_authUrl)
});
var token = callbackUrl.Split("#")[1].Split("&")[0].Split("=")[1];
LoadToken(token);
_logger.LogInformation("Google Drive login success");
return token;
}
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : AndrewButenko
License : MIT License
Project Creator : AndrewButenko
public static string UrlEncode(this Dictionary<string, object> parameters)
{
return string.Join("&", parameters.Select(x => $"{x.Key}={WebUtility.UrlEncode(x.Value.ToString())}"));
}
19
View Source File : UrlHelperExtensions.cs
License : GNU General Public License v3.0
Project Creator : andysal
License : GNU General Public License v3.0
Project Creator : andysal
public static string Beautify(this UrlHelper helper, string url)
{
string beautifiedUrl = Beautify(url);
return System.Net.WebUtility.UrlEncode(url);
}
19
View Source File : AuthorizeRequest.cs
License : MIT License
Project Creator : anjoy8
License : MIT License
Project Creator : anjoy8
public string Create(IDictionary<string, string> values)
{
var queryString = string.Join("&", values.Select(kvp => string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray());
return string.Format("{0}?{1}", _authorizeEndpoint.AbsoluteUri, queryString);
}
19
View Source File : IdentityService.cs
License : MIT License
Project Creator : anjoy8
License : MIT License
Project Creator : anjoy8
public async Task<UserToken> GetTokenAsync(string code)
{
string data = string.Format("grant_type=authorization_code&code={0}&redirect_uri={1}&code_verifier={2}", code, WebUtility.UrlEncode(GlobalSetting.Instance.Callback), _codeVerifier);
var token = await _requestProvider.PostAsync<UserToken>(GlobalSetting.Instance.TokenEndpoint, data, GlobalSetting.Instance.ClientId, GlobalSetting.Instance.ClientSecret);
return token;
}
19
View Source File : JenkinsBuild.cs
License : GNU Affero General Public License v3.0
Project Creator : AnyStatus
License : GNU Affero General Public License v3.0
Project Creator : AnyStatus
private Uri GetApiUri(JenkinsBuild build)
{
var relativeUri = new StringBuilder();
relativeUri.Append("buildWithParameters?delay=0sec");
if (build.BuildParameters != null && build.BuildParameters.Any())
{
foreach (var parameter in build.BuildParameters)
{
if (parameter == null ||
string.IsNullOrWhiteSpace(parameter.Name) ||
string.IsNullOrWhiteSpace(parameter.Value))
continue;
relativeUri.Append("&");
relativeUri.Append(WebUtility.UrlEncode(parameter.Name));
relativeUri.Append("=");
relativeUri.Append(WebUtility.UrlEncode(parameter.Value));
}
}
var baseUri = new Uri(build.Url);
return new Uri(baseUri, relativeUri.ToString());
}
19
View Source File : ControllerApi.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public string GetAPMServiceEndpoints(string applicationName, string tierName)
{
return this.apiGET(String.Format("controller/rest/applications/{0}/metrics?metric-path=Service Endpoints|{1}&time-range-type=BEFORE_NOW&duration-in-mins=15&output=JSON", applicationName, WebUtility.UrlEncode(tierName)), "application/json", false);
}
19
View Source File : ControllerApi.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public string GetAPMErrors(string applicationName, string tierName)
{
return this.apiGET(String.Format("controller/rest/applications/{0}/metrics?metric-path=Errors|{1}&time-range-type=BEFORE_NOW&duration-in-mins=15&output=JSON", applicationName, WebUtility.UrlEncode(tierName)), "application/json", false);
}
19
View Source File : ControllerApi.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public string GetMetricData(string applicationNameOrID, string metricPath, long startTimeInUnixEpochFormat, long endTimeInUnixEpochFormat, bool rollup)
{
return this.apiGET(
String.Format("controller/rest/applications/{0}/metric-data?metric-path={1}&time-range-type=BETWEEN_TIMES&start-time={2}&end-time={3}&rollup={4}&output=JSON",
applicationNameOrID,
WebUtility.UrlEncode(metricPath),
startTimeInUnixEpochFormat,
endTimeInUnixEpochFormat,
rollup),
"application/json",
false);
}
19
View Source File : Best2Pay.cs
License : Apache License 2.0
Project Creator : AppRopio
License : Apache License 2.0
Project Creator : AppRopio
private string Encode(string to)
{
string requestString = System.Net.WebUtility.UrlEncode(to);
requestString = requestString.Replace("%3D", "=");
requestString = requestString.Replace("%26", "&");
return requestString;
}
19
View Source File : Utilities.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
public static async Task<string> TranslateText(string inputText, string language)
{
string accessToken = await GetAuthenticationToken(Constants.TranslationAPIKey);
string url = "http://api.microsofttranslator.com/v2/Http.svc/Translate";
string query = $"?text={System.Net.WebUtility.UrlEncode(inputText)}&to={language}&contentType=text/plain";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await client.GetAsync(url + query);
var result = await response.Content.ReadreplacedtringAsync();
if (!response.IsSuccessStatusCode)
return "Failed: " + result;
var translatedText = XElement.Parse(result).Value;
return translatedText;
}
}
19
View Source File : Auth0AccessTokenJwtEvents.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public override async Task TokenValidated(TokenValidatedContext ctx)
{
var cache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
var jwt = (ctx.SecurityToken as JwtSecurityToken);
var token = jwt.RawData;
var cacheKey = $"auth0:userInfo:{token}";
var cid = ctx.Principal.Idenreplacedy as ClaimsIdenreplacedy;
if (_shouldGetRoles() && !_isUnattendedClient(cid))
{
CacheEntry cacheEntry = null;
var res = await cache.GetStringAsync(cacheKey);
if (res == null)
{
var t1 = cache.SetStringAsync(cacheKey, "Pending", new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
});
var userInfo = await _auth0.GetUserInfoAsync(token);
var policyPayload = jwt.Claims.FirstOrDefault(x => x.Type == Auth0ClaimTypes.PolicyPostPayload)?.Value;
if (userInfo != null)
{
cacheEntry = new CacheEntry
{
UserInfo = userInfo
};
if (policyPayload != null)
{
var authzToken = await _getAuthzToken(cache);
var url = $"{_authzApiUrl}/api/users/{WebUtility.UrlEncode(userInfo.UserId)}/policy/{WebUtility.UrlEncode(_clientId)}";
using (var client = new HttpClient())
using (var req = new HttpRequestMessage(HttpMethod.Post, url))
{
req.Content = new StringContent(policyPayload, Encoding.UTF8, "application/json");
req.Headers.Add("Authorization", "Bearer " + authzToken);
var policyRes = await client.SendAsync(req);
if (policyRes.IsSuccessStatusCode)
{
var policyJson = await policyRes.Content.ReadreplacedtringAsync();
var policy = JsonConvert.DeserializeObject<PolicyResult>(policyJson);
if (policy != null)
{
cacheEntry.Policy = policy;
}
else
{
cacheEntry = null;
}
}
else
{
cacheEntry = null;
}
}
}
}
await t1;
if (cacheEntry != null)
{
await cache.SetStringAsync(cacheKey, JsonConvert.SerializeObject(cacheEntry), new DistributedCacheEntryOptions
{
AbsoluteExpiration = jwt.ValidTo - TimeSpan.FromMinutes(2)
});
} else
{
await cache.RemoveAsync(cacheKey);
}
}
else if (res == "Pending")
{
res = await Policy.HandleResult<string>(r => r == "Pending")
.WaitAndRetryForeverAsync(x => TimeSpan.FromMilliseconds(100)) // Actually cannot be greater than 5sec as key would expire returning null
.ExecuteAsync(() => cache.GetStringAsync(cacheKey))
;
}
if (res != null)
{
cacheEntry = JsonConvert.DeserializeObject<CacheEntry>(res);
}
if (cacheEntry != null)
_convertUserToClaims(cid, cacheEntry);
}
// if the idenreplacedy still doesn't have a name (unattended client) add a name == nameidentifier for logging/metrics purporse
if (string.IsNullOrWhiteSpace(cid.Name))
{
cid.AddClaim(new Claim(cid.NameClaimType, jwt.Subject));
}
var scopes = cid.FindFirst(c => c.Type == "scope" && c.Issuer == _issuer)?.Value?.Split(' ');
if (scopes != null)
cid.AddClaims(scopes.Select(r => new Claim(Auth0ClaimTypes.Scope, r, ClaimValueTypes.String, _issuer)));
//if (ctx.Options.SaveToken)
// cid.AddClaim(new Claim("id_token", token, ClaimValueTypes.String, "Auth0"));
await base.TokenValidated(ctx);
}
19
View Source File : Auth0AccessTokenJwtEvents.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public override async Task TokenValidated(TokenValidatedContext ctx)
{
var cache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
var jwt = (ctx.SecurityToken as JwtSecurityToken);
var token = jwt.RawData;
var cacheKey = $"auth0:userInfo:{token}";
var cid = ctx.Principal.Idenreplacedy as ClaimsIdenreplacedy;
if (_shouldGetRoles() && !_isUnattendedClient(cid))
{
CacheEntry cacheEntry = null;
var res = await cache.GetStringAsync(cacheKey);
if (res == null)
{
var t1 = cache.SetStringAsync(cacheKey, "Pending", new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
});
var userInfo = await _auth0.GetUserInfoAsync(token);
var policyPayload = jwt.Claims.FirstOrDefault(x => x.Type == Auth0ClaimTypes.PolicyPostPayload)?.Value;
if (userInfo != null)
{
cacheEntry = new CacheEntry
{
UserInfo = userInfo
};
if (policyPayload != null)
{
var authzToken = await _getAuthzToken(cache);
var url = $"{_authzApiUrl}/api/users/{WebUtility.UrlEncode(userInfo.UserId)}/policy/{WebUtility.UrlEncode(_clientId)}";
using (var client = new HttpClient())
using (var req = new HttpRequestMessage(HttpMethod.Post, url))
{
req.Content = new StringContent(policyPayload, Encoding.UTF8, "application/json");
req.Headers.Add("Authorization", "Bearer " + authzToken);
var policyRes = await client.SendAsync(req);
if (policyRes.IsSuccessStatusCode)
{
var policyJson = await policyRes.Content.ReadreplacedtringAsync();
var policy = JsonConvert.DeserializeObject<PolicyResult>(policyJson);
if (policy != null)
{
cacheEntry.Policy = policy;
}
else
{
cacheEntry = null;
}
}
else
{
cacheEntry = null;
}
}
}
}
await t1;
if (cacheEntry != null)
{
await cache.SetStringAsync(cacheKey, JsonConvert.SerializeObject(cacheEntry), new DistributedCacheEntryOptions
{
AbsoluteExpiration = jwt.ValidTo - TimeSpan.FromMinutes(2)
});
} else
{
await cache.RemoveAsync(cacheKey);
}
}
else if (res == "Pending")
{
res = await Policy.HandleResult<string>(r => r == "Pending")
.WaitAndRetryForeverAsync(x => TimeSpan.FromMilliseconds(100)) // Actually cannot be greater than 5sec as key would expire returning null
.ExecuteAsync(() => cache.GetStringAsync(cacheKey))
;
}
if (res != null)
{
cacheEntry = JsonConvert.DeserializeObject<CacheEntry>(res);
}
if (cacheEntry != null)
_convertUserToClaims(cid, cacheEntry);
}
// if the idenreplacedy still doesn't have a name (unattended client) add a name == nameidentifier for logging/metrics purporse
if (string.IsNullOrWhiteSpace(cid.Name))
{
cid.AddClaim(new Claim(cid.NameClaimType, jwt.Subject));
}
var scopes = cid.FindFirst(c => c.Type == "scope" && c.Issuer == _issuer)?.Value?.Split(' ');
if (scopes != null)
cid.AddClaims(scopes.Select(r => new Claim(Auth0ClaimTypes.Scope, r, ClaimValueTypes.String, _issuer)));
//if (ctx.Options.SaveToken)
// cid.AddClaim(new Claim("id_token", token, ClaimValueTypes.String, "Auth0"));
await base.TokenValidated(ctx);
}
19
View Source File : UsageClient.cs
License : MIT License
Project Creator : arminreiter
License : MIT License
Project Creator : arminreiter
public UsageData Get(DateTime startDate, DateTime endDate, AggregationGranularity granularity, bool showDetails, string token)
{
if (startDate >= endDate)
throw new ArgumentException("Start date must be before the end date!");
if (endDate >= DateTime.Now.AddHours(-1))
{
endDate = DateTime.Now.AddHours(-1).ToUniversalTime();
}
DateTimeOffset startTime = new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0, DateTimeKind.Utc);
DateTimeOffset endTime = new DateTime(endDate.Year, endDate.Month, endDate.Day, 0, 0, 0, DateTimeKind.Utc);
if (granularity == AggregationGranularity.Hourly)
{
startTime = startTime.AddHours(startDate.Hour);
endTime = endTime.AddHours(endDate.Hour);
}
string st = WebUtility.UrlEncode(startTime.ToString("yyyy-MM-ddTHH:mm:sszzz"));
string et = WebUtility.UrlEncode(endTime.ToString("yyyy-MM-ddTHH:mm:sszzz"));
string url = $"https://management.azure.com/subscriptions/{SubscriptionId}/providers/Microsoft.Commerce/UsageAggregates?api-version={APIVERSION}&reportedStartTime={st}&reportedEndTime={et}&aggregationGranularity={granularity.ToString()}&showDetails={showDetails.ToString().ToLower()}";
string data = GetData(url, token);
if (String.IsNullOrEmpty(data))
return null;
var usageData = JsonConvert.DeserializeObject<UsageData>(data);
// read data from the usagedata api as long as the continuationtoken is set.
// usage data api returns 1000 values per api call, to receive all values,
// we have to call the url stored in nextLink property.
while (!String.IsNullOrEmpty(usageData.NextLink))
{
string next = GetData(usageData.NextLink, token);
var nextUsageData = JsonConvert.DeserializeObject<UsageData>(next);
usageData.Values.AddRange(nextUsageData.Values);
usageData.NextLink = nextUsageData.NextLink;
}
return usageData;
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : arqueror
License : MIT License
Project Creator : arqueror
public static string UrlEncode(this string url)
{
return WebUtility.UrlEncode(url);
}
19
View Source File : Authentication.cs
License : GNU General Public License v3.0
Project Creator : Artentus
License : GNU General Public License v3.0
Project Creator : Artentus
public async static Task<(string username, string token)> LogInAsync(string username, string preplacedword)
{
string username_enc = WebUtility.UrlEncode(username);
string preplacedword_enc = WebUtility.UrlEncode(preplacedword);
string contentString = $"api_version=2&require_game_ownership=true&username={username_enc}&preplacedword={preplacedword_enc}";
var content = Encoding.UTF8.GetBytes(contentString);
try
{
string doreplacedent = await WebHelper.RequestDoreplacedentAsync(LogInUrl, content);
dynamic response = JsonConvert.DeserializeObject(doreplacedent)!;
return (response.username, response.token);
}
catch (WebException ex)
{
throw ApiException.FromWebException(ex);
}
}
19
View Source File : Options.xaml.cs
License : MIT License
Project Creator : Assistant
License : MIT License
Project Creator : Assistant
private async Task UploadLog()
{
const string DateFormat = "yyyy-mm-dd HH:mm:ss";
DateTime now = DateTime.Now;
string logPath = Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);
string Log = Path.Combine(logPath, "log.log");
string GameLog = File.ReadAllText(Path.Combine(InstallDirectory, "Logs", "_latest.log"));
string Separator = File.Exists(Log) ? $"\n\n=============================================\n============= Mod replacedistant Log =============\n=============================================\n\n" : string.Empty;
string ModreplacedistantLog = File.Exists(Log) ? File.ReadAllText(Log) : string.Empty;
var nvc = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("replacedle", $"_latest.log ({now.ToString(DateFormat)})"),
new KeyValuePair<string, string>("expireUnit", "hour"),
new KeyValuePair<string, string>("expireLength", "5"),
new KeyValuePair<string, string>("code", $"{GameLog}{Separator}{ModreplacedistantLog}"),
};
string[] items = new string[nvc.Count];
for (int i = 0; i < nvc.Count; i++)
{
KeyValuePair<string, string> item = nvc[i];
items[i] = WebUtility.UrlEncode(item.Key) + "=" + WebUtility.UrlEncode(item.Value);
}
StringContent content = new StringContent(string.Join("&", items), null, "application/x-www-form-urlencoded");
HttpResponseMessage resp = await Http.HttpClient.PostAsync(Utils.Constants.TeknikAPIUrl + "Paste", content);
string body = await resp.Content.ReadreplacedtringAsync();
Utils.TeknikPasteResponse TeknikResponse = Http.JsonSerializer.Deserialize<Utils.TeknikPasteResponse>(body);
LogURL = TeknikResponse.result.url;
}
19
View Source File : TextUtility.cs
License : Apache License 2.0
Project Creator : authlete
License : Apache License 2.0
Project Creator : authlete
public static string UrlEncode(string plainText)
{
if (plainText == null)
{
return null;
}
// Convert the plain text into a URL-encoded string.
return WebUtility.UrlEncode(plainText);
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : AvapiDotNet
License : MIT License
Project Creator : AvapiDotNet
internal static string AsQueryString(IDictionary<string, string> parameters)
{
if (!parameters.Any())
return "";
var builder = new StringBuilder("?");
var separator = "";
foreach (var kvp in parameters.Where(kvp => kvp.Value != null))
{
builder.AppendFormat("{0}{1}={2}", separator, WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value.ToString()));
separator = "&";
}
return builder.ToString();
}
19
View Source File : AuthenticationHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : aweber
License : BSD 3-Clause "New" or "Revised" License
Project Creator : aweber
public AuthorizationUrl CreateAuthorizationUrl(IList<string> scopes, string clientId)
{
var state = CreateStateTokenForOAuth();
var url = string.Format(
"{0}/authorize?response_type={1}&client_id={2}&redirect_uri={3}&scope={4}&state={5}",
_oauthUri,
Code,
clientId,
WebUtility.UrlEncode(_redirectUri),
WebUtility.UrlEncode(string.Join(" ", scopes)),
state);
return new AuthorizationUrl {Url = url, State = state};
}
19
View Source File : Post.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public string GetEncodedLink() => $"/blog/{System.Net.WebUtility.UrlEncode(this.Slug)}/";
19
View Source File : DbfsApiClient.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public async Task<FileInfo> GetStatus(string path, CancellationToken cancellationToken = default)
{
var encodedPath = WebUtility.UrlEncode(path);
var url = $"dbfs/get-status?path={encodedPath}";
var result = await HttpGet<FileInfo>(this.HttpClient, url, cancellationToken).ConfigureAwait(false);
return result;
}
19
View Source File : DbfsApiClient.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public async Task<IEnumerable<FileInfo>> List(string path, CancellationToken cancellationToken = default)
{
var encodedPath = WebUtility.UrlEncode(path);
var url = $"dbfs/list?path={encodedPath}";
var result = await HttpGet<dynamic>(this.HttpClient, url, cancellationToken).ConfigureAwait(false);
return PropertyExists(result, "files")
? result.files.ToObject<IEnumerable<FileInfo>>()
: Enumerable.Empty<FileInfo>();
}
19
View Source File : DbfsApiClient.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public async Task<FileReadBlock> Read(string path, long offset, long length, CancellationToken cancellationToken = default)
{
var encodedPath = WebUtility.UrlEncode(path);
var url = $"dbfs/read?path={encodedPath}&offset={offset}&length={length}";
var result = await HttpGet<FileReadBlock>(this.HttpClient, url, cancellationToken).ConfigureAwait(false);
return result;
}
19
View Source File : EasyAuthTokenClient.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public async Task RefreshToken(JwtSecurityToken jwt, TokenBaseAttribute attribute)
{
if (string.IsNullOrEmpty(attribute.Resource))
{
throw new ArgumentException("A resource is required to renew an access token.");
}
if (string.IsNullOrEmpty(attribute.UserId))
{
throw new ArgumentException("A userId is required to renew an access token.");
}
if (string.IsNullOrEmpty(attribute.IdenreplacedyProvider))
{
throw new ArgumentException("A provider is necessary to renew an access token.");
}
string refreshUrl = $"https://{_options.HostName}/.auth/refresh?resource=" + WebUtility.UrlEncode(attribute.Resource);
using (var refreshRequest = new HttpRequestMessage(HttpMethod.Get, refreshUrl))
{
refreshRequest.Headers.Add("x-zumo-auth", jwt.RawData);
_log.LogTrace($"Refreshing ${attribute.IdenreplacedyProvider} access token for user ${attribute.UserId} at ${refreshUrl}");
using (HttpResponseMessage response = await _httpClient.SendAsync(refreshRequest))
{
_log.LogTrace($"Response from ${refreshUrl}: {response.StatusCode}");
if (!response.IsSuccessStatusCode)
{
string errorResponse = await response.Content.ReadreplacedtringAsync();
throw new InvalidOperationException($"Failed to refresh {attribute.UserId} {attribute.IdenreplacedyProvider} error={response.StatusCode} {errorResponse}");
}
}
}
}
See More Examples