Ejemplo n.º 1
0
        public void EncodeStringWithSpaceSetting(string?strEncoded, string?strDecoded)
        {
            var settings = new UrlEncodingSettings();

            settings.EncodedSpaceChar = '+';
            Assert.AreEqual(strEncoded, UrlEncoding.Encode(strDecoded, settings));
        }
Ejemplo n.º 2
0
    protected string GetViewArticleUrl(string id)
    {
        Article article = DocoManager.GetArticle(id);

        string root = Server.MapPath(Path.Combine("~/Doco/", System.Web.Configuration.WebConfigurationManager.AppSettings.Get(Resources.Resource.Root)));
        string path =
            string.Format(
                CultureInfo.InvariantCulture,
                Resource.NewObjectPath,
                root,
                article.Category.Id);

        if (!string.IsNullOrEmpty(article.FileName))
        {
            string url = string.Format(
                CultureInfo.InvariantCulture,
                Resource.DocoFilesLoc + Resource.FileOpen,
                UrlEncoding.Encode(Path.Combine(path, article.FileName)));
            return(url);
        }
        else
        {
            return(string.Empty);
        }
    }
Ejemplo n.º 3
0
    protected void lnkFileName_Click(object sender, EventArgs e)
    {
        string documentId = Request["id"]; //check for id in URL

        if (!string.IsNullOrEmpty(documentId))
        {
            Article article = DocoManager.GetArticle(documentId);
            AuditManager.Audit(Page.User.Identity.Name, article.Id, AuditRecord.AuditAction.Viewed);
            article = DocoManager.GetArticle(documentId);
            SetTrafficLight(article);

            string navigateUrl =
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resource.NewObjectPath,
                    "Files",
                    article.Category.Id);

            if (!string.IsNullOrEmpty(article.FileName))
            {
                navigateUrl = string.Format(
                    CultureInfo.InvariantCulture,
                    Resource.DocoFilesLoc + Resource.FileOpen,
                    UrlEncoding.Encode(Path.Combine(navigateUrl, article.FileName)));
                navigateUrl = navigateUrl.Insert(navigateUrl.IndexOf("&"), "&aid=" + article.Id);

                // go to that url
                Page.Response.Redirect(navigateUrl);
            }
        }
    }
Ejemplo n.º 4
0
    /// <summary>
    /// Deletes the specified sender.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    void Delete(object sender, CommandEventArgs e)
    {
        string file = e.CommandArgument.ToString();

        FileInfo fi = new FileInfo(file);

        // Determine type: folder or file.
        if (fi.Attributes == FileAttributes.Directory)
        {
            ReadOnlyFolderDelete(file);
        }
        else
        {
            // Remove all attributes first otherwise
            // this will fail against readonly files.
            fi.Attributes = FileAttributes.Normal;
            File.Delete(file);
        }

        // Send back to self to refresh.
        string deleteUrl =
            string.Format(
                CultureInfo.InvariantCulture,
                Resource.DeleteUrl,
                UrlEncoding.Encode(_root));

        HttpContext.Current.Response.Redirect(deleteUrl, true);
    }
        /// <summary>
        /// Creates a web panel that appears in the browser panel in superoffice with a button to open it.
        /// </summary>
        /// <param name="name">A string that represents the name of this panel. Cannot contain spaces. Spaces will be removed.</param>
        /// <param name="url">The URL the web panel will open to. </param>
        /// <param name="windowName">A string that represents the window name.</param>
        /// <param name="urlEncoding">URL encoding.</param>
        /// <param name="showInAddressBar">Determines whether the web panel displays the address bar.</param>
        /// <param name="showInMenuBar">Determines whether the web panel displays the browser menu.</param>
        /// <param name="showInStatusBar">Determines whether the web panel displays the browser status bar.</param>
        /// <param name="showInToolBar">Determines whether the web panel displays the toolbar.</param>
        /// <returns>Two web panel entities: one that represents the panel and one that represents the button.</returns>
        public WebPanelEntity[] CreateBrowserPanelWithButton(string name, string url, string windowName = null,
                                                             UrlEncoding urlEncoding = UrlEncoding.None,
                                                             bool showInAddressBar   = false,
                                                             bool showInMenuBar      = false,
                                                             bool showInStatusBar    = false,
                                                             bool showInToolBar      = false)
        {
            WebPanelEntity webPanelEntity;
            WebPanelEntity webButtonEntity;

            //Create the Panel
            string locWindowName = ParseSafeName(windowName ?? name, _windowPrefixFormat);

            if (!DoesWebPanelExist(name, locWindowName, out webPanelEntity))
            {
                webPanelEntity = CreateBasicWebPanel(name, locWindowName, url, Navigation.BrowserPanel, urlEncoding, showInAddressBar, showInMenuBar, showInStatusBar, showInToolBar);
            }

            string buttonName       = ParseSafeName(name, _buttonPrefixFormat);
            string buttonWindowName = ParseSafeName(windowName, _buttonWindowFormat);
            string buttonUrl        = string.Format(_locationPrefixFormat, buttonWindowName);

            //Create the button
            if (!DoesWebPanelExist(buttonName, buttonWindowName, out webButtonEntity))
            {
                webButtonEntity = CreateBasicWebPanel(buttonName, buttonWindowName, buttonUrl, Navigation.NavigatorButton, urlEncoding, showInAddressBar, showInMenuBar, showInStatusBar, showInToolBar);
            }

            return(new WebPanelEntity[] { webPanelEntity, webButtonEntity });
        }
        public WebPanelEntity UpdateWebPanel(int id, string name, string windowName, string url, string description, Navigation appearLocation,
                                             UrlEncoding urlEncoding = UrlEncoding.None,
                                             bool showInAddressBar   = false,
                                             bool showInMenuBar      = false,
                                             bool showInStatusBar    = false,
                                             bool showInToolBar      = false,
                                             bool deleted            = false)
        {
            WebPanelEntity webPanel;

            using (var listAgent = new ListAgent())
            {
                webPanel                     = listAgent.GetWebPanelEntity(id);
                webPanel.Name                = name;
                webPanel.Tooltip             = description;
                webPanel.WindowName          = windowName;
                webPanel.Url                 = url;
                webPanel.UrlEncoding         = urlEncoding;
                webPanel.VisibleIn           = appearLocation;
                webPanel.ShowInAddressBar    = showInAddressBar;
                webPanel.ShowInMenuBar       = showInMenuBar;
                webPanel.ShowInStatusBar     = showInStatusBar;
                webPanel.ShowInToolBar       = showInToolBar;
                webPanel.OnCentral           = true;
                webPanel.OnSalesMarketingWeb = true;
                webPanel.Deleted             = deleted;
                webPanel                     = listAgent.SaveWebPanelEntity(webPanel);
            }

            return(webPanel);
        }
Ejemplo n.º 7
0
        public void ChangeBytePrefixCharEncode()
        {
            var settings = new UrlEncodingSettings();

            settings.EncodedBytePrefixChar = '+';
            Assert.AreEqual("Hi+2c+20there", UrlEncoding.Encode("Hi, there", settings));
            Assert.AreEqual("Hi+2c+20there+20Ed+2e", UrlEncoding.Encode("Hi, there Ed.", settings));
        }
Ejemplo n.º 8
0
        public void ChangeBytePrefixCharToBackslashEncode()
        {
            var settings = new UrlEncodingSettings();

            settings.EncodedBytePrefixChar = '\\';
            Assert.AreEqual("Hi\\2c\\20there", UrlEncoding.Encode("Hi, there", settings));
            Assert.AreEqual("Hi\\2c\\20there\\20Ed\\2e", UrlEncoding.Encode("Hi, there Ed.", settings));
        }
Ejemplo n.º 9
0
        public void OnlyEncodeSpaces()
        {
            UrlEncodingSettings settings = new UrlEncodingSettings();

            settings.ShouldEncodeChar = delegate(char ch) { return(ch == ' '); };
            Assert.AreEqual("Hi,%20there", UrlEncoding.Encode("Hi, there", settings));
            Assert.AreEqual("Hi,%20there%20Ed.", UrlEncoding.Encode("Hi, there Ed.", settings));
        }
Ejemplo n.º 10
0
        public void OnlyEncodeSpaces()
        {
            var settings = new UrlEncodingSettings();

            settings.ShouldEncodeChar = ch => ch == ' ';
            Assert.AreEqual("Hi,%20there", UrlEncoding.Encode("Hi, there", settings));
            Assert.AreEqual("Hi,%20there%20Ed.", UrlEncoding.Encode("Hi, there Ed.", settings));
        }
Ejemplo n.º 11
0
        public void ChangeEncoding()
        {
            var settings = new UrlEncodingSettings();

            settings.TextEncoding = Encoding.UTF32;
            Assert.AreEqual("Hi%2c%00%00%00%20%00%00%00there", UrlEncoding.Encode("Hi, there", settings));
            Assert.AreEqual("Hi%2c%00%00%00%20%00%00%00there%20%00%00%00Ed%2e%00%00%00", UrlEncoding.Encode("Hi, there Ed.", settings));
        }
Ejemplo n.º 12
0
        public void UppercaseHexDigits()
        {
            var settings = new UrlEncodingSettings();

            Assert.AreEqual("Hi, there", UrlEncoding.Decode("Hi%2c%20there", settings));
            settings.UppercaseHexDigits = true;
            Assert.AreEqual("Hi, there", UrlEncoding.Decode("Hi%2C%20there", settings));
        }
Ejemplo n.º 13
0
 public static string UrlEncode(
     string s,
     UrlEncoding urlEncoding)
 {
     return(UrlEncode(
                s,
                urlEncoding,
                Encoding.UTF8));
 }
        ///// <summary>
        /////     编码(转义)为十六进制表示形式。所有字符在转义之前都会先转换为 UTF-8 格式。(对RFC 2396 保留字符不进行转换)
        ///// </summary>
        //public static string EscapeDataString(this string source)
        //{
        //    return Uri.EscapeDataString(source);
        //}

        /// <summary>
        ///     编码(转义)为十六进制表示形式,所有字符在转义之前都会先转换为指定的编码格式(默认为GBK)格式。(对RFC 2396 保留字符不进行转换)
        /// </summary>
        /// <param name="source">要进行编码的字符串</param>
        /// <param name="urlEncoding">编码枚举类型</param>
        /// <returns>经过编码的字符串</returns>
        public static string EscapeDataStringBy(this string source, UrlEncoding urlEncoding = UrlEncoding.GB2312)
        {
            if (Uri.IsWellFormedUriString(source, UriKind.RelativeOrAbsolute)) return source; //对RFC 2396 保留字符不进行转换
            var bytes = urlEncoding.ToEncoding().GetBytes(source);
            var re = new StringBuilder();
            foreach (var @byte in bytes)
                re.Append(Uri.HexEscape((char)@byte)); //等价于: re.Append("%" + @byte.ToString("X2"));
            return re.ToString();
        }
Ejemplo n.º 15
0
		/// <summary>
		/// URL-encode a text with the given encoding.
		/// </summary>
		/// <param name="s">The s.</param>
		/// <param name="urlEncoding">The URL encoding.</param>
		/// <returns></returns>
		public static string UrlEncode(
			string s,
			UrlEncoding urlEncoding )
		{
			return UrlEncode(
				s,
				urlEncoding,
				Encoding.UTF8 );
		}
Ejemplo n.º 16
0
        public void EncodeStringWithSpaceCustomShouldEncode(string?strEncoded, string?strDecoded)
        {
            var settings = new UrlEncodingSettings
            {
                EncodedSpaceChar = '+',
                ShouldEncodeChar = ch => ch == 'e',
            };

            Assert.AreEqual(strEncoded, UrlEncoding.Encode(strDecoded, settings));
            Assert.AreEqual(strDecoded, UrlEncoding.Decode(strEncoded, settings));
        }
Ejemplo n.º 17
0
    /// <summary>
    /// Renames the specified sender.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    void Rename(object sender, CommandEventArgs e)
    {
        string file      = e.CommandArgument.ToString();
        string renameUrl =
            string.Format(
                CultureInfo.InvariantCulture,
                Resource.RenameUrl,
                UrlEncoding.Encode(_root),
                UrlEncoding.Encode(file));

        HttpContext.Current.Response.Redirect(renameUrl, true);
    }
Ejemplo n.º 18
0
        internal static IEnumerable <KeyValuePair <string, string> > GetQueryParameters(string query)
        {
            if (query is null || query.Length < 2 || query[0] != '?')
            {
                return(Array.Empty <KeyValuePair <string, string> >());
            }

            return(query.Substring(1)
                   .Split('&')
                   .Select(str => str.Split(new[] { '=' }, 2))
                   .Select(x => new KeyValuePair <string, string>(UrlEncoding.Decode(x[0], UrlEncodingSettings.HttpUtilitySettings), x.Length == 1 ? "" : UrlEncoding.Decode(x[1], UrlEncodingSettings.HttpUtilitySettings))));
        }
        public Tuple <byte[], string> GetBinary(Localization localization, string urlPath)
        {
            var client = ApiClientFactory.Instance.CreateClient();
            var binary = client.GetBinaryComponent(localization.Namespace(), localization.PublicationId(),
                                                   UrlEncoding.UrlPartialPathEncode(urlPath), null, null);
            var data = GetBinaryData(client, binary);

            if (data == null)
            {
                throw new DxaItemNotFoundException(urlPath, localization.Id);
            }
            return(data);
        }
Ejemplo n.º 20
0
        public void SettingsFromSettings()
        {
            var settings = new UrlEncodingSettings();

            settings.TextEncoding = Encoding.UTF32;

            var settingsNew = settings.Clone();

            settingsNew.EncodedBytePrefixChar = '+';

            Assert.AreEqual("Hi+2c+00+00+00+20+00+00+00there", UrlEncoding.Encode("Hi, there", settingsNew));
            Assert.AreEqual("Hi+2c+00+00+00+20+00+00+00there+20+00+00+00Ed+2e+00+00+00", UrlEncoding.Encode("Hi, there Ed.", settingsNew));
        }
Ejemplo n.º 21
0
        ///// <summary>
        /////     编码(转义)为十六进制表示形式。所有字符在转义之前都会先转换为 UTF-8 格式。(对RFC 2396 保留字符不进行转换)
        ///// </summary>
        //public static string EscapeDataString(this string source)
        //{
        //    return Uri.EscapeDataString(source);
        //}

        /// <summary>
        ///     编码(转义)为十六进制表示形式,所有字符在转义之前都会先转换为指定的编码格式(默认为GBK)格式。(对RFC 2396 保留字符不进行转换)
        /// </summary>
        /// <param name="source">要进行编码的字符串</param>
        /// <param name="urlEncoding">编码枚举类型</param>
        /// <returns>经过编码的字符串</returns>
        public static string EscapeDataStringBy(this string source, UrlEncoding urlEncoding = UrlEncoding.GB2312)
        {
            if (Uri.IsWellFormedUriString(source, UriKind.RelativeOrAbsolute))
            {
                return(source);                                                               //对RFC 2396 保留字符不进行转换
            }
            var bytes = urlEncoding.ToEncoding().GetBytes(source);
            var re    = new StringBuilder();

            foreach (var @byte in bytes)
            {
                re.Append(Uri.HexEscape((char)@byte)); //等价于: re.Append("%" + @byte.ToString("X2"));
            }
            return(re.ToString());
        }
Ejemplo n.º 22
0
        public static Encoding ToEncoding(this UrlEncoding encoding)
        {
            switch (encoding)
            {
            case UrlEncoding.NONE:
                return(Encoding.Default);

            case UrlEncoding.UTF8:
            case UrlEncoding.GB2312:
                return(Encoding.GetEncoding((int)encoding));

            default:
                return(Encoding.Default);
            }
        }
        public async Task <Tuple <byte[], string> > GetBinaryAsync(Localization localization, string urlPath, CancellationToken cancellationToken = default(CancellationToken))
        {
            var client = ApiClientFactory.Instance.CreateClient();
            var binary =
                await
                client.GetBinaryComponentAsync(localization.Namespace(), localization.PublicationId(),
                                               UrlEncoding.UrlPartialPathEncode(urlPath), null, null, cancellationToken).ConfigureAwait(false);

            var data = await GetBinaryDataAsync(client, binary, cancellationToken).ConfigureAwait(false);

            if (data == null)
            {
                throw new DxaItemNotFoundException(urlPath, localization.Id);
            }
            return(data);
        }
Ejemplo n.º 24
0
        public void SettingsClone()
        {
            var settings = new UrlEncodingSettings
            {
                EncodedBytePrefixChar = '!',
                EncodedSpaceChar      = '$',
                PreventDoubleEncoding = true,
                UppercaseHexDigits    = true,
                ShouldEncodeChar      = ch => ch == '@',
                TextEncoding          = Encoding.UTF32,
            };
            var settingsClone = settings.Clone();

            Assert.AreEqual(settings.EncodedBytePrefixChar, settingsClone.EncodedBytePrefixChar);
            Assert.AreEqual(settings.EncodedSpaceChar, settingsClone.EncodedSpaceChar);
            Assert.AreEqual(settings.PreventDoubleEncoding, settingsClone.PreventDoubleEncoding);
            Assert.AreEqual(settings.UppercaseHexDigits, settingsClone.UppercaseHexDigits);
            Assert.AreEqual(UrlEncoding.Encode("!@#$ 駉", settings), UrlEncoding.Encode("!@#$ 駉", settingsClone));
        }
Ejemplo n.º 25
0
    /// <summary>
    /// Retrieves a URL friendly string that points to an article.
    /// </summary>
    /// <param name="name">The name of the article</param>
    /// <returns>A user friendly Url for the article</returns>
    protected string GetViewArticleUrl(string name)
    {
        // If it is an uploaded document, then view the document and set the acknowledged flag
        // to true (via audit).
        Article article = DocoManager.GetArticleByName(name, false);

        if (article.IsUpload)
        {
            if (!article.Acknowledged)
            {
                // todo Popup to say that this will be acknowledged.
                AuditManager.Audit(Page.User.Identity.Name, article.Id + article.Version.ToString(CultureInfo.InvariantCulture), AuditRecord.AuditAction.Acknowledged);
            }

            string root = Server.MapPath(System.IO.Path.Combine("../Doco/", System.Web.Configuration.WebConfigurationManager.AppSettings.Get(Resource.Root)));
            string path =
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resource.NewObjectPath,
                    root,
                    article.Category.Id);

            if (!string.IsNullOrEmpty(article.FileName))
            {
                string url = string.Format(
                    CultureInfo.InvariantCulture,
                    Resource.DocoFilesLoc + Resource.FileOpen,
                    UrlEncoding.Encode(System.IO.Path.Combine(path, article.FileName)));
                return(url);
            }
            else
            {
                return(string.Empty);
            }
        }
        else
        {
            return(Navigation.Doco_ViewArticle(name, 0).GetClientUrl(this, true) + "&cMode=pub&id=" + article.Category.Id);
        }
    }
        private WebPanelEntity CreateBasicWebPanel(string name, string windowName, string url, Navigation appearLocation,
                                                   UrlEncoding urlEncoding = UrlEncoding.None,
                                                   bool showInAddressBar   = false,
                                                   bool showInMenuBar      = false,
                                                   bool showInStatusBar    = false,
                                                   bool showInToolBar      = false)
        {
            WebPanelEntity mainWebPanelEntity;

            try
            {
                using (var listAgent = new SuperOffice.CRM.Services.ListAgent())
                {
                    mainWebPanelEntity            = listAgent.CreateDefaultWebPanelEntity();
                    mainWebPanelEntity.Tooltip    = _webPanelDescription;
                    mainWebPanelEntity.Name       = name;
                    mainWebPanelEntity.WindowName = windowName;

                    mainWebPanelEntity.Url              = url;
                    mainWebPanelEntity.UrlEncoding      = urlEncoding;
                    mainWebPanelEntity.VisibleIn        = appearLocation;
                    mainWebPanelEntity.ShowInAddressBar = showInAddressBar;
                    mainWebPanelEntity.ShowInMenuBar    = showInMenuBar;
                    mainWebPanelEntity.ShowInStatusBar  = showInStatusBar;
                    mainWebPanelEntity.ShowInToolBar    = showInToolBar;
                    //mainWebPanelEntity.OnCentral = true;
                    mainWebPanelEntity.OnSalesMarketingWeb = true;
                    mainWebPanelEntity.Rank = 100;

                    mainWebPanelEntity = listAgent.SaveWebPanelEntity(mainWebPanelEntity);
                }
            }
            catch (Exception)
            {
                throw;
            }


            return(mainWebPanelEntity);
        }
        /// <summary>
        /// Create a web panel in the logged in users' installation of SuperOffice.
        /// </summary>
        /// <param name="name">The string that uniquely identifies the web panel. This name will be stripped of spacing and special characters, and appended with "Panel", so it becomes namePanel.</param>
        /// <param name="appearLocation">Where in SuperOffice the panel will be shown</param>
        /// <param name="url">The url to show in the web panel</param>
        /// <param name="windowName">Window Name </param>
        /// <param name="urlEncoding"></param>
        public WebPanelEntity CreateWebPanel(
            string name,
            string url,
            Navigation appearLocation,
            string windowName       = null,
            UrlEncoding urlEncoding = UrlEncoding.None,
            bool showInAddressBar   = false,
            bool showInMenuBar      = false,
            bool showInStatusBar    = false,
            bool showInToolBar      = false)
        {
            WebPanelEntity webPanel;

            string locWindowName = ParseSafeName(windowName ?? name, _windowPrefixFormat);

            if (DoesWebPanelExist(name, locWindowName, out webPanel))
            {
                if (webPanel.Deleted)
                {
                    // this will happen when the user reinstalls a webpanel
                    WebPanelEntity webPanelEntity = UpdateWebPanel(webPanel.WebPanelId, name, locWindowName, url, _webPanelDescription, appearLocation
                                                                   , urlEncoding
                                                                   , showInAddressBar, showInMenuBar, showInStatusBar, showInToolBar
                                                                   , false); // NB!
                    return(webPanelEntity);
                }
                else
                {
                    throw new WebPanelNameNotUniqueException(
                              "WebPanelHelper: The name isn't unique, and it isn't marked as deleted. Did you already install this? You could try again with a different name...");
                }
            }
            else
            {
                WebPanelEntity webPanelEntity = CreateBasicWebPanel(name, locWindowName, url, appearLocation, urlEncoding, showInAddressBar, showInMenuBar, showInStatusBar, showInToolBar);
                return(webPanelEntity);
            }
        }
Ejemplo n.º 28
0
	    public static string UrlEncode(
	        string s,
	        UrlEncoding urlEncoding,
	        Encoding e)
	    {
	        if (s == null)
	        {
	            return null;
	        }
	        else if (s.Length <= 0)
	        {
	            return string.Empty;
	        }
	        else
	        {
	            var bytes = e.GetBytes(s);
	            return Encoding.ASCII.GetString(
	                urlEncodeToBytes(
	                    bytes,
	                    0, bytes.Length,
	                    urlEncoding));
	        }
	    }
Ejemplo n.º 29
0
        private void Response_SendingResponse(object sender, ResponseEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new HttpResponse.ResponseEventHandler(Response_SendingResponse), new object[] { sender, e });
                return;
            }

            ListViewItem item = clients[e.HttpClient] as ListViewItem;

            if (item == null)
            {
                return;
            }

            if (e.Response.Request.Uri != null)
            {
                item.SubItems[lastRequestColumn.Index].Text = UrlEncoding.Decode(e.Response.Request.Uri.PathAndQuery);
                item.SubItems[responseColumn.Index].Text    = StatusCodes.GetDescription(e.Response.ResponseCode);
            }

            item.Tag = new TransferTag(e.Response);
        }
Ejemplo n.º 30
0
 public static string UrlEncode(
     string s,
     UrlEncoding urlEncoding,
     Encoding e)
 {
     if (s == null)
     {
         return(null);
     }
     else if (s.Length <= 0)
     {
         return(string.Empty);
     }
     else
     {
         var bytes = e.GetBytes(s);
         return(Encoding.ASCII.GetString(
                    urlEncodeToBytes(
                        bytes,
                        0, bytes.Length,
                        urlEncoding)));
     }
 }
Ejemplo n.º 31
0
 public Url Encoding(UrlEncoding encoding)
 {
     _data.Encoding(encoding);
     return this;
 }
Ejemplo n.º 32
0
 public void DecodeString(string?strEncoded, string?strDecoded)
 {
     Assert.AreEqual(strDecoded, UrlEncoding.Decode(strEncoded));
 }
        private static byte[] urlEncodeToBytes(
			byte[] bytes,
			int offset,
			int count,
			UrlEncoding urlEncoding)
        {
            if (bytes == null)
                return null;

            var len = bytes.Length;
            if (len == 0)
                return new byte[0];

            if (offset < 0 || offset >= len)
            {
                throw new ArgumentOutOfRangeException(@"offset");
            }

            if (count < 0 || count > len - offset)
            {
                throw new ArgumentOutOfRangeException(@"count");
            }

            // --

            string additionalSafeChars;
            switch (urlEncoding)
            {
                case UrlEncoding.XAlphas:
                    additionalSafeChars = @"+";
                    break;
                case UrlEncoding.XPAlphas:
                    additionalSafeChars = @"+/";
                    break;
                case UrlEncoding.DosFile:
                    additionalSafeChars = @"+/:";
                    break;
                default:
                    additionalSafeChars = string.Empty;
                    break;
            }

            // --

            using (var result = new MemoryStream())
            {
                var end = offset + count;
                for (var i = offset; i < end; i++)
                {
                    var c = (char)bytes[i];

                    var isUnsafe =
                        (c == ' ') || (c < '0' && c != '-' && c != '.') ||
                            (c < 'A' && c > '9') ||
                                (c > 'Z' && c < 'a' && c != '_') ||
                                    (c > 'z');

                    if (isUnsafe &&
                        additionalSafeChars.IndexOf(c) >= 0)
                    {
                        isUnsafe = false;
                    }

                    if (isUnsafe)
                    {
                        // An unsafe character, must escape.
                        result.WriteByte((byte)'%');
                        var idx = c >> 4;
                        result.WriteByte((byte)HexChars[idx]);
                        idx = c & 0x0F;
                        result.WriteByte((byte)HexChars[idx]);
                    }
                    else
                    {
                        // A safe character just write.
                        result.WriteByte((byte)c);
                    }
                }

                return result.ToArray();
            }
        }
Ejemplo n.º 34
0
 public void DecodingError()
 {
     Assert.AreEqual("Hi\uFFFD there", UrlEncoding.Decode("Hi%A1 there"));
 }
Ejemplo n.º 35
0
		/// <summary>
		/// URLs the encode to bytes.
		/// </summary>
		/// <param name="bytes">The bytes.</param>
		/// <param name="offset">The offset.</param>
		/// <param name="count">The count.</param>
		/// <param name="urlEncoding">The URL encoding.</param>
		/// <returns></returns>
		private static byte[] UrlEncodeToBytes(
			byte[] bytes,
			int offset,
			int count,
			UrlEncoding urlEncoding )
		{
			if ( bytes == null )
			{
				return null;
			}
			else
			{
				int len = bytes.Length;
				if ( len == 0 )
				{
					return new byte[0];
				}
				if ( offset < 0 || offset >= len )
				{
					throw new ArgumentOutOfRangeException( @"offset" );
				}
				if ( count < 0 || count > len - offset )
				{
					throw new ArgumentOutOfRangeException( @"count" );
				}

				// --

				string additionalSafeChars;
				if ( urlEncoding == UrlEncoding.XAlphas )
				{
					additionalSafeChars = @"+";
				}
				else if ( urlEncoding == UrlEncoding.XPAlphas )
				{
					additionalSafeChars = @"+/";
				}
				else if ( urlEncoding == UrlEncoding.DosFile )
				{
					additionalSafeChars = @"+/:(){}[]$";
				}
				else
				{
					additionalSafeChars = string.Empty;
				}

				// --

				using ( MemoryStream result = new MemoryStream() )
				{
					int end = offset + count;
					for ( int i = offset; i < end; i++ )
					{
						char c = (char)bytes[i];

						bool isUnsafe =
							(c == ' ') ||
							(c < '0' && c != '-' && c != '.' && c != '!') ||
							(c < 'A' && c > '9') ||
							(c > 'Z' && c < 'a' && c != '_') ||
							(c > 'z');

						if ( isUnsafe &&
							additionalSafeChars.IndexOf( c ) >= 0 )
						{
							isUnsafe = false;
						}

						if ( isUnsafe )
						{
							// An unsafe character, must escape.
							result.WriteByte( (byte)'%' );
							int idx = ((int)c) >> 4;
							result.WriteByte( (byte)hexChars[idx] );
							idx = ((int)c) & 0x0F;
							result.WriteByte( (byte)hexChars[idx] );
						}
						else
						{
							// A safe character just write.
							result.WriteByte( (byte)c );
						}
					}

					return result.ToArray();
				}
			}
		}
Ejemplo n.º 36
0
 public void DecodeNullSettings()
 {
     Assert.Throws <ArgumentNullException>(() => UrlEncoding.Decode("test", null !));
 }