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 : ConfigServerConfigurationProvider.cs
License : Apache License 2.0
Project Creator : SteeltoeOSS

protected internal async Task<ConfigEnvironment> RemoteLoadAsync(string[] requestUris, string label)
        {
            // Get client if not already set
            _httpClient ??= GetHttpClient(_settings);

            Exception error = null;
            foreach (var requestUri in requestUris)
            {
                error = null;

                // Get a config server uri and username preplacedwords to use
                var trimUri = requestUri.Trim();
                var serverUri = _settings.GetRawUri(trimUri);
                var username = _settings.GetUserName(trimUri);
                var preplacedword = _settings.GetPreplacedword(trimUri);

                // Make Config Server URI from settings
                var path = GetConfigServerUri(serverUri, label);

                // Get the request message
                var request = GetRequestMessage(path, username, preplacedword);

                // If certificate validation is disabled, inject a callback to handle properly
                var prevProtocols = (SecurityProtocolType)0;
                HttpClientHelper.ConfigureCertificateValidation(_settings.ValidateCertificates, out prevProtocols, out var prevValidator);

                // Invoke config server
                try
                {
                    using var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

                    // Log status
                    var message = $"Config Server returned status: {response.StatusCode} invoking path: {requestUri}";
                    _logger?.LogInformation(WebUtility.UrlEncode(message));

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            return null;
                        }

                        // Throw if status >= 400
                        if (response.StatusCode >= HttpStatusCode.BadRequest)
                        {
                            // HttpClientErrorException
                            throw new HttpRequestException(message);
                        }
                        else
                        {
                            return null;
                        }
                    }

                    return await response.Content.ReadFromJsonAsync<ConfigEnvironment>(SerializerOptions).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    error = e;
                    _logger?.LogError(e, "Config Server exception, path: {requestUri}", WebUtility.UrlEncode(requestUri));
                    if (IsContinueExceptionType(e))
                    {
                        continue;
                    }

                    throw;
                }
                finally
                {
                    HttpClientHelper.RestoreCertificateValidation(_settings.ValidateCertificates, prevProtocols, prevValidator);
                }
            }

            if (error != null)
            {
                throw error;
            }

            return null;
        }

19 View Source File : ConfigServerConfigurationProvider.cs
License : Apache License 2.0
Project Creator : SteeltoeOSS

[Obsolete("Will be removed in next release. See RemoteLoadAsync(string[], string)")]
        protected internal virtual async Task<ConfigEnvironment> RemoteLoadAsync(string requestUri)
        {
            // Get client if not already set
            _httpClient ??= GetHttpClient(_settings);

            // Get the request message
            var request = GetRequestMessage(requestUri);

            // If certificate validation is disabled, inject a callback to handle properly
            HttpClientHelper.ConfigureCertificateValidation(_settings.ValidateCertificates, out var prevProtocols, out var prevValidator);

            // Invoke config server
            try
            {
                using var response = await _httpClient.SendAsync(request).ConfigureAwait(false);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        return null;
                    }

                    // Log status
                    var message = $"Config Server returned status: {response.StatusCode} invoking path: {requestUri}";

                    _logger?.LogInformation(WebUtility.UrlEncode(message));

                    // Throw if status >= 400
                    if (response.StatusCode >= HttpStatusCode.BadRequest)
                    {
                        throw new HttpRequestException(message);
                    }
                    else
                    {
                        return null;
                    }
                }

                return await response.Content.ReadFromJsonAsync<ConfigEnvironment>(SerializerOptions).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                // Log and rethrow
                _logger?.LogError("Config Server exception: {0}, path: {1}", e, WebUtility.UrlEncode(requestUri));
                throw;
            }
            finally
            {
                HttpClientHelper.RestoreCertificateValidation(_settings.ValidateCertificates, prevProtocols, prevValidator);
            }
        }

19 View Source File : UriInfo.cs
License : Apache License 2.0
Project Creator : SteeltoeOSS

protected internal Uri MakeUri(string scheme, string host, int port, string username, string preplacedword, string path, string query)
        {
            var cleanedPath = path == null || path.StartsWith("/") ? path : $"/{path}";
            cleanedPath = query != null ? cleanedPath + "?" + query : cleanedPath;

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(preplacedword))
            {
                var builder = new UriBuilder()
                {
                    Scheme = scheme,
                    Host = host,
                    Port = port,
                    UserName = WebUtility.UrlEncode(username),
                    Preplacedword = WebUtility.UrlEncode(preplacedword),
                    Path = cleanedPath
                };
                return builder.Uri;
            }
            else
            {
                var builder = new UriBuilder()
                {
                    Scheme = scheme,
                    Host = host,
                    Port = port,
                    Path = cleanedPath
                };
                return builder.Uri;
            }
        }

19 View Source File : OAuthV2Builder.cs
License : MIT License
Project Creator : stoiveyp

public Uri BuildUri()
        {
            var sb = new StringBuilder("?client_id=");
            sb.Append(System.Net.WebUtility.UrlEncode(ClientId));


            foreach (var set in new (string key, string value)[]
            {
                ("scope", BotScope),
                ("user_scope", UserScope),
                ("redirect_uri", RedirectUri),
                ("state", State)
            })
            {
                if (string.IsNullOrWhiteSpace(set.key)) continue;

                sb.Append("&");
                sb.Append(set.key);
                sb.Append("=");
                sb.Append(System.Net.WebUtility.UrlEncode(set.value));
            }

            return new UriBuilder("https", "slack.com", 443, "/oauth/v2/authorize")
            {
                Query = sb.ToString()
                    
            }.Uri;
        }

19 View Source File : AdrToolsImporter.cs
License : Apache License 2.0
Project Creator : structurizr

private string UrlEncode(string value)
        {
            return WebUtility.UrlEncode(value).Replace("+", "%20");
        }

19 View Source File : FilterWebsocketHandler.cs
License : Mozilla Public License 2.0
Project Creator : TechnikEmpire

public override async Task Handle(HttpContext context)
        {   
            ClientWebSocket wsServer = null;
            System.Net.WebSockets.WebSocket wsClient = null;
            
            try
            {
                // First we need the URL for this connection, since it's been requested to be
                // upgraded to a websocket.

                var connFeature = context.Features.Get<IHttpRequestFeature>();

                string fullUrl = string.Empty;

                if (connFeature != null && connFeature.RawTarget != null && !string.IsNullOrEmpty(connFeature.RawTarget) && !(string.IsNullOrWhiteSpace(connFeature.RawTarget)))
                {
                    fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{connFeature.RawTarget}";
                }
                else
                {
                    fullUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
                }

                // Need to replate the scheme with appropriate websocket scheme.
                if (fullUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                {
                    fullUrl = "ws://" + fullUrl.Substring(7);
                }
                else if (fullUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    fullUrl = "wss://" + fullUrl.Substring(8);
                }

                // Next we need to try and parse the URL as a URI, because the websocket client
                // requires this for connecting upstream.

                if (!Uri.TryCreate(fullUrl, UriKind.RelativeOrAbsolute, out Uri wsUri))
                {
                    LoggerProxy.Default.Error("Failed to parse websocket URI.");
                    return;
                }

                // Create the websocket that's going to connect to the remote server.
                wsServer = new ClientWebSocket();
                wsServer.Options.Cookies = new System.Net.CookieContainer();
                //wsServer.Options.SetBuffer((int)ushort.MaxValue * 16, (int)ushort.MaxValue * 16);
                
                foreach (var proto in context.WebSockets.WebSocketRequestedProtocols)
                {
                    wsServer.Options.AddSubProtocol(proto);
                }

                foreach (var hdr in context.Request.Headers)
                {
                    if (!ForbiddenWsHeaders.IsForbidden(hdr.Key))
                    {
                        try
                        {
                            wsServer.Options.SetRequestHeader(hdr.Key, hdr.Value.ToString());
                        }
                        catch (Exception hdrException)
                        {
                            LoggerProxy.Default.Error(hdrException);
                        }
                    }
                }

                foreach (var cookie in context.Request.Cookies)
                {
                    try
                    {
                        wsServer.Options.Cookies.Add(new Uri(fullUrl, UriKind.Absolute), new System.Net.Cookie(cookie.Key, System.Net.WebUtility.UrlEncode(cookie.Value)));
                    }
                    catch (Exception e)
                    {
                        LoggerProxy.Default.Error("Error while attempting to add websocket cookie.");
                        LoggerProxy.Default.Error(e);
                    }
                }

                if (context.Connection.ClientCertificate != null)
                {
                    wsServer.Options.ClientCertificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection(new[] { context.Connection.ClientCertificate.ToV2Certificate() });
                }

                // Connect the server websocket to the upstream, remote webserver.
                await wsServer.ConnectAsync(wsUri, context.RequestAborted);

                foreach (string key in wsServer.ResponseHeaders)
                {
                    if (!ForbiddenWsHeaders.IsForbidden(key))
                    {
                        try
                        {   
                            var value = wsServer.ResponseHeaders[key];
                            context.Response.Headers[key] = wsServer.ResponseHeaders[key];                            
                        }
                        catch (Exception hdrException)
                        {
                            LoggerProxy.Default.Error(hdrException);
                        }
                    }
                }
                
                // Create, via acceptor, the client websocket. This is the local machine's websocket.
                wsClient = await context.WebSockets.AcceptWebSocketAsync(wsServer.SubProtocol ?? null);
                
                // Match the HTTP version of the client on the upstream request. We don't want to
                // transparently preplaced around headers that are wrong for the client's HTTP version.
                Version upstreamReqVersionMatch = null;

                Match match = s_httpVerRegex.Match(context.Request.Protocol);
                if (match != null && match.Success)
                {
                    upstreamReqVersionMatch = Version.Parse(match.Value);
                }

                var msgNfo = new HttpMessageInfo
                {
                    Url = wsUri,
                    Method = new HttpMethod(context.Request.Method),
                    IsEncrypted = context.Request.IsHttps,
                    Headers = context.Request.Headers.ToNameValueCollection(),
                    HttpVersion = upstreamReqVersionMatch ?? new Version(1, 0),
                    MessageProtocol = MessageProtocol.WebSocket,
                    MessageType = MessageType.Request,
                    RemoteAddress = context.Connection.RemoteIpAddress,
                    RemotePort = (ushort)context.Connection.RemotePort,
                    LocalAddress = context.Connection.LocalIpAddress,
                    LocalPort = (ushort)context.Connection.LocalPort
                };

                _configuration.NewHttpMessageHandler?.Invoke(msgNfo);

                switch (msgNfo.ProxyNextAction)
                {
                    case ProxyNextAction.DropConnection:
                        {
                            await wsClient.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                            return;
                        }
                }

                var serverMessageInfo = new HttpMessageInfo
                {
                    Url = wsUri,
                    MessageId = msgNfo.MessageId,
                    Method = new HttpMethod(context.Request.Method),
                    IsEncrypted = context.Request.IsHttps,
                    Headers = context.Request.Headers.ToNameValueCollection(),
                    HttpVersion = upstreamReqVersionMatch ?? new Version(1, 0),
                    MessageProtocol = MessageProtocol.WebSocket,
                    MessageType = MessageType.Response,
                    RemoteAddress = context.Connection.RemoteIpAddress,
                    RemotePort = (ushort)context.Connection.RemotePort,
                    LocalAddress = context.Connection.LocalIpAddress,
                    LocalPort = (ushort)context.Connection.LocalPort
                };

                var clientMessageInfo = new HttpMessageInfo
                {
                    Url = wsUri,
                    MessageId = msgNfo.MessageId,
                    IsEncrypted = context.Request.IsHttps,
                    Headers = context.Request.Headers.ToNameValueCollection(),
                    HttpVersion = upstreamReqVersionMatch ?? new Version(1, 0),
                    MessageProtocol = MessageProtocol.WebSocket,
                    MessageType = MessageType.Request,
                    RemoteAddress = context.Connection.RemoteIpAddress,
                    RemotePort = (ushort)context.Connection.RemotePort,
                    LocalAddress = context.Connection.LocalIpAddress,
                    LocalPort = (ushort)context.Connection.LocalPort
                };

                bool inspect = true;

                switch (msgNfo.ProxyNextAction)
                {
                    case ProxyNextAction.AllowAndIgnoreContent:
                    case ProxyNextAction.AllowAndIgnoreContentAndResponse:
                        {
                            inspect = false;
                        }
                        break;
                }

                // Spawn an async task that will poll the remote server for data in a loop, and then
                // write any data it gets to the client websocket.
                var serverTask = Task.Run(async () =>
                {
                    System.Net.WebSockets.WebSocketReceiveResult serverResult = null;
                    var serverBuffer = new byte[1024 * 4];
                    try
                    {
                        bool looping = true;

                        serverResult = await wsServer.ReceiveAsync(new ArraySegment<byte>(serverBuffer), context.RequestAborted);

                        while (looping && !serverResult.CloseStatus.HasValue && !context.RequestAborted.IsCancellationRequested)
                        {

                            if (inspect)
                            {
                                serverMessageInfo.Body = new Memory<byte>(serverBuffer, 0, serverResult.Count);

                                switch (serverResult.MessageType)
                                {
                                    case System.Net.WebSockets.WebSocketMessageType.Binary:
                                        {
                                            serverMessageInfo.BodyContentType = s_octetStreamContentType;
                                        }
                                        break;

                                    case System.Net.WebSockets.WebSocketMessageType.Text:
                                        {
                                            serverMessageInfo.BodyContentType = s_plainTextContentType;
                                        }
                                        break;
                                }

                                _configuration.HttpMessageWholeBodyInspectionHandler?.Invoke(serverMessageInfo);
                            }

                            switch (serverMessageInfo.ProxyNextAction)
                            {
                                case ProxyNextAction.DropConnection:
                                    {
                                        looping = false;
                                    }
                                    break;

                                default:
                                    {
                                        await wsClient.SendAsync(new ArraySegment<byte>(serverBuffer, 0, serverResult.Count), serverResult.MessageType, serverResult.EndOfMessage, context.RequestAborted);

                                        if (!wsClient.CloseStatus.HasValue)
                                        {
                                            serverResult = await wsServer.ReceiveAsync(new ArraySegment<byte>(serverBuffer), context.RequestAborted);
                                            continue;
                                        }
                                    }
                                    break;
                            }

                            looping = false;
                        }

                        await wsClient.CloseAsync(serverResult.CloseStatus.Value, serverResult.CloseStatusDescription, context.RequestAborted);
                    }
                    catch (Exception err)
                    {
                        LoggerProxy.Default.Error(err);
                        try
                        {
                            var closeStatus = serverResult?.CloseStatus ?? System.Net.WebSockets.WebSocketCloseStatus.NormalClosure;
                            var closeMessage = serverResult?.CloseStatusDescription ?? string.Empty;

                            await wsClient.CloseAsync(closeStatus, closeMessage, context.RequestAborted);
                        }
                        catch { }
                    }
                });

                // Spawn an async task that will poll the local client websocket, in a loop, and then
                // write any data it gets to the remote server websocket.
                var clientTask = Task.Run(async () =>
                {
                    System.Net.WebSockets.WebSocketReceiveResult clientResult = null;
                    var clientBuffer = new byte[1024 * 4];
                    try
                    {
                        bool looping = true;

                        clientResult = await wsClient.ReceiveAsync(new ArraySegment<byte>(clientBuffer), context.RequestAborted);

                        while (looping && !clientResult.CloseStatus.HasValue && !context.RequestAborted.IsCancellationRequested)
                        {
                            if (inspect)
                            {
                                clientMessageInfo.Body = new Memory<byte>(clientBuffer, 0, clientResult.Count);

                                switch (clientResult.MessageType)
                                {
                                    case System.Net.WebSockets.WebSocketMessageType.Binary:
                                        {
                                            clientMessageInfo.BodyContentType = s_octetStreamContentType;
                                        }
                                        break;

                                    case System.Net.WebSockets.WebSocketMessageType.Text:
                                        {
                                            clientMessageInfo.BodyContentType = s_plainTextContentType;
                                        }
                                        break;
                                }

                                _configuration.HttpMessageWholeBodyInspectionHandler?.Invoke(clientMessageInfo);
                            }

                            switch (clientMessageInfo.ProxyNextAction)
                            {
                                case ProxyNextAction.DropConnection:
                                    {
                                        looping = false;
                                    }
                                    break;

                                default:
                                    {
                                        await wsServer.SendAsync(new ArraySegment<byte>(clientBuffer, 0, clientResult.Count), clientResult.MessageType, clientResult.EndOfMessage, context.RequestAborted);

                                        if (!wsServer.CloseStatus.HasValue)
                                        {
                                            clientResult = await wsClient.ReceiveAsync(new ArraySegment<byte>(clientBuffer), context.RequestAborted);
                                            continue;
                                        }
                                    }
                                    break;
                            }

                            looping = false;
                        }

                        await wsServer.CloseAsync(clientResult.CloseStatus.Value, clientResult.CloseStatusDescription, context.RequestAborted);
                    }
                    catch(Exception err)
                    {
                        LoggerProxy.Default.Error(err);
                        try
                        {
                            var closeStatus = clientResult?.CloseStatus ?? System.Net.WebSockets.WebSocketCloseStatus.NormalClosure;
                            var closeMessage = clientResult?.CloseStatusDescription ?? string.Empty;

                            await wsServer.CloseAsync(closeStatus, closeMessage, context.RequestAborted);
                        }
                        catch { }
                    }
                });

                // Above, we have created a bridge between the local and remote websocket. Wait for
                // both replacedociated tasks to complete.
                await Task.WhenAll(serverTask, clientTask);
            }
            catch (Exception wshe)
            {
                LoggerProxy.Default.Error(wshe);
            }
            finally
            {
                if (wsClient != null)
                {
                    wsClient.Dispose();
                    wsClient = null;
                }

                if (wsServer != null)
                {
                    wsServer.Dispose();
                    wsServer = null;
                }
            }
        }

19 View Source File : ApiUrlExtension.cs
License : MIT License
Project Creator : TelsaV

public static async Task<HttpResponseMessage> PostAsync(this HttpClient client, ApiUrl url, JObject json, int timeout)
        {
            var hasOrigin = client.DefaultRequestHeaders.TryGetValues("Origin", out IEnumerable<string> origin);

            if (url.Referer != null)
            {
                client.DefaultRequestHeaders.Referrer = new Uri(url.Referer);
            }
            if (client.DefaultRequestHeaders.Contains("Origin"))
            {
                client.DefaultRequestHeaders.Remove("Origin");
                client.DefaultRequestHeaders.Add("Origin", url.Origin);
            }
            else
            {
                client.DefaultRequestHeaders.Add("Origin", url.Origin);
            }

            HttpContent hc = new StringContent($"r={WebUtility.UrlEncode(json.ToString(Formatting.None))}", Encoding.UTF8);
            hc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/ x-www-form-urlencoded; charset=UTF-8");
            var response = client.PostAsync(url.Url, hc);
            response.Wait();

            // 复原client
            if (hasOrigin)
            {
                client.DefaultRequestHeaders.Remove("Origin");
                client.DefaultRequestHeaders.Add("Origin", origin);
            }
            else
            {
                client.DefaultRequestHeaders.Remove("Origin");
            }

            return await response;
        }

19 View Source File : HttpConnection.cs
License : Apache License 2.0
Project Creator : TencentCloud

private static string AppendQuery(StringBuilder builder, Dictionary<string, string> param)
        {
            foreach (KeyValuePair<string, string> kvp in param)
            {
                builder.Append($"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}&");
            }
            return builder.ToString().TrimEnd('&');
        }

19 View Source File : AbstractClient.cs
License : Apache License 2.0
Project Creator : TencentCloud

private string BuildCanonicalQueryString(AbstractModel request)
        {
            string httpRequestMethod = this.Profile.HttpProfile.ReqMethod;
            if (!HttpProfile.REQ_GET.Equals(httpRequestMethod))
            {
                return "";
            }
            Dictionary<string, string> param = new Dictionary<string, string>();
            request.ToMap(param, "");
            StringBuilder urlBuilder = new StringBuilder();
            foreach (KeyValuePair<string, string> kvp in param)
            {
                urlBuilder.Append($"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}&");
            }
            return urlBuilder.ToString().TrimEnd('&');
        }

19 View Source File : ConfluenceHttpClientTests.cs
License : Apache License 2.0
Project Creator : TinkoffCreditSystems

[Fact]
        public async Task GetPageContent_ResultsTakeTwoPages_ShouldReturnAllAndSpecifyDateAlsoSpecifyNextUrl()
        {
            // Arrange
            var date = DateTime.MinValue;
            var expectedEncodedDate = WebUtility.UrlEncode(date.ToString(CqlDateFormat));
            var pageContent = new List<ContentDto>
            {
                new ContentDto
                {
                    Id = "id1",
                    replacedle = "replacedle1",
                    Body = new ContentBodyDto
                    {
                        View = new ViewRepresentationDto
                        {
                            Value = "body goes here 1"
                        }
                    }
                },
                new ContentDto
                {
                    Id = "id2",
                    replacedle = "replacedle2",
                    Body = new ContentBodyDto
                    {
                        View = new ViewRepresentationDto
                        {
                            Value = "body goes here 2"
                        }
                    }
                }
            };

            var firstPage = new ContentResponse
            {
                Links = new LinksDto { Next = "next url request"},
                Results = pageContent
            };

            _httpClientMock.Setup(m => m.GetAsync(It.IsAny<string>()))
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(JsonConvert.SerializeObject(firstPage))
                });

            // Act
            var result = await _client.GetLatestPagesAsync(new []{"IH"}, date);
            
            // replacedert
            replacedert.Equal(result.Results.Count, pageContent.Count);
            _httpClientMock.Verify(m => m.GetAsync(It.Is<string>(q => q.Contains(expectedEncodedDate))),
                Times.Once);
        }

19 View Source File : FileStorage.cs
License : MIT License
Project Creator : TinyStuff

private string GetPath(string key)
        {
            if (string.IsNullOrWhiteSpace((cacheFolder)))
            {
                throw new Exception("Initialize has to be called before using TinyCache with file storage");
            }

            var encoded = WebUtility.UrlEncode(key);

            var name = string.Format("TinyCache_{0}.cache", encoded);

            return Path.Combine(cacheFolder, name);
        }

19 View Source File : TranslationClient.cs
License : MIT License
Project Creator : TinyStuff

private string GetUrl(string value) {
            var ret = System.Net.WebUtility.UrlEncode(value);
            return ret.Replace("+","%20");
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : ubisoft

private static string AddParameterInternal(string url, string parameterName, string stringValue)
        {
            var @operator = !url.Contains("?") ? "?" : "&";
            var formattedValue = WebUtility.UrlEncode(stringValue);
            var parameter = $"{@operator}{parameterName}={formattedValue}";
            return url + parameter;
        }

19 View Source File : WikiClient.cs
License : MIT License
Project Creator : ubisoft

public WikiPage Update(string slug, WikiPageUpdate wikiPage) => _api
            .Put().With(wikiPage)
            .To<WikiPage>(_projectPath + "/wikis/" + WebUtility.UrlEncode(slug));

19 View Source File : API.cs
License : MIT License
Project Creator : ubisoft

private string OpenPrivateSession()
        {
            var httpRequestor = new HttpRequestor(_credentials.HostUrl, string.Empty, MethodType.Post, RequestOptions);
            var url =
                $"/session?login={WebUtility.UrlEncode(_credentials.UserName)}&preplacedword={WebUtility.UrlEncode(_credentials.Preplacedword)}";
            try
            {
                var session = httpRequestor.To<Session>(url);
                return session.PrivateToken;
            }
            catch (GitLabException ex)
            {
                const string hiddenPreplacedword = "*****";

                var securedException = new GitLabException(ex.Message.Replace(_credentials.Preplacedword, hiddenPreplacedword))
                {
                    OriginalCall = new Uri(ex.OriginalCall.OriginalString.Replace(_credentials.Preplacedword, hiddenPreplacedword)),
                    StatusCode = ex.StatusCode,
                    ErrorObject = ex.ErrorObject,
                    MethodType = ex.MethodType,
                };

                throw securedException;
            }
        }

19 View Source File : CommitClient.cs
License : MIT License
Project Creator : ubisoft

public JobStatus GetJobStatus(string branchName)
        {
            var encodedBranch = WebUtility.UrlEncode(branchName);

            var latestCommit = _api.Get().To<Commit>(_repoPath + $"/commits/{encodedBranch}?per_page=1");
            if (latestCommit == null)
            {
                return JobStatus.Unknown;
            }

            if (string.IsNullOrEmpty(latestCommit.Status))
            {
                return JobStatus.NoBuild;
            }

            if (!Enum.TryParse(latestCommit.Status, ignoreCase: true, result: out JobStatus result))
            {
                throw new NotSupportedException($"Status {latestCommit.Status} is unrecognised");
            }

            return result;
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public IEnumerable<Membership> OfProject(string projectId, bool includeInheritedMembers)
        {
            return GetAll(Project.Url + "/" + WebUtility.UrlEncode(projectId), includeInheritedMembers);
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public IEnumerable<Membership> OfGroup(string groupId, bool includeInheritedMembers)
        {
            return GetAll(GroupsClient.Url + "/" + WebUtility.UrlEncode(groupId), includeInheritedMembers);
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public Membership GetMemberOfGroup(string groupId, string userId)
        {
            return _api.Get().To<Membership>(GroupsClient.Url + "/" + WebUtility.UrlEncode(groupId) + "/members/" + WebUtility.UrlEncode(userId));
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public Membership GetMemberOfProject(string projectId, string userId)
        {
            return _api.Get().To<Membership>(Project.Url + "/" + WebUtility.UrlEncode(projectId) + "/members/" + WebUtility.UrlEncode(userId));
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public Membership AddMemberToProject(string projectId, ProjectMemberCreate user)
        {
            return _api.Post().With(user).To<Membership>(Project.Url + "/" + WebUtility.UrlEncode(projectId) + "/members");
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public Membership UpdateMemberOfProject(string projectId, ProjectMemberUpdate user)
        {
            return _api.Put().With(user).To<Membership>(Project.Url + "/" + WebUtility.UrlEncode(projectId) + "/members/" + WebUtility.UrlEncode(user.UserId));
        }

19 View Source File : MembersClient.cs
License : MIT License
Project Creator : ubisoft

public Membership UpdateMemberOfProject(string projectId, ProjectMemberUpdate user)
        {
            return _api.Put().With(user).To<Membership>(Project.Url + "/" + WebUtility.UrlEncode(projectId) + "/members/" + WebUtility.UrlEncode(user.UserId));
        }

19 View Source File : TagClient.cs
License : MIT License
Project Creator : ubisoft

public void Delete(string name)
        {
            _api.Delete().Stream($"{_tagsPath}/{WebUtility.UrlEncode(name)}", _ => { });
        }

19 View Source File : WikiClient.cs
License : MIT License
Project Creator : ubisoft

public void Delete(string slug) => _api
            .Delete()
            .Execute(_projectPath + "/wikis/" + WebUtility.UrlEncode(slug));

19 View Source File : DiagnosticsHandler.cs
License : MIT License
Project Creator : ultranijia

private static void InjectHeaders(Activity currentActivity, HttpRequestMessage request)
        {
            if (currentActivity.IdFormat == ActivityIdFormat.W3C)
            {
                if (!request.Headers.Contains(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName))
                {
                    request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceParentHeaderName, currentActivity.Id);
                    if (currentActivity.TraceStateString != null)
                    {
                        request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.TraceStateHeaderName, currentActivity.TraceStateString);
                    }
                }
            }
            else
            {
                if (!request.Headers.Contains(DiagnosticsHandlerLoggingStrings.RequestIdHeaderName))
                {
                    request.Headers.TryAddWithoutValidation(DiagnosticsHandlerLoggingStrings.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(DiagnosticsHandlerLoggingStrings.CorrelationContextHeaderName, baggage);
                }
            }
        }

19 View Source File : AnnounceCommand.cs
License : MIT License
Project Creator : Ultz

[Command("Announce")]
        [Description("Allows you to construct a custom embed from Unix-style command arguments.")]
        [ShowUnixArgumentsInHelp(VolteUnixCommand.Announce)]
        public async Task<ActionResult> AnnounceAsync(
            [Remainder,
             Description(
                 "Unix-style command line arguments. Example: `-description=\"Some cool thing!\"` will set the embed's description.")]
            Dictionary<string, string> options)
        {
            static string GetRoleMention(TypeParserResult<SocketRole> res) =>
                res.IsSuccessful ? res.Value.Mention : null;

            static Color GetColor(TypeParserResult<Color> res) =>
                res.IsSuccessful ? res.Value : new Color(Config.SuccessColor);

            static bool TryGetUser(TypeParserResult<RestGuildUser> res, out RestGuildUser user)
            {
                user = res.IsSuccessful ? res.Value : null;
                return user != null;
            }

            var embed = new EmbedBuilder();

            if (options.TryGetValue("footer", out var result) || options.TryGetValue("foot", out result))
                embed.WithFooter(result);

            if (options.TryGetValue("thumbnail", out result))
            {
                if (!Uri.IsWellFormedUriString(result, UriKind.Absolute))
                    return BadRequest("Thumbnail URL must be a valid image URL.");

                embed.WithThumbnailUrl(result);
            }

            if (options.TryGetValue("image", out result))
            {
                if (!Uri.IsWellFormedUriString(result, UriKind.Absolute))
                    return BadRequest("Image URL must be a valid image URL.");

                embed.WithImageUrl(result);
            }

            if (options.TryGetValue("description", out result) || options.TryGetValue("desc", out result))
            {
                //must be a URL
                if (Uri.IsWellFormedUriString(WebUtility.UrlEncode(result), UriKind.RelativeOrAbsolute)
                    //must be a website/paste service that has support for raw paste viewing via a URL; feel free to PR more or to message me on discord to add some
                    && result.ContainsAnyIgnoreCase(AllowedPasteSites) 
                    //must be a url that leads to plaintext (aka raw on most websites) so it's not a bunch of HTML as the result.
                    && result.ContainsIgnoreCase("raw"))
                {
                    try
                    {
                        var m = await Http.GetAsync(WebUtility.UrlEncode(result));
                        result = await m.Content.ReadreplacedtringAsync();
                    }
                    catch { /* ignored */ }
                }
                
                embed.WithDescription(result);
            }

            if (options.TryGetValue("replacedle", out result))
                embed.Withreplacedle(result);

            if (options.TryGetValue("color", out result) || options.TryGetValue("colour", out result))
                embed.WithColor(GetColor(await CommandService.GetTypeParser<Color>()
                    .ParseAsync(null, result, Context)));

            if (options.TryGetValue("author", out result))
            {
                if (result.EqualsAnyIgnoreCase("self", "me"))
                    embed.WithAuthor(Context.User);
                else if (result.EqualsAnyIgnoreCase("bot", "you", "volte"))
                    embed.WithAuthor(Context.Guild.CurrentUser);
                else if (TryGetUser(await CommandService.GetTypeParser<RestGuildUser>()
                    .ParseAsync(null, result, Context), out var user))
                    embed.WithAuthor(user);
            }

            var mention = options.TryGetValue("mention", out result) || options.TryGetValue("ping", out result)
                ? result switch
                {
                    "none" => null,
                    "everyone" => "@everyone",
                    "here" => "@here",
                    _ => GetRoleMention(await CommandService.GetTypeParser<SocketRole>()
                        .ParseAsync(null, result, Context))
                }

19 View Source File : PreviewImg.xaml.cs
License : GNU General Public License v3.0
Project Creator : usaginya

public static string WebUrlEncode(string str)
        {
            return !string.IsNullOrEmpty(str) ?
                WebUtility.UrlEncode(str).Replace("+", "%20")
                .Replace("*", "%2A")
                .Replace("%7E", "~")
                .Replace("'", "%27")
                .Replace("(", "%28")
                .Replace(")", "%29")
                .Replace("%3A", ":")
                .Replace("%2F", "/")
                .Replace("%23", "#")
                : str;
        }

19 View Source File : UriUtils.cs
License : Mozilla Public License 2.0
Project Creator : UWPX

public static Uri buildUri(string bareJid, Dictionary<string, string> queryPairs)
        {
            string query = string.Join("&",
                queryPairs.Keys.Select(key => !string.IsNullOrWhiteSpace(queryPairs[key]) ? string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(queryPairs[key])) : WebUtility.UrlEncode(key)));

            UriBuilder builder = new UriBuilder
            {
                Scheme = "xmpp",
                Host = bareJid,
                Query = query
            };

            return builder.Uri;
        }

19 View Source File : HttpUtil.cs
License : MIT License
Project Creator : Varorbc

public static void Write(FileStream stream)
        {
            var size = stream.Length;
            var buffer = new byte[size];
            stream.Read(buffer, 0, (int)size);
            stream.Dispose();
            File.Delete(stream.Name);

            Current.Response.ContentType = "application/octet-stream";
            Current.Response.Headers.Add("Content-Disposition", "attachment;filename=" + WebUtility.UrlEncode(Path.GetFileName(stream.Name)));
            Current.Response.Headers.Add("Content-Length", size.ToString());

#if NETCOREAPP3_1
            Task.Run(async () =>
            {
                await Current.Response.Body.WriteAsync(buffer, 0, (int)size);
            })
            .GetAwaiter()
            .GetResult();
            Current.Response.Body.Close();
#else
            Current.Response.BinaryWrite(buffer);
            Current.Response.End();
            Current.Response.Close();
#endif
        }

19 View Source File : GatewayData.cs
License : MIT License
Project Creator : Varorbc

public string ToUrl(bool isUrlEncode = true)
        {
            return string.Join("&",
                _values
                .Select(a => $"{a.Key}={(isUrlEncode ? WebUtility.UrlEncode(a.Value.ToString()) : a.Value.ToString())}"));
        }

19 View Source File : TwoFactorAuthProvider.cs
License : MIT License
Project Creator : veler

public async Task SendPinByEmailAsync()
        {
            try
            {
                // Send verification code by email
                var param = new StringBuilder();

                param.Append("send=" + WebUtility.UrlEncode("true") + "&");
                param.Append("email=" + WebUtility.UrlEncode(GetRecoveryEmailAddressFromPreplacedowrdVault()) + "&");
                param.Append("key=" + WebUtility.UrlEncode(GeneratePin()) + "&");
                param.Append("lang=" + LanguageManager.Instance.GetCurrentCulture().TwoLetterISOLanguageName);

                var ascii = new ASCIIEncoding();
                var postBytes = ascii.GetBytes(param.ToString());
                var request = (HttpWebRequest)WebRequest.Create(new Uri(ServicesKeys.TwoFactorAuthenticationServiceUrl));

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers["Content-Length"] = postBytes.Length.ToString(CultureInfo.InvariantCulture);
                request.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                using (var postStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
                {
                    postStream.Write(postBytes, 0, postBytes.Length);
                    postStream.Flush();
                }

                await request.GetResponseAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogFault(SendPinByEmailAsyncFaultEvent, "Unable to send the two factor authentication PIN by email.", ex);
            }
        }

19 View Source File : BingEntitySearch.cs
License : MIT License
Project Creator : veler

internal async Task<(Uri organizationWebsite, Uri iconUrl)> GetOrganizationAndIconUrlAsync(string enreplacedyName, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(enreplacedyName))
            {
                return (null, null);
            }

            try
            {
                var market = LanguageManager.Instance.GetCurrentCulture().Name;
                var language = LanguageManager.Instance.GetCurrentCulture().TwoLetterISOLanguageName;
                var uri = string.Format(
                    CultureInfo.CurrentCulture,
                    BingEnreplacedySearchApiEndpoint,
                    WebUtility.UrlEncode(market),
                    WebUtility.UrlEncode(language),
                    WebUtility.UrlEncode(enreplacedyName));

                if (uri.Length >= QueryMaxLength)
                {
                    return (null, null);
                }

                using (var httpClient = new HttpClient())
                {
                    // Set the Azure API key.
                    httpClient.DefaultRequestHeaders.Add(AzureApiKeyHeaderName, ServicesKeys.MicrosoftAzure);

                    // Search if Bing Enreplacedy Search knows something about this enreplacedy name.
                    using (HttpResponseMessage result = await httpClient.GetAsync(new Uri(uri), cancellationToken).ConfigureAwait(false))
                    {
                        if (result.StatusCode == HttpStatusCode.OK)
                        {
                            string resultJson = await result.Content.ReadreplacedtringAsync().ConfigureAwait(false);
                            var bingEnreplacedySearchResponse = JsonConvert.DeserializeObject<BingEnreplacedySearchResponse>(resultJson);

                            if (bingEnreplacedySearchResponse?.Enreplacedies?.Value?.Length == 1)
                            {
                                if (bingEnreplacedySearchResponse.Enreplacedies.Value[0]?.Image?.Provider?.Length == 1
                                    && string.Equals(bingEnreplacedySearchResponse.Enreplacedies.Value[0].Image.Provider[0].Type, ExpectedProviderType, StringComparison.Ordinal))
                                {
                                    return (bingEnreplacedySearchResponse.Enreplacedies.Value[0].Url, bingEnreplacedySearchResponse.Enreplacedies.Value[0].Image.HostPageUrl);
                                }

                                return (bingEnreplacedySearchResponse.Enreplacedies.Value[0].Url, null);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogFault(BingEnreplacedySearchFaultEvent, $"Unable to detect an image URL throug Bing Enreplacedy Search.", ex);
            }

            return (null, null);
        }

19 View Source File : BingEntitySearch.cs
License : MIT License
Project Creator : veler

internal async Task<(Uri organizationWebsite, Uri iconUrl)> GetOrganizationAndIconUrlAsync(string enreplacedyName, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(enreplacedyName))
            {
                return (null, null);
            }

            try
            {
                var market = LanguageManager.Instance.GetCurrentCulture().Name;
                var language = LanguageManager.Instance.GetCurrentCulture().TwoLetterISOLanguageName;
                var uri = string.Format(
                    CultureInfo.CurrentCulture,
                    BingEnreplacedySearchApiEndpoint,
                    WebUtility.UrlEncode(market),
                    WebUtility.UrlEncode(language),
                    WebUtility.UrlEncode(enreplacedyName));

                if (uri.Length >= QueryMaxLength)
                {
                    return (null, null);
                }

                using (var httpClient = new HttpClient())
                {
                    // Set the Azure API key.
                    httpClient.DefaultRequestHeaders.Add(AzureApiKeyHeaderName, ServicesKeys.MicrosoftAzure);

                    // Search if Bing Enreplacedy Search knows something about this enreplacedy name.
                    using (HttpResponseMessage result = await httpClient.GetAsync(new Uri(uri), cancellationToken).ConfigureAwait(false))
                    {
                        if (result.StatusCode == HttpStatusCode.OK)
                        {
                            string resultJson = await result.Content.ReadreplacedtringAsync().ConfigureAwait(false);
                            var bingEnreplacedySearchResponse = JsonConvert.DeserializeObject<BingEnreplacedySearchResponse>(resultJson);

                            if (bingEnreplacedySearchResponse?.Enreplacedies?.Value?.Length == 1)
                            {
                                if (bingEnreplacedySearchResponse.Enreplacedies.Value[0]?.Image?.Provider?.Length == 1
                                    && string.Equals(bingEnreplacedySearchResponse.Enreplacedies.Value[0].Image.Provider[0].Type, ExpectedProviderType, StringComparison.Ordinal))
                                {
                                    return (bingEnreplacedySearchResponse.Enreplacedies.Value[0].Url, bingEnreplacedySearchResponse.Enreplacedies.Value[0].Image.HostPageUrl);
                                }

                                return (bingEnreplacedySearchResponse.Enreplacedies.Value[0].Url, null);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogFault(BingEnreplacedySearchFaultEvent, $"Unable to detect an image URL throug Bing Enreplacedy Search.", ex);
            }

            return (null, null);
        }

19 View Source File : FaviconFinder.cs
License : MIT License
Project Creator : veler

internal async Task<Uri> GetIconUrlAsync(string host, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(host))
            {
                return null;
            }

            try
            {
                var uri = string.Format(
                    CultureInfo.CurrentCulture,
                    FaviconFinderApiEndpoint,
                    WebUtility.UrlEncode(host));

                using (var httpClient = new HttpClient())
                using (HttpResponseMessage result = await httpClient.GetAsync(new Uri(uri), cancellationToken).ConfigureAwait(false))
                {
                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        string resultJson = await result.Content.ReadreplacedtringAsync().ConfigureAwait(false);
                        var faviconFinderResponse = JsonConvert.DeserializeObject<FaviconFinderResponse>(resultJson);

                        if (faviconFinderResponse?.Icons?.Length > 0)
                        {
                            for (int i = 0; i < faviconFinderResponse.Icons.Length; i++)
                            {
                                Icon icon = faviconFinderResponse.Icons[i];
                                if (icon != null && icon.Width >= Constants.AccountIconSize)
                                {
                                    return icon.Url;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogFault(FaviconFinderFaultEvent, $"Unable to detect an image URL throug Bing Enreplacedy Search.", ex);
            }

            return null;
        }

19 View Source File : IconService.cs
License : MIT License
Project Creator : veler

private async Task<string> GetIconFromRiteKit(string host, CancellationToken cancellationToken)
        {
            _logger.LogEvent(RiteKiteEvent, $"Querying RiteKit for '{host}'.");
            var requestUri = new Uri(string.Format(
                CultureInfo.CurrentCulture,
                RiteKitEndpoint,
                ServicesKeys.RiteKitClientId,
                WebUtility.UrlEncode(host)));

            var base64Icon = await DownloadAccountIconBase64Async(requestUri, shouldBeSquareShaped: true, cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(base64Icon))
            {
                _logger.LogEvent(RiteKiteEvent, $"RiteKit query succeeded.");
                return base64Icon;
            }

            return string.Empty;
        }

19 View Source File : IconService.cs
License : MIT License
Project Creator : veler

private async Task<string> GetIconFromClearBit(string host, CancellationToken cancellationToken)
        {
            _logger.LogEvent(RiteKiteEvent, $"Querying ClearBit for '{host}'.");
            var requestUri = new Uri(string.Format(
                CultureInfo.CurrentCulture,
                ClearBitEndpoint,
                WebUtility.UrlEncode(host),
                Constants.AccountIconSize));

            var base64Icon = await DownloadAccountIconBase64Async(requestUri, shouldBeSquareShaped: true, cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(base64Icon))
            {
                _logger.LogEvent(ClearBitEvent, $"ClearBit query succeeded.");
                return base64Icon;
            }

            return string.Empty;
        }

19 View Source File : IssueLauncher.cs
License : MIT License
Project Creator : VerifyTests

public static void LaunchForException(string message, Exception exception)
    {
        if (recorded.Contains(message))
        {
            return;
        }
        recorded.Add(message);

        var result = MessageBox.Show(
            [email protected]"An error occurred: {message}

Logged to: {Logging.Directory}

{exception.GetType().Name}: {exception.Message}

Open an issue on GitHub?",
            "DiffEngineTray Error",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Error);
        if (result == DialogResult.No)
        {
            return;
        }

        var extraBody = WebUtility.UrlEncode([email protected]"
 * Action: {message}
 * Exception:
```
{exception}
```");
        var url = $"https://github.com/VerifyTests/DiffEngine/issues/new?replacedle={message}&body={defaultBody}{extraBody}";
        LinkLauncher.LaunchUrl(url);
    }

19 View Source File : HttpSessionController.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private static string ToQueryString(Dictionary<string, string> nvc)
        {
            var array = (from item in nvc
                         select string.Format("{0}={1}", WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)))
                .ToArray();

            var args = string.Join("&", array);

            if (string.IsNullOrEmpty(args))
            {
                return args;
            }

            return "?" + args;
        }

19 View Source File : LibraryService.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

public Task<object> Get(GetDownload request)
        {
            var item = _libraryManager.GereplacedemById(request.Id);
            var auth = _authContext.GetAuthorizationInfo(Request);

            var user = auth.User;

            if (user != null)
            {
                if (!item.CanDownload(user))
                {
                    throw new ArgumentException("Item does not support downloading");
                }
            }
            else
            {
                if (!item.CanDownload())
                {
                    throw new ArgumentException("Item does not support downloading");
                }
            }

            var headers = new Dictionary<string, string>();

            if (user != null)
            {
                LogDownload(item, user, auth);
            }

            var path = item.Path;

            // Quotes are valid in linux. They'll possibly cause issues here
            var filename = (Path.GetFileName(path) ?? string.Empty).Replace("\"", string.Empty);
            if (!string.IsNullOrWhiteSpace(filename))
            {
                // Kestrel doesn't support non-ASCII characters in headers
                if (Regex.IsMatch(filename, @"[^\p{IsBasicLatin}]"))
                {
                    // Manually encoding non-ASCII characters, following https://tools.ietf.org/html/rfc5987#section-3.2.2
                    headers[HeaderNames.ContentDisposition] = "attachment; filename*=UTF-8''" + WebUtility.UrlEncode(filename);
                }
                else
                {
                    headers[HeaderNames.ContentDisposition] = "attachment; filename=\"" + filename + "\"";
                }
            }

            return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
            {
                Path = path,
                ResponseHeaders = headers
            });
        }

19 View Source File : AlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
        {
            var url = string.Format(
                CultureInfo.InvariantCulture,
                "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
                WebUtility.UrlEncode(albumName),
                WebUtility.UrlEncode(artistName));

            using (var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
            using (var stream = response.Content)
            using (var oReader = new StreamReader(stream, Encoding.UTF8))
            {
                var settings = new XmlReaderSettings()
                {
                    ValidationType = ValidationType.None,
                    CheckCharacters = false,
                    IgnoreProcessingInstructions = true,
                    IgnoreComments = true
                };

                using (var reader = XmlReader.Create(oReader, settings))
                {
                    return ReleaseResult.Parse(reader).FirstOrDefault();
                }
            }
        }

19 View Source File : TmdbSearch.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private async Task<List<RemoteSearchResult>> GetSearchResultsGeneric(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("name");
            }

            var url3 = string.Format(Search3, WebUtility.UrlEncode(name), TmdbUtils.ApiKey, language, type);

            using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url3,
                CancellationToken = cancellationToken,
                AcceptHeader = TmdbUtils.AcceptHeader

            }).ConfigureAwait(false))
            {
                using (var json = response.Content)
                {
                    var searchResults = await _json.DeserializeFromStreamAsync<TmdbSearchResult<MovieResult>>(json).ConfigureAwait(false);

                    var results = searchResults.Results ?? new List<MovieResult>();

                    return results
                        .Select(i =>
                        {
                            var remoteResult = new RemoteSearchResult
                            {
                                SearchProviderName = TmdbMovieProvider.Current.Name,
                                Name = i.replacedle ?? i.Name ?? i.Original_replacedle,
                                ImageUrl = string.IsNullOrWhiteSpace(i.Poster_Path) ? null : baseImageUrl + i.Poster_Path
                            };

                            if (!string.IsNullOrWhiteSpace(i.Release_Date))
                            {
                                // These dates are always in this exact format
                                if (DateTime.TryParseExact(i.Release_Date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out var r))
                                {
                                    remoteResult.PremiereDate = r.ToUniversalTime();
                                    remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
                                }
                            }

                            remoteResult.SetProviderId(MetadataProviders.Tmdb, i.Id.ToString(EnUs));

                            return remoteResult;

                        })
                        .ToList();
                }
            }
        }

19 View Source File : TmdbSearch.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private async Task<List<RemoteSearchResult>> GetSearchResultsTv(string name, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("name");
            }

            var url3 = string.Format(Search3, WebUtility.UrlEncode(name), TmdbUtils.ApiKey, language, "tv");

            using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url3,
                CancellationToken = cancellationToken,
                AcceptHeader = TmdbUtils.AcceptHeader

            }).ConfigureAwait(false))
            {
                using (var json = response.Content)
                {
                    var searchResults = await _json.DeserializeFromStreamAsync<TmdbSearchResult<TvResult>>(json).ConfigureAwait(false);

                    var results = searchResults.Results ?? new List<TvResult>();

                    return results
                        .Select(i =>
                        {
                            var remoteResult = new RemoteSearchResult
                            {
                                SearchProviderName = TmdbMovieProvider.Current.Name,
                                Name = i.Name ?? i.Original_Name,
                                ImageUrl = string.IsNullOrWhiteSpace(i.Poster_Path) ? null : baseImageUrl + i.Poster_Path
                            };

                            if (!string.IsNullOrWhiteSpace(i.First_Air_Date))
                            {
                                // These dates are always in this exact format
                                if (DateTime.TryParseExact(i.First_Air_Date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out var r))
                                {
                                    remoteResult.PremiereDate = r.ToUniversalTime();
                                    remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
                                }
                            }

                            remoteResult.SetProviderId(MetadataProviders.Tmdb, i.Id.ToString(EnUs));

                            return remoteResult;

                        })
                        .ToList();
                }
            }
        }

19 View Source File : OmdbItemProvider.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private async Task<IEnumerable<RemoteSearchResult>> GetSearchResultsInternal(ItemLookupInfo searchInfo, string type, bool isSearch, CancellationToken cancellationToken)
        {
            var episodeSearchInfo = searchInfo as EpisodeInfo;

            var imdbId = searchInfo.GetProviderId(MetadataProviders.Imdb);

            var urlQuery = "plot=full&r=json";
            if (type == "episode" && episodeSearchInfo != null)
            {
                episodeSearchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Imdb.ToString(), out imdbId);
            }

            var name = searchInfo.Name;
            var year = searchInfo.Year;

            if (!string.IsNullOrWhiteSpace(name))
            {
                var parsedName = _libraryManager.ParseName(name);
                var yearInName = parsedName.Year;
                name = parsedName.Name;
                year = year ?? yearInName;
            }

            if (string.IsNullOrWhiteSpace(imdbId))
            {
                if (year.HasValue)
                {
                    urlQuery += "&y=" + year.Value.ToString(CultureInfo.InvariantCulture);
                }

                // &s means search and returns a list of results as opposed to t
                if (isSearch)
                {
                    urlQuery += "&s=" + WebUtility.UrlEncode(name);
                }
                else
                {
                    urlQuery += "&t=" + WebUtility.UrlEncode(name);
                }
                urlQuery += "&type=" + type;
            }
            else
            {
                urlQuery += "&i=" + imdbId;
                isSearch = false;
            }

            if (type == "episode")
            {
                if (searchInfo.IndexNumber.HasValue)
                {
                    urlQuery += string.Format(CultureInfo.InvariantCulture, "&Episode={0}", searchInfo.IndexNumber);
                }
                if (searchInfo.ParentIndexNumber.HasValue)
                {
                    urlQuery += string.Format(CultureInfo.InvariantCulture, "&Season={0}", searchInfo.ParentIndexNumber);
                }
            }

            var url = OmdbProvider.GetOmdbUrl(urlQuery, _appHost, cancellationToken);

            using (var response = await OmdbProvider.GetOmdbResponse(_httpClient, url, cancellationToken).ConfigureAwait(false))
            {
                using (var stream = response.Content)
                {
                    var resultList = new List<SearchResult>();

                    if (isSearch)
                    {
                        var searchResultList = await _jsonSerializer.DeserializeFromStreamAsync<SearchResultList>(stream).ConfigureAwait(false);
                        if (searchResultList != null && searchResultList.Search != null)
                        {
                            resultList.AddRange(searchResultList.Search);
                        }
                    }
                    else
                    {
                        var result = await _jsonSerializer.DeserializeFromStreamAsync<SearchResult>(stream).ConfigureAwait(false);
                        if (string.Equals(result.Response, "true", StringComparison.OrdinalIgnoreCase))
                        {
                            resultList.Add(result);
                        }
                    }

                    return resultList.Select(result =>
                    {
                        var item = new RemoteSearchResult
                        {
                            IndexNumber = searchInfo.IndexNumber,
                            Name = result.replacedle,
                            ParentIndexNumber = searchInfo.ParentIndexNumber,
                            SearchProviderName = Name
                        };

                        if (episodeSearchInfo != null && episodeSearchInfo.IndexNumberEnd.HasValue)
                        {
                            item.IndexNumberEnd = episodeSearchInfo.IndexNumberEnd.Value;
                        }

                        item.SetProviderId(MetadataProviders.Imdb, result.imdbID);

                        if (result.Year.Length > 0
                            && int.TryParse(result.Year.Substring(0, Math.Min(result.Year.Length, 4)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedYear))
                        {
                            item.ProductionYear = parsedYear;
                        }

                        if (!string.IsNullOrEmpty(result.Released)
                            && DateTime.TryParse(result.Released, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var released))
                        {
                            item.PremiereDate = released;
                        }

                        if (!string.IsNullOrWhiteSpace(result.Poster) && !string.Equals(result.Poster, "N/A", StringComparison.OrdinalIgnoreCase))
                        {
                            item.ImageUrl = result.Poster;
                        }

                        return item;
                    });
                }
            }
        }

19 View Source File : TmdbPersonProvider.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
        {
            var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);

            var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);

            var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");

            if (!string.IsNullOrEmpty(tmdbId))
            {
                await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);

                var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
                var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);

                var images = (info.Images ?? new PersonImages()).Profiles ?? new List<Profile>();

                var result = new RemoteSearchResult
                {
                    Name = info.Name,

                    SearchProviderName = Name,

                    ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].File_Path)
                };

                result.SetProviderId(MetadataProviders.Tmdb, info.Id.ToString(_usCulture));
                result.SetProviderId(MetadataProviders.Imdb, info.Imdb_Id);

                return new[] { result };
            }

            if (searchInfo.IsAutomated)
            {
                // Don't hammer moviedb searching by name
                return new List<RemoteSearchResult>();
            }

            var url = string.Format(TmdbUtils.BaseTmdbApiUrl + @"3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), TmdbUtils.ApiKey);

            using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                AcceptHeader = TmdbUtils.AcceptHeader

            }).ConfigureAwait(false))
            {
                using (var json = response.Content)
                {
                    var result = await _jsonSerializer.DeserializeFromStreamAsync<TmdbSearchResult<PersonSearchResult>>(json).ConfigureAwait(false) ??
                                 new TmdbSearchResult<PersonSearchResult>();

                    return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
                }
            }
        }

19 View Source File : AlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
        {
            // TODO maybe remove when artist metadata can be disabled
            if (!Plugin.Instance.Configuration.Enable)
            {
                return Enumerable.Empty<RemoteSearchResult>();
            }

            var releaseId = searchInfo.GetReleaseId();
            var releaseGroupId = searchInfo.GetReleaseGroupId();

            string url;

            if (!string.IsNullOrEmpty(releaseId))
            {
                url = "/ws/2/release/?query=reid:" + releaseId.ToString(CultureInfo.InvariantCulture);
            }
            else if (!string.IsNullOrEmpty(releaseGroupId))
            {
                url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                var artistMusicBrainzId = searchInfo.GetMusicBrainzArtistId();

                if (!string.IsNullOrWhiteSpace(artistMusicBrainzId))
                {
                    url = string.Format(
                        CultureInfo.InvariantCulture,
                        "/ws/2/release/?query=\"{0}\" AND arid:{1}",
                        WebUtility.UrlEncode(searchInfo.Name),
                        artistMusicBrainzId);
                }
                else
                {
                    // I'm sure there is a better way but for now it resolves search for 12" Mixes
                    var queryName = searchInfo.Name.Replace("\"", string.Empty);

                    url = string.Format(
                        CultureInfo.InvariantCulture,
                        "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
                        WebUtility.UrlEncode(queryName),
                        WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
                }
            }

            if (!string.IsNullOrWhiteSpace(url))
            {
                using (var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
                using (var stream = response.Content)
                {
                    return GetResultsFromResponse(stream);
                }
            }

            return Enumerable.Empty<RemoteSearchResult>();
        }

19 View Source File : AlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : vesoapp

private async Task<ReleaseResult> GetReleaseResult(string albumName, string artistId, CancellationToken cancellationToken)
        {
            var url = string.Format("/ws/2/release/?query=\"{0}\" AND arid:{1}",
                WebUtility.UrlEncode(albumName),
                artistId);

            using (var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
            using (var stream = response.Content)
            using (var oReader = new StreamReader(stream, Encoding.UTF8))
            {
                var settings = new XmlReaderSettings()
                {
                    ValidationType = ValidationType.None,
                    CheckCharacters = false,
                    IgnoreProcessingInstructions = true,
                    IgnoreComments = true
                };

                using (var reader = XmlReader.Create(oReader, settings))
                {
                    return ReleaseResult.Parse(reader).FirstOrDefault();
                }
            }
        }

19 View Source File : EntityAdapter.cs
License : MIT License
Project Creator : vip32

private void Init(Key key, bool useConcurencyKey)
        {
            EnsureArg.IsNotNull(key, nameof(key));

            this.ParreplacedionKey = WebUtility.UrlEncode(key.ParreplacedionKey);
            this.RowKey = WebUtility.UrlEncode(key.RowKey);
            this.ETag = "*";
        }

19 View Source File : TableKeyValueStorage.cs
License : MIT License
Project Creator : vip32

private async Task<IEnumerable<Value>> FindAsync(
            string tableName,
            Key key = null,
            int take = -1,
            IEnumerable<Criteria> criterias = null)
        {
            var table = await this.EnsureTableAsync(tableName, false).AnyContext();
            if (table == null)
            {
                return new List<Value>();
            }

            var filters = new List<string>();
            if (key?.ParreplacedionKey != null)
            {
                filters.Add(TableQuery.GenerateFilterCondition(
                   "ParreplacedionKey",
                   QueryComparisons.Equal,
                   WebUtility.UrlEncode(key.ParreplacedionKey)));
            }

            if (key?.RowKey != null)
            {
                filters.Add(TableQuery.GenerateFilterCondition(
                   "RowKey",
                   QueryComparisons.Equal,
                   WebUtility.UrlEncode(key.RowKey)));
            }

            this.Map(criterias, filters);

            var query = new TableQuery();
            if (filters.Count > 0)
            {
                var filter = filters[0];
                for (var i = 1; i < filters.Count; i++)
                {
                    filter = TableQuery.CombineFilters(filter, TableOperators.And, filters[i]);
                }

                query = query.Where(filter);
            }

            if (take > 0)
            {
                query = query.Take(take);
            }

            TableContinuationToken token = null;
            var enreplacedies = new List<DynamicTableEnreplacedy>();
            do
            {
                var queryResults = await table.ExecuteQuerySegmentedAsync(query, token).AnyContext();
                enreplacedies.AddRange(queryResults.Results);
                token = queryResults.ContinuationToken;
            }
            while (token != null);

            return enreplacedies.Select(this.ToValue).ToList();
        }

19 View Source File : TableKeyValueStorage.cs
License : MIT License
Project Creator : vip32

private void Map(IEnumerable<Criteria> criterias, List<string> filters)
        {
            foreach (var criteria in criterias.Safe())
            {
                if (criteria.Value is int i)
                {
                    filters.Add(TableQuery.GenerateFilterConditionForInt(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       i));
                }
                else if (criteria.Value is double d)
                {
                    filters.Add(TableQuery.GenerateFilterConditionForDouble(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       d));
                }
                else if (criteria.Value is long l)
                {
                    filters.Add(TableQuery.GenerateFilterConditionForLong(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       l));
                }
                else if (criteria.Value is bool b)
                {
                    filters.Add(TableQuery.GenerateFilterConditionForBool(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       b));
                }
                else if (criteria.Value is DateTime dt)
                {
                    filters.Add(TableQuery.GenerateFilterConditionForDate(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       dt));
                }
                else
                {
                    filters.Add(TableQuery.GenerateFilterCondition(
                       criteria.Name,
                       criteria.Operator.ToAbbreviation(),
                       WebUtility.UrlEncode(criteria.Value.As<string>())));
                }
            }
        }

See More Examples