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

public void ReportIssue()
        {
            var version = typeof(GithubAdapter).replacedembly.GetName().Version;
            var body = "Expected behavior:\n" +
                       "* Step 1\n" +
                       "* Step 2\n" +
                       "* ...\n" +
                       "\n" +
                       "Observed behavior:\n" +
                       "* Step 1\n" +
                       "* Step 2\n" +
                       "* ...\n" +
                       "\n" +
                       $"Installed version: {version}\n" +
                       $".NET Version: {ClrVersion.Version}\n" +
                       $"OS Version: {Environment.OSVersion}";
            OpenUrl($"{BaseUrl}/issues/new?body={WebUtility.UrlEncode(body)}");
        }

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

public void OpenInstanceList(ZoneLocator zone)
        {
            var query = "[{\"k\":\"zoneForFilter\",\"v\":\"" + zone.Name + "\"}]";
            OpenUrl("https://console.cloud.google.com/compute/instances" +
                $"?project={zone.ProjectId}&instancesquery={WebUtility.UrlEncode(query)}");
        }

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

public void ReportIssue()
        {
            var version = typeof(GithubAdapter).replacedembly.GetName().Version;
            var body = "Expected behavior:\n" +
                       "* Step 1\n" +
                       "* Step 2\n" +
                       "* ...\n" +
                       "\n" +
                       "Observed behavior:\n" +
                       "* Step 1\n" +
                       "* Step 2\n" +
                       "* ...\n" +
                       "\n" +
                       $"Installed version: {version}\n" +
                       $".NET Version: {ClrVersion.Version}\n" +
                       $"OS Version: {Environment.OSVersion}";
            OpenUrl($"{BaseUrl}/issues/new?component=953762&template=1561579&description={WebUtility.UrlEncode(body)}");
        }

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

private Uri CreateUri(
            string sid,
            ulong ack)
        {
            var urlParams = new Dictionary<string, string>
            {
                { "project", this.VmInstance.ProjectId },
                { "zone", this.VmInstance.Zone },
                { "instance", this.VmInstance.Name },
                { "interface", this.Interface },
                { "port", this.Port.ToString() },
                { "_", Guid.NewGuid().ToString() }  // Cache buster.
            };

            if (sid != null)
            {
                urlParams["sid"] = sid;
                urlParams["ack"] = ack.ToString();
            }

            var queryString = string.Join(
                "&",
                urlParams.Select(kvp => kvp.Key + "=" + WebUtility.UrlEncode(kvp.Value)));

            return new Uri(
                (this.clientCertificate == null ? TlsBaseUri : MtlsBaseUri) +
                (sid == null ? "connect" : "reconnect") +
                "?" +
                queryString);
        }

19 View Source File : FacebookAuthenticationBuilder.cs
License : GNU General Public License v3.0
Project Creator : grandnode

public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration)
        {
            builder.AddFacebook(FacebookDefaults.AuthenticationScheme, options =>
            {
                var connection = DataSettingsManager.LoadSettings();

                var settings = new FacebookExternalAuthSettings();
                try
                {
                    var fbSettings = new MongoRepository<Setting>(connection.ConnectionString).Table.Where(x => x.Name.StartsWith("facebookexternalauthsettings"));
                    if (fbSettings.Any())
                    {
                        var metadata = fbSettings.FirstOrDefault().Metadata;
                        settings = JsonSerializer.Deserialize<FacebookExternalAuthSettings>(metadata);
                    }
                }
                catch (Exception ex) { Log.Error(ex, "AddFacebook"); };

                //no empty values allowed. otherwise, an exception could be thrown on application startup
                options.AppId = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";
                options.AppSecret = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";
                options.SaveTokens = true;
                //handles exception thrown by external auth provider
                options.Events = new OAuthEvents() {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.HandleResponse();
                        var errorCode = ctx.Request.Query["error_code"].FirstOrDefault();
                        var errorMessage = ctx.Request.Query["error_message"].FirstOrDefault();
                        var state = ctx.Request.Query["state"].FirstOrDefault();
                        errorCode = WebUtility.UrlEncode(errorCode);
                        errorMessage = WebUtility.UrlEncode(errorMessage);
                        ctx.Response.Redirect($"/fb-signin-failed?error_code={errorCode}&error_message={errorMessage}");

                        return Task.FromResult(0);
                    }
                };
            });
        }

19 View Source File : GoogleAuthenticationBuilder.cs
License : GNU General Public License v3.0
Project Creator : grandnode

public void AddAuthentication(AuthenticationBuilder builder, IConfiguration configuration)
        {
            builder.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
            {
                var connection = DataSettingsManager.LoadSettings();

                var settings = new GoogleExternalAuthSettings();
                try
                {
                    var gSettings = new MongoRepository<Setting>(connection.ConnectionString).Table.Where(x => x.Name.StartsWith("googleexternalauthsettings"));
                    if (gSettings.Any())
                    {
                        var metadata = gSettings.FirstOrDefault().Metadata;
                        settings = JsonSerializer.Deserialize<GoogleExternalAuthSettings>(metadata);
                    }
                }
                catch (Exception ex) { Log.Error(ex, "AddGoogle"); };

                options.ClientId = !string.IsNullOrWhiteSpace(settings.ClientKeyIdentifier) ? settings.ClientKeyIdentifier : "000";
                options.ClientSecret = !string.IsNullOrWhiteSpace(settings.ClientSecret) ? settings.ClientSecret : "000";
                options.SaveTokens = true;

                //handles exception thrown by external auth provider
                options.Events = new OAuthEvents() {
                    OnRemoteFailure = ctx =>
                    {
                        ctx.HandleResponse();
                        var errorMessage = ctx.Failure.Message;
                        var state = ctx.Request.Query["state"].FirstOrDefault();
                        errorMessage = WebUtility.UrlEncode(errorMessage);
                        ctx.Response.Redirect($"/google-signin-failed?error_message={errorMessage}");

                        return Task.FromResult(0);
                    }
                };
            });

        }

19 View Source File : SearchGridODataProcessor.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string Process()
        {
            string result = "";
            if (_grid.SearchingEnabled && !string.IsNullOrWhiteSpace(_settings.SearchValue))
            {
                result = "$search='" + WebUtility.UrlEncode(_settings.SearchValue.Replace("'", "''")) + "'";
            }
            return result;         
        }

19 View Source File : SortGridItemsProcessor.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string Process()
        {
            string result = GetSorting();
            if (!string.IsNullOrWhiteSpace(result))
            {
                result = "$orderby=" + WebUtility.UrlEncode(result) + "";
            }
            return result;
        }

19 View Source File : FilterGridODataProcessor.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string Process()
        {
            var filters = new List<string>();
            foreach (IGridColumn column in _grid.Columns)
            {
                var gridColumn = column as IGridColumn<T>;
                if (gridColumn == null) continue;
                if (gridColumn.Filter == null) continue;

                IEnumerable<ColumnFilterValue> options = _settings.IsInitState(column)
                                                             ? new List<ColumnFilterValue>
                                                                 {
                                                                     column.InitialFilterSettings
                                                                 }
                                                             : _settings.FilteredColumns.GetByColumn(column);

                var filter = gridColumn.Filter.GetFilter(options);
                if (!string.IsNullOrWhiteSpace(filter))
                    filters.Add(filter);
            }

            // workaround for lack of $search OData support
            var search = new List<string>();
            if (_grid.SearchingEnabled && !string.IsNullOrWhiteSpace(_searchSettings.SearchValue))
            {
                foreach (IGridColumn column in _grid.Columns)
                {
                    var gridColumn = column as IGridColumn<T>;
                    if (gridColumn == null) continue;
                    if (!_grid.SearchingHiddenColumns && gridColumn.Hidden) continue;
                    if (gridColumn.Filter == null) continue;                   
                    if (!gridColumn.Filter.IsTextColumn()) continue;

                    List<ColumnFilterValue> options = new List<ColumnFilterValue>();
                    var columnFilterValue = new ColumnFilterValue(column.Name, GridFilterType.Contains, _searchSettings.SearchValue);
                    options.Add(columnFilterValue);

                    var filter = gridColumn.Filter.GetFilter(options);
                    if (!string.IsNullOrWhiteSpace(filter))
                        search.Add(filter);
                }
            }
            string searchResult = "";
            for (int i = 0; i < search.Count; i++)
            {
                searchResult += "(" + search[i] + ")";
                if (i != search.Count - 1)
                    searchResult += " or ";
            }

            string filterResult = "";
            for (int i = 0; i < filters.Count; i++)
            {
                filterResult += "(" + filters[i] + ")";
                if (i != filters.Count - 1)
                    filterResult += " and ";
            }

            if (string.IsNullOrWhiteSpace(searchResult))
            {
                if (string.IsNullOrWhiteSpace(filterResult))
                {
                    return "";
                }
                else
                {
                    return "$filter=" + WebUtility.UrlEncode(filterResult);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(filterResult))
                {
                    return "$filter=" + WebUtility.UrlEncode(searchResult);
                }
                else
                {
                    return "$filter=(" + WebUtility.UrlEncode(searchResult) + ") and (" + WebUtility.UrlEncode(filterResult) + ")";
                }
            }
        }

19 View Source File : ExpandGridODataProcessor.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string Process()
        {
            string result = GetExpand();
            if (!string.IsNullOrWhiteSpace(result))
            {
                result = "$expand=" + WebUtility.UrlEncode(result) + "";
            }
            return result;
        }

19 View Source File : CustomQueryStringBuilder.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string GetQueryStringExcept(IList<string> parameterNames)
        {
            var result = new StringBuilder();
            foreach (string key in base.AllKeys)
            {
                if (string.IsNullOrEmpty(key) || parameterNames.Contains(key))
                    continue;
                string[] values = base.GetValues(key);
                if (values != null && values.Count() != 0)
                {
                    if (result.Length == 0)
                        result.Append("?");
                    foreach (string value in values)
                    {
                        // added to support multiple filters
                        string[] vals = value.Split(',');
                        foreach (string val in vals)
                        {
                            result.Append(key + "=" + WebUtility.UrlEncode(val) + "&");
                        }
                    }
                }
            }
            string resultString = result.ToString();
            return resultString.EndsWith("&") ? resultString.Substring(0, resultString.Length - 1) : resultString;
        }

19 View Source File : CustomQueryStringBuilder.cs
License : GNU Lesser General Public License v2.1
Project Creator : gustavnavar

public string GetQueryStringExcept(IList<Tuple<string, string>> parameterValues)
        {
            var result = new StringBuilder();
            foreach (string key in base.AllKeys)
            {
                if (string.IsNullOrEmpty(key))
                    continue;
                string[] values = base.GetValues(key);
                if (values != null && values.Count() != 0)
                {
                    if (result.Length == 0)
                        result.Append("?");
                    foreach (string value in values)
                    {
                        // added to support multiple filters
                        string[] vals = value.Split(',');
                        foreach (string val in vals)
                        {
                            var tuple = new Tuple<string, string>(key, val);
                            if (parameterValues.Contains(tuple))
                                continue;
                            result.Append(key + "=" + WebUtility.UrlEncode(val) + "&");
                        }
                    }
                }
            }
            string resultString = result.ToString();
            return resultString.EndsWith("&") ? resultString.Substring(0, resultString.Length - 1) : resultString;
        }

19 View Source File : UrlHelpers.cs
License : MIT License
Project Creator : Handlebars-Net

[HandlebarsWriter(WriterType.String)]
        public string EncodeUri(string value)
        {
            return WebUtility.UrlEncode(value);
        }

19 View Source File : FunctionalTestFixture.cs
License : Apache License 2.0
Project Creator : HealthCatalyst

private async Task replacedociateGroupsToRoles()
        {
            var roleRoute = $"/roles/{FunctionalTestConstants.Grain}/{FunctionalTestConstants.IdenreplacedyTestUser}/{WebUtility.UrlEncode(FunctionalTestConstants.GroupName)}";
            var response = await this.Get(this._authorizationClient.BaseAddress, roleRoute, this._installerAccessToken).ConfigureAwait(false);
            replacedert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);

            var stringResponse = await response.Content.ReadreplacedtringAsync();
            var roleResponse = stringResponse.FromJson<RoleApiModel[]>();
            var groupRoute = $"/groups/{WebUtility.UrlEncode(FunctionalTestConstants.GroupName)}/roles";
            var response2 = await this.PostWithJsonBody(this._authorizationClient.BaseAddress, groupRoute, string.Format("[{0}]", roleResponse[0].ToJson()), this._installerAccessToken).ConfigureAwait(false);
            replacedert.Equal(System.Net.HttpStatusCode.OK, response2.StatusCode);
        }

19 View Source File : FunctionalTestFixture.cs
License : Apache License 2.0
Project Creator : HealthCatalyst

private async Task replacedociateUserWithGroup()
        {
            var groupRoute = $"/groups/{WebUtility.UrlEncode(FunctionalTestConstants.GroupName)}/users";
            var response = await this.PostWithJsonBody(this._authorizationClient.BaseAddress, groupRoute, string.Format("[{0}]", FunctionalTestHelpers.UserBob), this._installerAccessToken).ConfigureAwait(false);
            replacedert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
        }

19 View Source File : HoneycombService.cs
License : Apache License 2.0
Project Creator : honeycombio

public async Task SendSingleAsync(HoneycombEvent ev)
        {
            _logger.LogTrace("Sending Honeycomb Data");

            var client = _httpClientFactory.CreateClient("honeycomb");

            var message = new HttpRequestMessage();
            var content = JsonConvert.SerializeObject(ev.Data);
            message.Content = new StringContent(content, Encoding.UTF8, "application/json");
            message.Method = HttpMethod.Post;
            message.RequestUri = new Uri($"{_settings.Value.ApiHost}/1/events/{WebUtility.UrlEncode(ev.DataSetName)}");
            message.Headers.UserAgent.Add(
                    new ProductInfoHeaderValue(
                        new ProductHeaderValue("libhoney-dotnet", _replacedemblyVersion)));
            message.Headers.Add("X-Honeycomb-Event-Time",
                ev.EventTime.ToUniversalTime().ToString(@"{0:yyyy-MM-ddTHH\:mm\:ss.fffK}"));
            message.Headers.Add("X-Honeycomb-Team", _settings.Value.WriteKey);

            var resp = await client.SendAsync(message);
            if (!resp.IsSuccessStatusCode)
                _logger.LogWarning("Error sending information to honeycomb status:{StatusCode}", resp.StatusCode);
        }

19 View Source File : HoneycombService.cs
License : Apache License 2.0
Project Creator : honeycombio

public async Task SendBatchAsync(IEnumerable<HoneycombEvent> items, string dataSetName)
        {
            _logger.LogTrace("Sending Honeycomb Data for {dataSetName} with {items} items", dataSetName, items.Count());

            var client = _httpClientFactory.CreateClient("honeycomb");

            var message = new HttpRequestMessage();

            var sendItems = items.Select(i =>
                new {
                    time = i.EventTime.ToUniversalTime().ToString(@"yyyy-MM-ddTHH\:mm\:ss.fffK"),
                    data = i.Data
                    });

            var content = JsonConvert.SerializeObject(sendItems);
            message.Content = new StringContent(content, Encoding.UTF8, "application/json");
            message.Method = HttpMethod.Post;
            message.RequestUri = new Uri($"{_settings.Value.ApiHost}/1/batch/{WebUtility.UrlEncode(dataSetName)}");
            message.Headers.UserAgent.Add(
                    new ProductInfoHeaderValue(
                        new ProductHeaderValue("libhoney-dotnet", _replacedemblyVersion)));
            message.Headers.Add("X-Honeycomb-Team", _settings.Value.WriteKey);

            var resp = await client.SendAsync(message);
            if (!resp.IsSuccessStatusCode)
                _logger.LogWarning("Error sending information to honeycomb status:{StatusCode}", resp.StatusCode);
        }

19 View Source File : WechatSogouBasic.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : hoyho

protected async Task<string> SearchAccountHtmlAsync(string name, int page = 1, int tryTime = 1)
        {
            string text = "";
            name = WebUtility.UrlEncode(name);
            string requestUrl =
                $"http://weixin.sogou.com/weixin?query={name}&_sug_type_=&_sug_=n&type=1&page={page}&ie=utf8";

            try
            {
                text = tryTime > 5 ? "" : await _browser.GetPageWithoutVcodeAsync(requestUrl);
            }
            catch (WechatSogouVcodeException vCodeEx)
            {
                var enableOnlineDecode = _configuration.GetSection("enableOnlineDecode").Get<bool>();
                await _browser.HandleSogouVcodeAsync(vCodeEx.VisittingUrl, enableOnlineDecode);
                Thread.Sleep(4000);
                tryTime++;
                text = tryTime > 5 ? "" : await _browser.GetPageWithoutVcodeAsync(requestUrl);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }

            return text;
        }

19 View Source File : FanburstSearchModel.cs
License : MIT License
Project Creator : Hrishi1999

public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            // Return a task that will get the items
            return Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(Query))
                    return new LoadMoreItemsResult { Count = 0 };

                // We are loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = true; });

                // Get the resource loader
                var resources = ResourceLoader.GetForViewIndependentUse();

                try
                {
                    // Search for matching tracks
                    var searchTracks = await SoundByteService.Current.GetAsync<List<dynamic>>(SoundByteService.ServiceType.Fanburst, "tracks/search", new Dictionary<string, string>
                    {
                        { "query", WebUtility.UrlEncode(Query) }
                    });

                    // Parse uri for offset
                 //   var param = new QueryParameterCollection(searchTracks.NextList);
                    var offset = "eol";//param.FirstOrDefault(x => x.Key == "offset").Value;

                    // Get the search offset
                    Token = string.IsNullOrEmpty(offset) ? "eol" : offset;

                    // Make sure that there are tracks in the list
                    if (searchTracks.Count > 0)
                    {
                        // Set the count variable
                        count = (uint)searchTracks.Count;

                        // Loop though all the tracks on the UI thread
                        await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                        {
                            foreach (var item in searchTracks)
                            {
                                Add(new Track
                                {
                                    ServiceType = ServiceType.Fanburst,
                                    Id = item.id,
                                    replacedle = item.replacedle,
                                    PermalinkUri = item.permalink,
                                    Duration = item.duration,
                                    CreationDate = (DateTime)item.published_at.Value,
                                    Kind = "track",
                                    User = new User
                                    {
                                        Id = item.user.id,
                                        Username = item.user.name,
                                        Country = item.user.location,
                                        ArtworkLink = item.user.avatar_url
                                    },
                                    ArtworkLink = item.images.square_500
                                });
                            }
                        });
                    }
                    else
                    {
                        // There are no items, so we added no items
                        count = 0;

                        // Reset the token
                        Token = "eol";

                        // No items tell the user
                        await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                        {
                            await new MessageDialog(resources.GetString("SearchTrack_Content"), resources.GetString("SearchTrack_Header")).ShowAsync();
                        });
                    }
                }
                catch (SoundByteException ex)
                {
                    // Exception, most likely did not add any new items
                    count = 0;

                    // Reset the token
                    Token = "eol";

                    // Exception, display error to the user
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
                        await new MessageDialog(ex.ErrorDescription, ex.Errorreplacedle).ShowAsync();
                    });
                }

                // We are not loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = false; });

                // Return the result
                return new LoadMoreItemsResult { Count = count };
            }).AsAsyncOperation();
        }

19 View Source File : FilterDialog.xaml.cs
License : MIT License
Project Creator : Hrishi1999

public async void Apply()
        {
            var filterArgs = string.Empty;

            // Check that they user has entred something in tags list
            if (!string.IsNullOrEmpty(SearchTags.Text))
            {
                try
                {
                    var tags = SearchTags.Text.Split(',');
                    filterArgs += "&tags=" + String.Join(",", tags);
                }
                catch (Exception)
                {
                    await new MessageDialog("Error: You must seperate each tag with a comma").ShowAsync();
                    return;
                }
            }

            // Get the base content
            string selectedLicense = ((ComboBoxItem)(SearchLicense).SelectedItem).Content.ToString();
            if (selectedLicense.ToLower() != "any")
            {
                selectedLicense = selectedLicense.ToLower().Replace(' ', '-');
                filterArgs += "&license=" + System.Net.WebUtility.UrlEncode(selectedLicense);
            }


            string selectedType = ((ComboBoxItem)(SearchType).SelectedItem).Content.ToString();
            if (selectedType.ToLower() != "any")
            {
                selectedType = selectedType.ToLower();
                filterArgs += "&types=" + System.Net.WebUtility.UrlEncode(selectedType);
            }

            if (!string.IsNullOrEmpty(SearchBPM.Text))
            {
                if (int.Parse(SearchBPM.Text) >= 10)
                {
                    filterArgs += "bpm[from]=" + (int.Parse(SearchBPM.Text) - 10) + "&bpm[to]=" + (int.Parse(SearchBPM.Text) + 10);
                }
                else
                {
                    filterArgs += "bpm[from]=0&bpm[to]=" + (int.Parse(SearchBPM.Text) + 10);
                }
            }

            // Create the arguments
            FilterAppliedArgs args = new FilterAppliedArgs { FilterArgs = filterArgs };
            // Call the event handler
            FilterApplied?.Invoke(this, args);
            // Hide the popup
            Hide();
        }

19 View Source File : SearchPlaylistModel.cs
License : MIT License
Project Creator : Hrishi1999

public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            // Return a task that will get the items
            return Task.Run(async () =>
            {
                // If the query is empty, tell the user that they can search something
                if (string.IsNullOrEmpty(Query))
                    return new LoadMoreItemsResult { Count = 0 };

                // We are loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = true; });

                // Get the resource loader
                var resources = ResourceLoader.GetForViewIndependentUse();

                try
                {
                    // Get the searched playlists
                    var searchPlaylists = await SoundByteService.Current.GetAsync<SearchPlaylistHolder>("/playlists", new Dictionary<string, string>
                    {
                        { "limit", SettingsService.TrackLimitor.ToString() },
                        { "linked_parreplacedioning", "1" },
                        { "offset", Token },
                        { "q",  WebUtility.UrlEncode(Query) }
                    });

                    // Parse uri for offset
                    var param = new QueryParameterCollection(searchPlaylists.NextList);
                    var offset = param.FirstOrDefault(x => x.Key == "offset").Value;

                    // Get the search playlists offset
                    Token = string.IsNullOrEmpty(offset) ? "eol" : offset;

                    // Make sure that there are playlists in the list
                    if (searchPlaylists.Playlists.Count > 0)
                    {
                        // Set the count variable
                        count = (uint)searchPlaylists.Playlists.Count;

                        // Loop though all the search playlists on the UI thread
                        await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                        {
                            searchPlaylists.Playlists.ForEach(Add);
                        });
                    }
                    else
                    {
                        // There are no items, so we added no items
                        count = 0;

                        // Reset the token
                        Token = "eol";

                        // No items tell the user
                        await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                        {
                            await new MessageDialog(resources.GetString("SearchPlaylist_Content"), resources.GetString("SearchPlaylist_Header")).ShowAsync();
                        });
                    }
                }
                catch (SoundByteException ex)
                {
                    // Exception, most likely did not add any new items
                    count = 0;

                    // Reset the token
                    Token = "eol";

                    // Exception, display error to the user
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
                        await new MessageDialog(ex.ErrorDescription, ex.Errorreplacedle).ShowAsync();
                    });
                }


                // We are not loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = false; });

                // Return the result
                return new LoadMoreItemsResult { Count = count };
            }).AsAsyncOperation();
        }

19 View Source File : SearchTrackModel.cs
License : MIT License
Project Creator : Hrishi1999

public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            // Return a task that will get the items
            return Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(Query))
                {
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
               //         await new MessageDialog("Type something to search for tracks on SoundCloud.", "Search Tracks").ShowAsync();
                    });

                    return new LoadMoreItemsResult { Count = 0 };
                }

                // We are loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = true; });

                // Get the resource loader
                var resources = ResourceLoader.GetForViewIndependentUse();

                try
                {
                    // Search for matching tracks
                    var searchTracks = await SoundByteService.Current.GetAsync<TrackListHolder>("/tracks", new Dictionary<string, string>
                    {
                        { "limit", SettingsService.TrackLimitor.ToString() },
                        { "linked_parreplacedioning", "1" },
                        { "offset", Token },
                        { "q",  WebUtility.UrlEncode(Query) + "&" + Filter }
                    });

                    // Parse uri for offset
                    var param = new QueryParameterCollection(searchTracks.NextList);
                    var offset = param.FirstOrDefault(x => x.Key == "offset").Value;

                    // Get the search offset
                    Token = string.IsNullOrEmpty(offset) ? "eol" : offset;

                    // Make sure that there are tracks in the list
                    if (searchTracks.Tracks.Count > 0)
                    {
                        // Set the count variable
                        count = (uint)searchTracks.Tracks.Count;

                        // Loop though all the tracks on the UI thread
                        await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                        {
                            searchTracks.Tracks.ForEach(Add);
                        });
                    }
                    else
                    {
                        // There are no items, so we added no items
                        count = 0;

                        // Reset the token
                        Token = "eol";

                        // No items tell the user
                        await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                        {
                            await new MessageDialog(resources.GetString("SearchTrack_Content"), resources.GetString("SearchTrack_Header")).ShowAsync();
                        });
                    }
                }
                catch (SoundByteException ex)
                {
                    // Exception, most likely did not add any new items
                    count = 0;

                    // Reset the token
                    Token = "eol";

                    // Exception, display error to the user
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
                        await new MessageDialog(ex.ErrorDescription, ex.Errorreplacedle).ShowAsync();
                    });
                }

                // We are not loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = false; });

                // Return the result
                return new LoadMoreItemsResult { Count = count };
            }).AsAsyncOperation();
        }

19 View Source File : SearchUserModel.cs
License : MIT License
Project Creator : Hrishi1999

public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            // Return a task that will get the items
            return Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(Query))
                {
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
               //         await new MessageDialog("Type something to search for users on SoundCloud.", "Search Users").ShowAsync();
                    });

                    return new LoadMoreItemsResult { Count = 0 };
                }

                // We are loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = true; });

                // Get the resource loader
                var resources = ResourceLoader.GetForViewIndependentUse();

                try
                {
                    // Get the searched users
                    var searchUsers = await SoundByteService.Current.GetAsync<UserListHolder>("/users", new Dictionary<string, string>
                    {
                        { "limit", SettingsService.TrackLimitor.ToString() },
                        { "linked_parreplacedioning", "1" },
                        { "offset", Token },
                        { "q",  WebUtility.UrlEncode(Query) }
                    });

                    // Parse uri for offset
                    var param = new QueryParameterCollection(searchUsers.NextList);
                    var offset = param.FirstOrDefault(x => x.Key == "offset").Value;

                    // Get the stream cursor
                    Token = string.IsNullOrEmpty(offset) ? "eol" : offset;

                    // Make sure that there are users in the list
                    if (searchUsers.Users.Count > 0)
                    {
                        // Set the count variable
                        count = (uint) searchUsers.Users.Count;

                        // Loop though all the tracks on the UI thread
                        await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                        {
                            searchUsers.Users.ForEach(Add);
                        });
                    }
                    else
                    {
                        // There are no items, so we added no items
                        count = 0;

                        // Reset the token
                        Token = "eol";

                        // No items tell the user
                        await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                        {
                            await new MessageDialog(resources.GetString("SearchUser_Content"), resources.GetString("SearchUser_Header")).ShowAsync();
                        });
                    }
                }
                catch (SoundByteException ex)
                {
                    // Exception, most likely did not add any new items
                    count = 0;

                    // Reset the token
                    Token = "eol";

                    // Exception, display error to the user
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async () =>
                    {
                        await new MessageDialog(ex.ErrorDescription, ex.Errorreplacedle).ShowAsync();
                    });
                }


                // We are not loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = false; });

                // Return the result
                return new LoadMoreItemsResult { Count = count };
            }).AsAsyncOperation();
        }

19 View Source File : BaseRequest.cs
License : MIT License
Project Creator : hueifeng

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 : UnionPayUntil.cs
License : MIT License
Project Creator : hueifeng

public static string GetSignContent(Dictionary<string, string> para, bool sort, bool encode)
        {
            if (para == null || para.Count == 0)
                return string.Empty;

            var list = new List<string>(para.Keys);

            if (sort)
                list.Sort(StringComparer.Ordinal);

            var sb = new StringBuilder();
            foreach (var key in list)
            {
                var value = para[key];
                if (encode)
                {
                    value = WebUtility.UrlEncode(value);
                }
                sb.Append(key).Append("=").Append(value).Append("&");
            }

            return sb.Remove(sb.Length - 1, 1).ToString();
        }

19 View Source File : RestRequest.cs
License : GNU General Public License v3.0
Project Creator : Hyddwn

private void AppendQueryString(StringBuilder stringBuilder, string key, string value)
        {
            if (stringBuilder.Length > 0)
                stringBuilder.Append("&");

            stringBuilder.Append(key);
            stringBuilder.Append("=");
            stringBuilder.Append(WebUtility.UrlEncode(value));
        }

19 View Source File : LavalinkRestClient.cs
License : MIT License
Project Creator : IDoEverything

public Task<LavalinkLoadResult> GetTracksAsync(string searchQuery, LavalinkSearchType type = LavalinkSearchType.Youtube)
        {
            string prefix;
            if (type == LavalinkSearchType.Youtube)
                prefix = "ytsearch";
            else
                prefix = "scsearch";

            var str = WebUtility.UrlEncode($"{prefix}:{searchQuery}");
            var tracksUri = new Uri($"{this.RestEndpoint.ToHttpString()}{Endpoints.LOAD_TRACKS}?identifier={str}");
            return this.InternalResolveTracksAsync(tracksUri);
        }

19 View Source File : SignatureUtils.cs
License : GNU General Public License v3.0
Project Creator : Ifropc

public static string SignedParams(Dictionary<string, string> parameters, string secret)
        {
            var builder = new StringBuilder();

            foreach (var (key, value) in parameters)
                builder.Append(key).Append('=').Append(WebUtility.UrlEncode(value)).Append('&');

            string signature = Sign(parameters, secret);

            builder.Append("api_sig=").Append(signature).Append("&format=json");

            return builder.ToString();
        }

19 View Source File : Knockout.cs
License : Apache License 2.0
Project Creator : IntelliTect

public static HtmlString SelectObject(PropertyViewModel propertyModel, string placeholder = "", string prefix = "", bool allowsClear = true)
        {

            if (prefix == "" && propertyModel.JsVariableIsReserved)
            {
                // This fixes bug #7799: in cases where the object that we're binding to is a js reserved word,
                // we need to prefix it with $data, which is used by knockout internally as follows.
                // I also made changes to a whole ton of other spots so that the new JsVariableForBinding() is used where appropriate for knockout bindings.
                /*
                    // Build the source for a function that evaluates "expression"
                    // For each scope variable, add an extra level of "with" nesting
                    // Example result: with(sc1) { with(sc0) { return (expression) } }
                    var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
                        functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
                    return new Function("$context", "$element", functionBody);
                 */
                // Note that $data is indeed publicly doreplacedented at http://knockoutjs.com/doreplacedentation/binding-context.html, so this should be safe to use.
                prefix = "$data.";
            }


            string filterString = "";

            if (propertyModel.HasAttribute<SelectFilterAttribute>())
            {
                string foreignPropName = propertyModel.GetAttributeValue<SelectFilterAttribute>(a => a.ForeignPropertyName);
                string localValue = propertyModel.GetAttributeValue<SelectFilterAttribute>(a => a.StaticPropertyValue);

                PropertyViewModel foreignProp = propertyModel.Object.PropertyByName(foreignPropName);
                if (localValue != null)
                {
                    filterString = $"?filter.{foreignProp.JsVariable}={System.Net.WebUtility.UrlEncode(localValue)}";
                }
                else
                {
                    string localPropName = propertyModel.GetAttributeValue<SelectFilterAttribute>(a => a.LocalPropertyName);
                    string localPropObjName = propertyModel.GetAttributeValue<SelectFilterAttribute>(a => a.LocalPropertyObjectName);


                    if (localPropObjName != null)
                    {
                        PropertyViewModel localPropObj = propertyModel.Parent.PropertyByName(localPropObjName);
                        PropertyViewModel localProp = localPropObj.PureType.ClreplacedViewModel.PropertyByName(localPropName ?? foreignPropName);

                        filterString = $"?filter.{foreignProp.JsVariable}=' + ({localPropObj.JsVariableForBinding()}() ? {localPropObj.JsVariableForBinding()}().{localProp.JsVariable}() : 'null') + '";
                    }
                    else
                    {
                        PropertyViewModel localProp = propertyModel.Parent.PropertyByName(localPropName ?? foreignPropName);
                        filterString = $"?filter.{foreignProp.JsVariable}=' + {localProp.JsVariableForBinding()}() + '";
                    }
                }
            }

            string result = string.Format(@"
                    <select clreplaced=""form-control"" 
                        data-bind=""select2Ajax: {6}{0}, url: function() {{ return '/api/{1}/list{8}' }}, idField: '{2}', textField: '{3}', object: {6}{4}, allowClear: {7}"" 
                        placeholder=""{5}"">
                            <option>{5}</option>
                    </select >
                    ",
                /*0*/ propertyModel.ForeignKeyProperty.JsVariable,
                /*1*/ propertyModel.PureType.ClreplacedViewModel.ApiControllerClreplacedName.Replace("Controller", ""),
                /*2*/ propertyModel.Object.PrimaryKey.Name,
                /*3*/ propertyModel.Object.ListTextProperty.Name,
                /*4*/ propertyModel.JsVariable,
                /*5*/ placeholder,
                /*6*/ prefix,
                /*7*/ allowsClear.ToString().ToLowerInvariant(),
                /*8*/ filterString);

            return new HtmlString(result);
        }

19 View Source File : BaseViewController.cs
License : Apache License 2.0
Project Creator : IntelliTect

protected ActionResult IndexImplementation(bool editable, string viewName = "~/Views/Api/Table.cshtml")
        {
            ViewBag.Editable = editable;
            ViewBag.Query = "";
            string[] pageParams = { "page", "pageSize", "search", "orderBy", "orderByDescending" };
            foreach (var kvp in Request.Query.Where( kvp => !pageParams.Contains(kvp.Key, StringComparer.InvariantCultureIgnoreCase) ))
            {
                ViewBag.Query = ViewBag.Query + WebUtility.UrlEncode(kvp.Key) + "=" + WebUtility.UrlEncode(kvp.Value) + "&";
            }
            ViewBag.Query = ViewBag.Query == "" ? null : new HtmlString( ViewBag.Query );

            @ViewBag.replacedle = ClreplacedViewModel.DisplayName + " List";

            return View(viewName, ClreplacedViewModel);
        }

19 View Source File : AuthorizeRequest.cs
License : Apache License 2.0
Project Creator : intuit

public string Create(IDictionary<string, string> values)
        {
            var qs = string.Join("&", values.Select(kvp => string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray());

            if (_authorizeEndpoint.IsAbsoluteUri)
            {

                return string.Format("{0}?{1}", _authorizeEndpoint.AbsoluteUri, qs);
            }
            else
            {
                return string.Format("{0}?{1}", _authorizeEndpoint.OriginalString, qs);
            }
          
        }

19 View Source File : UrlBuilder.cs
License : MIT License
Project Creator : jamesbrindle

public string CreateSearchUrl(string enreplacedy, string query, int limit, int offset)
        {
            query = WebUtility.UrlEncode(query);

            return string.Format(SearchTemplate, enreplacedy, query, limit, offset);
        }

19 View Source File : RmCloudDataSource.cs
License : MIT License
Project Creator : jamesf91

public async Task<RmDownloadedDoc> DownloadDoreplacedent(RmItem item)
        {
            if (!_initialized)
            {
                await Initialize();
            }

            if (item.Type != RmItem.DoreplacedentType)
            {
                Console.WriteLine($"RmCloudDataSource::DownloadDoreplacedent() - item with id {item.ID} is not doreplacedent type");
                return null;

            }

            try
            {
                // first get the blob url
                string url = $"/doreplacedent-storage/json/2/docs?doc={WebUtility.UrlEncode(item.ID)}&withBlob=true";
                HttpResponseMessage response = await Request(HttpMethod.Get, url, null, null);
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine("RmCloudDataSource::DownloadDoreplacedent() -  request failed with status code " + response.StatusCode.ToString());
                    return null;
                }
                List<RmItem> items = JsonSerializer.Deserialize<List<RmItem>>(response.Content.ReadreplacedtringAsync().Result);
                if (items.Count == 0)
                {
                    Console.WriteLine("RmCloudDataSource::DownloadDoreplacedent() - Failed to find doreplacedent with id: " + item.ID);
                    return null;
                }
                string blobUrl = items[0].BlobURLGet;
                Stream stream = await _client.GetStreamAsync(blobUrl);
                ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read);

                return new RmCloudDownloadedDoc(archive, item.ID);
            }
            catch (Exception err)
            {
                Console.WriteLine($"RmCloud::DownloadDoreplacedent() - failed for id {item.ID}. Error: {err.Message}");
                return null;
            }

        }

19 View Source File : AzureAdAuthMiddleware.cs
License : MIT License
Project Creator : jamesemann

public async Task OnTurn(ITurnContext context, MiddlewareSet.NextDelegate next)
        {
            var authToken = TokenStorage.LoadConfiguration(context.Activity.Conversation.Id);

            if (authToken == null)
            {
                if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation())
                {
                    var conversationReference = TurnContext.GetConversationReference(context.Activity);

                    var serializedCookie = WebUtility.UrlEncode(JsonConvert.SerializeObject(conversationReference));

                    var signInUrl = AzureAdExtensions.GetUserConsentLoginUrl(AzureAdTenant, AppClientId, AppRedirectUri, PermissionsRequested, serializedCookie);

                    var activity = context.Activity.CreateReply();
                    activity.AddSignInCard(signInUrl);

                    await context.SendActivity(activity);
                }
            }
            else if (authToken.ExpiresIn < DateTime.Now.AddMinutes(-10))
            {
                if (context.Activity.UserHasJustSentMessage() || context.Activity.UserHasJustJoinedConversation())
                {
                    var client = new HttpClient();
                    var accessToken = await AzureAdExtensions.GetAccessTokenUsingRefreshToken(client, AzureAdTenant, authToken.RefreshToken, AppClientId, AppRedirectUri, AppClientSecret, PermissionsRequested);

                    // have to save it
                    authToken = new ConversationAuthToken(context.Activity.Conversation.Id)
                    {
                        AccessToken = accessToken.accessToken,
                        RefreshToken = accessToken.refreshToken,
                        ExpiresIn = accessToken.refreshTokenExpiresIn
                    };
                    TokenStorage.SaveConfiguration(authToken);

                    // make the authtoken available to downstream pipeline components
                    context.Services.Add(AUTH_TOKEN_KEY, authToken);
                    await next();
                }
            }
            else
            {
                // make the authtoken available to downstream pipeline components
                context.Services.Add(AUTH_TOKEN_KEY, authToken);
                await next();
            }
        }

19 View Source File : RemoteConfigurationProvider.cs
License : MIT License
Project Creator : jamespratt

private async Task<IDictionary<string, string>> RequestConfigurationAsync()
        {
            var encodedConfigurationName = WebUtility.UrlEncode(_source.ConfigurationName);

            _logger.LogInformation("Requesting remote configuration {ConfigurationName} from {BaseAddress}.", _source.ConfigurationName, HttpClient.BaseAddress);

            try
            {
                using (var response = await HttpClient.GetAsync(encodedConfigurationName).ConfigureAwait(false))
                {
                    _logger.LogInformation("Received response status code {StatusCode} from endpoint for configuration '{ConfigurationName}'.",
                        response.StatusCode, _source.ConfigurationName);

                    if (response.IsSuccessStatusCode)
                    {
                        using (var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false))
                        {
                            _logger.LogInformation("Parsing remote configuration response stream ({Length:N0} bytes) for configuration '{ConfigurationName}'.",
                                stream.Length, _source.ConfigurationName);

                            Hash = ComputeHash(stream);
                            _logger.LogInformation("Computed hash for Configuration '{ConfigurationName}' is {Hash}.", _source.ConfigurationName, Hash);

                            stream.Position = 0;
                            var data = _parser.Parse(stream);

                            _logger.LogInformation("Configuration updated for '{ConfigurationName}'.", _source.ConfigurationName);

                            return data;
                        }
                    }

                    if (!_source.Optional)
                    {
                        throw new Exception($"Error calling remote configuration endpoint: {response.StatusCode} - {response.ReasonPhrase}");
                    }
                }
            }
            catch (Exception)
            {
                if (!_source.Optional)
                {
                    throw;
                }
            }

            return null;
        }

19 View Source File : Helper.cs
License : MIT License
Project Creator : jefersonsv

public static string EncodeID(string unencodedID)
        {
            return System.Net.WebUtility.UrlEncode(unencodedID);
        }

19 View Source File : LibraryController.cs
License : GNU General Public License v2.0
Project Creator : jellyfin

[HttpGet("Items/{itemId}/Download")]
        [Authorize(Policy = Policies.Download)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesFile("video/*", "audio/*")]
        public async Task<ActionResult> GetDownload([FromRoute, Required] Guid itemId)
        {
            var item = _libraryManager.GereplacedemById(itemId);
            if (item == null)
            {
                return NotFound();
            }

            var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);

            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");
                }
            }

            if (user != null)
            {
                await LogDownloadAsync(item, user, auth).ConfigureAwait(false);
            }

            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, StringComparison.Ordinal);
            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
                    filename = WebUtility.UrlEncode(filename);
                }
            }

            // TODO determine non-ASCII validity.
            return PhysicalFile(path, MimeTypes.GetMimeType(path), filename, true);
        }

19 View Source File : MusicBrainzAlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : jellyfin

public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
        {
            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, StringComparison.Ordinal);

                    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);
                await using var stream = await response.Content.ReadreplacedtreamAsync(cancellationToken).ConfigureAwait(false);
                return GetResultsFromResponse(stream);
            }

            return Enumerable.Empty<RemoteSearchResult>();
        }

19 View Source File : MusicBrainzArtistProvider.cs
License : GNU General Public License v2.0
Project Creator : jellyfin

private static string UrlEncode(string name)
        {
            return WebUtility.UrlEncode(name);
        }

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

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

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

            var urlQuery = "plot=full&r=json";
            if (type == "episode" && episodeSearchInfo != null)
            {
                episodeSearchInfo.SeriesProviderIds.TryGetValue(MetadataProvider.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 ??= 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);

            using var response = await OmdbProvider.GetOmdbResponse(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);
            await using var stream = await response.Content.ReadreplacedtreamAsync(cancellationToken).ConfigureAwait(false);
            var resultList = new List<SearchResult>();

            if (isSearch)
            {
                var searchResultList = await JsonSerializer.DeserializeAsync<SearchResultList>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
                if (searchResultList != null && searchResultList.Search != null)
                {
                    resultList.AddRange(searchResultList.Search);
                }
            }
            else
            {
                var result = await JsonSerializer.DeserializeAsync<SearchResult>(stream, _jsonOptions, cancellationToken).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(MetadataProvider.Imdb, result.imdbID);

                if (result.Year.Length > 0
                    && int.TryParse(result.Year.replacedpan().Slice(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 : MusicBrainzAlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : jellyfin

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);
            await using var stream = await response.Content.ReadreplacedtreamAsync(cancellationToken).ConfigureAwait(false);
            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 : MusicBrainzAlbumProvider.cs
License : GNU General Public License v2.0
Project Creator : jellyfin

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

            using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
            await using var stream = await response.Content.ReadreplacedtreamAsync(cancellationToken).ConfigureAwait(false);
            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 : GoogleBooksProvider.cs
License : MIT License
Project Creator : jellyfin

private async Task<SearchResult?> GetSearchResultsInternal(BookInfo item, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // pattern match the filename
            // year can be included for better results
            GetBookMetadata(item);

            var url = string.Format(GoogleApiUrls.SearchUrl, WebUtility.UrlEncode(item.Name), 0, 20);

            var httpClient = _httpClientFactory.CreateClient(NamedClient.Default);

            using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false);
            await using var stream = await response.Content.ReadreplacedtreamAsync(cancellationToken).ConfigureAwait(false);
            return await JsonSerializer.DeserializeAsync<SearchResult>(stream, JsonDefaults.Options, cancellationToken).ConfigureAwait(false);
        }

19 View Source File : TinyRestClient.cs
License : MIT License
Project Creator : jgiacomini

private Uri BuildRequestUri(string route, Dictionary<string, string> queryParameters)
        {
            var stringBuilder = new StringBuilder(string.Concat(_serverAddress, route));

            if (queryParameters != null && queryParameters.Any())
            {
                stringBuilder.Append("?");
                for (int i = 0; i < queryParameters.Count; i++)
                {
                    var item = queryParameters.ElementAt(i);
                    var separator = i == queryParameters.Count - 1 ? string.Empty : "&";
                    stringBuilder.Append($"{item.Key}={WebUtility.UrlEncode(item.Value)}{separator}");
                }
            }

            return new Uri(stringBuilder.ToString());
        }

19 View Source File : HuobiAuthenticationProvider.cs
License : MIT License
Project Creator : JKorf

internal Dictionary<string, object> SignRequest(
            string uri, 
            HttpMethod method, 
            Dictionary<string, object> parameters,
            string accessKeyName, 
            string methodName,
            string versionName,
            string timestampName,
            string signatureName,
            double signatureVersion)
        {
            if (Credentials.Key == null)
                throw new ArgumentException("ApiKey/secret not provided");

            var uriObj = new Uri(uri);
            var signParameters = new Dictionary<string, object>
            {
                { accessKeyName, Credentials.Key.GetString() },
                { methodName, "HmacSHA256" },
                { versionName, signatureVersion }
            };

            if (!parameters.ContainsKey(timestampName) || method != HttpMethod.Get)
                signParameters.Add(timestampName, DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss"));

            if (method == HttpMethod.Get)
            {
                foreach (var kvp in parameters)
                    signParameters.Add(kvp.Key, kvp.Value);
            }

            signParameters = signParameters.OrderBy(kv => Encoding.UTF8.GetBytes(WebUtility.UrlEncode(kv.Key)), new ByteOrderComparer()).ToDictionary(k => k.Key, k => k.Value);

            var paramString = signParameters.CreateParamString(true, ArrayParametersSerialization.MultipleValues);
            paramString = paramString.Replace("%2C", ".");

            signParameters = signParameters.OrderBy(kv => kv.Key).ToDictionary(k => k.Key, k => k.Value);

            var absolutePath = uriObj.AbsolutePath;
            if (absolutePath.StartsWith("/api"))
                // Russian api has /api prefix which shouldn't be part of the signature
                absolutePath = absolutePath.Substring(4);

            var signData = method + "\n";
            signData += uriObj.Host + "\n";
            signData += absolutePath + "\n";
            signData += paramString;
            byte[] signBytes;
            lock (encryptLock)
                signBytes = encryptor.ComputeHash(Encoding.UTF8.GetBytes(signData));
            signParameters.Add(signatureName, Convert.ToBase64String(signBytes));

            if (method != HttpMethod.Get)
            {
                foreach (var kvp in parameters)
                    signParameters.Add(kvp.Key, kvp.Value);
            }

            return signParameters;
        }

19 View Source File : GogApiClient.cs
License : MIT License
Project Creator : JosefNemec

public List<StoreGamesFilteredListResponse.Product> GetStoreSearch(string searchTerm)
        {
            var baseUrl = @"https://www.gog.com/games/ajax/filtered?limit=20&search={0}";
            var url = string.Format(baseUrl, WebUtility.UrlEncode(searchTerm));

            try
            {
                var stringData = HttpDownloader.DownloadString(url);
                return Serialization.FromJson<StoreGamesFilteredListResponse>(stringData)?.products;
            }
            catch (WebException exc)
            {
                logger.Warn(exc, "Failed to get GOG store search data for " + searchTerm);
                return null;
            }
        }

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

private static string ObjectToQueryString(object foo)
        {
            var properties = from p in foo.GetType().GetProperties()
                where p.GetValue(foo, null) != null
                select p.Name + "=" + WebUtility.UrlEncode(p.GetValue(foo, null).ToString());

            return string.Join("&", properties.ToArray());
        }

19 View Source File : ObjectStorageS3Service.cs
License : Apache License 2.0
Project Creator : KAMONOHASHI

public Uri GetMultiPartSignatureUrl(string key, string uploadId, int partNumber)
        {
            // 今はここは v2 でやっている。
            // v4 対応する場合、クライアントからリクエストボディのハッシュ値を計算
            // するなどしないといけない。
            // --------
            // v2 でやるにしてもクライアントライブラリをつかって
            // 本当はこんな感じでやりたいが、できないらしい。
            // JS とかだとできるっぽいけど。
            // https://github.com/aws/aws-sdk-js/issues/468
            // https://stackoverflow.com/questions/20847196/amazon-s3-multipart-upload-using-query-string-authentication-and-net-sdk
            // 
            // var presignedRequest = new GetPreSignedUrlRequest()
            // {
            //     Protocol = Protocol.HTTP,
            //     BucketName = bucket,
            //     Key = key,
            //     ContentType = "application/x-www-form-urlencoded",
            //     Verb = HttpVerb.PUT,
            //     Expires = DateTime.Now.AddSeconds(options.PreSignedUrlExpirationSec)
            // };
            // presignedRequest.Parameters.Add("uploadId", WebUtility.UrlEncode(uploadId));
            // presignedRequest.Parameters.Add("partNumber", WebUtility.UrlEncode(Convert.ToString(partNumber)));
            // var presignedResponse = client.GetPreSignedURL(presignedRequest);
            // return new Uri(presignedResponse);
            // --
            // 仕方がないので、三橋氏がWebから拾ってきた以下のソースコードを改変して使っている
            // http://gauravmantri.com/2014/01/06/create-pre-signed-url-using-c-for-uploading-large-files-in-amazon-s3/

            DateTime expiryDate = DateTime.UtcNow.AddSeconds(this.options.PreSignedUrlExpirationSec);
            DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan ts = new TimeSpan(expiryDate.Ticks - Jan1st1970.Ticks);
            var expiry = Convert.ToInt64(ts.TotalSeconds);
            var requestUrl = $"{this.client.Config.ServiceURL}{bucket}/{key}";
            var partUploadUrl = new Uri($"{requestUrl}?uploadId={WebUtility.UrlEncode(uploadId)}&partNumber={partNumber}");
            var content = "application/x-www-form-urlencoded";
            var stringToSign = GetStringToSign(partUploadUrl, "PUT", string.Empty, content, expiry, null);
            var partUploadSignature = CreateSignature(secretKey, stringToSign);
            var partUploadPreSignedUrl = new Uri(
                $"{requestUrl}?uploadId={WebUtility.UrlEncode(uploadId)}&partNumber={partNumber}&" +
                $"AWSAccessKeyId={this.accessKey}&Signature={WebUtility.UrlEncode(partUploadSignature)}&Expires={expiry}");
            return partUploadPreSignedUrl;
        }

19 View Source File : FinnhubClient.cs
License : Apache License 2.0
Project Creator : KevWK314

private string CreateParameters(Field[] fields)
        {
            if (string.IsNullOrEmpty(_config.ApiKey)) throw new InvalidOperationException("ApiKey not set");

            var parameters = string.Join("&", fields.Select(f => $"{f.Key}={WebUtility.UrlEncode(f.Value)}"));
            parameters = string.IsNullOrEmpty(parameters) ?
                string.Empty : "&" + parameters;

            return $"token={_config.ApiKey}{parameters}";
        }

19 View Source File : DanbooruUtility.cs
License : MIT License
Project Creator : KichangKim

public static string GetPostsUrl(long startId)
        {
            string query = $"id:>={startId} order:id_asc";
            string urlEncodedQuery = WebUtility.UrlEncode(query);
            return $"https://danbooru.donmai.us/posts.json?tags={urlEncodedQuery}&page=1&limit=1000";
        }

See More Examples