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 : IdentityManagementService.cs
License : MIT License
Project Creator : microsoft

public async Task<IActionResult> RemoveAuthorizedUser(string userPrincipalName)
        {
            try
            {
                if (!_idenreplacedyService.CurrentUserHasRole(AuthJanitorRoles.GlobalAdmin)) return new UnauthorizedResult();

                await _idenreplacedyServiceManager.RemoveAuthorizedUser(System.Net.WebUtility.UrlEncode(userPrincipalName));
            }
            catch (Exception ex) 
            {
                return new BadRequestObjectResult(ex);
            }
            return new OkResult();
        }

19 View Source File : IdentityManagementService.cs
License : MIT License
Project Creator : microsoft

public async Task<IActionResult> RemoveAuthorizedUser(string userPrincipalName, string role)
        {
            try
            {
                if (!_idenreplacedyService.CurrentUserHasRole(AuthJanitorRoles.GlobalAdmin)) return new UnauthorizedResult();

                await _idenreplacedyServiceManager.RemoveAuthorizedUser(
                    System.Net.WebUtility.UrlEncode(userPrincipalName),
                    role);
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult(ex);
            }
            return new OkResult();
        }

19 View Source File : QueryParser.TagValueParser.cs
License : MIT License
Project Creator : microsoft

private static DateTime ParseDateTime(string dateTime, string tagName)
        {
            // If the attribute has + in the value (for offset), it is converted to space by default.
            // Encoding it to get the + back such that it can be parsed as an offset properly.
            string encodedDateTime = WebUtility.UrlEncode(dateTime);

            if (!DateTime.TryParseExact(dateTime, DateTimeTagValueFormats, null, System.Globalization.DateTimeStyles.None, out DateTime parsedDateTime))
            {
                if (DateTime.TryParseExact(encodedDateTime, DateTimeTagValueWithOffsetFormats, null, System.Globalization.DateTimeStyles.None, out DateTime parsedDateTimeOffsetNotSupported))
                {
                    throw new QueryParseException(string.Format(DicomCoreResource.DateTimeWithOffsetNotSupported, encodedDateTime, tagName));
                }
                else
                {
                    throw new QueryParseException(string.Format(DicomCoreResource.InvalidDateTimeValue, encodedDateTime, tagName));
                }
            }

            return parsedDateTime;
        }

19 View Source File : GetCmdlet.cs
License : MIT License
Project Creator : microsoft

public string GetFunctionUrlSegment()
        {
            Type cmdletType = this.GetType();
            if (!(this is FunctionReturningEnreplacedyCmdlet) &&
                !(this is FunctionReturningCollectionCmdlet))
            {
                throw new PSArgumentException($"Cannot call method '{nameof(GetFunctionUrlSegment)}()' on a cmdlet of type '{cmdletType}'.");
            }

            // Create the list of arguments
            IEnumerable<string> paramArguments = this.GetBoundProperties(false).Select(param =>
            {
                object paramValue = param.GetValue(this);
                Type paramType = param.PropertyType;
                string oDataType = param.GetODataTypeAttribute()?.TypeFullName;

                // Check if we need special handling of the value based on the parameter type
                string paramArgumentValue = paramValue.ToODataString(oDataType, isArray: paramType.IsArray, isUrlValue: true);

                // Create the parameter mapping
                return $"{param.Name}={WebUtility.UrlEncode(paramArgumentValue)}";
            });

            // Join the list of arguments
            string result = string.Join(",", paramArguments);

            return result;
        }

19 View Source File : PackageUrl.cs
License : MIT License
Project Creator : microsoft

public override string ToString()
        {
            var purl = new StringBuilder();
            purl.Append(Scheme).Append(':');
            if (Type != null)
            {
                purl.Append(Type);
            }
            purl.Append('/');
            if (Namespace != null)
            {
                purl.Append(WebUtility.UrlEncode(Namespace));
                purl.Append('/');
            }
            if (Name != null)
            {
                purl.Append(Name);
            }
            if (Version != null)
            {
                purl.Append('@').Append(Version);
            }
            if (Qualifiers != null && Qualifiers.Count > 0)
            {
                purl.Append("?");
                foreach (var pair in Qualifiers)
                {
                    purl.Append(pair.Key.ToLower());
                    purl.Append('=');
                    purl.Append(pair.Value);
                    purl.Append('&');
                }
                purl.Remove(purl.Length - 1, 1);
            }
            if (Subpath != null)
            {
                purl.Append("#").Append(Subpath);
            }
            return purl.ToString();
        }

19 View Source File : IssueReport.cs
License : MIT License
Project Creator : microsoft

public string GetIssueReportUrlForGitHub (bool includeReport = true)
        {
            var builder = new System.Text.StringBuilder ();
            builder.Append ("https://github.com/Microsoft/workbooks/issues/new");
            if (includeReport)
                builder.Append ("?body=").Append (System.Net.WebUtility.UrlEncode (GetIssueReportForGitHub ()));
            return builder.ToString ();
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : microsoftgraph

public void ConfigureServices(IServiceCollection services)
        {
            _ = services ?? throw new ArgumentException(nameof(services));

            var scopesString = Configuration?.GetValue<string>("GraphScopes") ?? "User.Read";
            var scopesArray = scopesString.Split(' ');
            services
                // Use OpenId authentication
                .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                // Specify this is a web app and needs auth code flow
                .AddMicrosoftIdenreplacedyWebApp(options => {
                    Configuration.Bind("AzureAd", options);

                    options.Prompt = "select_account";

                    options.Events.OnAuthenticationFailed = context => {
                        var error = WebUtility.UrlEncode(context.Exception.Message);
                        context.Response
                            .Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
                        context.HandleResponse();

                        return Task.FromResult(0);
                    };

                    options.Events.OnRemoteFailure = context => {
                        if (context.Failure is OpenIdConnectProtocolException)
                        {
                            var error = WebUtility.UrlEncode(context.Failure.Message);
                            context.Response
                                .Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
                            context.HandleResponse();
                        }

                        return Task.FromResult(0);
                    };
                })
                // Add ability to call web API (Graph)
                // and get access tokens
                .EnableTokenAcquisitionToCallDownstreamApi(options => {
                    Configuration.Bind("AzureAd", options);
                }, scopesArray)
                // Add a GraphServiceClient via dependency injection
                .AddMicrosoftGraph(options => {
                    options.Scopes = scopesString;
                })
                // Use in-memory token cache
                // See https://github.com/AzureAD/microsoft-idenreplacedy-web/wiki/token-cache-serialization
                .AddInMemoryTokenCaches();

            // Add custom services
            services.AddSingleton<SubscriptionStore>();
            services.AddSingleton<CertificateService>();

            // Add SignalR
            services
                .AddSignalR(options => options.EnableDetailedErrors = true)
                .AddJsonProtocol();

            services.AddMvc(options => {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            // Add the Microsoft Idenreplacedy UI pages for signin/out
            .AddMicrosoftIdenreplacedyUI();
        }

19 View Source File : BingSearchHelper.cs
License : MIT License
Project Creator : MicrosoftLearning

public static async Task<IEnumerable<NewsArticle>> GetNewsSearchResults(string query, int count = 20, int offset = 0, string market = "en-US")
        {
            List<NewsArticle> articles = new List<NewsArticle>();

            var result = await RequestAndAutoRetryWhenThrottled(() => searchClient.GetAsync(string.Format("{0}/?q={1}&count={2}&offset={3}&mkt={4}", NewsSearchEndPoint, WebUtility.UrlEncode(query), count, offset, market)));
            result.EnsureSuccessStatusCode();
            var json = await result.Content.ReadreplacedtringAsync();
            dynamic data = JObject.Parse(json);

            if (data.value != null && data.value.Count > 0)
            {
                for (int i = 0; i < data.value.Count; i++)
                {
                    articles.Add(new NewsArticle
                    {
                        replacedle = data.value[i].name,
                        Url = data.value[i].url,
                        Description = data.value[i].description,
                        ThumbnailUrl = data.value[i].image?.thumbnail?.contentUrl,
                        Provider = data.value[i].provider?[0].name
                    });
                }
            }
            return articles;
        }

19 View Source File : BingSearchHelper.cs
License : MIT License
Project Creator : MicrosoftLearning

public static async Task<IEnumerable<string>> GetImageSearchResults(string query, string imageContent = "Face", int count = 20, int offset = 0)
        {
            List<string> urls = new List<string>();

            var result = await RequestAndAutoRetryWhenThrottled(() => searchClient.GetAsync(string.Format("{0}?q={1}&safeSearch=Strict&imageType=Photo&color=ColorOnly&count={2}&offset={3}{4}", ImageSearchEndPoint, WebUtility.UrlEncode(query), count, offset, string.IsNullOrEmpty(imageContent) ? "" : "&imageContent=" + imageContent)));
            result.EnsureSuccessStatusCode();
            var json = await result.Content.ReadreplacedtringAsync();
            dynamic data = JObject.Parse(json);
            if (data.value != null && data.value.Count > 0)
            {
                for (int i = 0; i < data.value.Count; i++)
                {
                    urls.Add(data.value[i].contentUrl.Value);
                }
            }

            return urls;
        }

19 View Source File : BingSearchHelper.cs
License : MIT License
Project Creator : MicrosoftLearning

public static async Task<IEnumerable<string>> GetAutoSuggestResults(string query, string market = "en-US")
        {
            List<string> suggestions = new List<string>();

            var result = await RequestAndAutoRetryWhenThrottled(() => autoSuggestionClient.GetAsync(string.Format("{0}/?q={1}&mkt={2}", AutoSuggestionEndPoint, WebUtility.UrlEncode(query), market)));
            result.EnsureSuccessStatusCode();
            var json = await result.Content.ReadreplacedtringAsync();
            dynamic data = JObject.Parse(json);
            if (data.suggestionGroups != null && data.suggestionGroups.Count > 0 &&
                data.suggestionGroups[0].searchSuggestions != null)
            {
                for (int i = 0; i < data.suggestionGroups[0].searchSuggestions.Count; i++)
                {
                    suggestions.Add(data.suggestionGroups[0].searchSuggestions[i].displayText.Value);
                }
            }

            return suggestions;
        }

19 View Source File : BingSearchHelper.cs
License : MIT License
Project Creator : MicrosoftLearning

private static async Task<HttpResponseMessage> CallBingImageInsightsAsync(string imgUrl, string module)
        {
            var result = await RequestAndAutoRetryWhenThrottled(() => searchClient.GetAsync(string.Format("{0}?imgUrl={1}&modules={2}", ImageInsightsEndPoint, WebUtility.UrlEncode(imgUrl), module)));
            result.EnsureSuccessStatusCode();
            return result;
        }

19 View Source File : SimpleNoteAPI.cs
License : MIT License
Project Creator : Mikescher

public static APIResultIndex ListBuckets(ISimpleJsonRest web)
		{
			try
			{
				var idx = web.Get<APIResultIndex>("note/index");

				while (!string.IsNullOrWhiteSpace(idx.mark))
				{
					var idx2 = web.Get<APIResultIndex>("note/index", "mark=" + WebUtility.UrlEncode(idx.mark));

					//idx.current = idx2.current;
					idx.mark = idx2.mark;
					idx.index.AddRange(idx2.index);
				}

				return idx;
			}
			catch (RestStatuscodeException e1)
			{
				if (e1.StatusCode == 400 && !string.IsNullOrWhiteSpace(e1.HTTPContent))
				{
					var req = web.ParseJsonOrNull<APIBadRequest>(e1.HTTPContent);
					if (req != null) throw new SimpleNoteAPIException($"Server returned status 400.\nField: '{req.field}'.\nMessage: '{req.message}'", e1);
				}

				throw;
			}
		}

19 View Source File : HttpService.cs
License : MIT License
Project Creator : mixcore

public Task<T> GetAsync<T>(
            string requestUrl,
            List<KeyValuePair<string, string>> queryParams = null,
            string bearerToken = null,
            List<KeyValuePair<string, string>> requestHeaders = null)
        {
            var urlQueryParamsPart = queryParams != null
                ? string.Join("&", queryParams.Select(p => $"{p.Key}={WebUtility.UrlEncode(p.Value)}"))
                : string.Empty;
            var requestUrlWithQueryParams = !string.IsNullOrEmpty(urlQueryParamsPart)
                ? (!requestUrl.Contains("?") ? $"{requestUrl}?{urlQueryParamsPart}" : $"{requestUrl}&{urlQueryParamsPart}")
                : requestUrl;
            return SendRequestAsync<T>(client => client.GetAsync(requestUrlWithQueryParams), bearerToken, requestHeaders);
        }

19 View Source File : HttpService.cs
License : MIT License
Project Creator : mixcore

public Task<T> GetBasicAuthAsync<T>(
            string requestUrl,
            string username, string preplacedword,
            List<KeyValuePair<string, string>> queryParams = null,
            List<KeyValuePair<string, string>> requestHeaders = null)
        {
            var urlQueryParamsPart = queryParams != null
                ? string.Join("&", queryParams.Select(p => $"{p.Key}={WebUtility.UrlEncode(p.Value)}"))
                : string.Empty;
            var requestUrlWithQueryParams = !string.IsNullOrEmpty(urlQueryParamsPart)
                ? (!requestUrl.Contains("?") ? $"{requestUrl}?{urlQueryParamsPart}" : $"{requestUrl}&{urlQueryParamsPart}")
                : requestUrl;
            return SendRequestAsync<T>(client => client.GetAsync(requestUrlWithQueryParams), username, preplacedword, requestHeaders);
        }

19 View Source File : Rest20.cs
License : MIT License
Project Creator : mrchrisok

protected static string CreateParamString(Dictionary<string, string> requestParams)
      {
         string requestBody = "";
         foreach (var pair in requestParams)
         {
            requestBody += WebUtility.UrlEncode(pair.Key) + "=" + WebUtility.UrlEncode(pair.Value) + "&";
         }
         requestBody = requestBody.Trim('&');
         return requestBody;
      }

19 View Source File : Rest20.cs
License : MIT License
Project Creator : mrchrisok

private static string CreateQueryString(Dictionary<string, string> requestParams)
      {
         string queryString = "";
         foreach (var pair in requestParams)
         {
            queryString += WebUtility.UrlEncode(pair.Key) + "=" + WebUtility.UrlEncode(pair.Value) + "&";
         }
         queryString = queryString.Trim('&');
         return queryString;
      }

19 View Source File : SearchDescriptionCommand.cs
License : MIT License
Project Creator : mrlacey

private async void Execute(object sender, EventArgs e)
#pragma warning restore VSTHRD100 // Avoid async void methods
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var desc = await this.GetDescriptionAsync();

            if (!string.IsNullOrEmpty(desc))
            {
                var searchEngine = ErrorHelperPackage.Instance?.Options?.SearchEngine;

                string url;
                switch (searchEngine)
                {
                    case SearchEngine.Google:
                        url = "https://www.google.com/search?q=";
                        break;
                    case SearchEngine.StackOverflow:
                        url = "https://stackoverflow.com/search?q=";
                        break;
                    case SearchEngine.Bing:
                    default:
                        url = "https://www.bing.com/search?q=";
                        break;
                }

                string query = desc;

                if (ErrorHelperPackage.Instance?.Options?.StripPaths ?? false)
                {
                    query = StripPaths(desc);
                }

                var ps = new ProcessStartInfo(url + WebUtility.UrlEncode(query))
                {
                    UseShellExecute = true,
                    Verb = "open",
                };
                Process.Start(ps);
            }
        }

19 View Source File : UrlHelper.cs
License : MIT License
Project Creator : msdn129

public string NodeSwitch(string id)
        {
            return To("/nodes/node/" + WebUtility.UrlEncode(id));
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : MSiccDev

public async Task<CoinPaprikaEnreplacedy<SearchResult>> SearchAsync(string searchterms, int limit = 6, List<SearchCategory> searchCategories = null, bool onlySymbols = false)
        {
            if (limit < 1 || limit > 250)
                throw new ArgumentOutOfRangeException(nameof(limit), "limit must be between 1 and 250");

            string categoriesToSearch = string.Empty;
            if (searchCategories == null)
                categoriesToSearch = "currencies,exchanges,icos,people,tags";
            else
            {
                foreach (var category in searchCategories)
                {
                    if (!string.IsNullOrWhiteSpace(categoriesToSearch))
                        categoriesToSearch += ",";

                    categoriesToSearch += category.ToString().ToLowerInvariant();
                }
            }

            var client = BaseClient.GetClient();

            var requestUrl = $"{_apiBaseUrl}/search?q={WebUtility.UrlEncode(searchterms)}&c={categoriesToSearch}&limit={limit}";

            if (onlySymbols)
                requestUrl.AddParameterToUrl("modifier", "symbol_search");

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

            var response = await client.SendAsync(request).ConfigureAwait(false);

            return new CoinPaprikaEnreplacedy<SearchResult>(response, false, !response.IsSuccessStatusCode, null);
        }

19 View Source File : QrCode.cs
License : GNU General Public License v3.0
Project Creator : myvas

public static async Task ShowQrcode(string ticket, Stream stream)
        {
            var api = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
            api = api.Replace("TICKET", WebUtility.UrlEncode(ticket));
            await HttpUtility.Download(api, stream);
        }

19 View Source File : QrCode.cs
License : GNU General Public License v3.0
Project Creator : myvas

public static string ShowQrcode(string ticket)
        {
            var api = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
            api = api.Replace("TICKET", WebUtility.UrlEncode(ticket));
            return api;
        }

19 View Source File : PushReceiver.cs
License : Apache License 2.0
Project Creator : nacos-group

private async Task RunAsync()
        {
            string udpPort = GetPushReceiverUdpPort();

            if (udpPort.IsNotNullOrWhiteSpace())
            {
                _port = Convert.ToInt32(udpPort);
                _udpClient = new UdpClient(_port);
                _logger?.LogInformation($"start up udp server....., port: {_port}");
            }
            else
            {
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        _port = new Random((int)DateTimeOffset.Now.ToUnixTimeSeconds()).Next(0, 1000) + 54951;
                        _udpClient = new UdpClient(_port);
                        _logger?.LogInformation($"start up udp server....., port: {_port}");
                        break;
                    }
                    catch (Exception ex)
                    {
                        _logger?.LogError(ex, "failed to start udp server {0}, {1}", i + 1, _port);
                    }
                }
            }

            while (!_closed)
            {
                try
                {
                    if (_udpClient == null)
                    {
                        _closed = true;
                        break;
                    }

                    var res = await _udpClient.ReceiveAsync().ConfigureAwait(false);

                    var json = Encoding.UTF8.GetString(TryDecompressData(res.Buffer));
                    _logger?.LogInformation("received push data: {0} from {1}", json, res.RemoteEndPoint.ToString());

                    var pushPacket = json.ToObj<PushPacket>();

                    var ack = string.Empty;

                    if (pushPacket.Type.Equals(PUSH_PACKAGE_TYPE_DOM, StringComparison.OrdinalIgnoreCase) || pushPacket.Type.Equals(PUSH_PACKAGE_TYPE_SERVICE, StringComparison.OrdinalIgnoreCase))
                    {
                        _serviceInfoHolder.ProcessServiceInfo(pushPacket.Data);

                        ack = new { type = "push-ack", lastRefTime = pushPacket.LastRefTime, data = string.Empty }.ToJsonString();
                    }
                    else if (pushPacket.Type.Equals(PUSH_PACKAGE_TYPE_DUMP, StringComparison.OrdinalIgnoreCase))
                    {
                        var map = System.Net.WebUtility.UrlEncode(_serviceInfoHolder.GetServiceInfoMap().ToJsonString());
                        ack = new { type = "dump-ack", lastRefTime = pushPacket.LastRefTime, data = map }.ToJsonString();
                    }
                    else
                    {
                        ack = new { type = "unknown-ack", lastRefTime = pushPacket.LastRefTime, data = string.Empty }.ToJsonString();
                    }

                    var ackByte = Encoding.UTF8.GetBytes(ack);
                    await _udpClient.SendAsync(ackByte, ackByte.Length, res.RemoteEndPoint).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, "[NA] error while receiving push data");
                }
            }
        }

19 View Source File : ServiceInfo.cs
License : Apache License 2.0
Project Creator : nacos-group

public string GetKeyEncoded() => GetKey(System.Net.WebUtility.UrlEncode(GetGroupedServiceName()), Clusters);

19 View Source File : ReadSideImpl.cs
License : Apache License 2.0
Project Creator : nagytech

public override void Register<TE>(Func<ReadSideProcessor<TE>> processorFactory)
        {
            if (!Config.Role.ForAll(Cluster.Get(System).SelfRoles.Contains))
                return;

            ReadSideProcessor<TE> dummyProcessor;
            try
            {
                dummyProcessor = processorFactory();
            }
            catch (Exception)
            {
                throw new InvalidOperationException(
                    "Cannot create instance of ReadSideProcessor"
                );
            }

            var readSideName = (Name.HasValue ? (Name.Value + "-") : "") + dummyProcessor.ReadSideName;
            var encodedReadSideName = WebUtility.UrlEncode(readSideName);
            var tags = dummyProcessor.AggregateTags;
            var enreplacedyIds = tags.Select(x => x.Tag);

            var globalPrepareTask = ClusterStartupTask.Apply(
                System,
                $"readSideGlobalPrepare-{encodedReadSideName}",
                () => processorFactory().BuildHandler().GlobalPrepare(),
                Config.GlobalPrepareTimeout,
                Config.Role,
                Config.MinBackoff,
                Config.MaxBackoff,
                Config.RandomBackoffFactor
            );

            var readSideProps = ReadSideActor.Props(
                Config,
                globalPrepareTask,
                Registry.EventStream<TE>,
                processorFactory
            );

            var shardingSettings = ClusterShardingSettings.Create(System).WithRole(Config.Role.OrElse(""));

            new ClusterDistributionExtensionProvider.ClusterDistribution(System).Start(
                readSideName,
                readSideProps,
                enreplacedyIds.ToArray(),
                new ClusterDistributionSettings(System, shardingSettings)
            );

        }

19 View Source File : ClusterDistribution.cs
License : Apache License 2.0
Project Creator : nagytech

public IActorRef Start(
                string typeName,
                Props enreplacedyProps,
                string[] enreplacedyIds,
                ClusterDistributionSettings settings)
            {

                ExtractEnreplacedyId extractEnreplacedyId = (msg) =>
                {
                    switch (msg)
                    {
                        case EnsureActive ensureActive:
                            return (ensureActive.EnreplacedyId, msg).ToTuple();
                        default:
                            return null;
                    }
                };
                ExtractShardId extractShardId = (msg) =>
                {
                    switch (msg)
                    {
                        case EnsureActive ensureActive:
                            if (enreplacedyIds.Length > MaxShards)
                                return Math.Abs(enreplacedyIds.Length % 1000).ToString();
                            return ensureActive.EnreplacedyId;
                        default:
                            return null;
                    }
                };

                var sharding = ClusterSharding.Get(ActorSystem);

                var role = String.IsNullOrEmpty(settings.ClusterShardingSettings.Role) ?
                    new Option<string>() : new Option<string>(settings.ClusterShardingSettings.Role);
                if (role.ForAll(Cluster.Get(ActorSystem).SelfRoles.Contains))
                {
                    var shardRegion = sharding.Start(
                        typeName,
                        enreplacedyProps,
                        settings.ClusterShardingSettings,
                        extractEnreplacedyId,
                        extractShardId
                    );

                    ActorSystem.ActorOf(
                        EnsureActiveActor.Props(
                            enreplacedyIds,
                            shardRegion,
                            settings.EnsureActiveInterval
                        ),
                        "cluster-distribution-" + WebUtility.UrlEncode(typeName)
                    );

                    return shardRegion;
                }
                else
                {
                    return sharding.StartProxy(
                        typeName,
                        settings.ClusterShardingSettings.Role,
                        extractEnreplacedyId,
                        extractShardId
                    );
                }

            }

19 View Source File : Request.cs
License : GNU General Public License v3.0
Project Creator : nahuelwexd

protected string GetParametersreplacedtring()
        {
            var joined_pairs = new List<string>();

            foreach (var item in this.parameters)
                if (string.IsNullOrWhiteSpace(item.Value))
                    joined_pairs.Add(WebUtility.UrlEncode(item.Key) + "=" +
                        WebUtility.UrlEncode(item.Value));

            return string.Join("&", joined_pairs);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : nanoframework

static string GetSharedAccessSignature(string keyName, string sharedAccessKey, string resource, TimeSpan tokenTimeToLive)
        {
            // http://msdn.microsoft.com/en-us/library/azure/dn170477.aspx
            // the canonical Uri scheme is http because the token is not amqp specific
            // signature is computed from joined encoded request Uri string and expiry string

            var exp = DateTime.UtcNow.ToUnixTimeSeconds() + (long)tokenTimeToLive.TotalSeconds;

            string expiry = exp.ToString();
            string encodedUri = WebUtility.UrlEncode(resource);

            
            byte[] hmac = SHA.computeHMAC_SHA256(Convert.FromBase64String(sharedAccessKey), Encoding.UTF8.GetBytes(encodedUri + "\n" + expiry));
            string sig = Convert.ToBase64String(hmac);

            if (keyName != null)
            {
                return String.Format(
                "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                encodedUri,
                WebUtility.UrlEncode(sig),
                WebUtility.UrlEncode(expiry),
                WebUtility.UrlEncode(keyName));
            }
            else
            {
                return String.Format(
                    "SharedAccessSignature sr={0}&sig={1}&se={2}",
                    encodedUri,
                    WebUtility.UrlEncode(sig),
                    WebUtility.UrlEncode(expiry));
            }
        }

19 View Source File : Fido2MetadataServiceRepository.cs
License : MIT License
Project Creator : neos-sdi

protected async Task<string> GetRawToc()
        {           
            var url = _tocUrl + "/?token=" + WebUtility.UrlEncode(_token);
            return await DownloadStringAsync(url);
        }

19 View Source File : Fido2MetadataServiceRepository.cs
License : MIT License
Project Creator : neos-sdi

public async Task<MetadataStatement> GetMetadataStatement(MetadataTOCPayloadEntry entry)
        {
            var statementBase64Url = await DownloadStringAsync(entry.Url + "/?token=" + WebUtility.UrlEncode(_token));
            var tocAlg = await GetTocAlg();

            var statementBytes = Base64Url.Decode(statementBase64Url);
            var statementString = Encoding.UTF8.GetString(statementBytes, 0, statementBytes.Length);
            var statement = Newtonsoft.Json.JsonConvert.DeserializeObject<MetadataStatement>(statementString);
            using (HashAlgorithm hasher = CryptoUtils.GetHasher(new HashAlgorithmName(tocAlg)))
            {
                statement.Hash = Base64Url.Encode(hasher.ComputeHash(Encoding.UTF8.GetBytes(statementBase64Url)));
            }

            if(!HashesAreEqual(entry.Hash, statement.Hash))
                throw new VerificationException("TOC entry and statement hashes do not match");

            return statement;
        }

19 View Source File : StoreController.cs
License : MIT License
Project Creator : netnr

[HttpPost]
        [ValidateAntiForgeryToken]
        public string QQAPI(string bucket, string path)
        {
            var cos = new CosCloud(AccessCOS.APPID, AccessCOS.SecretId, AccessCOS.SecretKey, UrlType.HB);

            string cmd = RouteData.Values["id"]?.ToString().ToLower();
            string result = "fail";

            switch (cmd)
            {
                #region 列表
                case "list":
                    try
                    {
                        //关键字搜索
                        string keywords = Request.Form["keywords"].ToString();
                        var folderlistParasDic = new Dictionary<string, string>
                        {
                            { CosParameters.PARA_NUM, "1000" },
                            { CosParameters.PARA_ORDER, "0" },
                            { CosParameters.PARA_PATTERN, FolderPattern.PATTERN_BOTH },
                            { CosParameters.PARA_PREFIX, keywords }
                        };
                        //桶、路径下
                        result = cos.GetFolderList(bucket, path, folderlistParasDic);
                        result = System.Net.WebUtility.UrlDecode(result);
                    }
                    catch (Exception)
                    {
                        result = "{}";
                    }
                    break;
                #endregion

                #region 存在
                case "exists":
                    try
                    {
                        result = "0";

                        //文件名搜索
                        string keywords = Request.Form["key"].ToString();
                        var folderlistParasDic = new Dictionary<string, string>
                        {
                            { CosParameters.PARA_NUM, "1000" },
                            { CosParameters.PARA_ORDER, "0" },
                            { CosParameters.PARA_PATTERN, FolderPattern.PATTERN_BOTH },
                            { CosParameters.PARA_PREFIX, keywords }
                        };
                        //桶、路径下
                        result = cos.GetFolderList(bucket, path, folderlistParasDic);
                        JObject jo = JObject.Parse(result);
                        if (jo["code"].ToStringOrEmpty() == "0")
                        {
                            var infos = jo["data"]["infos"];
                            foreach (var item in infos)
                            {
                                foreach (JProperty jp in item)
                                {
                                    if (jp.Name == "name" && jp.Value.ToStringOrEmpty().Equals(keywords))
                                    {
                                        result = "1";
                                        goto eachflag;
                                    }
                                }
                            }
                        }
                        eachflag: if (result == "1")
                        {
                            result = "1";
                        }
                        else
                        {
                            result = "0";
                        }
                    }
                    catch (Exception)
                    {
                        result = "0";
                    }
                    break;
                #endregion

                #region 新建文件夹
                case "newfolder":
                    try
                    {
                        path = path.EndsWith("/") ? path : path + "/";
                        string folder = Request.Form["folder"].ToString();
                        result = cos.CreateFolder(bucket, path + folder);
                    }
                    catch (Exception)
                    {
                        result = "{}";
                    }
                    break;
                #endregion

                #region 删除
                case "del":
                    {
                        path = path.EndsWith("/") ? path : path + "/";

                        //是否都删除成功
                        bool b1 = false;
                        //是否有部分失败
                        bool b2 = false;

                        List<string> files = Request.Form["files"].ToString().Split(',').ToList();
                        List<string> folder = Request.Form["folder"].ToString().Split(',').ToList();

                        foreach (var item in files)
                        {
                            try
                            {
                                if (!string.IsNullOrWhiteSpace(item))
                                {
                                    JObject jo = jo = JObject.Parse(cos.DeleteFile(bucket, path + item));
                                    if (jo["code"].ToStringOrEmpty() == "0")
                                    {
                                        b1 = true;
                                    }
                                    else
                                    {
                                        b2 = true;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        foreach (var item in folder)
                        {
                            try
                            {
                                if (!string.IsNullOrWhiteSpace(item))
                                {
                                    JObject jo = JObject.Parse(cos.DeleteFolder(bucket, path + System.Net.WebUtility.UrlEncode(item)));
                                    if (jo["code"].ToStringOrEmpty() == "0")
                                    {
                                        b1 = true;
                                    }
                                    else
                                    {
                                        b2 = true;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (b2)
                        {
                            result = "partialfail";
                        }
                        else
                        {
                            if (b1)
                            {
                                result = "success";
                            }
                            else
                            {
                                result = "fail";
                            }
                        }
                    }
                    break;
                #endregion
            }


            return result;
        }

19 View Source File : Extend.cs
License : MIT License
Project Creator : netnr

public static string ToUrlEncode(this string value)
        {
            return System.Net.WebUtility.UrlEncode(value);
        }

19 View Source File : StoreController.cs
License : MIT License
Project Creator : netnr

[HttpPost]
        [ValidateAntiForgeryToken]
        public string QQAPI(string bucket, string path)
        {
            var cos = new CosCloud(AccessCOS.APPID, AccessCOS.SecretId, AccessCOS.SecretKey, UrlType.HB);

            string cmd = RouteData.Values["id"]?.ToString().ToLower();
            string result = "fail";

            switch (cmd)
            {
                #region 列表
                case "list":
                    try
                    {
                        //关键字搜索
                        string keywords = Request.Form["keywords"].ToString();
                        var folderlistParasDic = new Dictionary<string, string>
                        {
                            { CosParameters.PARA_NUM, "1000" },
                            { CosParameters.PARA_ORDER, "0" },
                            { CosParameters.PARA_PATTERN, FolderPattern.PATTERN_BOTH },
                            { CosParameters.PARA_PREFIX, keywords }
                        };
                        //桶、路径下
                        result = cos.GetFolderList(bucket, path, folderlistParasDic);
                        result = System.Net.WebUtility.UrlDecode(result);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        result = "{}";
                    }
                    break;
                #endregion

                #region 存在
                case "exists":
                    try
                    {
                        result = "0";

                        //文件名搜索
                        string keywords = Request.Form["key"].ToString();
                        var folderlistParasDic = new Dictionary<string, string>
                        {
                            { CosParameters.PARA_NUM, "1000" },
                            { CosParameters.PARA_ORDER, "0" },
                            { CosParameters.PARA_PATTERN, FolderPattern.PATTERN_BOTH },
                            { CosParameters.PARA_PREFIX, keywords }
                        };
                        //桶、路径下
                        result = cos.GetFolderList(bucket, path, folderlistParasDic);
                        JObject jo = JObject.Parse(result);
                        if (jo["code"].ToStringOrEmpty() == "0")
                        {
                            var infos = jo["data"]["infos"];
                            foreach (var item in infos)
                            {
                                foreach (JProperty jp in item)
                                {
                                    if (jp.Name == "name" && jp.Value.ToStringOrEmpty().Equals(keywords))
                                    {
                                        result = "1";
                                        goto eachflag;
                                    }
                                }
                            }
                        }
                    eachflag: if (result == "1")
                        {
                            result = "1";
                        }
                        else
                        {
                            result = "0";
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        result = "0";
                    }
                    break;
                #endregion

                #region 新建文件夹
                case "newfolder":
                    try
                    {
                        path = path.EndsWith("/") ? path : path + "/";
                        string folder = Request.Form["folder"].ToString();
                        result = cos.CreateFolder(bucket, path + folder);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        result = "{}";
                    }
                    break;
                #endregion

                #region 删除
                case "del":
                    {
                        path = path.EndsWith("/") ? path : path + "/";

                        //是否都删除成功
                        bool b1 = false;
                        //是否有部分失败
                        bool b2 = false;

                        List<string> files = Request.Form["files"].ToString().Split(',').ToList();
                        List<string> folder = Request.Form["folder"].ToString().Split(',').ToList();

                        foreach (var item in files)
                        {
                            try
                            {
                                if (!string.IsNullOrWhiteSpace(item))
                                {
                                    JObject jo = jo = JObject.Parse(cos.DeleteFile(bucket, path + item));
                                    if (jo["code"].ToStringOrEmpty() == "0")
                                    {
                                        b1 = true;
                                    }
                                    else
                                    {
                                        b2 = true;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        foreach (var item in folder)
                        {
                            try
                            {
                                if (!string.IsNullOrWhiteSpace(item))
                                {
                                    JObject jo = JObject.Parse(cos.DeleteFolder(bucket, path + System.Net.WebUtility.UrlEncode(item)));
                                    if (jo["code"].ToStringOrEmpty() == "0")
                                    {
                                        b1 = true;
                                    }
                                    else
                                    {
                                        b2 = true;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        if (b2)
                        {
                            result = "partialfail";
                        }
                        else
                        {
                            if (b1)
                            {
                                result = "success";
                            }
                            else
                            {
                                result = "fail";
                            }
                        }
                    }
                    break;
                    #endregion
            }


            return result;
        }

19 View Source File : UserController.cs
License : MIT License
Project Creator : newbe36524

[HttpGet("{id}")]
        public async Task<IActionResult> Login(string id, string username, string preplacedword)
        {
            var userGrain = _grainFactory.GetGrain<IUserGrain>(id);
            var token = await userGrain.LoginAsync(username, preplacedword);
            return Json(new
            {
                token,
                validate = $"/api/user/{id}/validate?token={WebUtility.UrlEncode(token)}"
            });
        }

19 View Source File : PushGateway.cs
License : MIT License
Project Creator : nexogen-international

private HttpRequestMessage CreateRequestMessage(IExposable metrics, string job, Stream stream)
        {
            var path = string.Format("metrics/job/{0}", WebUtility.UrlEncode(job));
            
            if (!string.IsNullOrEmpty(instance))
            {
                path = string.Format("{0}/instance/{1}", path, WebUtility.UrlEncode(instance));
            }
            
            if (defaultLabels != null)
            {
                foreach (var pair in defaultLabels)
                {
                    if (string.IsNullOrEmpty(pair?.Item1) || string.IsNullOrEmpty(pair.Item2))
                    {
                        continue;
                    }
                    path = string.Format("{0}/{1}/{2}", path, WebUtility.UrlEncode(pair.Item1), WebUtility.UrlEncode(pair.Item2));
                }
            }

            var request = new HttpRequestMessage(HttpMethod.Post, path);
            request.Content = new StreamContent(stream);
            request.Content.Headers.TryAddWithoutValidation("Content-Type", "text/plain; version=0.0.4");

            return request;
        }

19 View Source File : PubSubApi.cs
License : Creative Commons Zero v1.0 Universal
Project Creator : NextGenSoftwareUK

public Task PublishAsync(string topic, byte[] message, CancellationToken cancel = default(CancellationToken))
        {
            var url = new StringBuilder();
            url.Append("/api/v0/pubsub/pub");
            url.Append("?arg=");
            url.Append(System.Net.WebUtility.UrlEncode(topic));
            url.Append("&arg=");
            var data = Encoding.ASCII.GetString(System.Net.WebUtility.UrlEncodeToBytes(message, 0, message.Length));
            url.Append(data);
            return ipfs.DoCommandAsync(new Uri(ipfs.ApiUri, url.ToString()), cancel);
        }

19 View Source File : IpfsClient.cs
License : Creative Commons Zero v1.0 Universal
Project Creator : NextGenSoftwareUK

Uri BuildCommand(string command, string arg = null, params string[] options)
        {
            var url = "/api/v0/" + command;
            var q = new StringBuilder();
            if (arg != null)
            {
                q.Append("&arg=");
                q.Append(WebUtility.UrlEncode(arg));
            }

            foreach (var option in options)
            {
                q.Append('&');
                var i = option.IndexOf('=');
                if (i < 0)
                {
                    q.Append(option);
                }
                else
                {
                    q.Append(option.Substring(0, i));
                    q.Append('=');
                    q.Append(WebUtility.UrlEncode(option.Substring(i + 1)));
                }
            }

            if (q.Length > 0)
            {
                q[0] = '?';
                q.Insert(0, url);
                url = q.ToString();
            }

            return new Uri(ApiUri, url);
        }

19 View Source File : UrlTokenModifier.cs
License : GNU General Public License v3.0
Project Creator : NHxD

public bool Mutate(string[] tokens, string[] namespaces, ref string value, ref int tokenIndex)
		{
			string result = null;

			if (namespaces[0].Equals(Namespace, StringComparison.OrdinalIgnoreCase))
			{
				if (namespaces[1].Equals("Encode", StringComparison.OrdinalIgnoreCase))
				{
					result = System.Net.WebUtility.UrlEncode(value);
				}
				else if (namespaces[1].Equals("Decode", StringComparison.OrdinalIgnoreCase))
				{
					result = System.Net.WebUtility.UrlDecode(value);
				}
			}

			if (result != null)
			{
				value = result;
				return true;
			}

			return false;
		}

19 View Source File : TagDefinition.cs
License : GNU General Public License v3.0
Project Creator : NHxD

private static void DefineTermBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			RunArg runArg = e.Argument as RunArg;
			string uri = string.Format(CultureInfo.InvariantCulture, "http://api.urbandictionary.com/v0/define?term={0}", WebUtility.UrlEncode(runArg.Term));

			try
			{
				using (HttpResponseMessage response = Task.Run(() => runArg.HttpClient?.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult())
				{
					if (!response.IsSuccessStatusCode)
					{
						response.EnsureSuccessStatusCode();
						//error = string.Format(CultureInfo.InvariantCulture, "{0} ({1})", response.ReasonPhrase, response.StatusCode);
						return;
					}
					else
					{
						try
						{
							string jsonText = Task.Run(() => response.Content.ReadreplacedtringAsync()).GetAwaiter().GetResult();

							e.Result = JsonConvert.DeserializeObject<SearchResult>(jsonText);
							return;
						}
						catch (Exception ex)
						{
							e.Result = ex;
							return;
						}
					}
				}
			}
			catch (Exception ex)
			{
				e.Result = ex;
				return;
			}
		}

19 View Source File : GoogleTranslate.cs
License : MIT License
Project Creator : noctwolf

static string TranslateCore(string text, string fromLanguage, string toLanguage)
        {
            text = text.StripBidiControlCharacter();
            var tk = GetTK(text, GetTKK(BaseUrl, out CookieContainer cc));
            string googleTransUrl = BaseUrl + "translate_a/single?client=webapp&sl=" + fromLanguage + "&tl=" + toLanguage + "&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=1&tk=" + tk + "&q=" + WebUtility.UrlEncode(text);
            var ResultHtml = GetResultHtml(googleTransUrl, cc, BaseUrl);
            dynamic TempResult = Newtonsoft.Json.JsonConvert.DeserializeObject(ResultHtml);
            string result = "";
            for (int i = 0; i < TempResult[0].Count; i++) result += Convert.ToString(TempResult[0][i][0]);
            return result;
        }

19 View Source File : BaipiaoEngine.cs
License : GNU General Public License v3.0
Project Creator : Noisyfox

public void Speak(string text, dynamic playDevice, bool isSync, float? volume)
        {
            var settings = _plugin.Settings.BaipiaoSettings;
            if (!settings.Accept)
            {
                return;
            }

            foreach (var illegalChar in IllegalChars)
            {
                text = text.Replace(illegalChar, ' ');
            }

            var wave = _plugin.Cache.GetOrCreateFile(
                this,
                text,
                "mp3",
                settings.ToString(),
                f =>
                {
                    var url =
                        $"https://fanyi.baidu.com/gettts?lan=zh&text={WebUtility.UrlEncode(text)}&spd={settings.Speed}&source=web";

                    Utils.Download(url, f);
                });

            _plugin.SoundPlayer.Play(wave, playDevice, isSync, volume);
        }

19 View Source File : CafeTTSEngine.cs
License : GNU General Public License v3.0
Project Creator : Noisyfox

public void Speak(string text, dynamic playDevice, bool isSync, float? volume)
        {
            var settings = _plugin.Settings.CafeTtsSettings;

            var wave = _plugin.Cache.GetOrCreateFile(
                this,
                text,
                "mp3",
                settings.ToString(),
                f =>
                {
                    var url = $"http://tts.wakingsands.com:3002/tts.mp3?voice_font={settings.Voice}&text={WebUtility.UrlEncode(text)}";

                    Utils.Download(url, f);
                });

            _plugin.SoundPlayer.Play(wave, playDevice, isSync, volume);
        }

19 View Source File : QueryHelpers.cs
License : MIT License
Project Creator : notion-dotnet

private static string AddQueryString(
            string uri,
            IEnumerable<KeyValuePair<string, string>> queryParams)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (queryParams == null)
            {
                throw new ArgumentNullException(nameof(queryParams));
            }

            queryParams = RemoveEmptyValueQueryParams(queryParams);

            var anchorIndex = uri.IndexOf('#');
            var uriToBeAppended = uri;
            var anchorText = "";

            if (anchorIndex != -1)
            {
                anchorText = uri.Substring(anchorIndex);
                uriToBeAppended = uri.Substring(0, anchorIndex);
            }

            var queryIndex = uriToBeAppended.IndexOf('?');
            var hasQuery = queryIndex != -1;

            var sb = new StringBuilder();
            sb.Append(uriToBeAppended);
            foreach (var parameter in queryParams)
            {
                sb.Append(hasQuery ? '&' : '?');
                sb.Append(WebUtility.UrlEncode(parameter.Key));
                sb.Append('=');
                sb.Append(WebUtility.UrlEncode(parameter.Value));
                hasQuery = true;
            }

            sb.Append(anchorText);
            return sb.ToString();
        }

public async Task<Result> TriggerPreplacedwordReset(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                _loggerAdapter.WarnFormat("Trigger preplacedword reset failed, user with email {0} not found", email);
                return Success(ResultKey.User.ResetPreplacedword.Success);
            }

            var token = await _userManager.GeneratePreplacedwordResetTokenAsync(user);

            var baseUrl = new Uri(_config.BaseUrl);
            var resetUrl = new Uri(baseUrl, $"resetPreplacedwordCallback?email={WebUtility.UrlEncode(email)}&token={WebUtility.UrlEncode(token)}").ToString();

            var nyssUser = await _nyssContext.Users.FilterAvailable().Include(u => u.ApplicationLanguage).SingleAsync(x => x.IdenreplacedyUserId == user.Id);
            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateResetPreplacedwordEmail(resetUrl, nyssUser.Name, nyssUser.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((email, nyssUser.Name), emailSubject, emailBody);
            
            return Success(ResultKey.User.ResetPreplacedword.Success);
        }

public async Task<Result> TriggerPreplacedwordReset(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                _loggerAdapter.WarnFormat("Trigger preplacedword reset failed, user with email {0} not found", email);
                return Success(ResultKey.User.ResetPreplacedword.Success);
            }

            var token = await _userManager.GeneratePreplacedwordResetTokenAsync(user);

            var baseUrl = new Uri(_config.BaseUrl);
            var resetUrl = new Uri(baseUrl, $"resetPreplacedwordCallback?email={WebUtility.UrlEncode(email)}&token={WebUtility.UrlEncode(token)}").ToString();

            var nyssUser = await _nyssContext.Users.FilterAvailable().Include(u => u.ApplicationLanguage).SingleAsync(x => x.IdenreplacedyUserId == user.Id);
            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateResetPreplacedwordEmail(resetUrl, nyssUser.Name, nyssUser.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((email, nyssUser.Name), emailSubject, emailBody);
            
            return Success(ResultKey.User.ResetPreplacedword.Success);
        }

public async Task SendVerificationEmail(User user, string securityStamp)
        {
            var baseUrl = new Uri(_config.BaseUrl);
            var verificationUrl = new Uri(baseUrl, $"verifyEmail?email={WebUtility.UrlEncode(user.EmailAddress)}&token={WebUtility.UrlEncode(securityStamp)}").ToString();

            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateEmailVerificationEmail(
                user.Role,
                verificationUrl,
                user.Name,
                user.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((user.EmailAddress, user.Name), emailSubject, emailBody);
        }

public async Task SendVerificationEmail(User user, string securityStamp)
        {
            var baseUrl = new Uri(_config.BaseUrl);
            var verificationUrl = new Uri(baseUrl, $"verifyEmail?email={WebUtility.UrlEncode(user.EmailAddress)}&token={WebUtility.UrlEncode(securityStamp)}").ToString();

            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateEmailVerificationEmail(
                user.Role,
                verificationUrl,
                user.Name,
                user.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((user.EmailAddress, user.Name), emailSubject, emailBody);
        }

public async Task SendVerificationForDataConsumersEmail(User user, string organizations, string securityStamp)
        {
            var baseUrl = new Uri(_config.BaseUrl);
            var verificationUrl = new Uri(baseUrl, $"verifyEmail?email={WebUtility.UrlEncode(user.EmailAddress)}&token={WebUtility.UrlEncode(securityStamp)}").ToString();

            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateEmailVerificationForDataConsumersEmail(
                user.Role,
                verificationUrl,
                organizations,
                user.Name,
                user.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((user.EmailAddress, user.Name), emailSubject, emailBody);
        }

public async Task SendVerificationForDataConsumersEmail(User user, string organizations, string securityStamp)
        {
            var baseUrl = new Uri(_config.BaseUrl);
            var verificationUrl = new Uri(baseUrl, $"verifyEmail?email={WebUtility.UrlEncode(user.EmailAddress)}&token={WebUtility.UrlEncode(securityStamp)}").ToString();

            var (emailSubject, emailBody) = await _emailTextGeneratorService.GenerateEmailVerificationForDataConsumersEmail(
                user.Role,
                verificationUrl,
                organizations,
                user.Name,
                user.ApplicationLanguage.LanguageCode);

            await _emailPublisherService.SendEmail((user.EmailAddress, user.Name), emailSubject, emailBody);
        }

19 View Source File : ProxyPasswordMaskValuesProvider.cs
License : Apache License 2.0
Project Creator : OctopusDeploy

public IEnumerable<string> GetProxyPreplacedwordMaskValues(string proxyPreplacedword)
        {
            if (string.IsNullOrEmpty(proxyPreplacedword)) 
                return Enumerable.Empty<string>();

            //$Env:HTTP_PROXY will contain the URL encoded version of the preplacedword
            //We also need to handle cases where the encoded hex is in upper or lower case
            //Calamari calls both WebUtility.UrlEncode (uppercase hex) and HttpUtility.UrlEncode (lowercase hex)
            string upperCaseUrlEncodedProxyPreplacedword = WebUtility.UrlEncode(proxyPreplacedword);
            string lowerCaseUrlEncodedProxyPreplacedword = UrlEncodedCharactersRegex.Replace(upperCaseUrlEncodedProxyPreplacedword, m => m.Value.ToLowerInvariant());
            
            return new[]
            {
                proxyPreplacedword,
                upperCaseUrlEncodedProxyPreplacedword,
                lowerCaseUrlEncodedProxyPreplacedword
            }.Distinct();
        }

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

[Read("thumb")]
        public FileResult GetThumb(string url)
        {
            if (!SecurityContext.IsAuthenticated || !(Configuration["bookmarking:thumbnail-url"] != null))
            {
                return null;
            }

            url = url.Replace("&", "&");
            url = WebUtility.UrlEncode(url);

            using var wc = new WebClient();
            var bytes = wc.DownloadData(string.Format(Configuration["bookmarking:thumbnail-url"], url));
            var type = wc.ResponseHeaders["Content-Type"] ?? "image/png";
            return File(bytes, type);
        }

See More Examples