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 : HtmlFactory.cs
License : MIT License
Project Creator : KirillOsenkov

public static string UrlEncode(string text)
        {
            return WebUtility.UrlEncode(text);
        }

19 View Source File : ChromeScreenShotHelper.cs
License : MIT License
Project Creator : Kooboo

public static string GetScreenShot(string url, int width = 600, int height =450)
        {
            url = System.Net.WebUtility.UrlEncode(url);
            var nodeScreenShotUrl = string.Format("{0}?url={1}&width={2}&height={3}", Data.AppSettings.ScreenShotUrl, url, width, height);
            try
            {
                var base64Image = HttpHelper.Get<string>(nodeScreenShotUrl);
                base64Image = GetThumbnailImage(base64Image, new ImageSize() {Width = width, Height = height});
                // should verify as base64 here.. 
                return base64Image;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }

        }

19 View Source File : IsThereAnyDealApi.cs
License : MIT License
Project Creator : Lacro59

public PlainData GetPlain(string replacedle, bool isSecond = false)
        {
            PlainData plainData = new PlainData();
            try
            {
                string url = baseAddress + $"v02/game/plain/?key={key}&replacedle={WebUtility.UrlEncode(WebUtility.HtmlDecode(replacedle))}";
#if DEBUG
                logger.Debug($"IsThereAnyDeal - GetPlain({replacedle}) - url: {url}");
#endif
                string responseData = string.Empty;
                try
                {
                    responseData = Web.DownloadStringData(url).GetAwaiter().GetResult();
                }
                catch (Exception ex)
                {
                    Common.LogError(ex, false, $"Failed to download {url}");
                }

                ItadPlain itadPlain = Serialization.FromJson<ItadPlain>(responseData);
                if (itadPlain.Meta.Match != "false")
                {
                    plainData.Plain = itadPlain.data?["plain"];
                    plainData.IsActive = itadPlain.Meta.Active;
                }
                else
                {
                    logger.Warn($"IsThereAnyDeal - not find for {WebUtility.HtmlDecode(replacedle)}");
                }
            }
            catch (Exception ex)
            {
                Common.LogError(ex, false, $"Error in GetPlain({WebUtility.HtmlDecode(replacedle)})");
            }

            if (!isSecond && plainData.Plain.IsNullOrEmpty())
            {
                plainData = GetPlain(replacedle.Split('-')[0].Trim(), true);
            }

            return plainData;
        }

19 View Source File : ExophaseAchievements.cs
License : MIT License
Project Creator : Lacro59

public List<SearchResult> SearchGame(string Name)
        {
            List<SearchResult> ListSearchGames = new List<SearchResult>();

            try
            {
                string UrlSearch = string.Format(UrlExophaseSearch, WebUtility.UrlEncode(Name));

                string StringJsonResult = Web.DownloadStringData(UrlSearch).GetAwaiter().GetResult();
                if (StringJsonResult == "{\"success\":true,\"games\":false}")
                {
                    logger.Warn($"No Exophase result for {Name}");
                    return ListSearchGames;
                }

                ExophaseSearchResult exophaseScheachResult = Serialization.FromJson<ExophaseSearchResult>(StringJsonResult);

                var ListExophase = exophaseScheachResult?.games?.list;
                if (ListExophase != null)
                {
                    ListSearchGames = ListExophase.Select(x => new SearchResult
                    {
                        Url = x.endpoint_awards,
                        Name = x.replacedle,
                        UrlImage = x.images.o,
                        Platforms = x.platforms.Select(p => p.name).ToList(),
                        AchievementsCount = x.total_awards
                    }).ToList();
                }
            }
            catch (Exception ex)
            {
                Common.LogError(ex, false, true, "SuccessStory");
            }

            return ListSearchGames;
        }

19 View Source File : TrueAchievements.cs
License : MIT License
Project Creator : Lacro59

public static List<TrueAchievementSearch> SearchGame(Game game, OriginData originData)
        {
            List<TrueAchievementSearch> ListSearchGames = new List<TrueAchievementSearch>();
            string Url;
            string UrlBase;
            if (originData == OriginData.Steam)
            {
                //TODO: Decide if editions should be removed here
                Url = string.Format(SteamUrlSearch, WebUtility.UrlEncode(PlayniteTools.NormalizeGameName(game.Name, true)));
                UrlBase = @"https://truesteamachievements.com";
            }
            else
            {
                //TODO: Decide if editions should be removed here
                Url = string.Format(XboxUrlSearch, WebUtility.UrlEncode(PlayniteTools.NormalizeGameName(game.Name, true)));
                UrlBase = @"https://www.trueachievements.com";
            }


            try
            {
                string WebData = Web.DownloadStringData(Url).GetAwaiter().GetResult();
                if (WebData.IsNullOrEmpty())
                {
                    logger.Warn($"No data from {Url}");
                    return ListSearchGames;
                }

                HtmlParser parser = new HtmlParser();
                IHtmlDoreplacedent htmlDoreplacedent = parser.Parse(WebData);

                if (WebData.IndexOf("There are no matching search results, please change your search terms") > -1)
                {
                    return ListSearchGames;
                }

                var SectionGames = htmlDoreplacedent.QuerySelector("#oSearchResults");

                if (SectionGames == null)
                {
                    string GameUrl = htmlDoreplacedent.QuerySelector("link[rel=\"canonical\"]")?.GetAttribute("href");
                    string GameImage = htmlDoreplacedent.QuerySelector("div.info img")?.GetAttribute("src");

                    ListSearchGames.Add(new TrueAchievementSearch
                    {
                        GameUrl = GameUrl,
                        GameName = game.Name,
                        GameImage = GameImage
                    });
                }
                else
                {
                    foreach (var SearchGame in SectionGames.QuerySelectorAll("tr"))
                    {
                        try
                        {
                            var GameInfos = SearchGame.QuerySelectorAll("td");
                            if (GameInfos.Count() > 2)
                            {
                                string GameUrl = UrlBase + GameInfos[0].QuerySelector("a")?.GetAttribute("href");
                                string GameName = GameInfos[1].QuerySelector("a")?.InnerHtml;
                                string GameImage = UrlBase + GameInfos[0].QuerySelector("a img")?.GetAttribute("src");

                                string ItemType = GameInfos[2].InnerHtml;

                                if (ItemType.IsEqual("game"))
                                {
                                    ListSearchGames.Add(new TrueAchievementSearch
                                    {
                                        GameUrl = GameUrl,
                                        GameName = GameName,
                                        GameImage = GameImage
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Common.LogError(ex, false, true, "SuccessStory");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogError(ex, false, true, "SuccessStory");
            }

            return ListSearchGames;
        }

19 View Source File : PCGamingWikiRequierements.cs
License : MIT License
Project Creator : Lacro59

private string FindGoodUrl(Game game, int SteamId = 0)
        {
            string url = string.Empty;
            string urlMatch = string.Empty;
            string WebResponse = string.Empty;

            if (SteamId != 0)
            {
                url = string.Format(UrlSteamId, SteamId);

                Thread.Sleep(1000);
                WebResponse = Web.DownloadStringData(url).GetAwaiter().GetResult();
                if (!WebResponse.ToLower().Contains("search results"))
                {
                    return url;
                }
            }


            url = string.Empty;
            if (game.Links != null)
            {
                foreach (Link link in game.Links)
                {
                    if (link.Url.ToLower().Contains("pcgamingwiki"))
                    {
                        url = link.Url;

                        if (url.Contains(@"http://pcgamingwiki.com/w/index.php?search="))
                        {
                            url = UrlPCGamingWikiSearch + WebUtility.UrlEncode(url.Replace(@"http://pcgamingwiki.com/w/index.php?search=", string.Empty));
                        }
                        if (url.Length == UrlPCGamingWikiSearch.Length)
                        {
                            url = string.Empty;
                        }
                    }
                }

                if (!url.IsNullOrEmpty())
                {
                    Thread.Sleep(1000);
                    WebResponse = Web.DownloadStringData(url).GetAwaiter().GetResult();
                    if (!WebResponse.ToLower().Contains("search results"))
                    {
                        return url;
                    }
                    else
                    {
                        urlMatch = GetUrlIsOneResult(WebResponse);
                        if (!urlMatch.IsNullOrEmpty())
                        {
                            return urlMatch;
                        }
                    }
                }
            }


            string Name = Regex.Replace(game.Name, @"([ ]demo\b)", string.Empty, RegexOptions.IgnoreCase);
            Name = Regex.Replace(Name, @"(demo[ ])", string.Empty, RegexOptions.IgnoreCase);
            Name = CommonPluginsShared.PlayniteTools.NormalizeGameName(Name);

            url = string.Empty;
            url = UrlPCGamingWikiSearch + WebUtility.UrlEncode(Name);

            Thread.Sleep(1000);
            WebResponse = Web.DownloadStringData(url).GetAwaiter().GetResult();
            if (!WebResponse.ToLower().Contains("search results"))
            {
                return url;
            }
            else
            {
                urlMatch = GetUrlIsOneResult(WebResponse);
                if (!urlMatch.IsNullOrEmpty())
                {
                    return urlMatch;
                }
            }


            url = string.Empty;
            url = UrlPCGamingWikiSearch + WebUtility.UrlEncode(game.Name);

            Thread.Sleep(1000);
            WebResponse = Web.DownloadStringData(url).GetAwaiter().GetResult();
            if (!WebResponse.ToLower().Contains("search results"))
            {
                return url;
            }
            else
            {
                urlMatch = GetUrlIsOneResult(WebResponse);
                if (!urlMatch.IsNullOrEmpty())
                {
                    return urlMatch;
                }
            }


            return string.Empty;
        }

19 View Source File : WebTool.cs
License : GNU General Public License v3.0
Project Creator : LeaFrock

public static string UrlEncodeByW3C(string text)
		{
			return WebUtility.UrlEncode(text);
		}

19 View Source File : WeatherOutputFormatter.cs
License : MIT License
Project Creator : lianggx

private string WriterText(WeatherForecast weather) => $"date={WebUtility.UrlEncode(weather.Date.ToString())}&temperatureC={weather.TemperatureC}&temperatureF={weather.TemperatureF}&summary={WebUtility.UrlEncode(weather.Summary)}";

19 View Source File : Warshipgirls.cs
License : MIT License
Project Creator : lone-wolf-akela

public void boat_renameship(int shipid, string newname)
        {
            JsonText Res = CreateJsonText(StdGetRequest($"boat/renameShip/{shipid}/{WebUtility.UrlEncode(newname)}/"));
            //TODO:更新数据
        }

19 View Source File : BaseControllerTests.cs
License : MIT License
Project Creator : luoyunchong

public string ToParams(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }

19 View Source File : CustomNotificationHubClient.cs
License : MIT License
Project Creator : LykkeCity

public async Task SendNotification(string payload, Dictionary<string, string> headers)
        {
            var request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";

            var epochTime = (long)(DateTime.UtcNow - new DateTime(1970, 01, 01)).TotalSeconds;
            var expiry = epochTime + (long)TimeSpan.FromHours(1).TotalSeconds;

            var encodedUrl = WebUtility.UrlEncode(_url);
            var stringToSign = encodedUrl + "\n" + expiry;
            var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_sharedAccessKey));

            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            var sasToken = $"SharedAccessSignature sr={encodedUrl}&sig={WebUtility.UrlEncode(signature)}&se={expiry}&skn={_sharedAccessKeyName}";

            request.Headers[HttpRequestHeader.Authorization] = sasToken;

            foreach (var header in headers)
                request.Headers[header.Key] = header.Value;

            using (var stream = await request.GetRequestStreamAsync())
            using (var streamWriter = new StreamWriter(stream))
            {
                streamWriter.Write(payload);
                streamWriter.Flush();
            }

            await request.GetResponseAsync();
        }

19 View Source File : EncoderUtil.cs
License : MIT License
Project Creator : lysilver

public static string WebUrlEncode(string str)
        {
            return WebUtility.UrlEncode(str);
        }

19 View Source File : MFWSVaultValueListItemOperations.cs
License : MIT License
Project Creator : M-Files

public async Task<Results<ValueLisreplacedem>> GetValueLisreplacedemsAsync(int valueListId, string nameFilter = null, CancellationToken token = default(CancellationToken), int limit = 0)
		{
			// Create the request.
			var request = new RestRequest($"/REST/valuelists/{valueListId}/items");

			// Filter by name?
			var querySeperator = "?";
			if (false == string.IsNullOrWhiteSpace(nameFilter))
			{
				request.Resource += "?filter=" + WebUtility.UrlEncode(nameFilter);
				querySeperator = "&";
			}

			if (limit > 0)
			{
				request.Resource += $"{querySeperator}limit={limit.ToString()}";
			}

			// Make the request and get the response.
			var response = await this.MFWSClient.Get<Results<ValueLisreplacedem>>(request, token)
				.ConfigureAwait(false);

			// Return the data.
			return response.Data;
		}

19 View Source File : MFWSVaultObjectSearchOperations.cs
License : MIT License
Project Creator : M-Files

public async Task<ObjectVersion[]> SearchForObjectsByConditionsAsync(CancellationToken token, int limit, params ISearchCondition[] searchConditions)
		{
			// Sanity.
			if (null == searchConditions)
				throw new ArgumentNullException(nameof(searchConditions));

			// Create the request.
			var request = new RestRequest("/REST/objects");

			// Append the conditions.
			request.Resource += "?";
			foreach (var searchCondition in searchConditions)
			{
				// Sanity.
				if (null == searchCondition)
					continue;

				// Build up the search condition as detailed at http://www.m-files.com/mfws/syntax.html#sect:search-encoding

				// Add on the expression.
				request.Resource += WebUtility.UrlEncode(searchCondition.Expression);

				// Add the operator (parsed from the enumerated value).
				request.Resource += this.GetSearchConditionOperator(searchCondition);

				// Add the value.  Handle the null special-case.
				request.Resource += null == searchCondition.EncodedValue ? "%00" : WebUtility.UrlEncode(searchCondition.EncodedValue);

				// We need to separate conditions with ampersands.
				request.Resource += "&";
			}

			// by default, the limit will be 500, when 0 it will be unlimited.
			if (limit > defaultSearchLimit)
			{
				request.Resource += $"limit={limit}";
			}

			// Strip last ampersand if needed.
			if (request.Resource.EndsWith("&"))
				request.Resource = request.Resource.Substring(0, request.Resource.Length - 1);

			// Strip last "?" if needed.
			if (request.Resource.EndsWith("?"))
				request.Resource = request.Resource.Substring(0, request.Resource.Length - 1);

			// Make the request and get the response.
			var response = await this.MFWSClient.Get<Results<ObjectVersion>>(request, token)
				.ConfigureAwait(false);

			// Return the data.
			return response.Data?.Items?.ToArray();
		}

19 View Source File : MFWSStructs.cs
License : MIT License
Project Creator : M-Files

public void GetUriParameters(out int objectTypeId, out string objectId)
		{
			// This one is easy.
			objectTypeId = this.Type;

			// If it has an internal ID then use that.
			// NOTE: We currently only support unmanaged doreplacedents, so we can short-cut if it's not a doreplacedent.
			if (this.ID > 0 || this.Type != 0)
			{
				objectId = this.ID.ToString();
				return;
			}

			// If the external repository name or object ID are blank then throw.
			if (string.IsNullOrWhiteSpace(this.ExternalRepositoryName)
				|| string.IsNullOrWhiteSpace(this.ExternalRepositoryObjectID))
			{
				throw new InvalidOperationException("The ObjID has neither an internal ID nor external repository data.");
			}

			// The object ID is:
			//		The letter "u",
			//		The external repository name (URI-encoded),
			//		The character ":",
			//		The external repository object ID (URI-encoded).
			//	This entire string is then URI-encoded again.
			objectId = WebUtility.UrlEncode("u"
											+ WebUtility.UrlEncode(this.ExternalRepositoryName)
											+ ":"
											+ WebUtility.UrlEncode(this.ExternalRepositoryObjectID));
		}

19 View Source File : FolderContentItemExtensionMethods.cs
License : MIT License
Project Creator : M-Files

public static string GetPath(this FolderContenreplacedem item)
		{
			// Sanity.
			if (null == item)
				return string.Empty;

			// The return value depends on the item type.
			// See: http://www.m-files.com/mfws/syntax.html
			switch (item.FolderContenreplacedemType)
			{
				case MFFolderContenreplacedemType.ExternalViewFolder:
					// NOTE: The string should be "u", followed by the URL-encoded external repository name, followed by a colon, followed by the URL-encoded view ID.
					// The entire string should then be URL-encoded a second time to ensure that it is preplaceded correctly.
					return WebUtility.UrlEncode($"u{WebUtility.UrlEncode(item.ExternalView.ExternalRepositoryName)}:{WebUtility.UrlEncode(item.ExternalView.ID)}");
				case MFFolderContenreplacedemType.ViewFolder:
					return "v" + item.View.ID;
				case MFFolderContenreplacedemType.TraditionalFolder:
					return "y" + item.TraditionalFolder.Item;
				case MFFolderContenreplacedemType.PropertyFolder:
					{
						string prefix = null;
						string suffix = item.PropertyFolder.Value?.ToString();
						switch (item.PropertyFolder.DataType)
						{
							case MFDataType.Text:
								prefix = "T";
								break;
							case MFDataType.MultiLineText:
								prefix = "M";
								break;
							case MFDataType.Integer:
								prefix = "I";
								break;
							case MFDataType.Integer64:
								prefix = "J";
								break;
							case MFDataType.Floating:
								prefix = "R";
								break;
							case MFDataType.Date:
								prefix = "D";
								break;
							case MFDataType.Time:
								prefix = "C";
								break;
							case MFDataType.FILETIME:
								prefix = "E";
								break;
							case MFDataType.Lookup:
								prefix = "L";
								suffix = (item.PropertyFolder.Lookup?.Item ?? 0).ToString();
								break;
							case MFDataType.MultiSelectLookup:
								prefix = "S";
								suffix = String.Join(",", item.PropertyFolder.Lookups?.Select(l => l.Item) ?? new int[0]);
								break;
							case MFDataType.Uninitialized:
								prefix = "-";
								break;
							case MFDataType.ACL:
								prefix = "A";
								break;
							case MFDataType.Boolean:
								prefix = "B";
								break;
						}

						// Sanity.
						if (null == prefix || null == suffix)
							return null;

						// Return the formatted value.
						return $"{prefix}{WebUtility.UrlEncode(suffix)}";
					}
				default:
					return null;
			}

		}

19 View Source File : FolderContentItemExtensionMethods.cs
License : MIT License
Project Creator : M-Files

public static string GetPath(this FolderContenreplacedem item)
		{
			// Sanity.
			if (null == item)
				return string.Empty;

			// The return value depends on the item type.
			// See: http://www.m-files.com/mfws/syntax.html
			switch (item.FolderContenreplacedemType)
			{
				case MFFolderContenreplacedemType.ExternalViewFolder:
					// NOTE: The string should be "u", followed by the URL-encoded external repository name, followed by a colon, followed by the URL-encoded view ID.
					// The entire string should then be URL-encoded a second time to ensure that it is preplaceded correctly.
					return WebUtility.UrlEncode($"u{WebUtility.UrlEncode(item.ExternalView.ExternalRepositoryName)}:{WebUtility.UrlEncode(item.ExternalView.ID)}");
				case MFFolderContenreplacedemType.ViewFolder:
					return "v" + item.View.ID;
				case MFFolderContenreplacedemType.TraditionalFolder:
					return "y" + item.TraditionalFolder.Item;
				case MFFolderContenreplacedemType.PropertyFolder:
					{
						string prefix = null;
						string suffix = item.PropertyFolder.Value?.ToString();
						switch (item.PropertyFolder.DataType)
						{
							case MFDataType.Text:
								prefix = "T";
								break;
							case MFDataType.MultiLineText:
								prefix = "M";
								break;
							case MFDataType.Integer:
								prefix = "I";
								break;
							case MFDataType.Integer64:
								prefix = "J";
								break;
							case MFDataType.Floating:
								prefix = "R";
								break;
							case MFDataType.Date:
								prefix = "D";
								break;
							case MFDataType.Time:
								prefix = "C";
								break;
							case MFDataType.FILETIME:
								prefix = "E";
								break;
							case MFDataType.Lookup:
								prefix = "L";
								suffix = (item.PropertyFolder.Lookup?.Item ?? 0).ToString();
								break;
							case MFDataType.MultiSelectLookup:
								prefix = "S";
								suffix = String.Join(",", item.PropertyFolder.Lookups?.Select(l => l.Item) ?? new int[0]);
								break;
							case MFDataType.Uninitialized:
								prefix = "-";
								break;
							case MFDataType.ACL:
								prefix = "A";
								break;
							case MFDataType.Boolean:
								prefix = "B";
								break;
						}

						// Sanity.
						if (null == prefix || null == suffix)
							return null;

						// Return the formatted value.
						return $"{prefix}{WebUtility.UrlEncode(suffix)}";
					}
				default:
					return null;
			}

		}

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : M-Files

private void ExpandTreeViewItem(TreeViewItem parent, string folder = null)
		{
			// Sanity.
			if (null == parent)
				return;
			folder = folder ?? "";

			// Remove anything including the "loading" item.
			parent.Items.Clear();

			this.Dispatcher.BeginInvoke(new Action(() =>
			{
				if (false == folder.EndsWith("/"))
					folder = folder + "/";

				// Get the items within the selected view.
				var response = this.client.Get<FolderContenreplacedems>(new RestRequest($"/REST/views{folder}items"));

				// Get everything in the preplaceded location.
				foreach (var item in response.Data.Items)
				{
					// Get the folder defs to use for this node.
					var tag = folder;

					// Create the tree view item depending on the type of item we've got.
					// Note: a lot of this is taken from https://github.com/M-Files/Libraries.MFWSClient/blob/da22e931a34f13fe3cb35c692ea9fe7645fc0c20/MFaaP.MFWSClient/ExtensionMethods/FolderContenreplacedemExtensionMethods.cs#L73.
					var treeViewItem = new TreeViewItem();
					switch (item.FolderContenreplacedemType)
					{
						// Render views.
						case MFFolderContenreplacedemType.ViewFolder:
							{
								// Set up the folder def to go "into" this view.
								tag += "v" + item.View.ID;

								// Set the header to the view name.
								treeViewItem.Header = item.View.Name;
							}
							break;
						// Render property groups.
						case MFFolderContenreplacedemType.PropertyFolder:
							{
								// Set up the folder def to go "into" this grouping.
								string prefix = null;
								string suffix = item.PropertyFolder.Value?.ToString();
								switch (item.PropertyFolder.DataType)
								{
									case MFDataType.Text:
										prefix = "T";
										break;
									case MFDataType.MultiLineText:
										prefix = "M";
										break;
									case MFDataType.Integer:
										prefix = "I";
										break;
									case MFDataType.Integer64:
										prefix = "J";
										break;
									case MFDataType.Floating:
										prefix = "R";
										break;
									case MFDataType.Date:
										prefix = "D";
										break;
									case MFDataType.Time:
										prefix = "C";
										break;
									case MFDataType.FILETIME:
										prefix = "E";
										break;
									case MFDataType.Lookup:
										prefix = "L";
										suffix = (item.PropertyFolder.Lookup?.Item ?? 0).ToString();
										break;
									case MFDataType.MultiSelectLookup:
										prefix = "S";
										suffix = String.Join(",", item.PropertyFolder.Lookups?.Select(l => l.Item) ?? new int[0]);
										break;
									case MFDataType.Uninitialized:
										prefix = "-";
										break;
									case MFDataType.ACL:
										prefix = "A";
										break;
									case MFDataType.Boolean:
										prefix = "B";
										break;
								}

								// Return the formatted value.
								tag += $"{prefix}{WebUtility.UrlEncode(suffix)}";

								// Set the header to the grouping name.
								treeViewItem.Header = item.PropertyFolder.DisplayValue;
							}
							break;
						default:
							// We should also handle other types of content, but this will do for now.
							continue;
					}
					if (null == treeViewItem.Header)
						continue;

					// Set up the tag.
					treeViewItem.Tag = tag;

					// Add the item to the list.
					treeViewItem.Items.Add(new TreeViewItem() { Header = "Loading...", IsEnabled = false });
					treeViewItem.Expanded += TreeViewItem_Expanded;
					parent.Items.Add(treeViewItem);
				}
			}));
		}

19 View Source File : MFWSStructs.cs
License : MIT License
Project Creator : M-Files

public void GetUriParameters(out int objectTypeId, out string objectId, out string objectVersionId)
		{
			// Use the base implementation to get the type and object IDs.
			base.GetUriParameters(out objectTypeId, out objectId);
			
			// If it has an internal ID and is a doreplacedent then treat it as an M-Files object (promoted or native).
			if (this.ID > 0 || this.Type != 0)
			{
				// If we have a version then use it, otherwise return "latest".
				objectVersionId = this.Version > 0
					? this.Version.ToString()
					: "latest";
				return;
			}

			// If we don't have an external version then use latest.
			if (string.IsNullOrWhiteSpace(this.ExternalRepositoryObjectVersionID))
			{
				objectVersionId = "latest";
				return;
			}

			// The version ID is:
			//		The letter "u",
			//		The external object version ID (URI-encoded).
			//	This entire string is then URI-encoded again.
			objectVersionId = WebUtility.UrlEncode($"u{WebUtility.UrlEncode(this.ExternalRepositoryObjectVersionID)}");
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : M-Files

static async Task UseApiDirectly()
		{
			// Build the url to request (note to encode the query term).
			var url =
				new Uri("http://kb.cloudvault.m-files.com/REST/objects?q=" + System.Net.WebUtility.UrlEncode("automatic filling of properties"));

			// Build the request.
			var httpClient = new HttpClient();

			// Start the request.
			var responseBody = await httpClient.GetStringAsync(url);

			// Output the body.
			// System.Console.WriteLine($"Raw content returned: {responseBody}.");

			// Attempt to parse it.  For this we will use the Json.NET library, but you could use others.
			var results = JsonConvert.DeserializeObject<Results<ObjectVersion>>(responseBody);
			if (0 == results.Items.Count)
			{
				// Could not find the object.
				Console.WriteLine($"\tDoreplacedent not found.");
				return;
			}

			// Whilst the checkout status is available in the ObjectVersion directly,
			// let's retrieve it to show the standard call.
			// Get the checkout status.
			url = 
				new Uri($"http://kb.cloudvault.m-files.com/REST/objects/{results.Items[0].ObjVer.Type}/{results.Items[0].ObjVer.ID}/{results.Items[0].ObjVer.Version}/checkedout");
			responseBody = await httpClient.GetStringAsync(url);

			// Attempt to parse it.
			var checkoutStatus = JsonConvert.DeserializeObject<PrimitiveType<MFCheckOutStatus>>(responseBody);

			Console.WriteLine($"\tCheckout status is: {checkoutStatus.Value}");

		}

19 View Source File : MFWSStructs.cs
License : MIT License
Project Creator : M-Files

public void GetUriParameters(out string fileId, out string fileVersionId)
		{
			// If we have an internal ID then we will return internal data.
			if (this.ID > 0)
			{
				fileId = this.ID.ToString();
				fileVersionId = this.Version > 0
					? this.Version.ToString()
					: "latest";
				return;
			}

			// The file ID is:
			//		The letter "u",
			//		The external file ID (URI-encoded).
			//	This entire string is then URI-encoded again.
			fileId = WebUtility.UrlEncode($"u{WebUtility.UrlEncode(this.ExternalRepositoryFileID)}");

			// If we don't have an external version then use latest.
			if (string.IsNullOrWhiteSpace(this.ExternalRepositoryFileVersionID))
			{
				fileVersionId = "latest";
				return;
			}

			// The version ID is:
			//		The letter "u",
			//		The external file version ID (URI-encoded).
			//	This entire string is then URI-encoded again.
			fileVersionId = WebUtility.UrlEncode($"u{WebUtility.UrlEncode(this.ExternalRepositoryFileVersionID)}");

		}

19 View Source File : Program.cs
License : MIT License
Project Creator : M-Files

static async Task UseApiDirectly()
		{
			// Build the url to request (note to encode the query term).
			var url =
				new Uri("http://kb.cloudvault.m-files.com/REST/objects?q=" + System.Net.WebUtility.UrlEncode(Program.queryTerm));

			// Build the request.
			var httpClient = new HttpClient();

			// Start the request.
			string responseBody = await httpClient.GetStringAsync(url);
			
			// Output the body.
			// System.Console.WriteLine($"Raw content returned: {responseBody}.");

			// Attempt to parse it.  For this we will use the Json.NET library, but you could use others.
			var results = JsonConvert.DeserializeObject<Results<ObjectVersion>>(responseBody);

			// Iterate over the results and output them.
			Console.WriteLine($"There were {results.Items.Count} results returned.");
			foreach (var objectVersion in results.Items)
			{
				Console.WriteLine($"\t{objectVersion.replacedle}");
				Console.WriteLine($"\t\tType: {objectVersion.ObjVer.Type}, ID: {objectVersion.ObjVer.ID}");

				// Create a folder for the files to go in.
				var folderPath =
					new System.IO.DirectoryInfo(System.IO.Path.Combine(Program.downloadFolder, objectVersion.ObjVer.ID.ToString()));
				if (false == folderPath.Exists)
					folderPath.Create();

				// Download the files.
				foreach (var file in objectVersion.Files)
				{
					// Generate a unique file name.
					var fileName = System.IO.Path.Combine(folderPath.FullName, file.ID + "." + file.Extension);

					// Download the file data.
					var data = await
						httpClient.GetByteArrayAsync(
							$"http://kb.cloudvault.m-files.com/REST/objects/{objectVersion.ObjVer.Type}/{objectVersion.ObjVer.ID}/{objectVersion.ObjVer.Version}/files/{file.ID}/content");

					// Open a stream to the file.
					using (var stream = System.IO.File.OpenWrite(fileName))
					{
						// Save the content to disk.
						stream.Write(data, 0, data.Length);
					}

					// Log.
					Console.WriteLine($"\t\t\tFile: {file.Name} output to {fileName}");

				}
			}

		}

19 View Source File : Program.cs
License : MIT License
Project Creator : M-Files

static async Task UseApiDirectly()
		{
			// Build the url to request (note to encode the query term).
			var url =
				new Uri("http://kb.cloudvault.m-files.com/REST/objects?q=" + System.Net.WebUtility.UrlEncode(Program.queryTerm));

			// Build the request.
			var httpClient = new HttpClient();

			// Start the request.
			var responseBody = await httpClient.GetStringAsync(url);

			// Output the body.
			// System.Console.WriteLine($"Raw content returned: {responseBody}.");

			// Attempt to parse it.  For this we will use the Json.NET library, but you could use others.
			var results = JsonConvert.DeserializeObject<Results<ObjectVersion>>(responseBody);
			Console.WriteLine($"There were {results.Items.Count} results returned.");

			// Get the object property values (not necessary, but shows how to retrieve multiple sets of properties in one call).
			url = new Uri("http://kb.cloudvault.m-files.com/REST/objects/properties;"
				        + Program.GetObjVersString(results.Items.Select(r => r.ObjVer)));
			responseBody = await httpClient.GetStringAsync(url);
			var properties = JsonConvert.DeserializeObject<PropertyValue[][]>(responseBody);

			// Iterate over the results and output them.
			for (var i = 0; i < results.Items.Count; i++)
			{
				// Output the object version details.
				var objectVersion = results.Items[i];
				Console.WriteLine($"\t{objectVersion.replacedle}");
				Console.WriteLine($"\t\tType: {objectVersion.ObjVer.Type}, ID: {objectVersion.ObjVer.ID}");

				// Output the properties.
				var objectProperties = properties[i];
				foreach (var property in objectProperties)
				{
					Console.WriteLine($"\t\tProperty: {property.PropertyDef}, Value: {property.TypedValue.Value}");
				}
			}

		}

19 View Source File : ServiceBase.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

protected async Task<HttpResponseMessage> SendGetRequest(string endpoint, IEnumerable<KeyValuePair<string, string>> data)
        {
            using (var httpClient = new HttpClient())
            {
                string queryString = string.Join("&", data.Select(x => $"{WebUtility.UrlEncode(x.Key)}={WebUtility.UrlEncode(x.Value)}"));
                if (queryString.Length > 0)
                    queryString = "?" + queryString;
                
                httpClient.DefaultRequestHeaders.Add("Authorization", $"{accountId}.{token}");
                var response = await httpClient.GetAsync($"{Constants.ServerAddress}/{apiEndpoint}/{serviceEndpoint}/{endpoint}{queryString}", HttpCompletionOption.ResponseContentRead);

                return response;
            }
        }

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

private void WebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            browserLoading.Visibility = Visibility.Collapsed;
            webBrowser.Visibility = Visibility.Visible;

            if ((e.Uri.AbsolutePath.Contains("/v2/Graph/Welcome")) && (e.Uri.Query.Length > 12))
            {
                Page2.Visibility = Visibility.Collapsed;

                string id = e.Uri.Query.Substring(11);
                Debug.WriteLine($"Account Id is: {id}");

                Settings.Data.AccountId = id;
                Settings.Save();

                Page3.Visibility = Visibility.Visible;
            }

#if !DEBUG
            AutoMeasurement.Client.TrackEvent("SignInBrowser", "Navigated", System.Net.WebUtility.UrlEncode(e.Uri.OriginalString));
#endif
        }

19 View Source File : FileReceiver.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

private static async Task ReceiveFailed(string serverIP, string key, string message)
        {
            var httpClient = new HttpClient();

            try
            {
                await httpClient.GetAsync("http://" + serverIP + ":" + Constants.CommunicationPort.ToString() + "/" + key + "/finish/?success=false&message=" + System.Net.WebUtility.UrlEncode(message));
            }
            catch { }
        }

19 View Source File : Authorization.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

public static string GetAuthorizationUrl(string state)
        {
            return "https://accounts.spotify.com/authorize?"
                + $"client_id={WebUtility.UrlEncode(Secrets.SpotifyClientId)}&"
                + $"response_type=code&"
                + $"redirect_uri={WebUtility.UrlEncode(RedirectUri)}&"
                + $"state={WebUtility.UrlEncode(state)}&"
                + $"scope={WebUtility.UrlEncode(Scopes)}&"
                + $"show_dialog=false";
        }

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

protected override void OnActivated(IActivatedEventArgs e)
        {
            Frame rootFrame = InitRootFrame(e.PreviousExecutionState);

            // Handle toast activation
            if (e.Kind == ActivationKind.ToastNotification)
            {
                var toastActivationArgs = e as ToastNotificationActivatedEventArgs;

                logger.Info($"ToastActivation with argument '{toastActivationArgs.Argument}'.");

                // Parse the query string (using QueryString.NET)
                var args = new WwwFormUrlDecoder(toastActivationArgs.Argument);

                // See what action is being requested 
                switch (args.GetFirstValueByName("action"))
                {
                    // Open the image
                    case "reopenApp":
                        if (rootFrame.Content == null)
                        {
                            rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
                        }
                        break;
                }
            }
            else if (e.Kind == ActivationKind.Protocol)
            {
                var args = e as ProtocolActivatedEventArgs;
                var uri = args.Uri.ToString();
                var currentMainPage = (rootFrame.Content as MainPage);

                logger.Info($"ProtocolActivation with uri '{uri}'.");

                var targetPwaUri = SpotifyShareUriHelper.GetPwaUri(uri);

                if (string.IsNullOrWhiteSpace(targetPwaUri))
                {
                    // Invalid uri, will launch default page

                    if (currentMainPage == null)
                    {
                        // if MainPage is not opened, navigate to MainPage with the necessary argument
                        rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
                    }
                }
                else
                {
                    var argument = "pageUrl=" + WebUtility.UrlEncode(targetPwaUri);

                    if (uri.ToLower().StartsWith("spotify:nl:"))
                    {
                        var autoplay = targetPwaUri.ToLower().Contains("/track/") ? "track" : "playlist";
                        argument += "&autoplay=" + autoplay;
                        argument += "&source=cortana";
                    }

                    if (currentMainPage == null)
                    {
                        // if MainPage is not opened, navigate to MainPage with the necessary argument
                        rootFrame.Navigate(typeof(MainPage), argument);
                    }
                    else
                    {
                        // if MainPage is opened already, send a signal to it so it can navigate to the new url.
                        currentMainPage.NavigateWithConfig(argument);
                    }
                }
            }

            // TODO: Handle other types of activation

            // Ensure the current window is active
            Window.Current.Activate();
        }

19 View Source File : ServerIPFinder.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

public static async Task ReceiveRequest(Dictionary<string, object> request)
        {
            string interruptKey = "";
            FileReceiver2.InitHandshakerEvents();

            try
            {
                if (!request.ContainsKey("IPs"))
                    throw new Exception("Invalid request. (A)");
                if (!request.ContainsKey("DefaultMessage"))
                    throw new Exception("Invalid request. (B)");
                if (!request.ContainsKey("InterruptKey"))
                    throw new Exception("Invalid request. (C)");

                var expectedMessage = request["DefaultMessage"] as string;

                interruptKey = request["InterruptKey"] as string;

                var IPs = JsonConvert.DeserializeObject<List<string>>(request["IPs"] as string);

                List<Task<bool>> tasks = new List<Task<bool>>();

                foreach (var ip in IPs)
                    tasks.Add(CheckIP(ip, expectedMessage));

                var success = await tasks.LogicalAny();

                if (!success)
                    throw new Exception("Couldn't find the ip.");

                await NotifySender(senderIP, interruptKey, "success=true");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                if ((interruptKey != "") && (senderIP != ""))
                {
                    await NotifySender(senderIP, interruptKey, "success=false&message=" + System.Net.WebUtility.UrlEncode(ex.Message));
                }
                IPDetectionFailed?.Invoke();
            }
        }

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

public void OpenWebApp()
        {
            var destinationUrl = "https://open.spotify.com";
            var navigateUrl = initialLoadPageUrl + "redirectUrl=" + System.Net.WebUtility.UrlEncode(destinationUrl);

            OpenWebApp(navigateUrl);
        }

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

public void OpenWebApp(string targetUrl)
        {
            if (TokenHelper.HasTokens())
            {
                if (LocalConfiguration.ApiTokenVersion < 2)
                {
                    var authorizeUrl = Authorization.GetAuthorizationUrl(targetUrl);
                    Controller.Navigate(new Uri($"ms-appx-web:///replacedets/ReauthorizeForV2.html?theme={(ThemeHelper.GetCurrentTheme() == Theme.Light ? "light" : "dark")}&" +
                        $"redirectUri={System.Net.WebUtility.UrlEncode(authorizeUrl)}"));
                }
                else
                {
                    if (LocalConfiguration.IsLoggedInByFacebook)
                    {
                        // We need to open the login page and click on facebook button
                        logger.Info("Logging in via Facebook...");
                        var loginUrl = "https://accounts.spotify.com/login?continue=" + System.Net.WebUtility.UrlEncode(targetUrl);
                        Controller.Navigate(new Uri(loginUrl));
                    }
                    else
                    {
                        Controller.Navigate(new Uri(targetUrl));
                    }
                }
            }
            else
            {
                Authorize(targetUrl, clearExisting: false);
            }
        }

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

public void OpenWebApp(string targetUrl)
        {
            if (TokenHelper.HasTokens())
            {
                if (LocalConfiguration.ApiTokenVersion < 2)
                {
                    var authorizeUrl = Authorization.GetAuthorizationUrl(targetUrl);
                    Controller.Navigate(new Uri($"ms-appx-web:///replacedets/ReauthorizeForV2.html?theme={(ThemeHelper.GetCurrentTheme() == Theme.Light ? "light" : "dark")}&" +
                        $"redirectUri={System.Net.WebUtility.UrlEncode(authorizeUrl)}"));
                }
                else
                {
                    if (LocalConfiguration.IsLoggedInByFacebook)
                    {
                        // We need to open the login page and click on facebook button
                        logger.Info("Logging in via Facebook...");
                        var loginUrl = "https://accounts.spotify.com/login?continue=" + System.Net.WebUtility.UrlEncode(targetUrl);
                        Controller.Navigate(new Uri(loginUrl));
                    }
                    else
                    {
                        Controller.Navigate(new Uri(targetUrl));
                    }
                }
            }
            else
            {
                Authorize(targetUrl, clearExisting: false);
            }
        }

19 View Source File : Authorization.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

public static string GetAuthorizationUrl(string state)
        {
            return "https://accounts.spotify.com/authorize?"
                + $"client_id={WebUtility.UrlEncode(Secrets.SpotifyClientId)}&"
                + $"response_type=code&"
                + $"redirect_uri={WebUtility.UrlEncode(RedirectUri)}&"
                + $"state={WebUtility.UrlEncode(state)}&"
                + $"scope={WebUtility.UrlEncode(Scopes)}&"
                + $"show_dialog=false";
        }

19 View Source File : TileHelper.cs
License : GNU General Public License v3.0
Project Creator : MahdiGhiasi

public static async Task<bool> PinPageToStart(string pageUrl, string replacedle)
        {
            // TODO: Download and use album/artist/playlist image for tile, if applicable

            string tileId = Guid.NewGuid().ToString();

            string arguments = "pageUrl=" + WebUtility.UrlEncode(pageUrl);

            SecondaryTile tile = new SecondaryTile(
                tileId,
                replacedle,
                arguments,
                new Uri("ms-appx:///replacedets/Logo/Square150x150Logo.png"),
                TileSize.Default);

            // Enable wide and large tile sizes
            tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///replacedets/Logo/Wide310x150Logo.png");
            tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///replacedets/Logo/LargeTile.png");

            var images = await GetTileImages(pageUrl);
            if (images != null)
            {
                tile.VisualElements.Square150x150Logo = images.SquareImage;
                tile.VisualElements.Wide310x150Logo = images.WideImage;
                tile.VisualElements.Square310x310Logo = images.SquareImage;
            }

            // Show the display name on all sizes
            tile.VisualElements.ShowNameOnSquare150x150Logo = true;
            tile.VisualElements.ShowNameOnWide310x150Logo = true;
            tile.VisualElements.ShowNameOnSquare310x310Logo = true;

            var result = await tile.RequestCreateAsync();

            if (!result)
                logger.Info("Tile creation failed");

            return result;
        }

19 View Source File : GitAnalysis.cs
License : MIT License
Project Creator : maikebing

public string BuildGitLabUrl(GitLabUrlType urlType, Tuple<int, int> selectionLineRange)
        {
            // https://GitLab.com/user/repo.git
            string urlRoot = GetRepoUrlRoot();

            // foo/bar.cs
            var rootDir = repository.Info.WorkingDirectory;
            var fileIndexPath = targetFullPath.Substring(rootDir.Length).Replace("\\", "/");

            var repositoryTarget = GetGitLabTargetPath(urlType);

            // line selection
            var fragment = (selectionLineRange != null)
                                ? (selectionLineRange.Item1 == selectionLineRange.Item2)
                                    ? string.Format("#L{0}", selectionLineRange.Item1)
                                    : string.Format("#L{0}-L{1}", selectionLineRange.Item1, selectionLineRange.Item2)
                                : "";

            var urlshowkind = "blob";
            if (urlType == GitLabUrlType.Blame)
            {
                urlshowkind = "blame";
            }
            if (urlType == GitLabUrlType.Commits)
            {
                urlshowkind = "commits";
            }
            var fileUrl = string.Format("{0}/{4}/{1}/{2}{3}", urlRoot.Trim('/'), WebUtility.UrlEncode(repositoryTarget.Trim('/')), fileIndexPath.Trim('/'), fragment, urlshowkind);

            return fileUrl;
        }

19 View Source File : GitAnalysis.cs
License : MIT License
Project Creator : maikebing

public string BuildGiteaUrl(GiteaUrlType urlType, Tuple<int, int> selectionLineRange)
        {
            // https://try.gitea.io/user/repo.git
            string urlRoot = GetRepoUrlRoot();

            // foo/bar.cs
            var rootDir = repository.Info.WorkingDirectory;
            var fileIndexPath = targetFullPath.Substring(rootDir.Length).Replace("\\", "/");

            var repositoryTarget = GetGiteaTargetPath(urlType);

            // line selection
            var fragment = (selectionLineRange != null)
                                ? (selectionLineRange.Item1 == selectionLineRange.Item2)
                                    ? string.Format("#L{0}", selectionLineRange.Item1)
                                    : string.Format("#L{0}-L{1}", selectionLineRange.Item1, selectionLineRange.Item2)
                                : "";

            var urlshowkind = "blob";
            if (urlType == GiteaUrlType.Blame)
            {
                urlshowkind = "blame";
            }
            if (urlType == GiteaUrlType.Commits)
            {
                urlshowkind = "commits";
            }
            var fileUrl = string.Format("{0}/{4}/{1}/{2}{3}", urlRoot.Trim('/'), WebUtility.UrlEncode(repositoryTarget.Trim('/')), fileIndexPath.Trim('/'), fragment, urlshowkind);

            return fileUrl;
        }

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

public static string AddQuerryString(string url, IEnumerable<KeyValuePair<string, string>> nameValueCollection)
        {
            if (nameValueCollection != null && nameValueCollection.Any())
            {
                string querryString = string.Join("&", nameValueCollection.Select(kvp => string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))));
                url = url.TrimEnd('/');
                url = string.Format("{0}?{1}", url, querryString);
            }

            return url;
        }

19 View Source File : CharacterBackupService.cs
License : MIT License
Project Creator : marius00

public string GetDownloadUrl(string character) {
            var url = $"{Uris.DownloadCharacterUrl}?name={WebUtility.UrlEncode(character)}";
            return _authService.GetRestService()?.Get<CharacterDownloadUrlDto>(url)?.Url;
        }

19 View Source File : CharacterBackupService.cs
License : MIT License
Project Creator : marius00

private void ExecuteInternal() {
            var lastSync = _settings.GetLocal().LastCharSyncUtc;
            var highestTimestamp = FileBackup.GetHighestCharacterTimestamp();
            var characters = FileBackup.ListCharactersNewerThan(lastSync);

            bool everythingSucceeded = true;
            foreach (var c in characters) {
                Logger.Info($"Backup up character {c} to the cloud");
                var filename = Path.Combine(GlobalPaths.CharacterBackupLocation, $"{DateTime.Now.DayOfWeek}-{c}.zip");
                FileBackup.BackupCharacter(filename, c); // TODO: IOException
                
                var url = $"{Uris.UploadCharacterUrl}?name={WebUtility.UrlEncode(c)}";
                var success = Post(url, filename);
                if (success) {
                    Logger.Info($"Character {c} successfully backed up to the cloud");
                }
                else {
                    Logger.Info($"An error occurred backing up character {c} to the cloud");
                    everythingSucceeded = false;
                }
            }

            if (FileBackup.IsStashFilesNewerThan(lastSync)) {
                var filename = Path.Combine(GlobalPaths.CharacterBackupLocation, $"{DateTime.Now.DayOfWeek}-common.zip");
                FileBackup.BackupCommon(filename);
                var url = $"{Uris.UploadCharacterUrl}?name=StashFiles-{DateTime.Now.DayOfWeek}";
                var success = Post(url, filename);
                if (success) {
                    Logger.Info($"Stash files successfully backed up to the cloud");
                }
                else {
                    Logger.Info($"An error occurred backing up stash files to the cloud");
                    everythingSucceeded = false;
                }
            }

            if (everythingSucceeded) {
                Logger.Info($"Character sync complete, updating character sync timestamp");
                _settings.GetLocal().LastCharSyncUtc = highestTimestamp;
            }
        }

19 View Source File : RendererHelper.cs
License : MIT License
Project Creator : matteobortolazzo

public static bool HandleUriClick(HtmlLabel label, string url)
		{

			if (url == null || !Uri.IsWellFormedUriString(WebUtility.UrlEncode(url), UriKind.RelativeOrAbsolute))
			{
				return false;
			}

			var args = new WebNavigatingEventArgs(WebNavigationEvent.NewPage, new UrlWebViewSource { Url = url }, url);

			label.SendNavigating(args);

			if (args.Cancel)
			{
				// Uri is handled because it is cancled;
				return true;
			}
			bool result = false;
			var uri = new Uri(url);

			if (uri.IsHttp())
			{
				uri.LaunchBrowser(label.BrowserLaunchOptions);
				result = true;
			}
			else if (uri.IsEmail())
			{
				result = uri.LaunchEmail();
			}
			else if (uri.IsTel())
			{
				result = uri.LaunchTel();
			}
			else if (uri.IsSms())
			{
				result = uri.LaunchSms();
			}
			else if (uri.IsGeo())
			{
				result = uri.LaunchMaps();
			}
			else
			{
				result = Launcher.TryOpenAsync(uri).Result;
			}
			// KWI-FIX What to do if the navigation failed? I replacedume not to spawn the SendNavigated event or introduce a fail bit on the args 
			label.SendNavigated(args);
			return result;
		}

19 View Source File : GraylogFixture.cs
License : MIT License
Project Creator : mattwcole

public async Task<List<dynamic>> WaitForMessagesAsync(int count = 1)
        {
            var query = $"test_id:\"{TestContext.TestId}\"";
            var url = $"search/universal/relative?query={WebUtility.UrlEncode(query)}&range=60";

            var messages = new List<dynamic>();

            await RepeatUntilAsync(async cancellation =>
            {
                messages.AddRange((await _httpClient.GetAsync(url, cancellation)).messages);
                return messages.Count == count;
            });

            return messages.Select(m => m.message).ToList();
        }

19 View Source File : App.xaml.cs
License : MIT License
Project Creator : mburbea

public static void ShowExceptionDialog(string mainInstruction, Exception exception)
        {
            string content = $"{exception.GetType().FullName}: {exception.Message}";
            TaskDialog dialog = new(new()
            {
                replacedle = "KoAR Save Editor",
                Instruction = mainInstruction,
                Text = content,
                Expander = {
                    Text = exception.StackTrace,
                    ExpandFooterArea = true,
                },
                CheckBox = new("Open GitHub bug report? (requires free account)"),
                Icon = TaskDialogStandardIcon.Error,
            });
            dialog.Show();
            if (dialog.Page.CheckBox.Checked)
            {
                string replacedle = $"{content} (in v{App.Version})";                
                Process.Start(new ProcessStartInfo($"https://github.com/mburbea/koar-item-editor/issues/new?labels=bug&template=bug_report.md&replacedle={WebUtility.UrlEncode(replacedle)}")
                {
                    UseShellExecute = true
                })?.Dispose();
            }
        }

19 View Source File : ApiProcessor.cs
License : MIT License
Project Creator : mboukhlouf

private static string GenerateQueryString(BaseRequest requestObject)
        {
            if (requestObject == null)
            {
                throw new ArgumentNullException(nameof(requestObject));
            }

            JObject obj = JObject.FromObject(requestObject, JsonSerializer.Create(SerializerSettings));
            return string.Join("&", obj.Children()
                .Cast<JProperty>()
                .Where(j => j.Value != null)
                .Select(j => j.Name + "=" + WebUtility.UrlEncode(j.Value.ToString())));
        }

19 View Source File : InMemoryProducerDiagnostics.cs
License : MIT License
Project Creator : mehdihadeli

private void InjectHeaders(Activity activity)
        {
            if (_httpContextAccessor.HttpContext is null)
                return;

            if (activity.IdFormat == ActivityIdFormat.W3C)
            {
                if (!_httpContextAccessor.HttpContext.Request.Headers.ContainsKey(Constants
                    .TraceParentHeaderName))
                {
                    _httpContextAccessor.HttpContext.Request.Headers[
                        Constants.TraceParentHeaderName] = activity.Id;
                    if (activity.TraceStateString != null)
                    {
                        _httpContextAccessor.HttpContext.Request.Headers[
                                Constants.TraceStateHeaderName] =
                            activity.TraceStateString;
                    }
                }
            }
            else
            {
                if (!_httpContextAccessor.HttpContext.Request.Headers.ContainsKey(Constants
                    .RequestIdHeaderName))
                {
                    _httpContextAccessor.HttpContext.Request.Headers[
                        Constants.RequestIdHeaderName] = activity.Id;
                }
            }

            // we expect baggage to be empty or contain a few items
            using IEnumerator<KeyValuePair<string, string>> e = activity.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());

                _httpContextAccessor.HttpContext.Request.Headers.AppendList(
                    Constants.CorrelationContextHeaderName,
                    baggage);
            }
        }

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

public override string ToString()
            => $"{FieldName}{(Value != null ? "=" : "")}{WebUtility.UrlEncode(Value)}";

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

internal async Task<bool> DeleteEnvironment(CloudHostedInstance instance)
        {
            var parameters = $"delete=&ActivityId={instance.ActivityId}&ProductName={WebUtility.UrlEncode(instance.ProductName)}&TopologyName={instance.TopologyName}&TopologyInstanceId={instance.InstanceId}&AzureSubscriptionId={instance.AzureSubscriptionId}&EnvironmentGroup=0&EnvironmentId={instance.EnvironmentId}&PreserveCustomerSignOff=false";
            using (_stringContent = new StringContent(parameters, Encoding.UTF8, "application/x-www-form-urlencoded"))
            {
                SetRequestVerificationToken($"{LcsUrl}/V2");
                var result = await _httpClient.PostAsync($"{LcsUrl}/Environment/DeleteEnvironment/{LcsProjectId}", _stringContent);
                result.EnsureSuccessStatusCode();
                var responseBody = result.Content.ReadreplacedtringAsync().Result;
                var response = JsonConvert.DeserializeObject<Response>(responseBody);
                return response.Success;
            }
        }

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

internal async Task<bool> StartStopDeployment(CloudHostedInstance instance, string action)
        {
            var parameters = $"{action}=&ActivityId={instance.ActivityId}&ProductName={WebUtility.UrlEncode(instance.ProductName)}&TopologyName={instance.TopologyName}&TopologyInstanceId={instance.InstanceId}&AzureSubscriptionId={instance.AzureSubscriptionId}&EnvironmentGroup=0";
            using (_stringContent = new StringContent(parameters, Encoding.UTF8, "application/x-www-form-urlencoded"))
            {
                SetRequestVerificationToken($"{LcsUrl}/V2");
                var result = await _httpClient.PostAsync($"{LcsUrl}/DeploymentPortal/StartStopDeployment/{LcsProjectId}", _stringContent);
                result.EnsureSuccessStatusCode();
                var responseBody = result.Content.ReadreplacedtringAsync().Result;
                return responseBody == "true";
            }
        }

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

protected async Task<HttpResponseMessage> Run(string enreplacedyName)
        {
            // Construct the uri to perform Bing Enreplacedy Search
            RequestParams = "mkt=en-us&q=" + System.Net.WebUtility.UrlEncode(enreplacedyName);
            BuildURI();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            HttpResponseMessage response = null;
            try
            {
                // Execute the REST API GET call asynchronously
                response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));
                response.EnsureSuccessStatusCode();
            }
            finally
            {
                stopwatch.Stop();
                string responseStatusCode = Telemetry.PropertyValue.NoResponse;
                if (response != null)
                {
                    responseStatusCode = response.StatusCode.ToString();
                }
                Telemetry.ApplicationLogger.Instance.SubmitApiCallEvent(Telemetry.EventName.CompleteApiCall,Telemetry.EventName.EnreplacedySearchApi, stopwatch.ElapsedMilliseconds, responseStatusCode);
            }

            return response;
        }

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

protected async Task<HttpResponseMessage> Run(string enreplacedyName)
        {
            // Construct the uri to perform Bing Enreplacedy Search
            RequestParams = "q=" + System.Net.WebUtility.UrlEncode(enreplacedyName);
            BuildURI();

            HttpResponseMessage response = null;
            // Execute the REST API GET call asynchronously and
            // await for non-blocking API call to Bing Enreplacedy Search
            response = await RequestAndRetry(() => CloudServiceClient.GetAsync(URI));
            response.EnsureSuccessStatusCode();

            return response;
        }

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

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

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

See More Examples