.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Differences between Encoding.GetEncoding and instantiating a specific encoding

Posted By:      Posted Date: October 02, 2010    Points: 0   Category :.NET Framework

Hi all,

is there any difference between the following lines? 

Encoding enc = Encoding.GetEncoding("utf-8");
Encoding enc = new UTF8Encoding();

Because when I use this in a custom message encoder for WCF, the behavior is different when using this encoding in an XmlWriter using XmlWriterSettings.

The first one result i

View Complete Post

More Related Resource Links

prevent browser specific url encoding


hello everyone,

postBackEventReference = this.Page.ClientScript.GetPostBackEventReference(postBackOptions, true);

has a different result depending on the agent which made the request.
I need to overwrite this behaviour in a server control and return exactly the same code for IE/FF/Chrome/...

My custom server control inherits from LinkButton. I'm overriding

protected override void AddAttributesToRender(HtmlTextWriter writer)

For example I'm adding a custom postback url. This url contains "<" in its markup which of course needs to be escaped to %3c.
The GetPostBackEventReference(..) method returns %3c if the request was made with FF/Chrome and so on and %253c if the Request was made with MSIE.
I'm having serious trouble getting %3c encoded urls to work in FF/Chrome and so on. So I went on and replaced escaped all '%' to '%25' one more time.

Unfortunately modifying the result of the GetPostBackEventReference(...) method has little effect. As soon as

writer.AddAttribute(HtmlTextWriterAttribute.Href, postBackEventReference);

is called, my postBackEventReference string is stripped of all the extra %25 encodings I put into the F

Encoding en Decoding HTML



I stored in a database a ntext "<b>Hello</b>";

But when  I read it from the database I see <b>Hello</b> instead of Hello.

In the html source I see this: &lt;b&gt;Hello&lt;/b&gt;

Any Idea?


ASP.NET XML Writer Encoding Problem


Hi everybody,

I'm working on an ASP.NET application which writes xml sitemap to xml file. while I'm generating the loc element, I found that the writer converts the "&" in dynamic URLs to "&amp;" which I think it's not acceptable by Google. is there any way to get out of this?

Part of my code is as follow:

                writer.WriteString("/english/pages/pages.aspx?sid=" + drSections("SectionID").ToString + "&pageid=" + drPages("PageID").ToString + "")

and my output comes like :

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

Express Yourself: Encoding Videos Using Microsoft Expression Encoder 3 SDK


Video on the Web involves huge amounts of data. Learn the best way to manage and move that data with the help of Microsoft Expression Encoder 3.

Adam Miller

MSDN Magazine June 2010

The XML Files: Web Services Encoding and More


Aaron Skonnard covers the difference between document/literal and rpc/encoded Web Services and the history behind them.

Aaron Skonnard

MSDN Magazine May 2003

Encoding Problems in Razor



On my projects I am using SquisIt Framework and I have the following on page head:


      .Render("~/Styles/FlyOnDreams.FlyOnPages.Core.min.css")) %>

This is working. However when I use Razor view engine I am using the following:


How do I avoid chunked encoding either in HttpListener or in SimpleWorkerRequest?



I am writing a simple web server that uses HttpListner (http.sys) as a listener and an output conduit, and a SimpleWorkerRequest to process ASP.NET requests. All works well, but when an application my server hosts outputs chunked response, ASP.NET calls SimpleWorkerRequest's SendResponseFromMemory() method and passes in data that is chunked-encoded. When I write the output to HttpListener's output stream, it gets chunk-encoded again, breaking the whole thing. So I ended up writing chunked decoder in the middle, which makes it inefficient because the response gets massaged three times instead of one:

  1. Chunked-encoded by ASP.NET HttpResponse, then
  2. Decoded by my code in the SimpleWorkerRequest.SendResponseFromMemory(), and
  3. Gets chunked-encoded again by writing to HttpListner's output stream.

My question is how do I tell either SimpleWorkerRequest or HttpListener not to chunk-encode the response so the encoding can be done only once by either of those? (Preferably, it's SimpleWorkerRequest that needs an option to pass the response to the web server without changing it so that HttpListener would encode all responses, whether the come from ASP.NET or not, for example from CGI request processor).

Thank you,

encoding/decoding a string to/from bitmap


I have two methods:

Encode - takes a string, converts it to array of bytes, uses bytes to specify colors, creates a color and sets a pixel based on bytes

Decode - takes a pixel, retrieves color (R,G,B) bytes and converts them to characters, that produces a string which was previously encoded

I'm using two for loops (img height/width) to specify position and access pixels

The issue is that once display (Control Panel\Appearance and Personalization\Display) changes to anything other then "Smaller - 100%",
bytes have different values during decoding, thus different string is produced (corrupted).

If the setting is set to "Smaller - 100%" the results are normal.

What can I do to avoid that problem?

Thanks in advance

Info Path form when modified by using UTF-8 encoding having issues with existing 'iso-8859-1' char



I am modifying the infio path form 2007 from my state machine workflow to constantly update the status fields in the request form.

below is the method i created for the same..

private void updateInfoPathRequestForm(string xpathNode, string nodeValue)
            SPUserToken token = workflowProperties.Web.CurrentUser.UserToken;
            using (SPSite _site = new SPSite(workflowProperties.Site.ID, token))
                _site.AllowUnsafeUpdates = true;
                using (SPWeb _web = _site.OpenWeb(workflowProperties.Web.ID))
                    SPListItem item = _web.Lists[workflowProperties.List.ID].Items[workflowProperties.Item.UniqueId];

Encoding.ASCII.GetString(bytes) return string with not expected

Example   byte[] bytes = {  0x36,0x92,0x30,0x94}; string rs=  Encoding.ASCII.GetString(bytes) ; //result rs = ?60?   Is Wrong Result; Result Right is     '60". So this function should fix to properly decode two symbols ' and " Code ASCII ' is 0x92,Code ACII for " is  0x94

Storing and displaying user input (encoding query)

Hello,I've just been reading up a little on security regarding user input and how to handle html and scripts.My question is, what if I build my own CMS?Isn't it inevitable that I'll want to store html code, possibly scripts, and almost certainly apostrophes and special characters, and then display them again.What's the best way to do this, since I wont want to display the encoded html, but the html itself.Would it be to encode everything then when I want to actually display the html, decode it, but everywhere else, keep it encoded?I'm just trying to think of all the scenario's that I could come across when I accept user input where I don't know what they could be typing in.What if I WANT the user to be able to display html?Is it possible to decode only some tags but leave all other tags encoded? 

UrlEncode does not appear to be encoding apostrophe's

All,I have spent quite a bit of time researching this here on Asp.Net's Forums, but also on the web in general, and I am still drawing a blank.The problem:  I am trying pass a values such as ... "Jacob's Carpentry" as a query string to another page.  However, the other pages keeps seeing "Jacob\\s Carpentry".What I have tried:  I have tried using both the Server.UrlEncode and HttpUtility.UrlEncode, and neither have worked.  I have also tried using them twice as was suggested in this article, but still with no luck.  Finally, I went so far as to try and encode the string, but then do a String.Replace on the " ' " apostrophe and substitute with a "%27".  This also did not work, as it appeared that the String.Replace wiped out the encoding.So I am stuck/lost.  It appears the standard PHP functions easily encode the apostrophe, but for some reason the .Net function isn't working.Here is the code I am using ..._postAReviewLinkButton.PostBackUrl = "~/ReviewskiPostReview.aspx?company=" + Server.UrlEncode(theCompany.CompanyName);As I understand it, when using the Request.QueryString method, it will automatically Decode the value as well, so when I read it, I am simply doing the following ...Company.GetByCompanyName(Request.QueryString["company"].ToString());I notice,

Content-Encoding Headers Being Removed?

Hello everyone. I've got a question.So I have an HttpModule that compresses the response with either gzip or deflate. Here's the code:     public class CompressionModule : IHttpModule    {        public void Dispose()        {        }        public void Init(HttpApplication context)        {            context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);            context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);        }        void context_ReleaseRequestState(object sender, EventArgs e)        {            // Get the application.            HttpApplication app = (HttpApplication)sender;            // The Accept-Encoding header from the client's browser.            string acceptE

Strings stripped of leading whitespace when using MTOM message encoding

Hello, I have a problem which I believe is actually caused by a bug in WCF 4 (.Net 4). I have a WCF service exposes two basicHttpBinding endpoints identical in everything but the message encoding used, one uses "text" and one "mtom" (i.e. the values for the messageEncoding attribute on the binding configuration). If I send a string with leading whitespaces to the "text endpoint" it is delivered to the service application code exactly as sent. If I send the string to the "mtom endpoint" it is stripped of the leading whitespaces before being handed over to the service application code. I have confirmed that the leading whitespaces are included in the message on the wire and using an IDispatchMessageInspector I have also confirmed that the whitespaces are still present after decoding the message (Message.ToString()). The whitespaces seem to disappear between this stage and when the message is deserialized. My current workaround is an IDispatchMessageInspector with the following AfterReceiveRequest method: public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { // Doing this roundtrip over MessageBuffer removes the problem // (i.e. leading whitespaces are not removed) request = request.CreateBufferedCopy(int.MaxValue).CreateMessage(); return null; } Am I missing something he

How to prevent special character encoding when using xslt value in javascript variable

Hi, I've created a dataview and inserting a little bit of javascript. I need to store one of the xslt values into a javascript variable. The problem is that when I get the value into my javascript variable, it is already encoding special characters . for example, instead of "<", I get "&lt;" Am I doing something inaccurate here? I even tried using the javascript unescape() function, but that didn't work. would you be able to advise how to get the xslt value into a javascript variable as it is without having the original data changed? <xsl:template ... ... <SCRIPT type="text/javaScript"> <![CDATA[ ...     var myData = ']]><xsl:value-of select="@sampleData" disable-output-escaping="yes"/><![CDATA['  ;  ... ]]> </SCRIPT> Pman http://www.pmansLab.com/

google Translate Encoding Problems With C#

//Create a Google Translate String To Translate From Google. string Translate(string inputStr, string fromLanguage, string toLanguage) { string url = string.Format("http://translate.google.com/translate_a/t?client=t&text={0}&hl=en&sl={1}&tl={2}&multires=1&pc=0&sc=1", inputStr, fromLanguage, toLanguage); WebClient tmpClient = new WebClient(); tmpClient.Encoding = System.Text.Encoding.UTF8; string result = tmpClient.DownloadString(url); return result; } Now The Problem is If You Pass something like that Translate("Hello","en","ur"); Return String: JSON String But Couldn't Really Get The Write Method to Get ???? ???? Instead Of ? ?? ?? ? { ur: [[["? ?? ?? ?","Hello World",""]],,"en"] }   In Browsers The URL is Showing Correct Returned String. Urdu is unicode Language. The String Return in result is Whole Messed up with ???? ?? ???? something like that. I tried to Convert it in Different Encodings But Not Couldn't get Anythine usefull. How Can I Correct That I Wanted To Further Save It In XML File.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend