Solved

Replacing backslashes in C#

Posted on 2004-09-03
26
1,087 Views
Last Modified: 2009-12-16
Hello all. What I am doing here is calling a a stored procedure (sproc) from C#, which is returning me a result set in xml format. The xml looks like this:

<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

But it should look like this:
<row Type="Revenue" Product="Payday" Frequency="Today" Value="1.500" Teller="" Location="1"/>

I am not sure where the \'s are coming from, looks like it might have to do with having quotes in my xml coming back and c# rendering it as an illegal escape sequence.. My sql does not have any \'s in them. I have a feeling that C# is treating this xml that gets returned by using my (XML Reader Object).ReadOuterXml(); . What am I doing wrong here folks. Please let me know. Thanks

slimbx
0
Comment
Question by:slimbx
  • 9
  • 9
  • 6
  • +1
26 Comments
 
LVL 10

Expert Comment

by:eternal_21
ID: 11975626
Where are you see this?  Try outputting your result set to the Console and see if it looks correct.  If you are seeing this in the debugger, that is just the way that Visual Studio represents strings, and everything should be okay.
0
 

Author Comment

by:slimbx
ID: 11975838
Here is my code to help:  (EXCUSE THE LACK INDENTATIONS)

private string GetXML(string sCmnd, string sParamList, SqlConnection oConn,ref string sErrMsg)
{
//The purpose of this function is to return xml data in a single node with attributes based on command passed in
string sRetXML = "";
string sStartDate = "";
string sEndDate = "";
clsUtility cUtil = new clsUtility();                  //instantiate clsUtility class for use

//parse out the data parameter line passed in
char[] sep = {','};
string[] sParams = sParamList.Split(sep);
                       
//determine the start and end dates prior to execution based on frequency, based on specified date
sStartDate = cUtil.GetStartDate(sParams[4].Trim(),sParams[5].Trim());
sEndDate = cUtil.GetEndDate(sParams[4].Trim(),sStartDate);
                  
//begin building the command object to execute selected sproc
SqlCommand sqlCmnd = new SqlCommand(sParams[0].Trim(),oConn);
sqlCmnd.CommandType = CommandType.StoredProcedure;
//XmlReader oReader = null;
SqlDataReader oReader = null;
                  
//perform call to correct stored procedure
try
{
      //build a command object based on stored procedure to query to retrieve xml
      sqlCmnd.Parameters.Add(new SqlParameter("@pQueryType",SqlDbType.VarChar,3));
      sqlCmnd.Parameters["@pQueryType"].Value = sParams[1];
      sqlCmnd.Parameters.Add(new SqlParameter("@pType",SqlDbType.VarChar,25));
      sqlCmnd.Parameters["@pType"].Value = sParams[2];
      sqlCmnd.Parameters.Add(new SqlParameter("@pProduct",SqlDbType.VarChar,15));
      sqlCmnd.Parameters["@pProduct"].Value = sParams[3];
      sqlCmnd.Parameters.Add(new SqlParameter("@pFrequency",SqlDbType.VarChar,5));
      sqlCmnd.Parameters["@pFrequency"].Value = sParams[4];
      sqlCmnd.Parameters.Add(new SqlParameter("@pStartDate",SqlDbType.SmallDateTime,0));
      sqlCmnd.Parameters["@pStartDate"].Value = sStartDate;
      sqlCmnd.Parameters.Add(new SqlParameter("@pEndDate",SqlDbType.SmallDateTime,0));
      sqlCmnd.Parameters["@pEndDate"].Value = sEndDate;
      sqlCmnd.Parameters.Add(new SqlParameter("@pTeller",SqlDbType.VarChar,3));
      sqlCmnd.Parameters["@pTeller"].Value = sParams[6];
      sqlCmnd.Parameters.Add(new SqlParameter("@pLocation",SqlDbType.Int,0));
      sqlCmnd.Parameters["@pLocation"].Value = sParams[7];
               //oReader = sqlCmnd.ExecuteXmlReader();                  
      oReader = sqlCmnd.ExecuteReader();
                                                        
      //determine if data reader returned an xml string or not
      if (oReader.Read())
      {
            //sRetXML = oReader.ReadOuterXml();
            sRetXML = oReader.GetString(0);
            //sRetXML = sRetXML.Replace("\\" & Chr(&H22),Chr(&H22));
      }
                }
      catch (Exception e)
      {
      sErrMsg = "Exception " + e.Source + " was thrown because " + e.Message + "\n";
      sRetXML = "";                        //errors raised, return blank string, no xml found      }
      sqlCmnd.Dispose();
      oReader.Close();
                  
      return sRetXML;
      }

So when I set sRetXML, it comes back as the following xml :
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

ANd this then is being added to an XmlDocument object, when later on I am transforming with xsl which gives me errors due to the structure of the xml.
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11975951
Well the quick way around is...
sRetXML = oReader.GetString(0);
sRetXML = sRetXML.Replace( "\\"", "\"" );

This isn't getting to the core of the problem, but is a quick solution around it.
0
 

Author Comment

by:slimbx
ID: 11976039
danielsonchris,

Trying your suggestion did not remove the escape sequences. I tried that one this morning, and its almost as if C# does not allow the escape characters to be picked up. Odd
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976278
THis is rather interesting.. crack open the debugger and give us a snippit of the hexadecimal values you are seeing in the string.  

Particularly.. translate this for us..
\"\"

Ordinarily this would be only 4 bytes, but you may see 8 bytes.  0x00 buffered. Basically we are all insterested in known if you are getting some UTF-16 translation from the SQL Server or in your C#.  If this is the case then you will need to take that into account prior to Replacing the string.

Regards,
-Chris
0
 

Author Comment

by:slimbx
ID: 11976609
It is showing up like this in the debugger:

<row Type="Revenue" Product="Payday" Frequency="Today" Value="7457.5000" Teller="" Location="1.400000000000000e+001"/>

Which looks normal. But when I save that sucker to my string var, I get the xml that has slashes everywhere. I think I understand what you said earlier danielsonchris, but can you explain it in c# for beginners terms, being that is kind of where I am, and also what I can do to get this xml spitting out like it does in the debugger into my string. Thanks!!!

slimbx
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976643
sorry about that.. do something like the following only for debugging purposes.

sRetXML = oReader.GetString(0);
char[] chr_array_data = sRetXML.toCharArray();

Set a break point somewhere after the chr_array_data has been filled.  Right click in the variable watch window and select "Hexadecimal Display".  From there you will be able to see the true nature of the beast.

Regards,
Chris
0
 

Author Comment

by:slimbx
ID: 11976684
This is what comes back:

"<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"7457.5000\" Teller=\"\" Location=\"14\"/>"

as the value of my variable sRetXML. I think this is what you want.
0
 

Author Comment

by:slimbx
ID: 11976728
FYI: This is the hexidecimal display watch value
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976833
Well not really, what I was wanting is the actual hexadecimal representation of the bytes.  (thus I had you create a char array above)

Here is a nasty massage technique that will massage to ASCII.

using System.Text;

ASCIIEncoding ascii = new ASCIIEncoding();
ascii.GetBytes( stringVal );
byte[] bt = ascii.GetBytes( sRetXML );
sRetXML = Encoding.ASCII.GetString( bt );

//At this point now try the replace...
sRetXML = sRetXML.Replace( "\\"", "\"" );

//Let's see if this works for you.
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11976836
slimbx, are you getting the value of sRetXML from a watch while the code is running?  I am asking as the only time that I see the " being escaped is when I am looking at the string in a watch. So, what does the string look like when you output it to the console or a file?  Or is this what you are doing?
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976837
ingore the
ascii.GetBytes( stringVal );
line from the post above.
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976849
NipNFriar_Tuck,
slimbx had claimed that the XML Parser was choking on it.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 5

Expert Comment

by:danielsonchris
ID: 11976869
That brings up a good point though.  What is the error code and string of XML that the parser is choking on?  Don't copy and paste from the debugger for this one.  Copy and paste from a console window.

Console.Write( sRetXML );
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11976873
It might be choking for another reason...  As I stated the only time that I have seen the quites being escaped is when I get the string through a watch or some other means while debugging.
0
 

Author Comment

by:slimbx
ID: 11976908
danielsonchris,

I tried the code and it didn't catch. My string variable still gets populated with the bad xml text I specified above.

slimbx


NipNFriar_Tuck,

When I display the xml to a file or variable, it spits out as:
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

When I display in the debug window it spits out as:
<row Type="Revenue" Product="Payday" Frequency="Today" Value="7457.5000" Teller="" Location="14"/>

slimbx
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11976961
Hmmm.... Then danielsonchris' code should have worked... I guess you could try a regex...

using System.Text.RegularExpressions;

Regex regex = new Regex(
    @"\\",
    RegexOptions.IgnoreCase
    | RegexOptions.Multiline
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );

then you would simply do

regex.Replace( sRetXML, "" );
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11976981
Sorry, the last line of the comment should read:

string sRet = regex.Replace( sRetXML, "" );
0
 

Author Comment

by:slimbx
ID: 11977041
NipNFriar_Tuck,

I pasted and used your code as well, the end result of the string continues to be:
<row Type=\"Revenue\" Product=\"Payday\" Frequency=\"Today\" Value=\"1.500\" Teller=\"\" Location=\"1\"/>

I guess the coding jinx is in town. For friendly competition, I have rasied the stakes. Please keep the ideas coming.

slimbx
 
0
 
LVL 5

Expert Comment

by:danielsonchris
ID: 11977065
I still think you need to do two things.

1)  Break the string into a character array
sRetXML = oReader.GetString(0);
char[] chr_array_data = sRetXML.toCharArray();
//NOW loook at the character array through a debugger using "Hexadecimal Display" and a nice chunk of the bytes here.

2)  Look into why the XML Parser is choking on the string.  What is the Exception string returned?  Also please paste the entire XML string here.

-Chris
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11977081
Is that the content of sRet or sRetXML?  The string without the \ will be in sRet...
0
 

Author Comment

by:slimbx
ID: 11977207
danielsonchris,
Sorry for the retardedness...Its Friday!

-      chr_array_data      {Length=0x62}      char[]
      [0x0]      0x3c '<'      char
      [0x1]      0x72 'r'      char
      [0x2]      0x6f 'o'      char
      [0x3]      0x77 'w'      char
      [0x4]      0x20 ' '      char
      [0x5]      0x54 'T'      char
      [0x6]      0x79 'y'      char
      [0x7]      0x70 'p'      char
      [0x8]      0x65 'e'      char
      [0x9]      0x3d '='      char
      [0xa]      0x22 '"'      char
      [0xb]      0x52 'R'      char
      [0xc]      0x65 'e'      char
      [0xd]      0x76 'v'      char
      [0xe]      0x65 'e'      char
      [0xf]      0x6e 'n'      char
      [0x10]      0x75 'u'      char
      [0x11]      0x65 'e'      char
      [0x12]      0x22 '"'      char
      [0x13]      0x20 ' '      char
      [0x14]      0x50 'P'      char
      [0x15]      0x72 'r'      char
      [0x16]      0x6f 'o'      char
      [0x17]      0x64 'd'      char
      [0x18]      0x75 'u'      char
      [0x19]      0x63 'c'      char
      [0x1a]      0x74 't'      char
      [0x1b]      0x3d '='      char
      [0x1c]      0x22 '"'      char
      [0x1d]      0x50 'P'      char
      [0x1e]      0x61 'a'      char
      [0x1f]      0x79 'y'      char
      [0x20]      0x64 'd'      char
      [0x21]      0x61 'a'      char
      [0x22]      0x79 'y'      char
      [0x23]      0x22 '"'      char
      [0x24]      0x20 ' '      char
      [0x25]      0x46 'F'      char
      [0x26]      0x72 'r'      char
      [0x27]      0x65 'e'      char
      [0x28]      0x71 'q'      char
      [0x29]      0x75 'u'      char
      [0x2a]      0x65 'e'      char
      [0x2b]      0x6e 'n'      char
      [0x2c]      0x63 'c'      char
      [0x2d]      0x79 'y'      char
      [0x2e]      0x3d '='      char
      [0x2f]      0x22 '"'      char
      [0x30]      0x54 'T'      char
      [0x31]      0x6f 'o'      char
      [0x32]      0x64 'd'      char
      [0x33]      0x61 'a'      char
      [0x34]      0x79 'y'      char
      [0x35]      0x22 '"'      char
      [0x36]      0x20 ' '      char
      [0x37]      0x56 'V'      char
      [0x38]      0x61 'a'      char
      [0x39]      0x6c 'l'      char
      [0x3a]      0x75 'u'      char
      [0x3b]      0x65 'e'      char
      [0x3c]      0x3d '='      char
      [0x3d]      0x22 '"'      char
      [0x3e]      0x37 '7'      char
      [0x3f]      0x34 '4'      char
      [0x40]      0x35 '5'      char
      [0x41]      0x37 '7'      char
      [0x42]      0x2e '.'      char
      [0x43]      0x35 '5'      char
      [0x44]      0x30 '0'      char
      [0x45]      0x30 '0'      char
      [0x46]      0x30 '0'      char
      [0x47]      0x22 '"'      char
      [0x48]      0x20 ' '      char
      [0x49]      0x54 'T'      char
      [0x4a]      0x65 'e'      char
      [0x4b]      0x6c 'l'      char
      [0x4c]      0x6c 'l'      char
      [0x4d]      0x65 'e'      char
      [0x4e]      0x72 'r'      char
      [0x4f]      0x3d '='      char
      [0x50]      0x22 '"'      char
      [0x51]      0x22 '"'      char
      [0x52]      0x20 ' '      char
      [0x53]      0x4c 'L'      char
      [0x54]      0x6f 'o'      char
      [0x55]      0x63 'c'      char
      [0x56]      0x61 'a'      char
      [0x57]      0x74 't'      char
      [0x58]      0x69 'i'      char
      [0x59]      0x6f 'o'      char
      [0x5a]      0x6e 'n'      char
      [0x5b]      0x3d '='      char
      [0x5c]      0x22 '"'      char
      [0x5d]      0x31 '1'      char
      [0x5e]      0x34 '4'      char
      [0x5f]      0x22 '"'      char
      [0x60]      0x2f '/'      char
      [0x61]      0x3e '>'      char


slimbx

NipNFriar_Tuck,

The content returned back that way in the sRet variable.

slimbx

0
 
LVL 5

Accepted Solution

by:
danielsonchris earned 100 total points
ID: 11977244
Awesome man.. now we can see the situation.
[0xa]     0x22 '"'     char
     [0xb]     0x52 'R'     char
     [0xc]     0x65 'e'     char
     [0xd]     0x76 'v'     char
     [0xe]     0x65 'e'     char
     [0xf]     0x6e 'n'     char
     [0x10]     0x75 'u'     char
     [0x11]     0x65 'e'     char
     [0x12]     0x22 '"'     char

The good news is that string is perfectly formed!  The bad news is that still doesn't solve why the XML parser is failing.  I think we need to see how the sRetXML looks.  Can you paste the entire XML string.  Beginning with:
<?xml version="1.0" encoding="UTF-8"?>
...

0
 

Author Comment

by:slimbx
ID: 11977375
danielsonchris,

The xml looks malformed in c#, but I let the app run, the way it is rendered is accurate to represent the escape sequences for that particular string. When I spit all of my xml values into an xml file and save it to the dom, all is well formed. I think that what I was assuming was the display of xml would be like what I am use to and it was not via c#. Thanks a million.

SLIMBX

NipNFriar_Tuck,

I feel bad because you were helping me as well. Want me to open a dummy question so you can accept for some points? Let me know.

slimbx
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
ID: 11977391
No, not at all... Glad you were able to figure it out...
0
 
LVL 10

Expert Comment

by:eternal_21
ID: 11985192
Wasn't that what I said in the beginning? ...
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now