System.Uri.UnescapeDataString(string)

Here are the examples of the csharp api System.Uri.UnescapeDataString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

511 Examples 7

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F

public static string MakeRelativePath(this string root, string path)
        {
            if(String.IsNullOrWhiteSpace(root) || String.IsNullOrWhiteSpace(path)) {
                return null;
            }

            if(!Uri.TryCreate(root.DirectoryPathFormat(), UriKind.Absolute, out Uri uriRoot)) {
                return null;
            }

            if(!Uri.TryCreate(path, UriKind.Absolute, out Uri uriPath)) {
                uriPath = new Uri(uriRoot, new Uri(path, UriKind.Relative));
            }

            Uri urirel  = uriRoot.MakeRelativeUri(uriPath);
            string ret  = Uri.UnescapeDataString(urirel.IsAbsoluteUri ? urirel.LocalPath : urirel.ToString());

            return ret.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }

19 View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab

[Route("^/shell/run$")]
        public static void Run(RequestContext context) {
            string command = Uri.UnescapeDataString(context.Request.QueryString.Get("command"));
            if (!string.IsNullOrEmpty(command))
                Run(command);

            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.StatusDescription = "OK";
        }

19 View Source File : PathHelper.cs
License : MIT License
Project Creator : absurd-joy

public static string MakeRelativePath(string fromPath, string toPath)
	{
		var fromUri = new Uri(Path.GetFullPath(fromPath));
		var toUri = new Uri(Path.GetFullPath(toPath));

		if (fromUri.Scheme != toUri.Scheme)
		{
			return toPath;
		}

		var relativeUri = fromUri.MakeRelativeUri(toUri);
		var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

		if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
		{
			relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
		}

		return relativePath;
	}

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

static public string replacedemblyLoadDirectory()
        {
            string codeBase = replacedembly.GetEntryreplacedembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

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

static public string replacedemblyExecuteablePath()
        {
            string codeBase = replacedembly.GetEntryreplacedembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            return Uri.UnescapeDataString(uri.Path);
        }

19 View Source File : RecordControllerBase.cs
License : Apache License 2.0
Project Creator : acblog

[HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesDefaultResponseType]
        public virtual async Task<ActionResult<T>> Get(string id)
        {
            id = Uri.UnescapeDataString(id);

            if (await Service.Exists(id))
                return Ok(await Service.Get(id));
            else
                return NotFound();
        }

19 View Source File : RecordControllerBase.cs
License : Apache License 2.0
Project Creator : acblog

[HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesDefaultResponseType]
        [Authorize]
        public virtual async Task<ActionResult<bool>> Update(string id, [FromBody] T value)
        {
            id = Uri.UnescapeDataString(id);
            value = value with { Id = id };
            if (await Service.Exists(value.Id))
                return Ok(await Service.Update(value));
            else
                return NotFound();
        }

19 View Source File : RecordControllerBase.cs
License : Apache License 2.0
Project Creator : acblog

[HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesDefaultResponseType]
        [Authorize]
        public virtual async Task<ActionResult<bool>> Delete(string id)
        {
            id = Uri.UnescapeDataString(id);

            if (await Service.Exists(id))
                return Ok(await Service.Delete(id));
            else
                return NotFound();
        }

19 View Source File : BasePage.cs
License : Apache License 2.0
Project Creator : acblog

private void LocationChanged(object sender, LocationChangedEventArgs args)
        {
            var url = NavigationManager.Uri;
            if (url.StartsWith(BaseUri))
            {
                var frag = url[BaseUri.Length..];
                if (frag.StartsWith("#"))
                {
                    LocalAnchorJump = Uri.UnescapeDataString(frag[1..]);
                    StateHasChanged();
                }
            }
        }

19 View Source File : EpubFile.cs
License : MIT License
Project Creator : Aeroblast

public EpubFileEntry GetFile()
        {
            return belongTo.GetFile(Uri.UnescapeDataString(href));
        }

19 View Source File : AeroEpubSchemeHandlerFactory.cs
License : MIT License
Project Creator : Aeroblast

public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
        {
            var uri = new Uri(request.Url);
            Log.log(request.Url);
            var route = uri.AbsolutePath.Split('/')[1];
            switch (route)
            {
                case "book":
                    {
                        if (uri.Query.Contains("footnote"))
                        {
                            return ResourceHandler.FromString("");
                        }
                        var epubItemPath = uri.AbsolutePath.Substring("/book/".Length);
                        if (epubItemPath[0] == '/') epubItemPath = epubItemPath.Substring(1);
                        Item i = Program.epub.Gereplacedem(epubItemPath);
                        if (i != null)
                        {
                            if (i.mediaType == "application/xhtml+xml")
                            {
                                string content = (i.GetFile() as TextEpubFileEntry).text;
                                content = HtmlHack.Hack(content);
                                return ResourceHandler.FromString(content);
                            }
                            if (i.mediaType == "text/css")
                            {
                                //html里的其实也应该处理……
                                string content = (i.GetFile() as TextEpubFileEntry).text;
                                content = CssHack.Hack(content);
                                return ResourceHandler.FromString(content, null, true, i.mediaType);
                            }
                            if (i.mediaType.StartsWith("image"))
                            {
                                //Image warm color process
                                if (uri.Query.Contains("warm"))
                                {
                                    switch (i.mediaType)
                                    {
                                        case "image/heic":
                                        case "image/webp":
                                            byte[] imageData = i.GetFile().GetBytes();
                                            var decoded = ImageHack.TryDecode(imageData);
                                            if (decoded != null)
                                            {
                                                return ResourceHandler.FromByteArray(ImageHack.Warmer(decoded), "image/bmp");
                                            }
                                            else//local decoder not found 
                                            {
                                                return ResourceHandler.FromByteArray(imageData, i.mediaType);
                                            }
                                        default:
                                            return ResourceHandler.FromByteArray(ImageHack.Warmer(i.GetFile().GetBytes()), "image/bmp");
                                    }
                                }
                                //do not return image but  a html page 
                                if (uri.Query.Contains("page"))
                                {
                                    if (imagePageSizeAttribute == null)
                                    {
                                        if (Program.epub.spine.pageProgressionDirection == "rtl")
                                        { imagePageSizeAttribute = "height=\"100%\""; }
                                        else
                                        { imagePageSizeAttribute = "width=\"100%\""; }
                                    }
                                    return ResourceHandler.FromString($"<html><head><link href=\"aeroepub://viewer/viewer-inject.css\" rel=\"stylesheet\" type=\"text/css\"/></head><body><img {imagePageSizeAttribute} src={("aeroepub://book" + uri.AbsolutePath)}><script src=\"aeroepub://viewer/viewer-inject.js\"></script></body></html>");
                                }
                                //normally return image data. Decode use system decoder for some format
                                switch (i.mediaType)
                                {
                                    case "image/heic":
                                        byte[] imageData = i.GetFile().GetBytes();
                                        var decoded = ImageHack.TryDecode(imageData);
                                        if (decoded != null)
                                        {
                                            return ResourceHandler.FromByteArray(decoded, "image/bmp");
                                        }
                                        else//local decoder not found 
                                        {
                                            return ResourceHandler.FromByteArray(imageData, i.mediaType);
                                        }
                                    default:
                                        return ResourceHandler.FromByteArray(i.GetFile().GetBytes(), i.mediaType);

                                }

                            }
                            return ResourceHandler.FromByteArray(i.GetFile().GetBytes(), i.mediaType);

                        }
                        else
                        {
                            Log.log("[Error]Cannot get " + uri);
                        }

                    }
                    break;
                case "viewer":
                    {
                        var filename = uri.AbsolutePath.Substring("/viewer/".Length).Replace("/", ".");
                        Stream fs = replacedembly.GetManifestResourceStream("AeroEpubViewer.Res." + filename);
                        string mime = Util.GetMimeType(filename);
                        if (mime != null)
                            return ResourceHandler.FromStream(fs, mime);
                        return ResourceHandler.FromStream(fs);
                    } //break;
                case "app":
                    {
                        string[] args = uri.AbsolutePath.Substring("/app/".Length).Split('/');
                        switch (args[0])
                        {
                            case "pos":
                                ResizeManage.SetPara(args);
                                return ResourceHandler.FromString("OK");
                            case "bookfontsize":
                                UserSettings.bookFontSize = int.Parse(args[1]);
                                EpubViewer.chromium.LoadingStateChanged += EpubViewer.SendDataWhenLoad;
                                EpubViewer.chromium.Reload(true);
                                return ResourceHandler.FromString("OK");
                            case "screentest":
                                CssHack.SetScreenTest(args);
                                return ResourceHandler.FromString("OK");
                            case "inspector":
                                EpubViewer.chromium.ShowDevTools();
                                return ResourceHandler.FromString("OK");
                            case "theme":
                                UserSettings.theme = args[1];
                                return ResourceHandler.FromString("OK");
                            case "ImageQuickView":
                                return ResourceHandler.FromString(SpecialPageService.ImageQuickView());
                            case "BookInfo":
                                return ResourceHandler.FromString(SpecialPageService.BookInfo());
                            case "StartSearch":
                                {
                                    var t = uri.AbsolutePath.Substring("/app/".Length);
                                    int i = t.IndexOf('/');
                                    var word = Uri.UnescapeDataString(t.Substring(i + 1));
                                    SearchService.Start(word);
                                    Log.log(word);
                                    return ResourceHandler.FromString("OK");
                                }
                            case "CheckSearchResult":
                                return ResourceHandler.FromString(SearchService.GetResult(int.Parse(args[1])));
                            case "CopyImage":
                                {
                                    string path = uri.AbsolutePath.Substring("/app/CopyImage/".Length);
                                    var f = Program.epub.GetFile(path);
                                    using (var stm = new MemoryStream(f.GetBytes()))
                                    using (var img = System.Drawing.Image.FromStream(stm))
                                        System.Windows.Forms.Clipboard.SetImage(img);
                                }
                                return ResourceHandler.FromString("OK");
                            case "UserBookCss":
                                return ResourceHandler.FromString(UserSettings.userBookCssContent, null, true, "text/css");
                            case "UserBookCssRtl":
                                return ResourceHandler.FromString(UserSettings.userBookCssContent_rtl, null, true, "text/css");
                            case "UserBookCssLtr":
                                return ResourceHandler.FromString(UserSettings.userBookCssContent_ltr, null, true, "text/css");
                            case "External":
                                System.Diagnostics.Process.Start("explorer.exe", Uri.UnescapeDataString(args[1]));
                                return ResourceHandler.FromString("OK");
                        }


                    }
                    break;


            }
            return null;
        }

19 View Source File : DatasourceConverter.cs
License : MIT License
Project Creator : afaniuolo

public override List<SCItem> ConvertValueElementToItems(SCField scField, string elementValue, MetadataTemplate metadataTemplate, SCItem sourceItem)
		{
			List<SCItem> convertedItems = new List<SCItem>();

			var decodedElementValue = Uri.UnescapeDataString(elementValue).Replace("+", " ");

			XmlNodeList queryElements = null;
			try
			{
				queryElements = XmlHelper.GetXmlElementNodeList(decodedElementValue, "query", true);
			}
			catch (Exception ex)
			{
				_logger.Log(new LogEntry(LoggingEventType.Error,
					string.Format("ConvertValueElementToItems - Failed to parse Xml value. ItemID = {0} - FieldID = {1} - ElementName = {2} - ElementValue_Decoded = {3}",
						scField.ItemId, scField.Id, "query", decodedElementValue), ex));
			}
			if (queryElements != null && queryElements.Count > 0)
			{
				foreach (XmlNode queryElement in queryElements)
				{
					if (queryElement.Attributes != null && queryElement.Attributes["t"] != null)
					{
						var queryType = queryElement.Attributes["t"].Value;
						if (string.Equals(queryType, "default", StringComparison.InvariantCultureIgnoreCase))
						{
							var value = XmlHelper.GetXmlElementValue(queryElement.InnerXml, "value");
							var displayName = value;
							var displayNames = new Dictionary<Tuple<string, int>, string>();
							var queryChildrenElements = XmlHelper.GetXmlElementNames(queryElement.InnerXml);
							foreach (string queryChildrenElementName in queryChildrenElements)
							{
								if (!string.Equals(queryChildrenElementName, "value", StringComparison.InvariantCultureIgnoreCase))
								{
									displayName = XmlHelper.GetXmlElementValue(queryElement.InnerXml, queryChildrenElementName);
									
										displayNames.Add(new Tuple<string, int>(queryChildrenElementName, 1), displayName);
																	
								}
							}

							if (!string.IsNullOrEmpty(value))
							{
								// Set item value
								metadataTemplate.fields.newFields
									.First(field => field.destFieldId == new Guid("{3A07C171-9BCA-464D-8670-C5703C6D3F11}")).value = value;
								// Set display name
								if (displayNames.Any())
								{
									metadataTemplate.fields.newFields
										.First(field => field.destFieldId == new Guid("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}")).values = displayNames;
								}
								else
								{
									metadataTemplate.fields.newFields
										.First(field => field.destFieldId == new Guid("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}")).value = displayName;
								}
								SCItem convertedItem = _itemFactory.Create(metadataTemplate.destTemplateId, sourceItem, value, metadataTemplate);
								convertedItems.Add(convertedItem);							
							}
						}
					}
				}				
			}

			return convertedItems;
		}

19 View Source File : DatasourceConverter.cs
License : MIT License
Project Creator : afaniuolo

public override List<SCField> ConvertValueElementToFields(SCField scField, string elementValue)
		{
			List<SCField> convertedFields = new List<SCField>();

			var decodedElementValue = Uri.UnescapeDataString(elementValue).Replace("+"," ");

			XmlNode queryElement = null;
			try
			{
				queryElement = XmlHelper.GetXmlElementNode(decodedElementValue, "query", true);
			}
			catch (Exception ex)
			{
				_logger.Log(new LogEntry(LoggingEventType.Error,
					string.Format("ConvertValueElementToFields - Failed to parse Xml value. ItemID = {0} - FieldID = {1} - ElementName = {2} - ElementValue_Decoded = {3}",
						scField.ItemId, scField.Id, "query", decodedElementValue), ex));
			}
			 
			if (queryElement != null)
			{
				if (queryElement.Attributes != null && queryElement.Attributes["t"] != null)
				{
					var queryType = queryElement.Attributes["t"].Value;
					if (string.Equals(queryType, "root", StringComparison.InvariantCultureIgnoreCase))
					{
						string rooreplacedemId = XmlHelper.GetXmlElementValue(queryElement.InnerXml, "value");
						string textFieldValue = queryElement.Attributes["tf"]?.Value ?? "__ItemName";
						string valueFieldValue = queryElement.Attributes["vf"]?.Value ?? "__ItemName";

						// Create fields
						var datasourceField = CreateFieldFromElement(scField, new Guid("{5BE76442-950F-4C1F-A797-BEBD71101ABB}"), rooreplacedemId, FieldType.Shared);
						if (datasourceField != null) convertedFields.Add(datasourceField);

						if (!string.IsNullOrEmpty(textFieldValue))
						{
							var displayField =
								CreateFieldFromElement(scField, new Guid("{492361E0-72D8-4847-82BA-EBFC235CF57B}"), textFieldValue, FieldType.Shared);
							if (displayField != null) convertedFields.Add(displayField);
						}

						if (!string.IsNullOrEmpty(valueFieldValue))
						{
							var valueField =
								CreateFieldFromElement(scField, new Guid("{78778432-6327-4CEA-A28B-E190E3541D28}"), valueFieldValue, FieldType.Shared);
							if (valueField != null) convertedFields.Add(valueField);
						}

						var isDynamicField = CreateFieldFromElement(scField, new Guid("{54424E06-0E7A-47A7-8CB2-7383D700472F}"), "1", FieldType.Shared);
						if (isDynamicField != null) convertedFields.Add(isDynamicField);
					}
				}
			}

			return convertedFields;
		}

19 View Source File : CookieService.cs
License : MIT License
Project Creator : agc93

public Dictionary<string, string> GetCookies() {
            
            if (Path.HasExtension(_config.Cookies) && File.Exists(_config.Cookies)) {
                var ckTxt = File.ReadAllLines(Path.GetFullPath(_config.Cookies));
                var ckSet = ParseCookiesTxt(ckTxt);
                return ckSet;
            } else if (_config.Cookies.StartsWith("{") || _config.Cookies.StartsWith("%7B")) {
                //almost certainly a raw sid, we'll replacedume it is
                var raw = Uri.UnescapeDataString(_config.Cookies);
                return new Dictionary<string, string> {["sid"] = Uri.EscapeDataString(raw)};
            } else {
                if (_config.Cookies.Contains('\n')) {
                    var ckSet = ParseCookiesTxt(_config.Cookies.Split('\n'));
                    return ckSet;
                } else {
                    return _config.Cookies.Split(';').Select(s => s.Trim(' ')).ToDictionary(s => s.Split('=').First(), s => s.Split('=').Last());
                }
            }
            
        }

19 View Source File : JsonSchemaBuilder.cs
License : MIT License
Project Creator : akaskela

private string UnescapeReference(string reference)
        {
            return Uri.UnescapeDataString(reference).Replace("~1", "/").Replace("~0", "~");
        }

19 View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma

private void ApplyNewName()
        {
            _tag.Visibility = Visibility.Visible;
            _renameBox.Visibility = Visibility.Collapsed;
            var oldPAth = Path;
            var newPath = Parent.Path + @"\" + _renameBox.Text;
            MagicLaboratory.CleanPath(ref newPath);
            try
            {
                if (!Folder)
                    if (File.Exists(Path))
                    {
                        File.Move(Path
                            , newPath);
                        ItemName = _renameBox.Text;
                        var itemName = ItemName;
                        MagicLaboratory.CleanPath(ref itemName);
                        ItemName = itemName;
                        Path = newPath;
                    }

                if (Directory.Exists(Path) && Path != newPath)
                {
                    Directory.Move(Path
                        , Uri.UnescapeDataString(newPath));
                    ItemName = _renameBox.Text;
                    var itemName = ItemName;
                    MagicLaboratory.CleanPath(ref itemName);
                    ItemName = itemName;
                    Path = newPath;
                    var node = Parent.Container.GetNode(oldPAth, Parent.Container.FoldersTree.Items);
                    var parentNode = Parent.Container.GetNode(Parent.Path, Parent.Container.FoldersTree.Items);
                    if (node == null)
                    {
                        parentNode.Items.Add(new TreeViewItem {Header = new FolderItem(Path, ItemName)});
                    }
                    else
                    {
                        var folderItem = node.Header as FolderItem;
                        if (folderItem != null)
                        {
                            folderItem.FolderName = itemName;
                            folderItem.Path = Path;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var result = MessageBox.Show(ex.Message + "\n" + "Try again?", "Couldn't modify the name.",
                    MessageBoxButton.YesNo, MessageBoxImage.Error);
                Parent.Container.Disable();
                if (result == MessageBoxResult.Yes)
                {
                    Parent.Container.Enable();
                    Rename();
                }
            }
        }

19 View Source File : Extensions.cs
License : Apache License 2.0
Project Creator : Algoryx

public static string MakeRelative( this string complete,
                                       string root,
                                       bool includeTopRoot = true )
    {
      var completeUri = new Uri( complete );
      var rootUri = new Uri( root );
      var relUri = rootUri.MakeRelativeUri( completeUri );
      var result = Uri.UnescapeDataString( relUri.ToString() );
      if ( !string.IsNullOrEmpty( result ) && !includeTopRoot ) {
        var di = new System.IO.DirectoryInfo( root );
        if ( result.StartsWith( di.Name ) )
          result = result.Remove( 0, di.Name.Length + 1 );
      }
      return result;
    }

19 View Source File : MapServer.cs
License : MIT License
Project Creator : AliFlux

Task Serve(IHttpContext context, Func<Task> next)
        {
            string prefix = context.Request.RequestParameters[0];

            if (prefix == "tiles")
            {
                int z = Convert.ToInt32(context.Request.RequestParameters[1]);
                int x = Convert.ToInt32(context.Request.RequestParameters[2]);
                int y = Convert.ToInt32(context.Request.RequestParameters[3]);
                y = (int)(Math.Pow(2, z) - y - 1);

                return ServeTile(context, next, x, y, z);
            }
            else if (prefix == "glyphs")
            {
                var components = context.Request.RequestParameters
                    .Skip(1)
                    .Select(p => Uri.UnescapeDataString(p))
                    .ToArray();
                var path = System.IO.Path.Combine(components);
                return ServeGlyph(context, next, path);
            }
            else
            {
                context.Response = new HttpResponse(HttpResponseCode.NotFound, "404 Not Found.", null, true, null);
                return Task.Factory.GetCompleted();
            }
        }

19 View Source File : StorageExtensions.cs
License : MIT License
Project Creator : Aminator

public static string GetRelativePath(string relativeTo, string path)
        {
            relativeTo = Path.IsPathRooted(relativeTo) ? relativeTo : "C:/" + relativeTo;
            path = Path.IsPathRooted(path) ? path : "C:/" + path;

            Uri path1 = new Uri(relativeTo + Path.DirectorySeparatorChar);
            Uri path2 = new Uri(path);

            Uri relativeUri = path1.MakeRelativeUri(path2);
            return Uri.UnescapeDataString(relativeUri.OriginalString.Replace('/', Path.DirectorySeparatorChar));
        }

19 View Source File : HotReloader.cs
License : MIT License
Project Creator : AndreiMisiukevich

private void HandleReloadRequest(HttpListenerContext context)
        {
            lock (_requestLocker)
            {
                try
                {
                    var request = context.Request;
                    if (request.HttpMethod == HttpMethod.Post.Method &&
                        request.HasEnreplacedyBody &&
                        request.RawUrl.StartsWith("/reload", StringComparison.InvariantCulture))
                    {
                        using (var bodyStream = request.InputStream)
                        {
                            using (var bodyStreamReader = new StreamReader(bodyStream, request.ContentEncoding))
                            {
                                var xaml = bodyStreamReader.ReadToEnd();
                                if (xaml == _prevXaml)
                                {
                                    return;
                                }
                                _prevXaml = xaml;

                                var path = request.QueryString["path"];
                                var unescapedPath = string.IsNullOrWhiteSpace(path)
                                    ? null
                                    : Uri.UnescapeDataString(path);

                                ReloadElements(xaml, unescapedPath);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }

                context.Response.Close();
            }
        }

19 View Source File : PathUtility.cs
License : MIT License
Project Creator : AndresTraks

public static string MakeRelativePath(string fromPath, string toPath)
        {
            if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(nameof(fromPath));
            if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException(nameof(toPath));

            var fromUri = new Uri(fromPath);
            var toUri = new Uri(toPath);

            if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.

            var relativeUri = fromUri.MakeRelativeUri(toUri);
            var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

            if (toUri.Scheme.ToUpperInvariant() == "FILE")
            {
                relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            }

            return relativePath;
        }

19 View Source File : CloudPayments3DSService.cs
License : Apache License 2.0
Project Creator : AppRopio

private bool ShoulStartLoad(WKWebView webView, NSUrlRequest request)
        {
            if (request.Url.AbsoluteString == _redirectUrl)
            {
                _webView.Hidden = true;

                var parameters = request.Body.ToString().ToParamsDictionary();
                foreach (var key in parameters.Keys.ToList())
                {
                    parameters[key] = Uri.UnescapeDataString(parameters[key]);
                }

				_webView.LoadError -= WebView_LoadError;

                if (!_tcs.Task.IsCanceled && !_tcs.Task.IsCompleted)
                    _tcs.TrySetResult(parameters);

                return false;
            }

            return true;
        }

19 View Source File : OwinHelpers.cs
License : Apache License 2.0
Project Creator : aspnet

internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, bool decodePlus, bool decodeKey, object state)
        {
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);
                    if (decodePlus)
                    {
                        name = name.Replace('+', ' ');
                        value = value.Replace('+', ' ');
                    }
                    if (decodeKey)
                    {
                        name = Uri.UnescapeDataString(name);
                    }
                    value = Uri.UnescapeDataString(value);
                    callback(name, value, state);
                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
        }

19 View Source File : PathString.cs
License : Apache License 2.0
Project Creator : aspnet

[SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "Requirements not compatible with Uri processing")]
        public static PathString FromUriComponent(string uriComponent)
        {
            // REVIEW: what is the exactly correct thing to do?
            return new PathString(Uri.UnescapeDataString(uriComponent));
        }

19 View Source File : TwitterAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

private async Task<AccessToken> ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier)
        {
            // https://dev.twitter.com/docs/api/1/post/oauth/access_token

            _logger.WriteVerbose("ObtainAccessToken");

            string nonce = Guid.NewGuid().ToString("N");

            var authorizationParts = new SortedDictionary<string, string>
            {
                { "oauth_consumer_key", consumerKey },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_token", token.Token },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_verifier", verifier },
                { "oauth_version", "1.0" },
            };

            var parameterBuilder = new StringBuilder();
            foreach (var authorizationKey in authorizationParts)
            {
                parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value));
            }
            parameterBuilder.Length--;
            string parameterString = parameterBuilder.ToString();

            var canonicalizedRequestBuilder = new StringBuilder();
            canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));

            string signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString());
            authorizationParts.Add("oauth_signature", signature);
            authorizationParts.Remove("oauth_verifier");

            var authorizationHeaderBuilder = new StringBuilder();
            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(
                    "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;

            var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint);
            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            var formPairs = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("oauth_verifier", verifier)
            };

            request.Content = new FormUrlEncodedContent(formPairs);

            HttpResponseMessage response = await _httpClient.SendAsync(request, Request.CallCancelled);

            if (!response.IsSuccessStatusCode)
            {
                _logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode);
                response.EnsureSuccessStatusCode(); // throw
            }

            string responseText = await response.Content.ReadreplacedtringAsync();

            IFormCollection responseParameters = WebHelpers.ParseForm(responseText);

            return new AccessToken
            {
                Token = Uri.UnescapeDataString(responseParameters["oauth_token"]),
                TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]),
                UserId = Uri.UnescapeDataString(responseParameters["user_id"]),
                ScreenName = Uri.UnescapeDataString(responseParameters["screen_name"])
            };
        }

19 View Source File : WsFederationAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

private static IDictionary<string, List<string>> ParseDelimited(string text)
        {
            char[] delimiters = new[] { '&', ';' };
            var acreplacedulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);

                    name = Uri.UnescapeDataString(name.Replace('+', ' '));
                    value = Uri.UnescapeDataString(value.Replace('+', ' '));

                    List<string> existing;
                    if (!acreplacedulator.TryGetValue(name, out existing))
                    {
                        acreplacedulator.Add(name, new List<string>(1) { value });
                    }
                    else
                    {
                        existing.Add(value);
                    }

                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
            return acreplacedulator;
        }

19 View Source File : SystemWebChunkingCookieManager.cs
License : Apache License 2.0
Project Creator : aspnet

public string GetRequestCookie(IOwinContext context, string key)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            if (webContext == null)
            {
                return Fallback.GetRequestCookie(context, key);
            }

            var requestCookies = webContext.Request.Cookies;
            var escapedKey = Uri.EscapeDataString(key);
            var cookie = requestCookies[escapedKey];
            if (cookie == null)
            {
                return null;
            }

            var value = cookie.Value;
            int chunksCount = ParseChunksCount(value);
            if (chunksCount > 0)
            {
                bool quoted = false;
                string[] chunks = new string[chunksCount];
                for (int chunkId = 1; chunkId <= chunksCount; chunkId++)
                {
                    cookie = requestCookies[escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture)];
                    if (cookie == null)
                    {
                        if (ThrowForPartialCookies)
                        {
                            int totalSize = 0;
                            for (int i = 0; i < chunkId - 1; i++)
                            {
                                totalSize += chunks[i].Length;
                            }
                            throw new FormatException(
                                string.Format(CultureInfo.CurrentCulture, Resources.Exception_ImcompleteChunkedCookie, chunkId - 1, chunksCount, totalSize));
                        }
                        // Missing chunk, abort by returning the original cookie value. It may have been a false positive?
                        return Uri.UnescapeDataString(value);
                    }
                    string chunk = cookie.Value;
                    if (IsQuoted(chunk))
                    {
                        // Note: Since we replacedume these cookies were generated by our code, then we can replacedume that if one cookie has quotes then they all do.
                        quoted = true;
                        chunk = RemoveQuotes(chunk);
                    }
                    chunks[chunkId - 1] = chunk;
                }
                string merged = string.Join(string.Empty, chunks);
                if (quoted)
                {
                    merged = Quote(merged);
                }
                return Uri.UnescapeDataString(merged);
            }
            return Uri.UnescapeDataString(value);
        }

19 View Source File : SystemWebCookieManager.cs
License : Apache License 2.0
Project Creator : aspnet

public string GetRequestCookie(IOwinContext context, string key)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            if (webContext == null)
            {
                return Fallback.GetRequestCookie(context, key);
            }

            var escapedKey = Uri.EscapeDataString(key);
            var cookie = webContext.Request.Cookies[escapedKey];
            if (cookie == null)
            {
                return null;
            }
            return Uri.UnescapeDataString(cookie.Value);
        }

19 View Source File : OpenidConnectAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

private AuthenticationProperties GetPropertiesFromState(string state)
        {
            // replacedume a well formed query string: <a=b&>OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey=kasjd;fljasldkjflksdj<&c=d>
            int startIndex = 0;
            if (string.IsNullOrWhiteSpace(state) || (startIndex = state.IndexOf(OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey, StringComparison.Ordinal)) == -1)
            {
                return null;
            }

            int authenticationIndex = startIndex + OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey.Length;
            if (authenticationIndex == -1 || authenticationIndex == state.Length || state[authenticationIndex] != '=')
            {
                return null;
            }

            // scan rest of string looking for '&'
            authenticationIndex++;
            int endIndex = state.Substring(authenticationIndex, state.Length - authenticationIndex).IndexOf("&", StringComparison.Ordinal);

            // -1 => no other parameters are after the AuthenticationPropertiesKey
            if (endIndex == -1)
            {
                return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex).Replace('+', ' ')));
            }
            else
            {
                return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex, endIndex).Replace('+', ' ')));
            }
        }

19 View Source File : TwitterAuthenticationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

private async Task<RequestToken> ObtainRequestTokenAsync(string consumerKey, string consumerSecret, string callBackUri, AuthenticationProperties properties)
        {
            _logger.WriteVerbose("ObtainRequestToken");

            string nonce = Guid.NewGuid().ToString("N");

            var authorizationParts = new SortedDictionary<string, string>
            {
                { "oauth_callback", callBackUri },
                { "oauth_consumer_key", consumerKey },
                { "oauth_nonce", nonce },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_timestamp", GenerateTimeStamp() },
                { "oauth_version", "1.0" }
            };

            var parameterBuilder = new StringBuilder();
            foreach (var authorizationKey in authorizationParts)
            {
                parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value));
            }
            parameterBuilder.Length--;
            string parameterString = parameterBuilder.ToString();

            var canonicalizedRequestBuilder = new StringBuilder();
            canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(RequestTokenEndpoint));
            canonicalizedRequestBuilder.Append("&");
            canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));

            string signature = ComputeSignature(consumerSecret, null, canonicalizedRequestBuilder.ToString());
            authorizationParts.Add("oauth_signature", signature);

            var authorizationHeaderBuilder = new StringBuilder();
            authorizationHeaderBuilder.Append("OAuth ");
            foreach (var authorizationPart in authorizationParts)
            {
                authorizationHeaderBuilder.AppendFormat(
                    "{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
            }
            authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;

            var request = new HttpRequestMessage(HttpMethod.Post, RequestTokenEndpoint);
            request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());

            HttpResponseMessage response = await _httpClient.SendAsync(request, Request.CallCancelled);
            response.EnsureSuccessStatusCode();
            string responseText = await response.Content.ReadreplacedtringAsync();

            IFormCollection responseParameters = WebHelpers.ParseForm(responseText);
            if (string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.InvariantCulture))
            {
                return new RequestToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), CallbackConfirmed = true, Properties = properties };
            }

            return new RequestToken();
        }

19 View Source File : Extensions.cs
License : Apache License 2.0
Project Creator : aspnet

private static Dictionary<string, string> ParseItems(string content)
        {
            var items = new Dictionary<string, string>();
            if (content != null)
            {
                var contentString = Uri.UnescapeDataString(content.TrimStart('?'));

                var parts = contentString
                    .Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(q => q.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries));

                foreach (var item in parts)
                {
                    var value = item.Length == 2 ? item[1] : null;
                    items.Add(item[0], value);
                }
            }

            return items;
        }

19 View Source File : FileUtils.cs
License : MIT License
Project Creator : Astropilot

public static string GetRelativePath(string fullPath, string basePath)
        {
            if (!basePath.EndsWith("\\"))
                basePath += "\\";

            Uri baseUri = new Uri(basePath);
            Uri fullUri = new Uri(fullPath);

            Uri relativeUri = baseUri.MakeRelativeUri(fullUri);
            var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

            return relativePath.Replace('/', Path.DirectorySeparatorChar);

        }

19 View Source File : PathPolyfill.cs
License : Apache License 2.0
Project Creator : asynkron

public static string GetRelativePath(string relativeTo, string path)
        {
            if (string.IsNullOrEmpty(relativeTo))
            {
                throw new ArgumentException("value cannot be null or empty", nameof(relativeTo));
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("value cannot be null or empty", nameof(path));
            }

            var relativeToUri = GetUri(relativeTo);
            var pathUri = GetUri(path);

            if (relativeToUri.Scheme != pathUri.Scheme)
            {
                return path;
            }

            var relativeUri = relativeToUri.MakeRelativeUri(pathUri);

            var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

            if (string.Equals(pathUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
            {
                relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            }

            relativePath = relativePath.TrimEnd(Path.DirectorySeparatorChar);

            if (relativePath == string.Empty)
            {
                relativePath = ".";
            }

            return relativePath;
        }

19 View Source File : UriHelper.cs
License : Apache License 2.0
Project Creator : atteneder

public static Uri GetUriString( string uri, Uri baseUri ) {
            uri = Uri.UnescapeDataString(uri);
            if(Uri.TryCreate(uri, UriKind.Absolute, out var result)){
                return result;
            }

            if (baseUri != null) {
                uri = RemoveDotSegments(uri, out var parentLevels);
                if (baseUri.IsAbsoluteUri) {
                    for (int i = 0; i < parentLevels; i++) {
                        baseUri = new Uri(baseUri, "..");
                    }
                    return new Uri(baseUri, uri);
                }

                var parentPath = baseUri.OriginalString;
                for (int i = 0; i < parentLevels; i++) {
                    parentPath = Path.GetDirectoryName(parentPath);
                    if (string.IsNullOrEmpty(parentPath)) {
                        baseUri = new Uri("",UriKind.Relative);
                        break;
                    }
                    baseUri = new Uri(parentPath, UriKind.Relative);
                }
                return new Uri(Path.Combine(baseUri.OriginalString, uri), UriKind.Relative);
            }
            return new Uri(uri,UriKind.RelativeOrAbsolute);
        }

19 View Source File : Derivatives.cs
License : MIT License
Project Creator : Autodesk-Forge

private static PathInfo DecomposeURN(string encodedUrn)
    {
      string urn = Uri.UnescapeDataString(encodedUrn);

      string rootFileName = urn.Substring(urn.LastIndexOf('/') + 1);
      string basePath = urn.Substring(0, urn.LastIndexOf('/') + 1);
      string localPath = basePath.Substring(basePath.IndexOf('/') + 1);
      localPath = Regex.Replace(localPath, "[/]?output/", string.Empty);

      return new PathInfo()
      {
        RootFileName = rootFileName,
        BasePath = basePath,
        LocalPath = localPath,
        URN = urn
      };
    }

19 View Source File : Derivatives.cs
License : MIT License
Project Creator : Autodesk-Forge

public async static Task<List<Resource>> ExtractSVFAsync(string urn, string accessToken)
    {
      DerivativesApi derivativeApi = new DerivativesApi();
      derivativeApi.Configuration.AccessToken = accessToken;

      // get the manifest for the URN
      dynamic manifest = await derivativeApi.GetManifestAsync(urn);

      // list items of the manifest file
      List<Manifesreplacedem> urns = ParseManifest(manifest.derivatives);

      // iterate on what's on the file
      foreach (Manifesreplacedem item in urns)
      {
        switch (item.MIME)
        {
          case "application/autodesk-svf":
            item.Path.Files = await SVFDerivates(item, accessToken);
            break;
          case "application/autodesk-f2d":
            item.Path.Files = await F2DDerivates(item, accessToken);
            break;
          case "application/autodesk-db":
            item.Path.Files = new List<string>()
            {
              "objects_attrs.json.gz",
              "objects_vals.json.gz",
              "objects_offs.json.gz",
              "objects_ids.json.gz",
              "objects_avs.json.gz",
              item.Path.RootFileName
            };
            break;
          default:
            item.Path.Files = new List<string>()
            {
              item.Path.RootFileName
            };
            break;
        }
      }

      // now organize the list for external usage
      List<Resource> resouces = new List<Resource>();
      foreach (Manifesreplacedem item in urns)
      {
        foreach (string file in item.Path.Files)
        {
          Uri myUri = new Uri(new Uri(item.Path.BasePath), file);
          resouces.Add(new Resource()
          {
            FileName = file,
            RemotePath = DERIVATIVE_PATH + Uri.UnescapeDataString(myUri.AbsoluteUri),
            LocalPath = Path.Combine(item.Path.LocalPath, file)
          });
        }
      }

      return resouces;
    }

19 View Source File : AllurePlugin.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

private static string GetreplacedemblyDirectory()
        {
            string codeBase = replacedembly.GetExecutingreplacedembly().Location;
            var uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : AssemblyFacade.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public string GetreplacedemblyDirectory()
        {
            var codeBase = replacedembly.GetExecutingreplacedembly().Location;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : ReflectionFacade.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public string GetRunningreplacedemblyPath()
        {
            var codeBase = replacedembly.GetExecutingreplacedembly().Location;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : ProcessProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public static string GetEntryProcessApplicationPath()
        {
            // If we will write tests some day, create separate interfaces for below clreplacedes. But I think there is no need.
            string codeBase = replacedembly.GetExecutingreplacedembly().Location;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : ProcessProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public static string GetExecutingreplacedemblyFolder()
        {
            string codeBase = replacedembly.GetExecutingreplacedembly().Location;
            var uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : CookiesService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public void AddCookie(string cookieName, string cookieValue, string path = "/")
        {
            cookieValue = Uri.UnescapeDataString(cookieValue);
            var cookie = new Cookie(cookieName, cookieValue, path);
            WrappedDriver.Manage().Cookies.AddCookie(cookie);
        }

19 View Source File : CookiesService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public void AddCookie(System.Net.Cookie cookieToAdd)
        {
            var cookieValue = Uri.UnescapeDataString(cookieToAdd.Value);

            Cookie updatedCookie = new ReturnedCookie(
                cookieToAdd.Name,
                cookieValue,
                cookieToAdd.Domain,
                cookieToAdd.Path,
                cookieToAdd.Expires == default ? null : (DateTime?)cookieToAdd.Expires,
                cookieToAdd.Secure,
                cookieToAdd.HttpOnly);

            WrappedDriver.Manage().Cookies.AddCookie(updatedCookie);
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public static string GetExecutingreplacedemblyFolder()
        {
            var codeBase = replacedembly.GetExecutingreplacedembly().CodeBase;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : ReflectionProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public string GetRunningreplacedemblyPath()
        {
            string codeBase = replacedembly.GetExecutingreplacedembly().CodeBase;
            var uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : ProcessProvider.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet

public string GetEntryProcessApplicationPath()
        {
            // If we will write tests some day, create separate interfaces for below clreplacedes. But I think there is no need.
            string codeBase = replacedembly.GetExecutingreplacedembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }

19 View Source File : BaiduApiHelper.cs
License : MIT License
Project Creator : awesomedotnetcore

private string CanonicalRequest(HttpWebRequest req)
        {
            Uri uri = req.RequestUri;
            StringBuilder canonicalReq = new StringBuilder();
            canonicalReq.Append(req.Method).Append("\n").Append(UriEncode(Uri.UnescapeDataString(uri.AbsolutePath))).Append("\n");

            var parameters = HttpUtility.ParseQueryString(uri.Query);
            List<string> parameterStrings = new List<string>();
            foreach (KeyValuePair<string, string> entry in parameters)
            {
                parameterStrings.Add(UriEncode(entry.Key) + '=' + UriEncode(entry.Value));
            }
            parameterStrings.Sort();
            canonicalReq.Append(string.Join("&", parameterStrings.ToArray())).Append("\n");

            string host = uri.Host;
            if (!(uri.Scheme == "https" && uri.Port == 443) && !(uri.Scheme == "http" && uri.Port == 80))
            {
                host += ":" + uri.Port;
            }
            canonicalReq.Append("host:" + UriEncode(host));
            return canonicalReq.ToString();
        }

19 View Source File : PathIcon.cs
License : MIT License
Project Creator : ay2015

public void InitXmlToStream()
        {

            if (!_Init)
            {
                string dllPath = null;
                string _ad = null;
                if (WpfDesign.IsInDesignMode)
                {
                    var _a = Application.Current.Resources["design"] as DesignDevSupport;
                    _ad = System.IO.Path.Combine(_a.ContentDirectory, @"Icon\Path");
                    //_ad = System.IO.Path.Combine(@"E:\新建文件夹\AYUI7\AyWpfProject\bin\Debug\Content", @"Icon\Path");
                }
                else
                {
                    dllPath = Uri.UnescapeDataString(System.IO.Path.GetDirectoryName(new Uri(this.GetType().replacedembly.CodeBase).AbsolutePath));
                    _ad = System.IO.Path.Combine(dllPath, @"Content\Icon\Path");
                }
        
                var files = System.IO.Directory.GetFiles(_ad, "*.ayicon", System.IO.SearchOption.AllDirectories);
                if (files.Length > 1)
                {
                    xmlDoc = XDoreplacedent.Load(files[0]);
                }
                for (int i = 1; i < files.Length; i++)
                {
                    var xmlDoc1 = XDoreplacedent.Load(files[i]);
                    xmlDoc.Root.Add(xmlDoc1.Root.Elements());
                }
                _Init = false;
            }
        }

19 View Source File : JsonDataObjects.cs
License : MIT License
Project Creator : azist

public static JsonDataMap FromURLEncodedString(string content, bool caseSensitive = false)
    {
      var result = new JsonDataMap(caseSensitive);

      if (content.IsNullOrWhiteSpace()) return result;

      int queryLen = content.Length;
      int idx = 0;

      while (idx < queryLen)
      {
        int ampIdx = content.IndexOf('&', idx);
        int kvLen = (ampIdx != -1) ? ampIdx - idx : queryLen - idx;

        if (kvLen < 1)
        {
          idx = ampIdx + 1;
          continue;
        }

        int eqIdx = content.IndexOf('=', idx, kvLen);
        if (eqIdx == -1)
        {
          var key = Uri.UnescapeDataString(content.Substring(idx, kvLen).Replace('+',' '));
          result.Add(key, null);
        }
        else
        {
          int keyLen = eqIdx - idx;
          if (keyLen > 0)
          {
            var key = Uri.UnescapeDataString(content.Substring(idx, keyLen).Replace('+',' '));
            var val = Uri.UnescapeDataString(content.Substring(eqIdx + 1, kvLen - keyLen - 1).Replace('+',' '));

            result.Add(key, val);
          }
        }

        idx += kvLen + 1;
      }

      return result;
    }

19 View Source File : URIPattern.cs
License : MIT License
Project Creator : azist

public JsonDataMap MatchURIPath(Uri uri, bool senseCase = false)
    {
      JsonDataMap result = null;
      if (m_MatchChunks.Count==0) return new JsonDataMap(false);

      var segs = uri.AbsolutePath.Split('/');

      var ichunk = -1;
      chunk chunk = null;
      var wildCard = false;
      foreach(var seg in segs)
      {
        if (seg.Length==0) continue;//skip empty ////

        if (!wildCard)
        {
          ichunk++;
          if (ichunk>=m_MatchChunks.Count) return null;
          chunk = m_MatchChunks[ichunk];
        }

        if (chunk.Portion!=chunkPortion.Path) return null;

        if (chunk.IsWildcard)
        {
          wildCard = true;
          if (result==null) result = new JsonDataMap(false);
          if (!result.ContainsKey(chunk.Name))
            result[chunk.Name] = Uri.UnescapeDataString(seg);
          else
            result[chunk.Name] = (string)result[chunk.Name] + '/' + Uri.UnescapeDataString(seg);
        }
        else
        if (chunk.IsVar)
        {
          if (result==null) result = new JsonDataMap(false);
          result[chunk.Name] = Uri.UnescapeDataString(seg);
        }
        else
        if (!chunk.Name.Equals(seg, senseCase ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) return null;
      }//foreach

      ichunk++;
      while(ichunk<m_MatchChunks.Count)
      {
        chunk=m_MatchChunks[ichunk];
        if (!chunk.IsVar) return null;//some trailing elements that are not vars and  do not match
        if (result==null)
          result = new JsonDataMap(false);
        if (!result.ContainsKey(chunk.Name))
          result[chunk.Name] = chunk.DefaultValue;
        ichunk++;
      }

      return result ?? new JsonDataMap(false);
    }

See More Examples