System.Net.WebUtility.UrlEncode(string)

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 7

19 View Source File : AppRouteView.cs
License : MIT License
Project Creator : cornflourblue

protected override void Render(RenderTreeBuilder builder)
        {
            var authorize = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AuthorizeAttribute)) != null;
            if (authorize && AuthenticationService.User == null)
            {
                var returnUrl = WebUtility.UrlEncode(new Uri(NavigationManager.Uri).PathAndQuery);
                NavigationManager.NavigateTo($"login?returnUrl={returnUrl}");
            }
            else
            {
                base.Render(builder);
            }
        }

19 View Source File : AppRouteView.cs
License : MIT License
Project Creator : cornflourblue

protected override void Render(RenderTreeBuilder builder)
        {
            var authorize = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AuthorizeAttribute)) != null;
            if (authorize && AccountService.User == null)
            {
                var returnUrl = WebUtility.UrlEncode(new Uri(NavigationManager.Uri).PathAndQuery);
                NavigationManager.NavigateTo($"account/login?returnUrl={returnUrl}");
            }
            else
            {
                base.Render(builder);
            }
        }

19 View Source File : BceAttribute.cs
License : Apache License 2.0
Project Creator : cosmos-open

public Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
        {
            if (parameter.Value is BceObjectWrapper wrapper)
            {
                var date = DateTime.UtcNow;
                var canonicalRequest = $"POST\n/{WebUtility.UrlEncode(wrapper.UrlSegment)}\n\nhost:{WebUtility.UrlEncode(wrapper.ApiServerUrl)}";
                //var canonicalRequest = $"POST\n/{(wrapper.UrlSegment)}\n\nhost:{(wrapper.ApiServerUrl)}";
                var content = wrapper.Message.ToSendObject(wrapper.Config).ToJson();

                context.RequestMessage.Headers.TryAddWithoutValidation("x-bce-date", date.ToString("YYYY-MM-DD"));
                context.RequestMessage.Headers.TryAddWithoutValidation("Authorization", wrapper.BceObject.GetAuthString(date, canonicalRequest, "host"));
                context.RequestMessage.Headers.TryAddWithoutValidation("x-bce-content-sha256", SHA256HashingProvider.Signature(content, encoding: Encoding.UTF8));
            }

            return Task.CompletedTask;
        }

19 View Source File : EnumerableExtensions.cs
License : Apache License 2.0
Project Creator : crazyants

public static string BuildQueryString(this NameValueCollection nvc, Encoding encoding, bool encode = true)
        {
            var sb = new StringBuilder();

            if (nvc != null)
            {
                foreach (string str in nvc)
                {
                    if (sb.Length > 0)
                        sb.Append('&');

                    if (!encode)
                        sb.Append(str);
                    else
                        sb.Append(WebUtility.UrlEncode(str));


                    sb.Append('=');

                    if (!encode)
                        sb.Append(nvc[str]);
                    else
                        sb.Append(WebUtility.UrlEncode(nvc[str]));

                }
            }

            return sb.ToString();
        }

19 View Source File : StackOverflowCom.cs
License : Apache License 2.0
Project Creator : cs-util-com

public static async Task<string> Ask(string question, List<string> tags, int maxResults = 3) {
            var bestAnswers = await GetBestAnswersFor(question, tags, maxResults);
            if (bestAnswers.IsEmpty()) { throw new Error("No answers found for " + question); }
            var answerStrings = bestAnswers.Map(a => {
                var answerHtmlAsText = RestRequestHelper.HtmlToPlainText(a.Value.body);
                var questi = $"?? Question ({a.Key.score} votes):  {WebUtility.HtmlDecode(a.Key.replacedle)}";
                var answer = $">> Answer {a.Value.answer_url} ({a.Value.score} votes): \n{answerHtmlAsText}";
                return "\n" + questi + ":\n" + answer + "\n";
            });
            var searchSentence = question + " " + tags.ToStringV2("[", "]", "] [");
            var s = "https://stackoverflow.com/search?q=" + WebUtility.UrlEncode(searchSentence);
            return $"\n{question}\nSearching.. {s}\n{answerStrings.ToStringV2("", "", "")}";
        }

19 View Source File : StackOverflowCom.cs
License : Apache License 2.0
Project Creator : cs-util-com

public static async Task<ApiResponse> Search(string question, List<string> tags) {
            var q = WebUtility.UrlEncode(question);
            string url = $"https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q={q}&site=stackoverflow";
            if (!tags.IsNullOrEmpty()) {
                url += "&tagged=" + WebUtility.UrlEncode(tags.ToStringV2("", "", ";"));
            }
            ApiResponse apiResponse;
            try {
                apiResponse = await new Uri(url).SendGET().GetResult<ApiResponse>();
            }
            catch (Exception e) {
                throw new Error("Failed to Get questions from " + url, e);
            }
            return apiResponse.ThrowIfError();
        }

19 View Source File : StackOverflowCom.cs
License : Apache License 2.0
Project Creator : cs-util-com

public static async Task<ApiResponse> Search(string question, List<string> tags) {
            var q = WebUtility.UrlEncode(question);
            string url = $"https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=relevance&q={q}&site=stackoverflow";
            if (!tags.IsNullOrEmpty()) {
                url += "&tagged=" + WebUtility.UrlEncode(tags.ToStringV2("", "", ";"));
            }
            ApiResponse apiResponse;
            try {
                apiResponse = await new Uri(url).SendGET().GetResult<ApiResponse>();
            }
            catch (Exception e) {
                throw new Error("Failed to Get questions from " + url, e);
            }
            return apiResponse.ThrowIfError();
        }

19 View Source File : ShoutoutCommand.cs
License : MIT License
Project Creator : csharpfritz

public async Task Execute(IChatService chatService, string userName, bool isModerator, bool isVip, bool isBroadcaster, ReadOnlyMemory<char> rhs)
		{

			if (!(isModerator || isVip || isBroadcaster)) return;

			var rhsTest = rhs.ToString();
			if (rhsTest.StartsWith("@")) rhsTest = rhsTest.Substring(1);
			if (rhsTest.StartsWith("http")) return;
			if (rhsTest.Contains(" ")) return;

			rhsTest = WebUtility.UrlEncode(rhsTest);
			var result = await _HttpClient.GetAsync($"?login={rhsTest}");
			if (result.StatusCode == HttpStatusCode.Unauthorized) {
				_Logger.LogError("Request to Twitch endpoint was unauthorized -- consider rotating keys");
				return;
			}
			else if (result.StatusCode != HttpStatusCode.OK)
			{
				_Logger.LogWarning($"Unable to verify Shoutout for {rhsTest}");
				return;
			}

			await chatService.SendMessageAsync($"Please follow @{rhsTest} at: https://twitch.tv/{rhsTest}");

		}

19 View Source File : ParametersBuilder.cs
License : MIT License
Project Creator : CurlyBraceTT

public virtual string Build<T>(T parameters)
        {
            var result = new StringBuilder();
            var properties = typeof(T).GetProperties();
            foreach (var property in properties)
            {
                var value = property.GetValue(parameters);

                if (value == null || string.IsNullOrEmpty(value.ToString()))
                {
                    continue;
                }

                var name = property.Name.Substring(0, 1).ToLower() + property.Name.Substring(1);
                var stringValue = string.Empty;

                if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
                {
                    var date = DateTime.Parse(value.ToString());
                    stringValue = date.ToString("yyyy-mm-dd");
                }
                else
                {
                    stringValue = value.ToString();
                }

                if (result.Length == 0)
                {
                    result.AppendFormat("{0}={1}", name, WebUtility.UrlEncode(stringValue));
                }
                else
                {
                    result.AppendFormat("&{0}={1}", name, WebUtility.UrlEncode(stringValue));
                }
            }

            return result.ToString();
        }

19 View Source File : CustomProxyHttpMessageInvoker.cs
License : MIT License
Project Creator : damikun

private static HttpRequestMessage HandleTelemetryContextPropagation(HttpRequestMessage request){
            var currentActivity = Activity.Current;

            if (currentActivity.IdFormat == ActivityIdFormat.W3C)
            {
                if (!request.Headers.Contains(TraceParentHeaderName))
                {
                    request.Headers.TryAddWithoutValidation(TraceParentHeaderName, currentActivity.Id);
                    if (currentActivity.TraceStateString != null)
                    {
                        request.Headers.TryAddWithoutValidation(TraceStateHeaderName, currentActivity.TraceStateString);
                    }
                }
            }
            else
            {
                if (!request.Headers.Contains(RequestIdHeaderName))
                {
                    request.Headers.TryAddWithoutValidation(RequestIdHeaderName, currentActivity.Id);
                }
            }

                        // we expect baggage to be empty or contain a few items
            using (IEnumerator<KeyValuePair<string, string>> e = currentActivity.Baggage.GetEnumerator())
            {
                if (e.MoveNext())
                {
                    var baggage = new List<string>();
                    do
                    {
                        KeyValuePair<string, string> item = e.Current;
                        baggage.Add(new NameValueHeaderValue(WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)).ToString());
                    }
                    while (e.MoveNext());
                    request.Headers.TryAddWithoutValidation(CorrelationContextHeaderName, baggage);
                }
            }

            return request;
        }

19 View Source File : LogglyHttpLogger.cs
License : MIT License
Project Creator : dansiegel

protected virtual string Tags(IList<string> tags)
        {
            return string.Join(",", tags.Select(x => WebUtility.UrlEncode(x)));
        }

19 View Source File : AppRouteView.cs
License : MIT License
Project Creator : devmentors

protected override void Render(RenderTreeBuilder builder)
        {
            var authorize = Attribute.GetCustomAttribute(RouteData.PageType, typeof(AuthorizeAttribute)) is {};
            if (authorize && AuthenticationService.User is null)
            {
                var returnUrl = WebUtility.UrlEncode(new Uri(NavigationManager.Uri).PathAndQuery);
                NavigationManager.NavigateTo($"login?returnUrl={returnUrl}");
            }
            else
            {
                base.Render(builder);
            }
        }

19 View Source File : AuthHandler.cs
License : Apache License 2.0
Project Creator : digimarc-corp

private async Task<string> GetTokenAsync(string scope)
        {
            using (var client = new HttpClient())
            {
                var uri = new UriBuilder(Realm);
                logger.LogTrace($"Authenticating against {Realm}");

                var parameters = $"service={WebUtility.UrlEncode(Service)}";
                parameters += string.IsNullOrEmpty(scope) ? string.Empty : $"&scope={WebUtility.UrlEncode(scope)}";
                uri.Query = $"?{parameters}";

                var useDefaultCreds = scope == CatalogScope() && !string.IsNullOrEmpty(config.RegistryUser);

                // if we're getting catalog info, and we have a default user configured, use that instead
                if (useDefaultCreds)
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", EncodeDefaultCredentials());
                }
                else if (!string.IsNullOrEmpty(username))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", EncodeCredentials());
                }
                var response = await client.GetAsync(uri.Uri);

                if (response.IsSuccessStatusCode)
                {
                    return JsonConvert.DeserializeAnonymousType(response.Content.ReadreplacedtringAsync().Result, new { token = "" }).token;
                }
                else
                {
                    logger.LogDebug($"Authentication failed: {response.StatusCode} - {response.Content.ReadreplacedtringAsync().Result}");
                    if (useDefaultCreds) { logger.LogError($"{this} failed to authenticate with configured default user."); }
                    return null;
                }
            }
        }

19 View Source File : WikipediaService.cs
License : MIT License
Project Creator : discord-csharp

public async Task<WikipediaResponse> GetWikipediaResultsAsync(string phrase)
        {
            var query = string.Join(" ", phrase);
            query = WebUtility.UrlEncode(query);
            var client = HttpClientFactory.CreateClient();
            var response = await client.GetAsync(string.Format(WikipediaApiScheme, query));

            if (!response.IsSuccessStatusCode)
            {
                throw new WebException("Something failed while querying the Wikipedia API.");
            }

            var jsonResponse = await response.Content.ReadreplacedtringAsync();
            return JsonConvert.DeserializeObject<WikipediaResponse>(jsonResponse);
        }

19 View Source File : WumpusRequester.cs
License : MIT License
Project Creator : discord-net

private string GenerateBucketId(IRequestInfo request)
        {
            if (request.Path == null || (!request.PathParams.Any() && !request.PathProperties.Any()))
                return request.Path;

            var sb = new StringBuilder(request.Path);
            foreach (var pathParam in request.PathParams.Concat(request.PathProperties))
            {
                var serialized = pathParam.SerializeToString(FormatProvider);
                if (serialized.Key != "channelId" && serialized.Key != "guildId")
                    continue;

                // Space needs to be treated separately
                string value = pathParam.UrlEncode ? WebUtility.UrlEncode(serialized.Value ?? string.Empty).Replace("+", "%20") : serialized.Value;
                sb.Replace("{" + (serialized.Key ?? string.Empty) + "}", value);
            }
            return sb.ToString();
        }

19 View Source File : KrakenClient.cs
License : MIT License
Project Creator : discosultan

public async Task<KrakenResponse<T>> QueryPrivate<T>(
            string requestUrl,
            Dictionary<string, string> args = null,
            int apiCallCost = 1)
        {
            if (requestUrl == null) throw new ArgumentNullException(nameof(requestUrl));

            args = args ?? new Dictionary<string, string>(AdditionalPrivateQueryArgs);

            // Add additional args.
            string nonce = null;
            if (GetNonce != null)
            {
                nonce = (await GetNonce().ConfigureAwait(false)).ToString(Culture);
                args["nonce"] = nonce;
            }
            if (GetTwoFactorPreplacedword != null)
            {
                args["otp"] = WebUtility.UrlEncode(await GetTwoFactorPreplacedword().ConfigureAwait(false));
            }

            // Setup request.
            string urlEncodedArgs = UrlEncode(args);
            var req = new HttpRequestMessage(HttpMethod.Post, requestUrl)
            {
                Content = new StringContent(urlEncodedArgs, Encoding.UTF8, "application/x-www-form-urlencoded")
            };

            // Add API key header.
            req.Headers.Add("API-Key", ApiKey);

            // Add content signature header.
            byte[] urlBytes = Encoding.UTF8.GetBytes(requestUrl);
            byte[] dataBytes = _sha256.ComputeHash(Encoding.UTF8.GetBytes(nonce + urlEncodedArgs));

            var buffer = new byte[urlBytes.Length + dataBytes.Length];
            Buffer.BlockCopy(urlBytes, 0, buffer, 0, urlBytes.Length);
            Buffer.BlockCopy(dataBytes, 0, buffer, urlBytes.Length, dataBytes.Length);
            byte[] signature = _sha512PrivateKey.ComputeHash(buffer);

            req.Headers.Add("API-Sign", Convert.ToBase64String(signature));

            // Send request and deserialize response.
            return await SendRequest<T>(req, apiCallCost).ConfigureAwait(false);
        }

19 View Source File : KrakenClient.cs
License : MIT License
Project Creator : discosultan

private static string UrlEncode(Dictionary<string, string> args) => string.Join(
            "&",
            args.Where(x => x.Value != null).Select(x => x.Key + "=" + WebUtility.UrlEncode(x.Value))
        );

19 View Source File : OpenWikiPageKeybindHandler.cs
License : MIT License
Project Creator : domialex

private Task OpenPoeWiki(Item item)
        {
            // determine search link, so wiki can be opened for any item
            var searchLink = item.Metadata.Name ?? item.Metadata.Type;
            // replace space encodes with '_' to match the link layout of the poe wiki and then url encode it
            var itemLink = System.Net.WebUtility.UrlEncode(searchLink.Replace(" ", "_"));

            return mediator.Send(new OpenBrowserCommand(new Uri($"https://pathofexile.gamepedia.com/{itemLink}")));
        }

19 View Source File : Bittrex.cs
License : MIT License
Project Creator : Domysee

private string convertParameterListToString(IDictionary<string, string> parameters)
        {
            if (parameters.Count == 0) return "";
            return parameters.Select(param => WebUtility.UrlEncode(param.Key) + "=" + WebUtility.UrlEncode(param.Value)).Aggregate((l, r) => l + "&" + r);
        }

19 View Source File : MBIHelper.cs
License : MIT License
Project Creator : dongle-the-gadget

private async static Task<string> GetBearerTokenForScope(string email, string preplacedword, string targetscope, string clientId = "ms-app://s-1-15-2-1929064262-2866240470-255121345-2806524548-501211612-2892859406-1685495620/")
        {
            string retVal = string.Empty;
            email = WebUtility.UrlEncode(email);
            preplacedword = WebUtility.UrlEncode(preplacedword);
            targetscope = WebUtility.UrlEncode(targetscope);
            clientId = WebUtility.UrlEncode(clientId);
            HttpWebRequest hwreq = (HttpWebRequest)WebRequest.Create($"https://login.live.com/oauth20_authorize.srf?client_id={clientId}&scope={targetscope}&response_type=token&redirect_uri=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf");
            string MSPOK = string.Empty;
            string urlPost;
            string PPFT;
            try
            {
                HttpWebResponse hwresp = (HttpWebResponse)(await hwreq.GetResponseAsync().ConfigureAwait(false));

                foreach (string oCookie in hwresp.Headers["Set-Cookie"].Split(','))
                {
                    if (oCookie.Trim().StartsWith("MSPOK"))
                    {
                        MSPOK = oCookie.Trim()[6..oCookie.IndexOf(';')];
                        MSPOK = WebUtility.UrlEncode(MSPOK);
                        break;
                    }
                }

                string responsePlain = string.Empty;
                using (StreamReader reader = new(hwresp.GetResponseStream(), Encoding.UTF8))
                {
                    responsePlain = reader.ReadToEnd();
                }
                PPFT = responsePlain[responsePlain.IndexOf("name=\"PPFT\"")..];
                PPFT = PPFT[(PPFT.IndexOf("value=") + 7)..];
                PPFT = PPFT.Substring(0, PPFT.IndexOf('\"'));
                urlPost = responsePlain[(responsePlain.IndexOf("urlPost:") + 9)..];
                urlPost = urlPost.Substring(0, urlPost.IndexOf('\''));
            }
            catch { return string.Empty; }

            HttpClientHandler httpClientHandler = new()
            {
                AllowAutoRedirect = false
            };

            CookieContainer hwreqCC = new();
            hwreqCC.Add(new Uri("https://login.live.com"), new Cookie("MSPOK", MSPOK) { Domain = "login.live.com" });
            httpClientHandler.CookieContainer = hwreqCC;

            HttpClient client = new(httpClientHandler);

            StringContent queryString = new($"login={email}&preplacedwd={preplacedword}&PPFT={PPFT}", Encoding.UTF8);

            queryString.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            byte[] POSTByteArray = Encoding.UTF8.GetBytes($"login={email}&preplacedwd={preplacedword}&PPFT={PPFT}");
            queryString.Headers.ContentLength = POSTByteArray.Length;

            HttpResponseMessage hwresp2 = await client.PostAsync(new Uri(urlPost), queryString).ConfigureAwait(false);

            try
            {
                foreach (string oLocationBit in hwresp2.Headers.Location.AbsoluteUri.Split('&'))
                {
                    if (oLocationBit.Contains("access_token"))
                    {
                        retVal = oLocationBit[(oLocationBit.IndexOf("access_token") + 13)..];
                        if (retVal.Contains("&"))
                        {
                            retVal = retVal.Substring(0, retVal.IndexOf('&'));
                        }

                        break;
                    }
                }
            }
            catch { return string.Empty; }
            return WebUtility.UrlDecode(retVal);
        }

19 View Source File : YahooSnapshot.cs
License : MIT License
Project Creator : dshe

private static IEnumerable<Uri> GetUris(IEnumerable<Symbol> symbols)
        {
            const string baseUrl = "https://query2.finance.yahoo.com/v7/finance/quote?symbols=";

            return symbols
                .Select(symbol => WebUtility.UrlEncode(symbol.Name))
                .Chunk(100)
                .Select(s => $"{baseUrl}{string.Join(",", s)}")
                .Select(s => new Uri(s));
        }

19 View Source File : EncodedQueryStringVariableHandler.cs
License : MIT License
Project Creator : dukeofharen

public string Parse(string input, IEnumerable<Match> matches)
        {
            var queryDict = _httpContextService.GetQueryStringDictionary();
            foreach (var match in matches)
            {
                if (match.Groups.Count != 3)
                {
                    continue;
                }

                var queryStringName = match.Groups[2].Value;
                queryDict.TryGetValue(queryStringName, out var replaceValue);

                replaceValue = WebUtility.UrlEncode(replaceValue);
                input = input.Replace(match.Value, replaceValue);
            }

            return input;
        }

19 View Source File : StubDynamicModeIntegrationTests.cs
License : MIT License
Project Creator : dukeofharen

[TestMethod]
        public async Task StubIntegration_RegularGet_Dynamic_Query()
        {
            // arrange
            const string query1Val = "John";
            const string query2Val = "=";
            var expectedResult = $"The value is {query1Val} {WebUtility.UrlEncode(query2Val)}";
            var url = $"{TestServer.BaseAddress}dynamic-query.txt?queryString1={query1Val}&queryString2={query2Val}";

            // act / replacedert
            using var response = await Client.GetAsync(url);
            var content = await response.Content.ReadreplacedtringAsync();
            replacedert.AreEqual(expectedResult, content);
            replacedert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            replacedert.AreEqual("text/plain", response.Content.Headers.ContentType.ToString());
        }

19 View Source File : SearchClientService.cs
License : GNU General Public License v3.0
Project Creator : efonsecab

public async Task<VideoInfoModel[]> SearchPublicProcessedVideosAsync(string searchTerm)
        {
            var anonymousHttpClient = this.HttpClientService.CreateAnonymousClient();
            return await anonymousHttpClient.GetFromJsonAsync<VideoInfoModel[]>(
                $"{ApiRoutes.SearchController.SearchPublicProcessedVideos}" +
                $"?searchTerm={WebUtility.UrlEncode(searchTerm)}");
        }

19 View Source File : AliyunSmsSdk.cs
License : MIT License
Project Creator : ElderJames

private string SignRequestParameters(Dictionary<string, string> requestParameters)
        {
            string nonce = Guid.NewGuid().ToString("N").Substring(4, 8);
            var parameters = new Dictionary<string, string>
            {
                {"Format", "JSON"},
                {"Version", "2017-05-25"},
                {"SignatureMethod", "HMAC-SHA1"},
                {"SignatureVersion", "1.0"},
                {"AccessKeyId", _accessKeyId},
                {"SignatureNonce", nonce},
                {"Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")},
                {"Action", "SendSms"},
                {"RegionId", "cn-hangzhou"}
            };

            foreach (string key in requestParameters.Keys)
            {
                parameters.Add(key, requestParameters[key]);
            }

            string signature = GenerateSignature(_accessKeySecret, parameters);
            parameters.Add("Signature", signature);

            return string.Join("&", parameters.Select(kv => $"{kv.Key}={WebUtility.UrlEncode(kv.Value)}"));
        }

19 View Source File : AliyunSmsSdk.cs
License : MIT License
Project Creator : ElderJames

private static string GenerateSignature(string accessKeySecret, Dictionary<string, string> parametersBeforeSign)
        {
            string Encode(string p)
            {
                return WebUtility.UrlEncode(p)
                    ?.Replace("+", "20%")
                                .Replace("*", "%2A")
                                .Replace("%7E", "~");
            }

            string Hmac(string val, string keySecret)
            {
                byte[] bytes = Encoding.ASCII.GetBytes(val);
                byte[] key = Encoding.ASCII.GetBytes(keySecret + "&");

                using (var hmacsha1 = new HMACSHA1(key))
                using (var stream = new MemoryStream(bytes))
                {
                    return Convert.ToBase64String(hmacsha1.ComputeHash(stream));
                }
            }

            IEnumerable<string> encodedParameters = parametersBeforeSign
                .OrderBy(kv => kv.Key, StringComparer.Ordinal)
                .Select(kv => $"{Encode(kv.Key)}={Encode(kv.Value)}");

            string canonicalizedQueryString = string.Join("&", encodedParameters);
            string stringToSign = $"POST&%2F&{Encode(canonicalizedQueryString)}";
            return Hmac(stringToSign, accessKeySecret);
        }

19 View Source File : ContextExtensions.cs
License : MIT License
Project Creator : Ellerbach

public static async Task Logout(this IBotContext context)
        {
            context.UserData.RemoveValue(ContextConstants.AuthResultKey);
            context.UserData.RemoveValue(ContextConstants.MagicNumberKey);
            context.UserData.RemoveValue(ContextConstants.MagicNumberValidated);
            string signoutURl = "https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=" + System.Net.WebUtility.UrlEncode(AuthSettings.RedirectUrl);
            await context.PostAsync($"In order to finish the sign out, please click at this [link]({signoutURl}).");
        }

19 View Source File : YouTubeSearchProvider.cs
License : GNU Affero General Public License v3.0
Project Creator : Emzi0767

public async Task<IEnumerable<YouTubeSearchResult>> SearchAsync(string term)
        {
            var uri = new Uri($"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&type=video&fields=items(id(videoId),snippet(replacedle,channelreplacedle))&key={this.ApiKey}&q={WebUtility.UrlEncode(term)}");

            var json = "{}";
            using (var req = await this.Http.GetAsync(uri))
            using (var res = await req.Content.ReadreplacedtreamAsync())
            using (var sr = new StreamReader(res, CompanionCubeUtilities.UTF8))
                json = await sr.ReadToEndAsync();

            var jsonData = JObject.Parse(json);
            var data = jsonData["items"].ToObject<IEnumerable<YouTubeApiResponseItem>>();

            return data.Select(x => new YouTubeSearchResult(x.Snippet.replacedle, x.Snippet.Author, x.Id.VideoId));
        }

19 View Source File : YouTubeSearchProvider.cs
License : GNU Affero General Public License v3.0
Project Creator : Emzi0767

public async Task<IEnumerable<YouTubeSearchResult>> SearchAsync(string term)
        {
            var uri = new Uri($"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&type=video&fields=items(id(videoId),snippet(replacedle,channelreplacedle))&key={this.ApiKey}&q={WebUtility.UrlEncode(term)}");

            var json = "{}";
            using (var req = await this.Http.GetAsync(uri))
            using (var res = await req.Content.ReadreplacedtreamAsync())
            using (var sr = new StreamReader(res, TurretUtilities.UTF8))
                json = await sr.ReadToEndAsync();

            var jsonData = JObject.Parse(json);
            var data = jsonData["items"].ToObject<IEnumerable<YouTubeApiResponseItem>>();

            return data.Select(x => new YouTubeSearchResult(x.Snippet.replacedle, x.Snippet.Author, x.Id.VideoId));
        }

19 View Source File : QueryParameter.cs
License : MIT License
Project Creator : EncompassRest

public override string ToString() => $"{WebUtility.UrlEncode(Name)}={WebUtility.UrlEncode(Value)}";

19 View Source File : QueryParameter.cs
License : MIT License
Project Creator : EncompassRest

public override string ToString() => $"{WebUtility.UrlEncode(Name)}={WebUtility.UrlEncode(Value)}";

19 View Source File : LavaRestClient.cs
License : GNU Lesser General Public License v3.0
Project Creator : Energizers

public async Task<SearchResult> SearchTracksAsync(string query, bool loadFullPlaylist = false)
        {
            if (!loadFullPlaylist)
                query = query.SanitizeYoutubeUrl();

            var url = $"http://{this._rest.Host}:{this._rest.Port}/loadtracks?identifier={WebUtility.UrlEncode(query)}";
            var request = await HttpHelper.Instance
                .WithCustomHeader("Authorization", this._rest.Preplacedword)
                .GetStringAsync(url).ConfigureAwait(false);

            var json = JObject.Parse(request);
            var result = json.ToObject<SearchResult>();
            var trackInfo = json.GetValue("tracks").ToObject<JArray>();
            var hashset = new HashSet<ILavaTrack>();

            foreach (var info in trackInfo)
            {
                ILavaTrack track = info["info"].ToObject<LavaTrack>();
                track.Hash = info["track"].ToObject<string>();
                hashset.Add(track);
            }

            result.Tracks = hashset;
            return result;
        }

19 View Source File : AlipayUtility.cs
License : MIT License
Project Creator : essensoft

public static string BuildQuery(IDictionary<string, string> dictionary)
        {
            if (dictionary == null || dictionary.Count == 0)
            {
                throw new ArgumentNullException(nameof(dictionary));
            }

            var sb = new StringBuilder();
            foreach (var iter in dictionary)
            {
                if (!string.IsNullOrEmpty(iter.Value))
                {
                    sb.Append(iter.Key + "=" + WebUtility.UrlEncode(iter.Value) + "&");
                }
            }

            return sb.ToString()[0..^1];
        }

private Task<IMiraiSessionConfig> GetConfigAsync(InternalSessionInfo session, CancellationToken token = default)
        {
            return _client.GetAsync($"{_options.BaseUrl}/config?sessionKey={WebUtility.UrlEncode(session.SessionKey)}", session.Token)
                .AsApiRespAsync<IMiraiSessionConfig, MiraiSessionConfig>(session.Token);
        }

19 View Source File : NeteaseMusicApi.cs
License : GNU General Public License v3.0
Project Creator : Executor-Cheng

public string GetFormdata()
                    => $"params={WebUtility.UrlEncode(Params)}&encSecKey={WebUtility.UrlEncode(EncSecKey)}";

19 View Source File : WebUtils.cs
License : MIT License
Project Creator : FastReports

internal static void CopyCookies(WebRequest request, HttpContext context)
        {
            CookieContainer cookieContainer = new CookieContainer();
            UriBuilder uri = new UriBuilder
            {
                Scheme = context.Request.Scheme,
                Host = context.Request.Host.Host
            };

            string ARRAffinity = GetWebsiteInstanceId();
            if (!String.IsNullOrEmpty(ARRAffinity))
                cookieContainer.Add(uri.Uri, new Cookie("ARRAffinity", ARRAffinity));

            foreach (string key in context.Request.Cookies.Keys)
                cookieContainer.Add(uri.Uri, new Cookie(key, WebUtility.UrlEncode(context.Request.Cookies[key])));

            HttpWebRequest req = (HttpWebRequest)request;
            req.CookieContainer = cookieContainer;
        }

19 View Source File : main.cs
License : MIT License
Project Creator : FastReports

string template_resource_url(string resourceName, string contentType) => $"{template_ROUTE_BASE_PATH}/resources.getResource?resourceName={WebUtility.UrlEncode(resourceName)}&contentType={WebUtility.UrlEncode(contentType)}";

19 View Source File : InvidiousApi.cs
License : GNU General Public License v3.0
Project Creator : fmbot-discord

public async Task<InvidiousSearchResult> SearchVideoAsync(string searchQuery)
        {
            var queryParams = new Dictionary<string, string>
            {
                {"q", WebUtility.UrlEncode(searchQuery) },
            };

            var url = this._url + "api/v1/search";
            url = QueryHelpers.AddQueryString(url, queryParams);

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };

            try
            {
                using var httpResponse = await this._client.SendAsync(request);

                if (httpResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }

                var stream = await httpResponse.Content.ReadreplacedtreamAsync();
                using var streamReader = new StreamReader(stream);
                var requestBody = await streamReader.ReadToEndAsync();

                var jsonSerializerOptions = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };

                var result = JsonSerializer.Deserialize<List<InvidiousSearchResult>>(requestBody, jsonSerializerOptions);

                if (result != null && result.Any())
                {
                    return result.First();
                }

                return null;
            }
            catch (Exception ex)
            {
                Log.Error("Something went wrong while deserializing the stuff from the Invidious API", ex);
                return null;
            }
        }

19 View Source File : APIController.cs
License : MIT License
Project Creator : ForkGG

public async Task<FileInfo> DownloadPluginAsync(InstalledPlugin plugin, string targetPath)
        {
            if (!IsAPIAvailable())
            {
                ErrorLogger.Append(new WebException("api.Fork.gg is not online or operational"));
                return null;
            }

            try
            {
                string pluginUrl = WebUtility.UrlEncode(plugin.Plugin.file.url);
                WebClient webClient = new WebClient();
                webClient.Headers.Add("user-agent",ApplicationManager.UserAgent);
                await webClient.DownloadFileTaskAsync(new Uri(apiBaseURL+"plugins/download?url="+pluginUrl), targetPath);
                
                FileInfo pluginFile = new FileInfo(targetPath);
                if (pluginFile.Exists)
                {
                    return pluginFile;
                }
            }
            catch (Exception e)
            {
                ErrorLogger.Append(e);
            }
            return null;
        }

19 View Source File : SEApiService.cs
License : MIT License
Project Creator : g3rv4

public string GetInitialOauthUrl(string returnUrl, string state = null)
        {
            return $"https://stackoverflow.com/oauth?client_id={_clientId}&redirect_uri={WebUtility.UrlEncode(returnUrl)}" +
                (state == null ? string.Empty : $"&state={WebUtility.UrlEncode(state)}");
        }

19 View Source File : Search.cshtml.cs
License : GNU General Public License v3.0
Project Creator : ganjoor

public async Task<IActionResult> OnGetAsync()
        {
            LoggedIn = !string.IsNullOrEmpty(Request.Cookies["Token"]);

            Query = Request.Query["s"].ApplyCorrectYeKe().Trim();
            bool quotes = Query.IndexOf("\"") != -1;
            Query = LanguageUtils.MakeTextSearchable(Query); //replace zwnj with space
            if (quotes)
                Query = $"\"{Query}\"";
            PoetId = string.IsNullOrEmpty(Request.Query["author"]) ? 0 : int.Parse(Request.Query["author"]);
            CatId = string.IsNullOrEmpty(Request.Query["cat"]) ? 0 : int.Parse(Request.Query["cat"]);

            ViewData["GooglereplacedyticsCode"] = _configuration["GooglereplacedyticsCode"];

            //todo: use html master layout or make it partial
            // 1. poets 
            if (false == (await preparePoets()))
                return Page();

            var poetName = Poets.SingleOrDefault(p => p.Id == PoetId);
            if (poetName != null)
            {
                ViewData["replacedle"] = $"گنجور » نتایج جستجو برای {Query} » {poetName?.Name}";
            }
            else
            {
                if(!string.IsNullOrEmpty(Query))
                {
                    ViewData["replacedle"] = $"گنجور » نتایج جستجو برای {Query}";
                }
                else
                {
                    ViewData["replacedle"] = $"گنجور » جستجو";
                }
                
            }

            if (PoetId != 0)
            {
                if (false == (await preparePoet()))
                    return Page();
            }

            // 2. search verses
            int pageNumber = 1;
            if (!string.IsNullOrEmpty(Request.Query["page"]))
            {
                pageNumber = int.Parse(Request.Query["page"]);
            }

            HttpResponseMessage searchQueryResponse = null;

            if (!string.IsNullOrEmpty(Query))
            {
                searchQueryResponse = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poems/search?term={Query}&poetId={PoetId}&catId={CatId}&PageNumber={pageNumber}&PageSize=20");

                if (!searchQueryResponse.IsSuccessStatusCode)
                {
                    LastError = JsonConvert.DeserializeObject<string>(await searchQueryResponse.Content.ReadreplacedtringAsync());
                    return Page();
                }

                Poems = JArray.Parse(await searchQueryResponse.Content.ReadreplacedtringAsync()).ToObject<List<GanjoorPoemCompleteViewModel>>();
            }
            

            if(Poems != null && Poems.Count == 0)
            {
                Poems = null;
            }

            if(Poems != null)
            {
                // highlight searched word
                string[] queryParts = Query.IndexOf('"') == 0 && Query.LastIndexOf('"') == (Query.Length - 1) ?
                       new string[] { Query.Replace("\"", "") }
                       :
                       Query.Replace("\"", "").Split(' ', StringSplitOptions.RemoveEmptyEntries);

                foreach (var poem in Poems)
                {
                    string[] lines = poem.PlainText.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
                    List<int> linesInExcerpt = new List<int>();
                    for (int i = 0; i < lines.Length; i++)
                    {
                        foreach (var queryPart in queryParts)
                        {
                            if(lines[i].IndexOf(queryPart) != -1)
                            {
                                if (i > 0)
                                {
                                    if (linesInExcerpt.IndexOf(i - 1) == -1)
                                    {
                                        linesInExcerpt.Add(i - 1);
                                    }
                                }
                                if(linesInExcerpt.IndexOf(i) == -1)
                                {
                                    linesInExcerpt.Add(i);
                                }

                                if (i < (lines.Length - 1))
                                    linesInExcerpt.Add(i + 1);
                                
                                break;
                            }
                        }
                    }


                    string plainText = "";
                    for (int i = 0; i < linesInExcerpt.Count; i++)
                    {
                        if (linesInExcerpt[i] > 0 && linesInExcerpt.IndexOf(linesInExcerpt[i] - 1) == -1)
                            plainText += "... ";
                        plainText += $"{lines[linesInExcerpt[i]]}";
                        if (linesInExcerpt[i] < (lines.Length - 1) && linesInExcerpt.IndexOf(linesInExcerpt[i] + 1) == -1)
                            plainText += " ...";
                        plainText += $"{Environment.NewLine}";
                    }

                    string finalPlainText = "";
                    foreach (string line in plainText.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries))
                    {
                        finalPlainText += $"<p>{line}</p>";
                    }
                    poem.PlainText = finalPlainText;

                    for (int i = 0; i < queryParts.Length; i++)
                    {
                        string cssClreplaced = i % 3 == 0 ? "hilite" : i % 3 == 1 ? "hilite2" : "hilite3";
                        poem.PlainText = Regex.Replace(poem.PlainText, queryParts[i], $"<span clreplaced=\"{cssClreplaced}\">{queryParts[i]}</span>", RegexOptions.IgnoreCase | RegexOptions.RightToLeft); ;
                    }


                }

                if(searchQueryResponse != null)
                {
                    string paginationMetadataJsonValue = searchQueryResponse.Headers.GetValues("paging-headers").FirstOrDefault();

                    if (!string.IsNullOrEmpty(paginationMetadataJsonValue))
                    {
                        PaginationMetadata paginationMetadata = JsonConvert.DeserializeObject<PaginationMetadata>(paginationMetadataJsonValue);
                        string catQuery = "";
                        if(!string.IsNullOrEmpty(Request.Query["cat"]))
                        {
                            catQuery = $"&cat={Request.Query["cat"]}";
                        }
                        PagingToolsHtml = GeneratePagingBarHtml(paginationMetadata, $"/search?s={WebUtility.UrlEncode(Query)}&author={PoetId}{catQuery}");
                    }
                }

               
            }

           

            return Page();
        }

19 View Source File : RequestBuilder.cs
License : MIT License
Project Creator : GavinPower747

private static string ApplyPrimativeValue(string url, string propName, string value)
        {
            var separator = url.Contains("?") ? "&" : "?";

            return $"{url}{separator}{propName}={WebUtility.UrlEncode(value)}";
        }

19 View Source File : RemoteLRS.cs
License : MIT License
Project Creator : gblxapi

private MyHTTPResponse MakeSyncRequest(MyHTTPRequest req)
        {
            String url;
            if (req.resource.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
            {
                url = req.resource;
            }
            else
            {
                url = endpoint.ToString();
                if (! url.EndsWith("/") && ! req.resource.StartsWith("/")) {
                    url += "/";
                }
                url += req.resource;
            }

            if (req.queryParams != null)
            {
                String qs = "";
                foreach (KeyValuePair<String, String> entry in req.queryParams)
                {
                    if (qs != "")
                    {
                        qs += "&";
                    }
                    qs += WebUtility.UrlEncode(entry.Key) + "=" + WebUtility.UrlEncode(entry.Value);
                }
                if (qs != "")
                {
                    url += "?" + qs;
                }
            }

            // TODO: handle special properties we recognize, such as content type, modified since, etc.
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            webReq.Method = req.method;

            webReq.Headers.Add("X-Experience-API-Version", version.ToString());
            if (auth != null)
            {
                webReq.Headers.Add("Authorization", auth);
            }
            if (req.headers != null)
            {
                foreach (KeyValuePair<String, String> entry in req.headers)
                {
                    webReq.Headers.Add(entry.Key, entry.Value);
                }
            }

            if (req.contentType != null)
            {
                webReq.ContentType = req.contentType;
            }
            else
            {
                webReq.ContentType = "application/octet-stream";
            }

            if (req.content != null)
            {
                webReq.ContentLength = req.content.Length;
                using (var stream = webReq.GetRequestStream())
                {
                    stream.Write(req.content, 0, req.content.Length);
                }
            }

            MyHTTPResponse resp;

            // TODO: this is blocking the thread
            try
            {
                using (var webResp = (HttpWebResponse)webReq.GetResponse())
                {
                    resp = new MyHTTPResponse(webResp);
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (var webResp = (HttpWebResponse)ex.Response)
                    {
                        resp = new MyHTTPResponse(webResp);
                    }
                }
                else
                {
                    resp = new MyHTTPResponse();
                    resp.content = Encoding.UTF8.GetBytes("Web exception without '.Response'");
                }
                resp.ex = ex;
            }

            return resp;
        }

19 View Source File : ListMultipartUploadsTests.cs
License : MIT License
Project Creator : Genbox

[Theory]
        [MultipleProviders(S3Provider.All)]
        public async Task ListMultipartUploads(S3Provider provider, string _, ISimpleClient client)
        {
            await CreateTempBucketAsync(provider, client, async tempBucket =>
            {
                //The percentage sign at the end is to test if encoding works correctly
                string objName = nameof(ListMultipartUploads) + "%";

                CreateMultipartUploadResponse createResp = await client.CreateMultipartUploadAsync(tempBucket, objName).ConfigureAwait(false);
                replacedert.Equal(200, createResp.StatusCode);

                byte[] file = new byte[5 * 1024];

                await using (MemoryStream ms = new MemoryStream(file))
                    await client.UploadPartAsync(tempBucket, objName, 1, createResp.UploadId, ms).ConfigureAwait(false);

                ListMultipartUploadsResponse listResp = await client.ListMultipartUploadsAsync(tempBucket, r => r.EncodingType = EncodingType.Url).ConfigureAwait(false);
                replacedert.Equal(200, listResp.StatusCode);
                replacedert.Equal(tempBucket, listResp.Bucket);

                if (provider == S3Provider.AmazonS3)
                {
                    replacedert.Equal(WebUtility.UrlEncode(objName), listResp.NextKeyMarker);
                    replacedert.NotEmpty(listResp.NextUploadIdMarker);
                }

                replacedert.Equal(1000, listResp.MaxUploads);
                replacedert.False(listResp.IsTruncated);

                S3Upload? upload = replacedert.Single(listResp.Uploads);
                replacedert.Equal(WebUtility.UrlEncode(objName), upload.ObjectKey);

                if (provider == S3Provider.AmazonS3)
                    replacedert.Equal(listResp.NextUploadIdMarker, upload.UploadId);

                replacedert.Equal(StorageClreplaced.Standard, upload.StorageClreplaced);
                replacedert.Equal(DateTime.UtcNow, upload.Initiated.DateTime, TimeSpan.FromSeconds(5));
            }).ConfigureAwait(false);
        }

19 View Source File : ListPartsTests.cs
License : MIT License
Project Creator : Genbox

[Theory]
        [MultipleProviders(S3Provider.All)]
        public async Task ListParts(S3Provider provider, string _, ISimpleClient client)
        {
            await CreateTempBucketAsync(provider, client, async tempBucket =>
            {
                //We add the special characters at the end to test EncodingType support.
                string objName = nameof(ListParts) + "%";

                CreateMultipartUploadResponse createResp = await client.CreateMultipartUploadAsync(tempBucket, objName).ConfigureAwait(false);

                ListPartsResponse listResp1 = await client.ListPartsAsync(tempBucket, objName, createResp.UploadId).ConfigureAwait(false);

                replacedert.Equal(tempBucket, listResp1.BucketName);
                replacedert.Equal(objName, listResp1.ObjectKey);
                replacedert.Equal(createResp.UploadId, listResp1.UploadId);
                replacedert.Equal(StorageClreplaced.Standard, listResp1.StorageClreplaced);
                replacedert.Equal(0, listResp1.PartNumberMarker);
                replacedert.Equal(0, listResp1.NextPartNumberMarker);
                replacedert.Equal(1000, listResp1.MaxParts);
                replacedert.False(listResp1.IsTruncated);

                if (provider == S3Provider.AmazonS3)
                    replacedert.Equal(TestConstants.TestUsername, listResp1.Owner.Name);

                replacedert.Empty(listResp1.Parts);

                UploadPartResponse uploadResp;

                byte[] file = new byte[5 * 1024];

                await using (MemoryStream ms = new MemoryStream(file))
                    uploadResp = await client.UploadPartAsync(tempBucket, objName, 1, createResp.UploadId, ms).ConfigureAwait(false);

                ListPartsResponse listResp2 = await client.ListPartsAsync(tempBucket, objName, createResp.UploadId, r => r.EncodingType = EncodingType.Url).ConfigureAwait(false);

                replacedert.Equal(tempBucket, listResp2.BucketName);

                if (provider == S3Provider.AmazonS3)
                    replacedert.Equal(WebUtility.UrlEncode(objName), listResp2.ObjectKey); //It should be encoded at this point
                else
                    replacedert.Equal(objName, listResp2.ObjectKey); //Only amazon supports encoding apparently

                replacedert.Equal(createResp.UploadId, listResp2.UploadId);
                replacedert.Equal(StorageClreplaced.Standard, listResp2.StorageClreplaced);
                replacedert.Equal(0, listResp2.PartNumberMarker);

                if (provider == S3Provider.GoogleCloudStorage)
                    replacedert.Equal(0, listResp2.NextPartNumberMarker);
                else
                    replacedert.Equal(1, listResp2.NextPartNumberMarker);

                replacedert.Equal(1000, listResp2.MaxParts);
                replacedert.False(listResp2.IsTruncated);

                if (provider == S3Provider.AmazonS3)
                    replacedert.Equal(TestConstants.TestUsername, listResp2.Owner.Name);

                S3Part? part = replacedert.Single(listResp2.Parts);

                replacedert.Equal(1, part.PartNumber);
                replacedert.Equal(DateTime.UtcNow, part.LastModified.DateTime, TimeSpan.FromSeconds(5));
                replacedert.Equal("\"32ca18808933aa12e979375d07048a11\"", part.ETag);
                replacedert.Equal(file.Length, part.Size);

                CompleteMultipartUploadResponse completeResp = await client.CompleteMultipartUploadAsync(tempBucket, objName, createResp.UploadId, new[] { uploadResp }).ConfigureAwait(false);
                replacedert.Equal(200, completeResp.StatusCode);

                ListPartsResponse listResp3 = await client.ListPartsAsync(tempBucket, objName, createResp.UploadId).ConfigureAwait(false);
                replacedert.Equal(404, listResp3.StatusCode);
            }).ConfigureAwait(false);
        }

19 View Source File : SarifErrorLogger.cs
License : MIT License
Project Creator : GGG-KILLER

protected static string GetUri(string path)
        {
            RoslynDebug.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 (!PathUtilities.IsUnixLikePlatform)
                {
                    path = path.Replace(@"\\", @"\");
                    path = PathUtilities.NormalizeWithForwardSlash(path);
                }

                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 : AuthenticationClient.cs
License : MIT License
Project Creator : glacasa

public string OAuthUrl(string? redirectUri = null)
        {
            if (AppRegistration == null)
            {
                throw new Exception("The app must be registered before you can connect");
            }

            if (redirectUri != null)
            {
                redirectUri = WebUtility.UrlEncode(WebUtility.UrlDecode(redirectUri));
            }
            else
            {
                redirectUri = "urn:ietf:wg:oauth:2.0:oob";
            }

            return $"https://{this.Instance}/oauth/authorize?response_type=code&client_id={AppRegistration.ClientId}&scope={GetScopeParam(AppRegistration.Scope).Replace(" ", "%20")}&redirect_uri={redirectUri ?? "urn:ietf:wg:oauth:2.0:oob"}";
        }

19 View Source File : Endpoints.cs
License : MIT License
Project Creator : glitch100

private static string GenerateQueryStringFromData(IRequest request)
        {
            if (request == null)
            {
                throw new Exception("No request data provided - query string can't be created");
            }

            //TODO: Refactor to not require double JSON loop
            var obj = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(request, _settings), _settings);

            return String.Join("&", obj.Children()
                .Cast<JProperty>()
                .Where(j => j.Value != null)
                .Select(j => j.Name + "=" + System.Net.WebUtility.UrlEncode(j.Value.ToString())));
        }

19 View Source File : MethodDetails.cs
License : Apache License 2.0
Project Creator : googleapis

private IEnumerable<RoutingHeader> ReadRoutingHeaders(HttpRule http, MessageDescriptor requestDesc)
        {
            if (http != null)
            {
                // Read routing headers(s) from any of the http urls
                var url =
                    !string.IsNullOrEmpty(http.Get) ? http.Get :
                    !string.IsNullOrEmpty(http.Post) ? http.Post :
                    !string.IsNullOrEmpty(http.Put) ? http.Put :
                    !string.IsNullOrEmpty(http.Patch) ? http.Patch :
                    !string.IsNullOrEmpty(http.Delete) ? http.Delete : null;
                if (url != null)
                {
                    foreach (var path in ExtractBracedPaths(url))
                    {
                        var desc = requestDesc;
                        var fields = new List<FieldDescriptor>();
                        FieldDescriptor finalField = null;
                        foreach (var fieldName in path.Split('.'))
                        {
                            var field = finalField = desc.FindFieldByName(fieldName);
                            desc = field.FieldType == FieldType.Message ? field.MessageType : null;
                            if (field == null)
                            {
                                throw new InvalidOperationException($"Invalid path in http url: '{path}'. '{fieldName}' does not exist.");
                            }
                            fields.Add(field);
                        }
                        if (finalField.FieldType != FieldType.String)
                        {
                            throw new InvalidOperationException($"Path in http url must resolve to a string field: '{path}'.");
                        }
                        yield return new RoutingHeader(WebUtility.UrlEncode(path), fields);
                    }
                }
            }

            IEnumerable<string> ExtractBracedPaths(string s)
            {
                var sb = new StringBuilder();
                int i = 0;
                while (i < s.Length)
                {
                    while (i < s.Length && s[i] != '{')
                    {
                        i++;
                    }
                    i++;
                    while (i < s.Length && s[i] != '=' && s[i] != '}')
                    {
                        sb.Append(s[i++]);
                    }
                    if (sb.Length > 0)
                    {
                        yield return sb.ToString();
                        sb.Clear();
                    }
                }
            }
        }

19 View Source File : CloudConsoleService.cs
License : Apache License 2.0
Project Creator : GoogleCloudPlatform

private void OpenLogs(string projectId, string query)
        {
            OpenUrl("https://console.cloud.google.com/logs/query;" +
                $"query={WebUtility.UrlEncode(query)};timeRange=PT1H;summaryFields=:true:32:beginning?" +
                $"project={projectId}");
        }

See More Examples