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 : ImmortalSeed.cs
License : GNU General Public License v3.0
Project Creator : Prowlarr
License : GNU General Public License v3.0
Project Creator : Prowlarr
private IEnumerable<IndexerRequest> GetPagedRequests(string term, int[] categories, string imdbId = null)
{
var searchUrl = Settings.BaseUrl + "browse.php";
if (term.IsNotNullOrWhiteSpace())
{
searchUrl += string.Format("?do=search&keywords={0}&search_type=t_name&category=0&include_dead_torrents=no", WebUtility.UrlEncode(term));
}
if (categories != null && categories.Length > 0)
{
searchUrl += "&selectedcats2=" + string.Join(",", Capabilities.Categories.MapTorznabCapsToTrackers(categories));
}
var request = new IndexerRequest(searchUrl, HttpAccept.Html);
yield return request;
}
19
View Source File : TorrentLeech.cs
License : GNU General Public License v3.0
Project Creator : Prowlarr
License : GNU General Public License v3.0
Project Creator : Prowlarr
private IEnumerable<IndexerRequest> GetPagedRequests(string term, int[] categories, string imdbId = null)
{
var searchString = Regex.Replace(term, @"(^|\s)-", " ");
var searchUrl = Settings.BaseUrl + "torrents/browse/list/";
if (Settings.FreeLeechOnly)
{
searchUrl += "facets/tags%3AFREELEECH/";
}
if (imdbId.IsNotNullOrWhiteSpace())
{
searchUrl += "imdbID/" + imdbId + "/";
}
else if (!string.IsNullOrWhiteSpace(searchString))
{
searchUrl += "exact/1/query/" + WebUtility.UrlEncode(searchString) + "/";
}
var cats = Capabilities.Categories.MapTorznabCapsToTrackers(categories);
if (cats.Count > 0)
{
searchUrl += "categories/" + string.Join(",", cats);
}
else
{
searchUrl += "newfilter/2"; // include 0day and music
}
var request = new IndexerRequest(searchUrl, HttpAccept.Rss);
yield return request;
}
19
View Source File : HttpServerUtility.cs
License : MIT License
Project Creator : purestackorg
License : MIT License
Project Creator : purestackorg
public string UrlEncode(string s)
{
return System.Net.WebUtility.UrlEncode(s);
}
19
View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : ramtinak
License : MIT License
Project Creator : ramtinak
public static string AsQueryString(this Dictionary<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));
separator = "&";
}
return builder.ToString();
}
19
View Source File : ExtensionHelper.cs
License : MIT License
Project Creator : ramtinak
License : MIT License
Project Creator : ramtinak
public static string EncodeUri(this string data)
{
return System.Net.WebUtility.UrlEncode(data);
}
19
View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : RatScanner
License : GNU General Public License v3.0
Project Creator : RatScanner
private static void CreateGitHubIssue(string message, Exception e)
{
var body = "**Error**\n" + message + "\n";
if (e != null) body += "```\n" + LimitLength(e.ToString(), 1000) + "\n```\n";
body += "<details>\n<summary>Log</summary>\n\n```\n";
body += LimitLength(ReadAll(), 3000);
body += "\n```\n</details>";
var replacedle = message;
var labels = "bug";
var url = ApiManager.GetResource(ApiManager.ResourceType.GithubLink);
url += "/issues/new";
url += "?body=" + WebUtility.UrlEncode(body);
url += "&replacedle=" + WebUtility.UrlEncode(replacedle);
url += "&labels=" + WebUtility.UrlEncode(labels);
OpenURL(url);
}
19
View Source File : PageService.cs
License : Apache License 2.0
Project Creator : rayrfan
License : Apache License 2.0
Project Creator : rayrfan
public async Task<Page> GetAsync(params string[] slugs)
{
if (slugs == null || slugs.Length <= 0)
{
throw new ArgumentNullException(nameof(slugs));
}
if (slugs[0] == "preview")
{
throw new FanException(EExceptionType.ResourceNotFound);
}
// caching
var key = GetCacheKey(WebUtility.UrlEncode(slugs[0]));
var time = BlogCache.Time_ParentPage;
if (slugs.Length > 1 && !slugs[1].IsNullOrEmpty()) // child page
{
key = GetCacheKey(slugs[0], slugs[1]);
time = BlogCache.Time_ChildPage;
}
return await cache.GetAsync(key, time, async () =>
{
var parents = await GetParentsAsync(withChildren: true);
// find slugs[0], throw if not found or draft, url encode takes care of url with foreign chars
var page = parents.SingleOrDefault(p => p.Slug.Equals(WebUtility.UrlEncode(slugs[0]), StringComparison.CurrentCultureIgnoreCase));
if (page == null || page.Status == EPostStatus.Draft)
{
throw new FanException(EExceptionType.ResourceNotFound);
}
// page requested is a child, throw if not found or draft
if (page.IsParent && slugs.Length > 1 && !slugs[1].IsNullOrEmpty())
{
var child = page.Children.SingleOrDefault(p => p.Slug.Equals(WebUtility.UrlEncode(slugs[1]), StringComparison.CurrentCultureIgnoreCase));
if (child == null || child.Status == EPostStatus.Draft)
{
throw new FanException(EExceptionType.ResourceNotFound);
}
page = child;
}
return page;
});
}
19
View Source File : PageService.cs
License : Apache License 2.0
Project Creator : rayrfan
License : Apache License 2.0
Project Creator : rayrfan
public static string SlugifyPagereplacedle(string replacedle)
{
if (replacedle.IsNullOrEmpty()) return replacedle;
var slug = Util.Slugify(replacedle, maxlen: PostreplacedleValidator.replacedLE_MAXLEN);
if (slug.IsNullOrEmpty())
{
slug = WebUtility.UrlEncode(replacedle);
if (slug.Length > PostreplacedleValidator.replacedLE_MAXLEN)
{
slug = slug.Substring(0, PostreplacedleValidator.replacedLE_MAXLEN);
}
}
return slug;
}
19
View Source File : BlogController.cs
License : Apache License 2.0
Project Creator : rayrfan
License : Apache License 2.0
Project Creator : rayrfan
[ModelPreRender]
public IActionResult PreviewPage(string parentSlug, string childSlug)
{
try
{
// slugs coming in are not url encoded, encode them for the key to tempdata
if (!parentSlug.IsNullOrEmpty()) parentSlug = WebUtility.UrlEncode(parentSlug);
if (!childSlug.IsNullOrEmpty()) childSlug = WebUtility.UrlEncode(childSlug);
var key = BlogRoutes.GetPagePreviewRelativeLink(parentSlug, childSlug);
var pageVM = TempData.Get<PageVM>(key);
return pageVM == null ? View("404") : View("Page", pageVM);
}
catch (Exception)
{
// when user access the preview link directly or when user clicks on other links
// and navigates away during the preview, hacky need to find a better way.
return RedirectToAction("ErrorCode", "Home", new { statusCode = 404 });
}
}
19
View Source File : PageServiceTest.cs
License : Apache License 2.0
Project Creator : rayrfan
License : Apache License 2.0
Project Creator : rayrfan
[Fact]
public void Page_with_Chinese_replacedle_produces_UrlEncoded_slug_which_may_get_trimmed()
{
// Given a page replacedle of 30 Chinese chars, which will translate into a slug over 250
// chars due to url encoding
var pagereplacedle = string.Join("", Enumerable.Repeat<char>('验', 30));
var page = new Page
{
replacedle = pagereplacedle,
};
// When the replacedle is processed, I expect the slug to be 250 char as follows
// '验' -> "%E9%AA%8C" 9 chars, 27 * 9 + 7 = 250
var expectedSlug = WebUtility.UrlEncode(string.Join("", Enumerable.Repeat<char>('验', 27))) + "%E9%AA%";
replacedert.Equal(250, expectedSlug.Length);
// Then the slug comes out to be 250 long
replacedert.Equal(expectedSlug, PageService.SlugifyPagereplacedle(page.replacedle));
}
19
View Source File : PageServiceTest.cs
License : Apache License 2.0
Project Creator : rayrfan
License : Apache License 2.0
Project Creator : rayrfan
[Fact]
public async void Page_replacedle_resulting_duplicate_slug_throws_FanException()
{
// Given a post slug with max length of 250 chars
var slug = WebUtility.UrlEncode(string.Join("", Enumerable.Repeat<char>('验', 27))) + "%E9%AA%";
IList<Post> list = new List<Post> {
new Post { Slug = slug, Type = EPostType.Page, Id = 1 },
};
postRepoMock.Setup(repo => repo.GetListAsync(It.IsAny<PostListQuery>())).Returns(Task.FromResult((list, 1)));
// When create/update a page replacedle that conflits the existing slug
// Then you get FanException
var givenreplacedle = string.Join("", Enumerable.Repeat<char>('验', 30));
var page = new Page { replacedle = givenreplacedle };
var slug2 = PageService.SlugifyPagereplacedle(page.replacedle);
await replacedert.ThrowsAsync<FanException>(() => pageService.EnsurePageSlugAsync(slug2, page));
}
19
View Source File : ServerDetailsWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : Razzmatazzz
License : GNU General Public License v3.0
Project Creator : Razzmatazzz
private void menuConnectCheckExternal_Click(object sender, RoutedEventArgs e)
{
//Process.Start("cmd", $"/C start https://southnode.net/form_get.php?ip={_externalIP}");
Process.Start("cmd", $"/C start https://geekstrom.de/valheim/check/?host={WebUtility.UrlEncode($"{ValheimServer.ExternalIP}:{Server.Port + 1}")}");
}
19
View Source File : Response.cs
License : MIT License
Project Creator : RedHttp
License : MIT License
Project Creator : RedHttp
public async Task<HandlerType> SendFile(string filePath, string? contentType = null, bool handleRanges = true,
string? fileName = null, HttpStatusCode status = HttpStatusCode.OK)
{
if (handleRanges) Headers["Accept-Ranges"] = "bytes";
var fileSize = new FileInfo(filePath).Length;
var range = Context.AspNetContext.Request.GetTypedHeaders().Range;
var encodedFilename = WebUtility.UrlEncode(fileName ?? Path.GetFileName(filePath));
Headers["Content-disposition"] = $"inline; filename=\"{encodedFilename}\"";
if (range != null && range.Ranges.Any())
{
var firstRange = range.Ranges.First();
if (range.Unit != "bytes" || !firstRange.From.HasValue && !firstRange.To.HasValue)
{
await SendStatus(HttpStatusCode.BadRequest);
return HandlerType.Error;
}
var offset = firstRange.From ?? fileSize - firstRange.To ?? 0;
var length = firstRange.To.HasValue
? fileSize - offset - (fileSize - firstRange.To.Value)
: fileSize - offset;
AspNetResponse.StatusCode = (int) HttpStatusCode.PartialContent;
AspNetResponse.ContentType = Handlers.GetMimeType(contentType, filePath);
AspNetResponse.ContentLength = length;
Headers["Content-Range"] = $"bytes {offset}-{offset + length - 1}/{fileSize}";
await AspNetResponse.SendFileAsync(filePath, offset, length, Aborted);
}
else
{
AspNetResponse.StatusCode = (int) status;
AspNetResponse.ContentType = Handlers.GetMimeType(contentType, filePath);
AspNetResponse.ContentLength = fileSize;
await AspNetResponse.SendFileAsync(filePath, Aborted);
}
return HandlerType.Final;
}
19
View Source File : XamarinAuthMiddleware.cs
License : MIT License
Project Creator : Redth
License : MIT License
Project Creator : Redth
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.HasValue && context.Request.Path.StartsWithSegments(new PathString(options.AuthPath)))
{
// Get the scheme being used
var path = context.Request.Path.Value;
var scheme = path.Substring(path.LastIndexOf('/')).Trim('/');
var auth = await context.AuthenticateAsync(scheme);
if (!auth.Succeeded || auth?.Principal == null || !auth.Principal.Idenreplacedies.Any(id => id.IsAuthenticated))
{
// Not authenticated, challenge
await context.ChallengeAsync(scheme);
}
else
{
// Parse out items to send back to app
var refresh = auth.Properties.GetTokenValue("refresh_token");
var access = auth.Properties.GetTokenValue("access_token");
long expires = -1;
if (auth.Properties.ExpiresUtc.HasValue)
expires = auth.Properties.ExpiresUtc.Value.ToUnixTimeSeconds();
if (string.IsNullOrEmpty(access))
{
// No access token, challenge
await context.ChallengeAsync(scheme);
}
else
{
var qs = new Dictionary<string, string>();
qs.Add("access_token", access);
if (!string.IsNullOrEmpty(refresh))
qs.Add("refresh_token", refresh);
if (expires >= 0)
qs.Add("expires_in", expires.ToString());
// Give the consumer of the library a chance to change the parameters
if (options.AuthenticatedRedirectHandler != null)
options.AuthenticatedRedirectHandler.Invoke(context, auth, qs);
var sep = options.UseUrlFragmentForRedirectParameters ? "#" : "?";
// Build the result url
var url = options.CallbackUri.ToString()
+ sep + string.Join("&", qs.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
// Redirect to final url
context.Response.Redirect(url);
}
}
}
else
{
// Not us to handle, call the next delegate/middleware in the pipeline
await _next(context);
}
}
19
View Source File : WebUtils.shared.cs
License : MIT License
Project Creator : Redth
License : MIT License
Project Creator : Redth
public static string ToQueryString(this Dictionary<string, string> items)
{
var r = new StringBuilder();
foreach (var i in items)
{
r.Append(System.Net.WebUtility.UrlEncode(i.Key));
r.Append("=");
r.Append(System.Net.WebUtility.UrlEncode(i.Value));
r.Append("&");
}
return "?" + r.ToString().TrimEnd('&');
}
19
View Source File : AppleSignInClient.cs
License : MIT License
Project Creator : Redth
License : MIT License
Project Creator : Redth
public virtual Uri GenerateAuthorizationUrl()
{
var respType = "code";
var p = new Dictionary<string, string>
{
{ "response_type", respType },
{ "response_mode", "form_post" },
{ "client_id", ServerId },
{ "redirect_uri", RedirectUri.OriginalString },
{ "nonce", Nonce },
{ "state", State },
{ "scope", "name email" }
};
var qs = string.Empty;
foreach (var i in p)
qs += WebUtility.UrlEncode(i.Key) + "=" + WebUtility.UrlEncode(i.Value) + "&";
return new Uri(AppleAuthorizationUrl + "?" + qs.TrimEnd('&'));
}
19
View Source File : UrlHelperExtensions.cs
License : MIT License
Project Creator : RemiBou
License : MIT License
Project Creator : RemiBou
public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
{
ActionContext actionContext = urlHelper.ActionContext;
Microsoft.AspNetCore.Http.HttpContext httpContext = actionContext.HttpContext;
Microsoft.AspNetCore.Http.HttpRequest request = httpContext.Request;
var host = request.Host;
var ub = new UriBuilder(scheme, host.Host)
{
Path = $"account/confirmationEmail/{WebUtility.UrlEncode(userId)}/{WebUtility.UrlEncode(code)}",
Port = host.Port.GetValueOrDefault(80)
};
return ub.ToString();
}
19
View Source File : UrlHelperExtensions.cs
License : MIT License
Project Creator : RemiBou
License : MIT License
Project Creator : RemiBou
public static string ResetPreplacedwordCallbackLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
{
var host = urlHelper.ActionContext.HttpContext.Request.Host;
var ub = new UriBuilder(scheme, host.Host)
{
Path = $"account/resetPreplacedword/{WebUtility.UrlEncode(userId)}/{WebUtility.UrlEncode(code)}",
Port = host.Port.GetValueOrDefault(80)
};
return ub.ToString();
}
19
View Source File : CallsService.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public async Task<string> GetShortenedAudioUrlAsync(int callId, int callAttachmentId)
{
try
{
if (callAttachmentId > 0)
{
var encryptedQuery =
WebUtility.UrlEncode(SymmetricEncryption.Encrypt(callAttachmentId.ToString(), Config.SystemBehaviorConfig.ExternalAudioUrlParamPreplacedhprase));
string shortenedUrl =
await _shortenUrlProvider.Shorten(
$"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/v3/calls/getcallaudio?query={encryptedQuery}");
if (String.IsNullOrWhiteSpace(shortenedUrl))
return String.Empty;
return shortenedUrl;
}
else
{
var attachment = await
_callAttachmentRepository.GetCallAttachmentByCallIdAndTypeAsync(callId, CallAttachmentTypes.DispatchAudio);
if (attachment == null)
return String.Empty;
var encryptedQuery =
WebUtility.UrlEncode(SymmetricEncryption.Encrypt(attachment.CallAttachmentId.ToString(), Config.SystemBehaviorConfig.ExternalAudioUrlParamPreplacedhprase));
string shortenedUrl =
await _shortenUrlProvider.Shorten(
$"{Config.SystemBehaviorConfig.ResgridApiBaseUrl}/api/v3/calls/getcallaudio?query={encryptedQuery}");
if (String.IsNullOrWhiteSpace(shortenedUrl))
return String.Empty;
return shortenedUrl;
}
}
catch (Exception ex)
{
Logging.LogException(ex);
return String.Empty;
}
}
19
View Source File : CallsService.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public async Task<string> GetShortenedCallLinkUrl(int callId, bool pdf = false, int? stationId = null)
{
try
{
string encryptedQuery = "";
if (!stationId.HasValue && !pdf)
{
encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt(callId.ToString(), Config.SystemBehaviorConfig.ExternalLinkUrlParamPreplacedphrase));
}
else
{
string type = pdf ? "pdf" : "web";
string station = stationId.HasValue ? stationId.Value.ToString() : "0";
encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt($"{callId.ToString()}|${type}|${station}", Config.SystemBehaviorConfig.ExternalLinkUrlParamPreplacedphrase));
}
string shortenedUrl =
await _shortenUrlProvider.Shorten(
$"{Config.SystemBehaviorConfig.ResgridBaseUrl}/User/Dispatch/CallExportEx?query={encryptedQuery}");
if (String.IsNullOrWhiteSpace(shortenedUrl))
return String.Empty;
return shortenedUrl;
}
catch (Exception ex)
{
Logging.LogException(ex);
return String.Empty;
}
}
19
View Source File : CallsService.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public string GetCallPdfUrl(int callId, bool pdf = false, int? stationId = null)
{
try
{
string encryptedQuery = "";
if (!stationId.HasValue && !pdf)
{
encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt(callId.ToString(), Config.SystemBehaviorConfig.ExternalLinkUrlParamPreplacedphrase));
}
else
{
string type = pdf ? "pdf" : "web";
string station = stationId.HasValue ? stationId.Value.ToString() : "0";
encryptedQuery = WebUtility.UrlEncode(SymmetricEncryption.Encrypt($"{callId.ToString()}|{type}|{station}", Config.SystemBehaviorConfig.ExternalLinkUrlParamPreplacedphrase));
}
return $"{Config.SystemBehaviorConfig.ResgridBaseUrl}/User/Dispatch/CallExportPdf?query={encryptedQuery}";
}
catch (Exception ex)
{
Logging.LogException(ex);
return String.Empty;
}
}
19
View Source File : GeoLocationProvider.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public Coordinates GetLatLonFromAddressLocationIQ(string address)
{
Coordinates coordinates = new Coordinates();
try
{
var client = new RestClient("http://locationiq.org");
var request = new RestRequest($"/v1/search.php?key={Config.MappingConfig.LocationIQApiKey}&format=json&q={WebUtility.UrlEncode(address)}", Method.GET);
var response = client.Execute<dynamic>(request);
if (response.IsSuccessful && response.Data != null)
{
var geocode = response.Data[0];
double lareplacedude = 0;
double longitude = 0;
if (double.TryParse(geocode["lat"], out lareplacedude) &&
double.TryParse(geocode["lon"], out longitude))
{
coordinates.Lareplacedude = lareplacedude;
coordinates.Longitude = longitude;
return coordinates;
}
}
}
catch { }
return null;
}
19
View Source File : GeoLocationProvider.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public string GetAddressFromLatLonLocationIQ(string lat, string lon)
{
try
{
var client = new RestClient("http://locationiq.org");
var request = new RestRequest($"/v1/reverse.php?key={Config.MappingConfig.LocationIQApiKey}&format=json&lat={WebUtility.UrlEncode(lat)}&lon={WebUtility.UrlEncode(lon)}&zoom=18", Method.GET);
var response = client.Execute<dynamic>(request);
if (response.Data != null)
{
var geocode = response.Data[0];
return geocode["display_name"];
}
}
catch { }
return null;
}
19
View Source File : ShortenUrlProvider.cs
License : Apache License 2.0
Project Creator : Resgrid
License : Apache License 2.0
Project Creator : Resgrid
public async Task<string> Shorten(string long_url)
{
if (Config.SystemBehaviorConfig.LinkProviderType == Config.LinksProviderTypes.Bitly)
{
if (await CheckAccessToken())
{
using (HttpClient client = new HttpClient())
{
string temp = string.Format(Config.LinksConfig.BitlyApi, ACCESS_TOKEN, WebUtility.UrlEncode(long_url));
var res = await client.GetAsync(temp);
if (res.IsSuccessStatusCode)
{
var message = await res.Content.ReadreplacedtringAsync();
dynamic obj = JsonConvert.DeserializeObject(message);
return obj.results[long_url].shortUrl;
}
else
{
return "Can not short URL";
}
}
}
else
{
return "Can not short URL";
}
}
else if (Config.SystemBehaviorConfig.LinkProviderType == Config.LinksProviderTypes.Polr)
{
using (HttpClient client = new HttpClient())
{
string temp = string.Format(Config.LinksConfig.PolrApi, Config.LinksConfig.PolrAccessToken, WebUtility.UrlEncode(long_url));
var res = await client.GetAsync(temp);
if (res.IsSuccessStatusCode)
{
var message = await res.Content.ReadreplacedtringAsync();
return message.Trim();
}
else
{
return "Can not short URL";
}
}
}
return "Can not short URL";
}
19
View Source File : RemoteViewModel.cs
License : MIT License
Project Creator : rremote
License : MIT License
Project Creator : rremote
public async Task PressKeyboardKey(string key)
{
var prefix = "";
if (key.Length == 1)
prefix = "Lit_";
await RokuClient.PressKey(SelectedDevice.Endpoint, prefix + WebUtility.UrlEncode(key));
}
19
View Source File : SignalRPersistentConnectionSyncApiClient.cs
License : Apache License 2.0
Project Creator : Rubius
License : Apache License 2.0
Project Creator : Rubius
private async Task Reconnect()
{
try
{
if (IsConnected)
{
IsConnected = false;
OnConnectedStateChanged();
}
Logger.Info("Reconnect started");
_hubUnsubscribe();
_hubUnsubscribe = () => { };
var parameters = GetParameters(Uri);
parameters[Constants.LastDownloadParameterName] =
WebUtility.UrlEncode(
JsonConvert.SerializeObject(_startOptions.LastDownloaded ??
new Dictionary<string, DateTimeOffset>()));
parameters[Constants.SyncTypesParameterName] = string.Join(",", _startOptions.Types);
var connectionUri = Uri.ToString();
if (!string.IsNullOrEmpty(Uri.Query))
{
connectionUri = connectionUri.Replace(Uri.Query, string.Empty);
}
var connection = new Connection(connectionUri, parameters);
_connection = connection;
_connection.Received += ConnectionOnReceived;
_hubUnsubscribe += () =>
{
_connection.Received -= ConnectionOnReceived;
_connection?.Dispose();
};
Logger.Info(
$" --Connections configured, connecting to {connectionUri}?{string.Join("&", parameters.Select(x => x.Key + "=" + x.Value))}");
await _connection.Start();
Logger.Info(" --Connected");
OnConnected();
Logger.Info("OnConnected finished");
}
catch (Exception ex)
{
if (ex is HttpRequestException ||
ex is WebException ||
ex is HttpClientException ||
ex is TimeoutException ||
ex is StartException ||
ex is ObjectDisposedException)
{
LogAndReconnectWithDelay(ex);
return;
}
Logger.Info($"Unknown error in Reconnect! Stop Reconnections!!! {ex}");
#if DEBUG
throw;
#endif
}
}
19
View Source File : SignalRSyncApiClient.cs
License : Apache License 2.0
Project Creator : Rubius
License : Apache License 2.0
Project Creator : Rubius
private async Task Reconnect()
{
try
{
if (IsConnected)
{
IsConnected = false;
OnConnectedStateChanged();
}
Logger.Info("Reconnect started");
_hubUnsubscribe();
_hubUnsubscribe = () => { };
var parameters = GetParameters(Uri);
parameters[Constants.LastDownloadParameterName] =
WebUtility.UrlEncode(JsonConvert.SerializeObject(_startOptions.LastDownloaded ?? new Dictionary<string, DateTimeOffset>()));
parameters[Constants.SyncTypesParameterName] = string.Join(",", _startOptions.Types);
var connectionUri = Uri.ToString();
if (!string.IsNullOrEmpty(Uri.Query))
{
connectionUri = connectionUri.Replace(Uri.Query, "");
}
var hubConnection = new HubConnection(connectionUri, parameters);
_hubConnection = hubConnection;
_hubProxy = _hubConnection.CreateHubProxy(HubName);
_downloadHandler = _hubProxy.On<DownloadDataResponse>("DataDownloaded", OnNewDataDownloaded);
_unauthorizedHandler = _hubProxy.On<UnauthorizedResponse>("Unauthorized", OnUnauthorized);
_hubUnsubscribe += () =>
{
_downloadHandler?.Dispose();
_unauthorizedHandler?.Dispose();
_hubConnection?.Dispose();
};
Logger.Info(
$" --Connections configured, connecting to {Uri}?{string.Join("&", parameters.Select(x => x.Key + "=" + x.Value))}");
await _hubConnection.Start();
Logger.Info(" --Connected");
OnConnected();
Logger.Info("OnConnected finished");
}
catch (HttpRequestException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (WebException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (HttpClientException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (TimeoutException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (StartException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (ObjectDisposedException webEx)
{
LogAndReconnectWithDelay(webEx);
}
catch (Exception ex)
{
Logger.Info($"Unknown error in Reconnect! Stop Reconnections!!! {ex}");
#if DEBUG
throw;
#endif
}
}
19
View Source File : RideRecap.cs
License : MIT License
Project Creator : ruffk
License : MIT License
Project Creator : ruffk
private void RideRecap_Load(object sender, EventArgs e)
{
/*
#000001 BackColor
#000002 ActiveFormBorderColor
#000003 ForeColor
#000004 ActivereplacedleGradientEnd
*/
MSoffice2010ColorManager colorTable = ZAMappearance.GetColorTable();
this.pControls.BackColor = colorTable.FormBackground;
this.pControls.ForeColor = colorTable.FormTextColor;
this.toolStrip.BackColor = colorTable.FormBackground;
string styleSheet = Properties.Resources.StyleSheet;
styleSheet = styleSheet.Replace("000001", $"{colorTable.FormBackground.R:X2}{ colorTable.FormBackground.G:X2}{ colorTable.FormBackground.B:X2}");
styleSheet = styleSheet.Replace("000002", $"{colorTable.ActiveFormBorderColor.R:X2}{ colorTable.ActiveFormBorderColor.G:X2}{ colorTable.ActiveFormBorderColor.B:X2}");
styleSheet = styleSheet.Replace("000003", $"{colorTable.FormTextColor.R:X2}{ colorTable.FormTextColor.G:X2}{ colorTable.FormTextColor.B:X2}");
styleSheet = styleSheet.Replace("000004", $"{colorTable.ActivereplacedleGradientEnd.R:X2}{ colorTable.ActivereplacedleGradientEnd.G:X2}{ colorTable.ActivereplacedleGradientEnd.B:X2}");
mRideRecapHtml = Properties.Resources.RideRecap;
StringBuilder xAxis = new StringBuilder("");
StringBuilder yAxis = new StringBuilder("");
if (this.mRideRecapMetrics.Power.Length > 0)
{
foreach (var power in this.mRideRecapMetrics.Power)
{
xAxis.Append($"'{DurationEnum.Instance.GetText(power.DurationType)}',");
yAxis.Append($"{power.APwattsMax},");
}
}
else
{
// no power values, build an empty chart
foreach(var item in DurationEnum.Instance.GetValues())
{
xAxis.Append($"'{item}',");
}
}
string chartDef = "{type:'line',data:{labels:[xAxisValues],datasets:[{fill:true,lineTension:0,backgroundColor:'#000004',borderColor:'#000002',data:[yAxisValues],}]},options:{legend:{display:false},replacedle:{display:true,text:'Peak Power',fontSize:20,fontFamily:'Segoe UI, sans-serif',fontColor:'#000003',},scales:{yAxes:[{ticks:{fontFamily:'Segoe UI, sans-serif',fontColor: '#000003'},scaleLabel:{display:true,labelString:'Watts',fontSize:16,fontFamily:'Segoe UI, sans-serif',fontColor:'#000003',},gridLines:{display:false,}}],xAxes:[{ticks:{fontFamily:'Segoe UI, sans-serif',fontColor: '#000003'},scaleLabel:{display:false,labelString:'Time',fontSize:16,fontFamily:'Segoe UI, sans-serif',fontColor:'#000003',},gridLines:{display:false,}}],}}}";
chartDef = chartDef.Replace("xAxisValues", xAxis.ToString());
chartDef = chartDef.Replace("yAxisValues", yAxis.ToString());
// Define and encode the chart URL
string urlStr = WebUtility.UrlEncode(chartDef);
Debug.WriteLine(urlStr);
mRideRecapHtml = mRideRecapHtml.Replace("EncodedChartUrl", urlStr);
mRideRecapHtml = mRideRecapHtml.Replace("000001", $"{colorTable.FormBackground.R:X2}{ colorTable.FormBackground.G:X2}{ colorTable.FormBackground.B:X2}");
mRideRecapHtml = mRideRecapHtml.Replace("000002", $"{colorTable.ActiveFormBorderColor.R:X2}{ colorTable.ActiveFormBorderColor.G:X2}{ colorTable.ActiveFormBorderColor.B:X2}");
mRideRecapHtml = mRideRecapHtml.Replace("000003", $"{colorTable.FormTextColor.R:X2}{ colorTable.FormTextColor.G:X2}{ colorTable.FormTextColor.B:X2}");
mRideRecapHtml = mRideRecapHtml.Replace("000004", $"{colorTable.ActivereplacedleGradientEnd.R:X2}{ colorTable.ActivereplacedleGradientEnd.G:X2}{ colorTable.ActivereplacedleGradientEnd.B:X2}");
//public TimeSpan Duration { get; set; }
//public double DistanceKm { get; set; }
//public double DistanceMi { get; set; }
//public double AverageKph { get; set; }
//public double AverageMph { get; set; }
//public int APwatts { get; set; }
//public double? APwattsPerKg { get; set; }
//public int NPwatts { get; set; }
//public double? NPwattsPerKg { get; set; }
//public double? IntensityFactor { get; set; } // null if FTP not set
//public int? TrainingStressScore { get; set; } // null if FTP not set
mRideRecapHtml = mRideRecapHtml.Replace("Duration", $"{this.mRideRecapMetrics.Duration.ToString("hh\\:mm\\:ss")}");
mRideRecapHtml = mRideRecapHtml.Replace("DistanceKm", $"{this.mRideRecapMetrics.DistanceKm:0.0}");
mRideRecapHtml = mRideRecapHtml.Replace("DistanceMi", $"{this.mRideRecapMetrics.DistanceMi:0.0}");
mRideRecapHtml = mRideRecapHtml.Replace("AverageKph", $"{this.mRideRecapMetrics.AverageKph:0.0}");
mRideRecapHtml = mRideRecapHtml.Replace("AverageMph", $"{this.mRideRecapMetrics.AverageMph:0.0}");
mRideRecapHtml = mRideRecapHtml.Replace("APwattsPerKg", $"{(this.mRideRecapMetrics.APwattsPerKg.HasValue ? this.mRideRecapMetrics.APwattsPerKg.Value.ToString("0.00") + " w/kg" : "")}");
mRideRecapHtml = mRideRecapHtml.Replace("APwatts", $"{this.mRideRecapMetrics.APwatts}");
mRideRecapHtml = mRideRecapHtml.Replace("NPwattsPerKg", $"{(this.mRideRecapMetrics.NPwattsPerKg.HasValue ? this.mRideRecapMetrics.NPwattsPerKg.Value.ToString("0.00") + " w/kg" : "")}");
mRideRecapHtml = mRideRecapHtml.Replace("NPwatts", $"{this.mRideRecapMetrics.NPwatts}");
mRideRecapHtml = mRideRecapHtml.Replace("IntensityFactor", $"{(this.mRideRecapMetrics.IntensityFactor.HasValue ? this.mRideRecapMetrics.IntensityFactor.Value.ToString(".00") : "")}");
mRideRecapHtml = mRideRecapHtml.Replace("TrainingStressScore", $"{(this.mRideRecapMetrics.TrainingStressScore.HasValue ? this.mRideRecapMetrics.TrainingStressScore.Value : "")}");
mRideRecapHtml = mRideRecapHtml.Replace("WorkKiloJoules", $"{this.mRideRecapMetrics.KiloJoules}");
StringBuilder powerStr = new StringBuilder("");
foreach (var power in this.mRideRecapMetrics.Power)
{
powerStr.AppendLine("<tr>");
powerStr.AppendLine($"<td>{DurationEnum.Instance.GetText(power.DurationType)}</td>");
powerStr.AppendLine($"<td>{power.APwattsMax}</td>");
powerStr.AppendLine($"<td>{(power.APwattsKgMax.HasValue ? power.APwattsKgMax.Value.ToString("0.00") : "")}</td>");
powerStr.AppendLine("</tr>");
}
mRideRecapHtml = mRideRecapHtml.Replace("RideRecapPower", powerStr.ToString());
/*
<tr>
<td>1</td>
<td>1:45:43</td>
<td>34.5 km/h (25.3 mi/h)</td>
<td>21.0 km (18.3 mi)</td>
<td>245 (3.2 w/kg)</td>
<td>05:45:43</td>
</tr>
*/
StringBuilder lapStr = new StringBuilder("");
foreach (var lap in this.mRideRecapMetrics.Laps)
{
lapStr.AppendLine("<tr>");
lapStr.AppendLine($"<td>{lap.LapNumber}</td>");
lapStr.AppendLine($"<td>{lap.LapTime.ToString("hh\\:mm\\:ss")}</td>");
lapStr.AppendLine($"<td>{lap.LapSpeedKph:0.0} km/h ({lap.LapSpeedMph:0.0} mi/h)</td>");
lapStr.AppendLine($"<td>{lap.LapDistanceKm:0.0} km ({lap.LapDistanceMi:0.0} mi)</td>");
lapStr.AppendLine($"<td>{lap.LapAPwatts} w{(lap.LapAPwattsPerKg.HasValue ? " (" + lap.LapAPwattsPerKg.Value.ToString("0.00") + " w/kg)" : "")}</td>");
lapStr.AppendLine($"<td>{lap.TotalTime.ToString("hh\\:mm\\:ss")}</td>");
lapStr.AppendLine("</tr>");
}
mRideRecapHtml = mRideRecapHtml.Replace("RideRecapLaps", lapStr.ToString());
/*
<tr>
<td>1</td>
<td>1:45:43</td>
<td>34.5 km/h (25.3 mi/h)</td>
<td>21.0 km (18.3 mi)</td>
<td>05:45:43</td>
<td>-01:43</td>
</tr>
*/
StringBuilder splitStr = new StringBuilder("");
foreach (var split in this.mRideRecapMetrics.Splits)
{
string delta;
//string deltaColorCode;
if (split.DeltaTime.HasValue)
{
TimeSpan std = (TimeSpan)split.DeltaTime;
bool negated = false;
if (std.TotalSeconds < 0)
{
std = std.Negate();
negated = true;
}
delta = $"{(negated ? "-" : "+")}{(std.Minutes > 0 ? std.ToString("m'@QT's'\"'").Replace("@QT", "\'") : std.ToString("s'\"'"))}";
//deltaColorCode = negated ? "00C000" : "C00000";
}
else
{
delta = "No Goal";
}
splitStr.AppendLine("<tr>");
splitStr.AppendLine($"<td>{split.SplitNumber}</td>");
splitStr.AppendLine($"<td>{split.SplitTime.ToString("hh\\:mm\\:ss")}</td>");
splitStr.AppendLine($"<td>{split.SplitSpeedKph:0.0} km/h ({split.SplitSpeedMph:0.0} mi/h)</td>");
splitStr.AppendLine($"<td>{split.SplitDistanceKm:0.0} km ({split.SplitDistanceMi:0.0} mi)</td>");
splitStr.AppendLine($"<td>{split.TotalTime.ToString("hh\\:mm\\:ss")}</td>");
splitStr.AppendLine($"<td>{delta}</td>");
splitStr.AppendLine("</tr>");
}
mRideRecapHtml = mRideRecapHtml.Replace("RideRecapSplits", splitStr.ToString());
Logger.LogDebug($"{this.GetType()}::RideRecap_Load - \n{mRideRecapHtml}");
this.webBrowser.BrowserControl.DoreplacedentText = styleSheet + mRideRecapHtml;
tsbEmail.ToolTipText = this.CurrentUserProfile.EmailAddress.Length > 0 ? "MailTo:" + this.CurrentUserProfile.EmailAddress : "Please set email address in your user profile to use this feature.";
}
19
View Source File : Engine.FormSubmit.cs
License : MIT License
Project Creator : RusKnyaz
License : MIT License
Project Creator : RusKnyaz
private async void OnFormSubmit(HtmlFormElement form, HtmlElement submitElement)
{
var method = form.Method;
var action = form.Action;
var enctype = form.Enctype;
var target = form.Target;
if (submitElement is HtmlButtonElement button)
{
if (!string.IsNullOrEmpty(button.FormMethod))
method = button.FormMethod;
if (!string.IsNullOrEmpty(button.FormAction))
action = button.FormAction;
if (!string.IsNullOrEmpty(button.FormEnctype))
enctype = button.FormEnctype;
if (!string.IsNullOrEmpty(button.FormTarget))
target = button.FormTarget;
}
if (string.IsNullOrEmpty(action))
return;
var dataElements = form.Elements.OfType<IFormElement>()
.Where(x =>
!string.IsNullOrEmpty(x.Name)
&& !(x is HtmlInputElement input && input.Type == "checkbox" && !input.Checked) //skip unchecked checkboxes
&& !x.Disabled);
var replaceSpaces = method != "post" || enctype != "multipart/form-data";
var data = string.Empty;
if (method == "get")
{
data = string.Join("&", dataElements.Select(x =>
x.Name + "=" + (GetValue(x) is string strValue ? (replaceSpaces ? strValue.Replace(' ', '+') : strValue) : "")
));
if (enctype == "application/x-www-form-urlencoded")
{
data = System.Uri.EscapeUriString(data);
}
}
else if(method == "post")
{
if (enctype == "application/x-www-form-urlencoded")
{
data = string.Join("&", dataElements.Select(x =>
x.Name + "=" + (GetValue(x) is string strValue ? WebUtility.UrlEncode(strValue).Replace("!", "%21") : "")
));
}
else if (enctype == "text/plain")
{
data = string.Concat(dataElements.Select(x => (x.Name + "=" + (GetValue(x) ?? "")) + "\r\n"));
}
else
{
throw new NotImplementedException("multipart-form-data form encryption type is not supported");
}
}
var isGet = method == "get";
var url = isGet
? action.Split('?')[0] + (string.IsNullOrEmpty(data) ? "" : "?"+data)
: action;
if (action != "about:blank")
{
HtmlDoreplacedent doreplacedent;
HtmlIFrameElement targetFrame;
if (!string.IsNullOrEmpty(form.Target) &&
(targetFrame = Doreplacedent.GetElementsByName(target).FirstOrDefault() as HtmlIFrameElement) != null)
{
doreplacedent = targetFrame.ContentDoreplacedent = new HtmlDoreplacedent(Window);
}
else
{
ResetDoreplacedent(true);
doreplacedent = Doreplacedent;
}
var request = CreateRequest(url);
if (!isGet)
{
//todo: use right encoding and enctype
request.Method = "POST";
request.Data = Encoding.UTF8.GetBytes(data);
request.Headers["Content-Type"] = enctype;
}
var response = await ResourceProvider.SendRequestAsync(request);
//what should we do if the frame is not found?
if (response != null && (response.Type == null || response.Type.StartsWith(ResourceTypes.Html)))
{
LoadFromResponse(doreplacedent, response);
}
}
//todo: handle 'about:blank'
}
19
View Source File : OcelotSwaggerMiddleware.cs
License : MIT License
Project Creator : Rwing
License : MIT License
Project Creator : Rwing
public async Task InvokeAsync(HttpContext httpContext)
{
var path = httpContext.Request.Path.Value;
string cacheEntry = null;
string cacheKey = null;
if (this._options.Cache?.Enabled == true)
{
cacheKey = this._options.Cache.KeyPrefix + WebUtility.UrlEncode(path);
cacheEntry = await this._cache.GetStringAsync(cacheKey);
}
if (cacheEntry != null)
{
CachedPathTemplate[] templates;
using (var jsonReader = new JsonTextReader(new StringReader(cacheEntry)))
{
templates = JsonConvert.DeserializeObject<CachedPathTemplate[]>(cacheEntry);
}
var newContent = await this.ReadContentAsync(httpContext);
newContent = templates.Aggregate(
newContent,
(current, template) => current.Replace(
template.DownstreamPathTemplate,
template.UpstreamPathTemplate));
await this.WriteContentAsync(httpContext, newContent);
}
else if (this._options.SwaggerEndPoints.Exists(i => i.Url == path))
{
var ocelotConfig = this._internalConfiguration.Get().Data;
var matchedReRoute = (from i in ocelotConfig.ReRoutes
from j in i.DownstreamReRoute
where j.UpstreamPathTemplate.OriginalValue.Equals(
path,
StringComparison.OrdinalIgnoreCase)
select j).ToList();
if (matchedReRoute.Count > 0)
{
var matchedHost = matchedReRoute.First().DownstreamAddresses.First();
var anotherReRoutes = (from i in ocelotConfig.ReRoutes
from j in i.DownstreamReRoute
where j.DownstreamAddresses.Exists(
k => k.Host == matchedHost.Host && k.Port == matchedHost.Port)
select j).ToList();
var templates = this._options.Cache?.Enabled == true
? new List<CachedPathTemplate>(anotherReRoutes.Count)
: null;
var newContent = await this.ReadContentAsync(httpContext);
foreach (var downstreamReRoute in anotherReRoutes)
{
var newDownstreamPathTemplate = PathTemplateRegex.Replace(
downstreamReRoute.DownstreamPathTemplate.Value,
string.Empty);
var newUpstreamPathTemplate = PathTemplateRegex.Replace(
downstreamReRoute.UpstreamPathTemplate.OriginalValue,
string.Empty);
templates?.Add(new CachedPathTemplate(newDownstreamPathTemplate, newUpstreamPathTemplate));
newContent = newContent.Replace(newDownstreamPathTemplate, newUpstreamPathTemplate);
}
if (this._options.Cache?.Enabled == true)
{
await Task.WhenAll(
this._cache.SetStringAsync(
cacheKey,
JsonConvert.SerializeObject(templates),
new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromSeconds(
this._options.Cache.SlidingExpirationInSeconds)
}),
this.WriteContentAsync(httpContext, newContent));
}
else
{
await this.WriteContentAsync(httpContext, newContent);
}
}
}
else
{
await this._next(httpContext);
}
}
19
View Source File : RedumpWebClient.cs
License : GNU General Public License v3.0
Project Creator : SabreTools
License : GNU General Public License v3.0
Project Creator : SabreTools
public bool? Login(string username, string preplacedword)
{
// Credentials verification
if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(preplacedword))
{
Console.WriteLine("Credentials entered, will attempt Redump login...");
}
else if (!string.IsNullOrWhiteSpace(username) && string.IsNullOrWhiteSpace(preplacedword))
{
Console.WriteLine("Only a username was specified, will not attempt Redump login...");
return false;
}
else if (string.IsNullOrWhiteSpace(username))
{
Console.WriteLine("No credentials entered, will not attempt Redump login...");
return false;
}
// HTTP encode the preplacedword
preplacedword = WebUtility.UrlEncode(preplacedword);
// Attempt to login up to 3 times
for (int i = 0; i < 3; i++)
{
try
{
// Get the current token from the login page
var loginPage = DownloadString(Constants.LoginUrl);
string token = Constants.TokenRegex.Match(loginPage).Groups[1].Value;
// Construct the login request
Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
Encoding = Encoding.UTF8;
var response = UploadString(Constants.LoginUrl, $"form_sent=1&redirect_url=&csrf_token={token}&req_username={username}&req_preplacedword={preplacedword}&save_preplaced=0");
if (response.Contains("Incorrect username and/or preplacedword."))
{
Console.WriteLine("Invalid credentials entered, continuing without logging in...");
return false;
}
// The user was able to be logged in
Console.WriteLine("Credentials accepted! Logged into Redump...");
LoggedIn = true;
// If the user is a moderator or staff, set accordingly
if (response.Contains("http://forum.redump.org/forum/9/staff/"))
IsStaff = true;
return true;
}
catch (Exception ex)
{
Console.WriteLine($"An exception occurred while trying to log in on attempt {i}: {ex}");
}
}
Console.WriteLine("Could not login to Redump in 3 attempts, continuing without logging in...");
return false;
}
19
View Source File : MiscFilters.cs
License : MIT License
Project Creator : sebastienros
License : MIT License
Project Creator : sebastienros
public static ValueTask<FluidValue> UrlEncode(FluidValue input, FilterArguments arguments, TemplateContext context)
{
return new StringValue(WebUtility.UrlEncode(input.ToStringValue()));
}
19
View Source File : SyncService.cs
License : MIT License
Project Creator : sebcam
License : MIT License
Project Creator : sebcam
private async Task PullAsync()
{
Debug.WriteLine("PullAsync");
try
{
using (var client = new HttpClient
{
BaseAddress = new Uri(configuration.ApiBaseUrl),
Timeout = new TimeSpan(0, 0, 5)
})
{
var response = await client.GetAsync(ApiUri + "?from=" + WebUtility.UrlEncode(lastSync.ToString()));
response.EnsureSuccessStatusCode();
var items = JsonConvert.DeserializeObject<IEnumerable<T>>(await response.Content.ReadreplacedtringAsync());
var ids = items.Select(f => new { f.Id, f.Version });
var enreplacedies = await GetAllAsync(f => ids.Any(g => g.Id == f.Id));
var idsToUpdate = enreplacedies.Select(f => f.Id).ToList();
var pendingOperations = context.Operations.Where(f => idsToUpdate.Contains(f.EnreplacedyId));
Debug.WriteLine($"{items.Count()} éléments a récupérer");
foreach (var enreplacedy in enreplacedies)
{
var serverValue = items.FirstOrDefault(f => f.Id == enreplacedy.Id);
if (serverValue.Version == enreplacedy.Version)
{
continue;
}
var pendingOperation = pendingOperations.FirstOrDefault(f => f.EnreplacedyId == enreplacedy.Id);
if (pendingOperation != null)
{
T resolvedEnreplacedy = serverValue;
if (this is IConflictHandler<T> conflictHandler)
{
resolvedEnreplacedy = (await conflictHandler.HandleConflict(enreplacedy, serverValue));
context.Operations.Remove(pendingOperation);
}
await UpdateAsync(enreplacedy.Id, resolvedEnreplacedy);
context.Entry(enreplacedy).CurrentValues.SetValues(resolvedEnreplacedy);
await CompleteUpdateAsync(enreplacedy, resolvedEnreplacedy);
await UpdateForeignKeys(new[] { enreplacedy });
}
else
{
var newValuesEnreplacedy = items.First(f => f.Id == enreplacedy.Id);
context.Entry(enreplacedy).CurrentValues.SetValues(newValuesEnreplacedy);
await CompleteUpdateAsync(enreplacedy, newValuesEnreplacedy);
await UpdateForeignKeys(new[] { enreplacedy });
}
}
var itemsToAdd = items.Except(enreplacedies, new IdComparer());
if (itemsToAdd.Any())
{
await UpdateForeignKeys(itemsToAdd);
await (context as DbContext).AddRangeAsync(itemsToAdd);
}
await context.CommitAsync(true);
}
}
catch (HttpRequestException ex)
{
Debug.WriteLine(ex);
}
catch (Exception ex)
{
Debug.WriteLine($"Exception en synchro : {ex.Message}");
Debug.WriteLine($"Exception en synchro inner : {ex.InnerException}");
Debug.WriteLine($"{ex.StackTrace}");
}
}
19
View Source File : SarifErrorLogger.cs
License : GNU Lesser General Public License v3.0
Project Creator : security-code-scan
License : GNU Lesser General Public License v3.0
Project Creator : security-code-scan
protected static string GetUri(string path)
{
Debug.replacedert(!string.IsNullOrEmpty(path));
// Note that in general, these "paths" are opaque strings to be
// interpreted by resolvers (see SyntaxTree.FilePath doreplacedentation).
// Common case: absolute path -> absolute URI
if (Path.IsPathRooted(path))
{
// N.B. URI does not handle multiple backslashes or `..` well, so call GetFullPath
// to normalize before going to URI
var fullPath = Path.GetFullPath(path);
if (Uri.TryCreate(fullPath, UriKind.Absolute, out var uri))
{
// We use Uri.AbsoluteUri and not Uri.ToString() because Uri.ToString()
// is unescaped (e.g. spaces remain unreplaced by %20) and therefore
// not well-formed.
return uri.AbsoluteUri;
}
}
else
{
// Attempt to normalize the directory separators
if (Path.DirectorySeparatorChar != '/')
{
path = path.Replace(@"\\", @"\");
path = Path.DirectorySeparatorChar == '/' ? path : path.Replace(Path.DirectorySeparatorChar, '/');
}
if (Uri.TryCreate(path, UriKind.Relative, out var uri))
{
// First fallback attempt: attempt to interpret as relative path/URI.
// (Perhaps the resolver works that way.)
// There is no AbsoluteUri equivalent for relative URI references and ToString()
// won't escape without this relative -> absolute -> relative trick.
return s_fileRoot.MakeRelativeUri(new Uri(s_fileRoot, uri)).ToString();
}
}
// Last resort: UrlEncode the whole opaque string.
return System.Net.WebUtility.UrlEncode(path);
}
19
View Source File : WebCodingExtensions.cs
License : Apache License 2.0
Project Creator : Senparc
License : Apache License 2.0
Project Creator : Senparc
public static string UrlEncode(this string url)
{
return WebUtility.UrlEncode(url);//转义后字母为大写
}
19
View Source File : PageController.cs
License : GNU General Public License v3.0
Project Creator : SeriaWei
License : GNU General Public License v3.0
Project Creator : SeriaWei
public IActionResult RedirectView(string Id, bool? preview)
{
var pathArray = Service.Get(Id).Url.Split('/');
for (int i = 1; i < pathArray.Length; i++)
{
pathArray[i] = WebUtility.UrlEncode(pathArray[i]);
}
var url = string.Join("/", pathArray);
return Redirect(url + ((preview ?? true) ? "?ViewType=" + ReView.Review : ""));
}
19
View Source File : PageUtils.cs
License : MIT License
Project Creator : siteserver
License : MIT License
Project Creator : siteserver
public static string UrlEncode(string url)
{
return WebUtility.UrlEncode(url);
}
19
View Source File : HubSpotContactClient.cs
License : MIT License
Project Creator : skarpdev
License : MIT License
Project Creator : skarpdev
public async Task<T> CreateOrUpdateAsync<T>(IContactHubSpotEnreplacedy enreplacedy) where T : IHubSpotEnreplacedy, new()
{
Logger.LogDebug("Contact CreateOrUpdateAsync");
var path = PathResolver(enreplacedy, HubSpotAction.CreateOrUpdate)
.Replace(":contactemail:", WebUtility.UrlEncode(enreplacedy.Email));
var data = await PostAsync<T>(path, enreplacedy);
return data;
}
19
View Source File : UrlDecoder.cs
License : MIT License
Project Creator : Softeq
License : MIT License
Project Creator : Softeq
public string EncodeUrl(string input)
{
return WebUtility.UrlEncode(input);
}
19
View Source File : UrlBuilder.cs
License : Apache License 2.0
Project Creator : sotsera
License : Apache License 2.0
Project Creator : sotsera
public UrlBuilder Add(string name, string value)
{
if (name.IsEmpty()) throw new ArgumentNullException(nameof(name));
if (value.IsEmpty()) return this;
Builder.Append(FirstParameter ? "?" : "&");
Builder.Append(WebUtility.UrlEncode(name));
Builder.Append("=");
Builder.Append(WebUtility.UrlEncode(value));
FirstParameter = false;
return this;
}
19
View Source File : PlayerLocator.cs
License : MIT License
Project Creator : space-wizards
License : MIT License
Project Creator : space-wizards
public async Task<LocatedPlayerData?> LookupIdByNameAsync(string playerName, CancellationToken cancel = default)
{
// Check people currently on the server, the easiest case.
if (_playerManager.TryGetSessionByUsername(playerName, out var session))
{
var userId = session.UserId;
var address = session.ConnectedClient.RemoteEndPoint.Address;
var hwId = session.ConnectedClient.UserData.HWId;
return new LocatedPlayerData(userId, address, hwId);
}
// Check database for past players.
var record = await _db.GetPlayerRecordByUserName(playerName, cancel);
if (record != null)
return new LocatedPlayerData(record.UserId, record.LastSeenAddress, record.HWId);
// If all else fails, ask the auth server.
var client = new HttpClient();
var authServer = _configurationManager.GetCVar(CVars.AuthServer);
var requestUri = $"{authServer}api/query/name?name={WebUtility.UrlEncode(playerName)}";
using var resp = await client.GetAsync(requestUri, cancel);
if (resp.StatusCode == HttpStatusCode.NotFound)
return null;
if (!resp.IsSuccessStatusCode)
{
Logger.ErrorS("PlayerLocate", "Auth server returned bad response {StatusCode}!", resp.StatusCode);
return null;
}
var responseData = await resp.Content.ReadFromJsonAsync<UserDataResponse>(cancellationToken: cancel);
if (responseData == null)
{
Logger.ErrorS("PlayerLocate", "Auth server returned null response!");
return null;
}
return new LocatedPlayerData(new NetUserId(responseData.UserId), null, null);
}
19
View Source File : PlayerLocator.cs
License : MIT License
Project Creator : space-wizards
License : MIT License
Project Creator : space-wizards
public async Task<LocatedPlayerData?> LookupIdAsync(NetUserId userId, CancellationToken cancel = default)
{
// Check people currently on the server, the easiest case.
if (_playerManager.TryGetSessionById(userId, out var session))
{
var address = session.ConnectedClient.RemoteEndPoint.Address;
var hwId = session.ConnectedClient.UserData.HWId;
return new LocatedPlayerData(userId, address, hwId);
}
// Check database for past players.
var record = await _db.GetPlayerRecordByUserId(userId, cancel);
if (record != null)
return new LocatedPlayerData(record.UserId, record.LastSeenAddress, record.HWId);
// If all else fails, ask the auth server.
var client = new HttpClient();
var authServer = _configurationManager.GetCVar(CVars.AuthServer);
var requestUri = $"{authServer}api/query/userid?userid={WebUtility.UrlEncode(userId.UserId.ToString())}";
using var resp = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, requestUri), cancel);
if (resp.StatusCode == HttpStatusCode.NotFound)
return null;
if (!resp.IsSuccessStatusCode)
{
Logger.ErrorS("PlayerLocate", "Auth server returned bad response {StatusCode}!", resp.StatusCode);
return null;
}
return new LocatedPlayerData(userId, null, null);
}
19
View Source File : PathExtensions.cs
License : MIT License
Project Creator : spectresystems
License : MIT License
Project Creator : spectresystems
public static Uri ToUri(this Path path, string scheme, IDictionary<string, string> parameters = null)
{
if (path != null)
{
var uri = $"{scheme}:///{WebUtility.UrlEncode(path.FullPath)}";
if (parameters != null)
{
var joinedParameters = parameters.Select(x => $"{x.Key}={WebUtility.UrlEncode(x.Value)}");
uri = string.Concat(uri, "?", string.Join("&", joinedParameters));
}
return new Uri(uri);
}
return null;
}
19
View Source File : GoogleProvider.cs
License : MIT License
Project Creator : spectresystems
License : MIT License
Project Creator : spectresystems
public override async Task<IEnumerable<IQueryResult>> QueryAsync(Query query)
{
Ensure.NotNull(query, nameof(query));
if (string.IsNullOrWhiteSpace(query.Argument))
{
var uri = new Uri("https://google.com");
return new[]
{
(IQueryResult)new GoogleResult(
uri, true, "Open Google in browser",
uri.AbsoluteUri, 0, 0)
};
}
try
{
var uri = $"https://www.google.com/complete/search?output=chrome&q={WebUtility.UrlEncode(query.Argument)}";
var result = await _client.GetAsync(uri);
if (result.IsSuccessStatusCode)
{
var data = await result.Content.ReadreplacedtringAsync();
var queryResults = JArray.Parse(data)[1]
.Where(x => x.Type == JTokenType.String).Select(x => x.Value<string>())
.ToList();
return queryResults.Any()
? queryResults.Select(x => GoogleResult.Create(query, x))
: new[] { GoogleResult.Create(query, description: $"Search Google for '{query.Argument}'") };
}
}
catch (Exception e)
{
_log.Error(e, "An error occured while querying Google.");
}
return Enumerable.Empty<IQueryResult>();
}
19
View Source File : UwpIndexSourceEntry.cs
License : MIT License
Project Creator : spectresystems
License : MIT License
Project Creator : spectresystems
public override FileResult GetFileResult(string query, float distance, float score)
{
return new FileResult(
QueryResultType.Application,
new Uri($"uwp:///{WebUtility.UrlEncode(Id)}?aumid={WebUtility.UrlEncode(AppUserModelId)}"), Icon,
replacedle, Description, distance, score);
}
19
View Source File : GoogleResult.cs
License : MIT License
Project Creator : spectresystems
License : MIT License
Project Creator : spectresystems
public static IQueryResult Create(Query query, string term = null, string description = null)
{
Ensure.NotNull(query, nameof(query));
term = term ?? query.Argument;
description = description ?? term;
var isGoogleQuery = !(term.StartsWith("http://") || term.StartsWith("https://"));
var uri = isGoogleQuery ? new Uri($"https://www.google.com/search?q={WebUtility.UrlEncode(term)}") : new Uri(term);
return new GoogleResult(uri, isGoogleQuery, description, uri.AbsoluteUri,
isGoogleQuery ? LevenshteinScorer.Score(term, query.Argument, false) : 0,
isGoogleQuery ? LevenshteinScorer.Score(term, query.Argument) : 0);
}
19
View Source File : WikipediaProvider.cs
License : MIT License
Project Creator : spectresystems
License : MIT License
Project Creator : spectresystems
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string Encode(string term)
{
return WebUtility.UrlEncode(
term.Replace(" ", "_")
.Replace("#", "♯"));
}
19
View Source File : UserController.cs
License : MIT License
Project Creator : sphildreth
License : MIT License
Project Creator : sphildreth
[HttpGet("accountsettings/{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(204)]
[ProducesResponseType(404)]
public async Task<IActionResult> GetAccountSettings(Guid id, string inc = null)
{
var user = await CurrentUserModel().ConfigureAwait(false);
var result = await CacheManager.GetAsync($"urn:user_edit_model_by_id:{id}", async () => await UserService.ByIdAsync(user, id, (inc ?? Library.Models.Users.User.DefaultIncludes).ToLower().Split(","), true).ConfigureAwait(false), ControllerCacheRegionUrn).ConfigureAwait(false);
if (result?.IsNotFoundResult != false)
{
return NotFound();
}
if (!result.IsSuccess)
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
result.AdditionalClientData = new Dictionary<string, object>();
if (RoadieSettings.Integrations.LastFmProviderEnabled)
{
var lastFmCallBackUrl = $"{RoadieHttpContext.BaseUrl}/users/integration/grant?userId={user.UserId}&iname=lastfm";
result.AdditionalClientData.Add("lastFMIntegrationUrl", $"http://www.last.fm/api/auth/?api_key={RoadieSettings.Integrations.LastFMApiKey}&cb={WebUtility.UrlEncode(lastFmCallBackUrl)}");
}
return Ok(result);
}
19
View Source File : AccountController.cs
License : MIT License
Project Creator : StarEliteCore
License : MIT License
Project Creator : StarEliteCore
public virtual IActionResult QQAuthorize()
{
var appId = "101945230";
var url = string.Format("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={0}&redirect_uri={1}&state=State", appId, WebUtility.UrlEncode("http://localhost:50001/signin-qq"));
return new RedirectResult(url);
}
19
View Source File : HttpClientHelper.cs
License : Apache License 2.0
Project Creator : SteeltoeOSS
License : Apache License 2.0
Project Creator : SteeltoeOSS
private static async Task<string> GetAccessTokenInternal(
Uri accessTokenUri,
string clientId,
string clientSecret,
int timeout,
bool validateCertificates,
HttpClient httpClient,
Dictionary<string, string> additionalParams,
ILogger logger)
{
var request = new HttpRequestMessage(HttpMethod.Post, accessTokenUri);
logger?.LogInformation("HttpClient not provided, a new instance will be created and disposed after retrieving a token");
var client = httpClient ?? GetHttpClient(validateCertificates, timeout);
// If certificate validation is disabled, inject a callback to handle properly
ConfigureCertificateValidation(validateCertificates, out var prevProtocols, out var prevValidator);
var auth = new AuthenticationHeaderValue("Basic", GetEncodedUserPreplacedword(clientId, clientSecret));
request.Headers.Authorization = auth;
var reqparams = additionalParams is null
? new Dictionary<string, string> { { "grant_type", "client_credentials" } }
: new Dictionary<string, string>(additionalParams) { { "grant_type", "client_credentials" } };
request.Content = new FormUrlEncodedContent(reqparams);
try
{
using var response = await client.SendAsync(request).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
logger?.LogInformation(
"GetAccessToken returned status: {0} while obtaining access token from: {1}",
response.StatusCode,
WebUtility.UrlEncode(accessTokenUri.OriginalString));
return null;
}
var payload = JsonDoreplacedent.Parse(await response.Content.ReadreplacedtringAsync().ConfigureAwait(false));
var token = payload.RootElement.EnumerateObject().FirstOrDefault(n => n.Name.Equals("access_token")).Value;
if (httpClient is null)
{
client.Dispose();
}
return token.ToString();
}
catch (Exception e)
{
logger?.LogError("GetAccessToken exception: {0}, obtaining access token from: {1}", e, WebUtility.UrlEncode(accessTokenUri.OriginalString));
}
finally
{
RestoreCertificateValidation(validateCertificates, prevProtocols, prevValidator);
}
return null;
}
See More Examples