Showing posts with label write. Show all posts
Showing posts with label write. Show all posts

Monday, March 26, 2012

stringbuilder & javascript (escape characters for quotes?)

Hey,

Im trying to write a javascript array from .net. The values of the array will sometimes have single quotes in - therefore I need some way to process the quotes so that I can output the javascript in the correct way.

I have:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString() +"','"+ dr[1].ToString()+"','"+ dr[2].ToString() +"');\n");

However, this does not deal with the quotes. I tried:


sb.Append("templateDetails["+ i +"] = new Array('"+ dr[0].ToString().Replace("'","\'") +"','"+ dr[1].ToString().Replace("'","\'") +"','"+ dr[2].ToString().Replace("'","\'") +"');\n");

This was to try and replace all single quotes with \' which is the javascript escape character.
However, the double quotes dont work because .net think I'm adding more code.

kind of like in original asp when you have to have multiple quotes to get in a single quote...you know what I mean :)

any help much appreciated,

PeteThe first code sample should do fine.. single quote isnt going to trip anything up. If you were wanting to use double quotes in your string-builder for javascript, you would have to escape them with \" .

Now, are you anticipating a single quote will be in your datareader columns that you are building the stringbuilder with? If so, replacethose values with \' instead of the whole stringbuilder.
Cheers Sharbel,

Trying that today.

Pete
Hold on :)

I am anticipating single quotes in the data columns. Example: " today it's the first day ... " etc etc.

I've tried putting the dataReader columns into strings then replacing single quotes with \' but that doesnt seem to work...

Pete
Hey,

completely by chance I found that backslash is an escape character for .net as well as javascript:

hence:


dr[4].ToString().Replace("'","\\'")

works fine

Cheers,

Pete
Hi Pete,

FYI, the slash isn't a ".NET" escape character, per se; it works in C# because C# shares a lot of common syntax with Javascript (and Java, and C++, and any other languages that descended from C in one form or another).

In VB.NET, you escape double quotes by repeating them, just like in old "Classic" ASP with VBScript (although if you used JScript for Classic ASP, you *would* need to use the slash to escape characters).

Cheers,

StringBuilder and memory management

I'm constructing a long SQL string using StringBuilder. Every 100 or so
iterations, I write the SQL to the database, and use the
StringBuilder.Remove method to "zero out" the string: e.g.,
"oStringBuilder.Remove(0,oStringBuilder.Length)". I then reuse
oStringBuilder to build the next SQL statement.

Sometimes this coding works fine, but as often as not the system reports
an out-of-memory error. I'm guessing that the Remove method deletes the
text in a string, but does not remove its memory allocation, and when I
reuse it, the string grows ever larger.

Is there any mechanism to destroy memory used -- or shrink it to zero
(or something!) -- within the StringBuilder class? If not, any other ideas?

Many thanks.

-- Brent

//==================================================
//Code snippet builds a valid MySQL statement
sqlstart = "Insert into myTable (Field1, Field2) Values ";
string field;
int count = 1;
StringBuilder sql = new StringBuilder(sqlstart);
char[] fieldsplitter = {'|'};

//after getting an array of text rows
for(int i = 0; i < arrRows.Length; i++, count++)
{
string[] arrFields = arrRows[i].Split(fieldsplitter);
sql.Append("(");
for(int j=0; j < arrFields.Length; j++)
{
field = arrFields[j];
sql.Append("'"+field+"',");

}
if (count==100 | i == arrRows.Length - 2)
{
sql.Append(");");
try
{
//write SQL to DB using "run" class
run.exec(sql.ToString());
}
catch //error in sql
{
Response.Write("SQL error: " + sql);

}

count = 0;
sql.Remove(0,sql.Length);
sql.Append(sqlstart);

}
else{sql.Append("),");}
}

//===============================================why not just reinstantiate the object? i don't know how the
stringbuilder class keeps references to its data, so it might not be
killing all references to it (keeping gc from happening).
reinitializing the stringbuilder ought to fix it if it's causing the
problem.

if that doesn't fix it, i'd suggest running a profiler on your
application to see where memory is getting sucked out.

hth
terry
Thanks for the tip. Turns out that I was reading in very large strings
from a file, and the memory was eaten up by that portion of the code,
not the code I posted earlier.

Thanks for your help!

theath wrote:
> why not just reinstantiate the object? i don't know how the
> stringbuilder class keeps references to its data, so it might not be
> killing all references to it (keeping gc from happening).
> reinitializing the stringbuilder ought to fix it if it's causing the
> problem.
> if that doesn't fix it, i'd suggest running a profiler on your
> application to see where memory is getting sucked out.
> hth
> terry

Stringbuilder equivalent to XMLTextWriter?

I want to write an XML file but not to a file...just into memory, so I can
then pass it to a string and stick it in a database.

Seems that XMLtextWriter requires that I write to a filestream.

What I'm looking for is the ease of writing XML that XMLTextWriter has with
the ability to just write to memory like Stringbuilder can do. Is there such
a thing?

-Darrel> What I'm looking for is the ease of writing XML that XMLTextWriter has
> with the ability to just write to memory like Stringbuilder can do. Is
> there such a thing?

Hmm...I found this article:

http://www.15seconds.com/issue/050615.htm

Which mentions:

"the XmlWriter can generate its output as a disk file, a stream, a
StringBuilder or another writer instance."

So, it looks like it can generate a stringbuilder. I just need to find an
example of that... ;o)

-Darrel
> So, it looks like it can generate a stringbuilder. I just need to find an
> example of that... ;o)

A bit more digging and I think I've figure it out:

Dim sbXML As New System.Text.StringBuilder

Dim swXML As New System.IO.StringWriter(sbXML)

Dim twXML As New System.xml.XmlTextWriter(swXML)

-Darrel

Stringbuilder equivalent to XMLTextWriter?

I want to write an XML file but not to a file...just into memory, so I can
then pass it to a string and stick it in a database.
Seems that XMLtextWriter requires that I write to a filestream.
What I'm looking for is the ease of writing XML that XMLTextWriter has with
the ability to just write to memory like Stringbuilder can do. Is there such
a thing?
-Darrel> What I'm looking for is the ease of writing XML that XMLTextWriter has
> with the ability to just write to memory like Stringbuilder can do. Is
> there such a thing?
Hmm...I found this article:
http://www.15seconds.com/issue/050615.htm
Which mentions:
"the XmlWriter can generate its output as a disk file, a stream, a
StringBuilder or another writer instance."
So, it looks like it can generate a stringbuilder. I just need to find an
example of that... ;o)
-Darrel

> So, it looks like it can generate a stringbuilder. I just need to find an
> example of that... ;o)
A bit more digging and I think I've figure it out:
Dim sbXML As New System.Text.StringBuilder
Dim swXML As New System.IO.StringWriter(sbXML)
Dim twXML As New System.xml.XmlTextWriter(swXML)
-Darrel

StringBuilder with line break escape.

I created a StringBuilder and append string values to it, but each string I inserted a "\n" to sparate values. When I write the StringBuilder values out to a text file. The line break with "\n" did not work. Anybody knows why?

StringBuilder sb = new StringBuilder();
sb.Append("Some Value \n");
sb.Append("Another Value \n");

// create a stream writer and write all string values to the file
StreamWriter sw = File.CreateText(path)
sw.WriteLine(sb.ToString());

Another question, what is the default Capacity of a StringBuilder object created like the code above?\n is a javascript newline but you are not using javascript...instead do something like this:


StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbcrlf);
sb.Append("Another Value" & vbcrlf);

'or

StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbnewline);
sb.Append("Another Value" & vbnewline);


oooh, just realized that this is c#....I know the vbnewline and vbcrlf do new lines in VB but not sure about c#...sorry

Also, to your other question...from the online notes for stringbuilder:
----------------------
Notes to Implementers: The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue.
----------------------

MajorCats
All .net languages support the Environment.NewLine property. The property value is a constant customized specifically for the current platform. This value is automatically appended to text when using WriteLine methods.

Try that instead.

However, couldn't you simply rewrite the entire chunk as:


StreamWriter sw = File.CreateText(path)
sw.WriteLine("Some Value");
sw.WriteLine("Another Value");
...and avoid the StringBuilder entirely (since the WriteLine method will automatically insert on a newline?

Not sure about the Capacity question. From MSDN:

Capacity does not affect the string value of the current instance. Capacity can be decreased as long as it is not less than Length.

The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.
First of al it is better to use Environment.NewLine.
But if you realy want to use it, use \r\n ... that will work
Cool, thank you all.

Environment.NewLine works perfectly in my situation, "\r\n" works as well in C#.
In addition to daver's post:

The StringBuilder allows for specifying the capacity by using the Capacity property:
sb.Capacity = 200 allows for 200 characters. The default capacity is 16.

so don't think that you should never use StringBuilder. The StringBuilder should be used in place of concatenating strings instead of using the &= as that creates a new instance of the string each time it is used and should provide better performance with large strings.
I use StringBuilder just for the performance reason you mentioned. But, I don't believe its default capacity is 16, as it's too small. The first replier said it is the maximum value of int. This sounds reasonable to me. Are you saying that it initially allocate a buffer for 16 characters, and will auto-expand the buffer as needed? The fininal buffer size would not exceed StringBuilder's default capacity. Is this right?
The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue (2,147,483,647; that is, hexadecimal 0x7FFFFFFF)
Hi, adec

What do you mean by "this implementation"? When I create a StringBuilder object by:

StringBuilder sb = new StringBuilder();

What does the "16" mean to me? I should not worry about anything as long as total number of char in my final string is less than Int32.MaxValue, shouldn't I?
You do not really have to worry about it. If you are pretty sure to what capacity your SB should cater, set it to limit the memory allocated. If you don't, the SB will automatically adapt. In fact you may well set it to 16 (characters) in the first place. It will dynamically adapt.
I've never done the performance comparison,
but rather than concatenate the newline (we're avoiding concatenation - right?)

try using the stringbuilder.appendformat method

sb.AppendFormat("Some Value{0}", Environment.NewLine);
sb.Appendformat("Another Value{0}", Environment.NewLine);
As a general rule, if you need to create a lot of text, do not use Concatenation. Performance wise, the Stringbuilder is superior to Concatenation, and should be used in place of this.
try this:


StringBuilder s = new StringBuilder();
s.Append("HEllo <BR>");
s.Append("World");
Response.Write(s);

I am actually kind of curious as to why one would instantiate a StringBuilder (using line terminations), use the File.CreateText to create a StreamWriter, and then call StreamWriter.Write() passing the StringBuilder to the StreamWriter when the StreamWriter does it all?
StreamWriter sw = new StreamWriter(@."path");
sw.WriteLine("SomeValue");
sw.WriteLine("AnotherValue");
sw.Close();

Is there anything wrong with this approach?
I suppose that all depends on what you need the string for.

if you need it for multiple purposes, then creating a stringbuilder is ok as its reusable.
if you need to perform replacements then appendformat is very useful.
if you have additional concatenations to perform then stringbuilder is best.
i.e. dont do (sw.WriteLine("SomeValue" & "somother value" & "yet anothervalue");

if you're just blasting data into a disk file, then perhaps a stringbuilder represents an extra [unnecessary] step.

of course, we're all just speculating about the real world requirement behind the original posters question...

strings

Pls help me write a function in c#, to exclude all the dots(.) from a string.
Like the string "123.0000" should return "1230000"
Thanks a ton.Use the Replace function or regular expressions
Thanks...