Showing posts with label stringbuilder. Show all posts
Showing posts with label stringbuilder. Show all posts

Saturday, March 31, 2012

string vs stringbuilder

What can I better use?

StringBuilder sb =newStringBuilder();

sb.Append("SELECT ");

sb.Append("count(*) ");

sb.Append("FROM ");

sb.Append("table");

Or

query ="SELECT count(*) FROM table";

Look String is immutual object . you can't perform modification operation but in Stringbuilder is New type of Collection Class that provide feasibility to modify and other string operation without losing value


Hi

Strings of type System.String are immutable in .Net. That means any change to a string cause the runtime to create new string and abandon old one.

That happens invisibly, and many programmers might be surprised that following code allocate four new string in memory:

string s;

s = "select "; // "select"

s += " * from "; // "select * from"

s += " tablename"; // "select * from tablename"

Only the last string has a reference, the other two will be disposed of during garbage collection. Avoiding these types of temporary string helps avoid unnecessary garbage collection, which improve performance.

Use StringBuilder class to create dynamic (mutable) strings.

StringBuilder can span multiple statements. The default constructor creates a buffer of 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like.

As in your case, if you do not need to break statement in query thanstringworks. Use StringBuilder when you want to span your query in multiple statement.

Hope this helps you.

Regards,

Mustakim Mansuri



If thats the case it better to use String because you did your query is simple BUT if you are trying to DO Insert with multiple values then you can use the StringBuilder to append values...

Just a little Gee-Whiz info as to how much better StringBuilder can be when you are making several concatenations (especially in a loop):

I was building an HTML string in a while(datareader.Read()) loop, and setting a divs InnerHtml equal to that string at the end. I didn't know any better, I never heard of StringBuilder. Then I came across an article about it, so I figured I'd give it a try. In one of my examples, I had about 1000 rows being returned and was making maybe 2 string concatenations within each iteration of the loop. Needless to say, it was running a little slow (between 3-5 seconds each time the user tried to access the page). After replacing straight string concatenations with StringBuilder.Append() statements, the page loaded almost immediately. A few seconds saved was pretty nice, but what further drove the importance home for me was when I remembered that the database connection was open that whole time. Multiply that by several users hitting the site at the same time, and it became very clear.

string.ReadLine

hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value
instead of
"my string" value
how do i keep the value on the same line as my string?
thanks,
rodcharRemove the new-line char before appending.
"rodchar" <rodchar@.discussions.microsoft.com> wrote in message
news:3F4906CE-8C17-4026-83D7-974DEB940147@.microsoft.com...
hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value
instead of
"my string" value
how do i keep the value on the same line as my string?
thanks,
rodchar
Sorry, ignore my reply.
"Siva M" <shiva_sm@.online.excite.com> wrote in message
news:OGy8ypG$GHA.4464@.TK2MSFTNGP02.phx.gbl...
Remove the new-line char before appending.
"rodchar" <rodchar@.discussions.microsoft.com> wrote in message
news:3F4906CE-8C17-4026-83D7-974DEB940147@.microsoft.com...
hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value
instead of
"my string" value
how do i keep the value on the same line as my string?
thanks,
rodchar
Howdy,
Dim reader As StreamReader = File.OpenText(pathToMyFile)
Dim line As String = reader.ReadLine()
Dim builder As New System.Text.StringBuilder()
Do Until line Is Nothing
builder.Append("my value")
builder.Append(line)
line = reader.ReadLine()
Loop
TextBox1.Text = builder.ToString()
Milosz Skalecki
MCAD
"rodchar" wrote:

> hey all,
> i'm trying to read a text document line by line into a stringbuilder and a
n
> issue i'm running into is this:
> do while streamReader.ReadLine
> stringBuilder.Append("my string" & string.ReadLine)
> is showing up like this:
> "my string"
> value
> instead of
> "my string" value
> how do i keep the value on the same line as my string?
> thanks,
> rodchar
thanks for the help. rod.
"Milosz Skalecki" wrote:
> Howdy,
>
> Dim reader As StreamReader = File.OpenText(pathToMyFile)
> Dim line As String = reader.ReadLine()
> Dim builder As New System.Text.StringBuilder()
>
> Do Until line Is Nothing
> builder.Append("my value")
> builder.Append(line)
> line = reader.ReadLine()
> Loop
>
> TextBox1.Text = builder.ToString()
> --
> Milosz Skalecki
> MCAD
>
> "rodchar" wrote:
>

Wednesday, March 28, 2012

string.ReadLine

hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value

instead of
"my string" value

how do i keep the value on the same line as my string?

thanks,
rodcharRemove the new-line char before appending.

"rodchar" <rodchar@.discussions.microsoft.comwrote in message
news:3F4906CE-8C17-4026-83D7-974DEB940147@.microsoft.com...
hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value

instead of
"my string" value

how do i keep the value on the same line as my string?

thanks,
rodchar
Sorry, ignore my reply.

"Siva M" <shiva_sm@.online.excite.comwrote in message
news:OGy8ypG$GHA.4464@.TK2MSFTNGP02.phx.gbl...
Remove the new-line char before appending.

"rodchar" <rodchar@.discussions.microsoft.comwrote in message
news:3F4906CE-8C17-4026-83D7-974DEB940147@.microsoft.com...
hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value

instead of
"my string" value

how do i keep the value on the same line as my string?

thanks,
rodchar
Howdy,

Dim reader As StreamReader = File.OpenText(pathToMyFile)
Dim line As String = reader.ReadLine()
Dim builder As New System.Text.StringBuilder()

Do Until line Is Nothing

builder.Append("my value")
builder.Append(line)

line = reader.ReadLine()

Loop

TextBox1.Text = builder.ToString()

--
Milosz Skalecki
MCAD

"rodchar" wrote:

Quote:

Originally Posted by

hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value
>
instead of
"my string" value
>
how do i keep the value on the same line as my string?
>
thanks,
rodchar


thanks for the help. rod.

"Milosz Skalecki" wrote:

Quote:

Originally Posted by

Howdy,
>
>
Dim reader As StreamReader = File.OpenText(pathToMyFile)
Dim line As String = reader.ReadLine()
Dim builder As New System.Text.StringBuilder()
>
>
Do Until line Is Nothing
>
builder.Append("my value")
builder.Append(line)
>
line = reader.ReadLine()
>
Loop
>
>
TextBox1.Text = builder.ToString()
>
--
Milosz Skalecki
MCAD
>
>
"rodchar" wrote:
>

Quote:

Originally Posted by

hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value

instead of
"my string" value

how do i keep the value on the same line as my string?

thanks,
rodchar


Np, You're welcome
--
Milosz Skalecki
MCAD

"rodchar" wrote:

Quote:

Originally Posted by

thanks for the help. rod.
>
"Milosz Skalecki" wrote:
>

Quote:

Originally Posted by

Howdy,

Dim reader As StreamReader = File.OpenText(pathToMyFile)
Dim line As String = reader.ReadLine()
Dim builder As New System.Text.StringBuilder()

Do Until line Is Nothing

builder.Append("my value")
builder.Append(line)

line = reader.ReadLine()

Loop

TextBox1.Text = builder.ToString()

--
Milosz Skalecki
MCAD

"rodchar" wrote:

Quote:

Originally Posted by

hey all,
i'm trying to read a text document line by line into a stringbuilder and an
issue i'm running into is this:
do while streamReader.ReadLine
stringBuilder.Append("my string" & string.ReadLine)
is showing up like this:
"my string"
value
>
instead of
"my string" value
>
how do i keep the value on the same line as my string?
>
thanks,
rodchar

Monday, March 26, 2012

StringBuilder

Can anyone tell me why I get an error that StringBuilder not found? Am I missing a directive?

using System;
using System.IO;
namespace Formatting
{
public class MyDates
{
[STAThread]
static void Main(string[] args)
{
StringBuilder MyStringBuilder = new StringBuilder("Hello !");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);

}

}
}


ThanksThe StringBuilder is found in System.Text namespace.

You forgot to add


using System.Text;

thus the application cannot know who StringBuilder is.
Hi,

You need to put using System.Text;

thanks.

StringBuilder

I don't know why but in my stringbuilder. The string is cut off I set the
size but it is still missing part of the string.

Here is the codebehind:

public System.Text.StringBuilder BindData(System.DateTime SDate,
System.DateTime EDate)
{
string strEventSelect="SELECT EVNR_tbl.* FROM EVNR_tbl, img_tbl WHERE
EVNR_tbl._Date BETWEEN '" + SDate.ToString("yyyy/MM/dd") + "' AND '" +
EDate.ToString("yyyy/MM/dd") + "' ORDER BY EVNR_tbl._Date ASC";
clubconn=new SqlConnection(strclubconn);
clubconn.Open();
dsClub=new DataSet();
clubadapt=new SqlDataAdapter(strEventSelect,clubconn);
clubadapt.FillSchema(dsClub,SchemaType.Source,"EVNR_tbl");
clubadapt.Fill(dsClub,"EVNR");

MailString=new System.Text.StringBuilder(5000);
// Set Email Body.
MailString.Append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0
Transitional//EN' >");
MailString.Append("<HTML>");
MailString.Append("<HEAD>");
MailString.Append("<meta name='GENERATOR' Content='Microsoft Visual
Studio .NET 7.1'>");
MailString.Append("<meta name='CODE_LANGUAGE' Content='C#'>");
MailString.Append("<meta name='vs_defaultClientScript'
content='JavaScript'>");
MailString.Append("<meta name='vs_targetSchema'
content='http://schemas.microsoft.com/intellisense/ie5'>");
MailString.Append("</HEAD>");
MailString.Append("<body MS_POSITIONING='GridLayout' bgColor='black'>");
MailString.Append("<form id='Form1' method='post' runat='server'>");
MailString.Append("<table borderColor='#ffffff' cellSpacing='0'
cellPadding='0' width='500' align='center' border='1'>");
MailString.Append("<tr>");
MailString.Append("<td>");
MailString.Append("<table cellSpacing='0' cellPadding='0' width='100%'
border='0'>");
MailString.Append("<tr>");
MailString.Append("<td colspan='2'><IMG
SRC='http://www.sonar.bc.ca/images/Header.jpg'></td>");
MailString.Append("</tr>");
MailString.Append("<tr>");
MailString.Append("<td colspan='2' style='HEIGHT: 48px'>");
MailString.Append("<table cellpadding='10' cellspacing='0' border='0'
width='100%'>");
MailString.Append("<tr>");
MailString.Append("<td style='FONT-SIZE: 10px; COLOR: white; FONT-FAMILY:
Verdana'>" + EMessage + "</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("<tr>");
MailString.Append("<td>");
MailString.Append("<table cellpadding='10' cellspacing='0' border='0'
width='100%'>");
MailString.Append("<tr>");
MailString.Append("<td style='FONT-SIZE: 10px; WIDTH: 251px; COLOR:
white; FONT-FAMILY: Verdana' vAlign='Top'>");
DataTable dt=dsClub.Tables["EVNR"];
foreach(DataRow dr in dt.Rows)
{
MailString.Append(System.Convert.ToDateTime(dr["_Date"]) + " " +
dr["EventTitle"] + "<br>");
MailString.Append(dr["Description"].ToString().Replace("\n","<br>").Trim() + "<br>");
MailString.Append("For more details press <a
href='http://www.sonar.bc.ca/EventCalendar.aspx'> here </a>" + "<br>");
}
MailString.Append("</td>");
MailString.Append("<td style='FONT-SIZE: 10px; COLOR: white; FONT-FAMILY:
Verdana' vAlign='top'>");
foreach(ListItem i in IMGList.Items)
{
if(i.Selected)
{
MailString.Append("<img src='http://www.sonar.bc.ca/BroadcastIMG/" +
i.Text + "'" + ">" +"<br>");
}
}
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</form>");
MailString.Append("</body>");
MailString.Append("</HTML>");

return MailString;
}
if someone can tell me what I am doing wrong I'd greatly appreciate it.

Thank you,probaly a mismatched quote ...

check this line

MailString.Append("<img src='http://www.sonar.bc.ca/BroadcastIMG/" +
i.Text + "'" + ">" +"<br>");
probaly a mismatched quote ...

check this line

MailString.Append("<img src='http://www.sonar.bc.ca/BroadcastIMG/" +
i.Text + "'" + ">" +"<br>");
What part is exactly missing?

Gabriel Lozano-Morn
What part is exactly missing?

Gabriel Lozano-Morn

StringBuilder

I don't know why but in my stringbuilder. The string is cut off I set the
size but it is still missing part of the string.
Here is the codebehind:
public System.Text.StringBuilder BindData(System.DateTime SDate,
System.DateTime EDate)
{
string strEventSelect="SELECT EVNR_tbl.* FROM EVNR_tbl, img_tbl WHERE
EVNR_tbl._Date BETWEEN '" + SDate.ToString("yyyy/MM/dd") + "' AND '" +
EDate.ToString("yyyy/MM/dd") + "' ORDER BY EVNR_tbl._Date ASC";
clubconn=new SqlConnection(strclubconn);
clubconn.Open();
dsClub=new DataSet();
clubadapt=new SqlDataAdapter(strEventSelect,clubconn);
clubadapt.FillSchema(dsClub,SchemaType.Source,"EVNR_tbl");
clubadapt.Fill(dsClub,"EVNR");
MailString=new System.Text.StringBuilder(5000);
// Set Email Body.
MailString.Append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0
Transitional//EN' >");
MailString.Append("<HTML>");
MailString.Append("<HEAD>");
MailString.Append("<meta name='GENERATOR' Content='Microsoft Visual
Studio .NET 7.1'>");
MailString.Append("<meta name='CODE_LANGUAGE' Content='C#'>");
MailString.Append("<meta name='vs_defaultClientScript'
content='JavaScript'>");
MailString.Append("<meta name='vs_targetSchema'
content='http://schemas.microsoft.com/intellisense/ie5'>");
MailString.Append("</HEAD>");
MailString.Append("<body MS_POSITIONING='GridLayout' bgColor='black'>");
MailString.Append("<form id='Form1' method='post' runat='server'>");
MailString.Append("<table borderColor='#ffffff' cellSpacing='0'
cellPadding='0' width='500' align='center' border='1'>");
MailString.Append("<tr>");
MailString.Append("<td>");
MailString.Append("<table cellSpacing='0' cellPadding='0' width='100%'
border='0'>");
MailString.Append("<tr>");
MailString.Append("<td colspan='2'><IMG
SRC='http://www.sonar.bc.ca/images/Header.jpg'></td>");
MailString.Append("</tr>");
MailString.Append("<tr>");
MailString.Append("<td colspan='2' style='HEIGHT: 48px'>");
MailString.Append("<table cellpadding='10' cellspacing='0' border='0'
width='100%'>");
MailString.Append("<tr>");
MailString.Append("<td style='FONT-SIZE: 10px; COLOR: white; FONT-FAMILY:
Verdana'>" + EMessage + "</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("<tr>");
MailString.Append("<td>");
MailString.Append("<table cellpadding='10' cellspacing='0' border='0'
width='100%'>");
MailString.Append("<tr>");
MailString.Append("<td style='FONT-SIZE: 10px; WIDTH: 251px; COLOR:
white; FONT-FAMILY: Verdana' vAlign='Top'>");
DataTable dt=dsClub.Tables["EVNR"];
foreach(DataRow dr in dt.Rows)
{
MailString.Append(System.Convert.ToDateTime(dr["_Date"]) + " " +
dr["EventTitle"] + "<br>");
MailString.Append(dr["Description"].ToString().Replace("\n","<br>").Trim() +
"<br>");
MailString.Append("For more details press <a
href='http://www.sonar.bc.ca/EventCalendar.aspx'> here </a>" + "<br>");
}
MailString.Append("</td>");
MailString.Append("<td style='FONT-SIZE: 10px; COLOR: white; FONT-FAMILY:
Verdana' vAlign='top'>");
foreach(ListItem i in IMGList.Items)
{
if(i.Selected)
{
MailString.Append("<img src='http://www.sonar.bc.ca/BroadcastIMG/" +
i.Text + "'" + ">" +"<br>");
}
}
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</td>");
MailString.Append("</tr>");
MailString.Append("</table>");
MailString.Append("</form>");
MailString.Append("</body>");
MailString.Append("</HTML>");
return MailString;
}
if someone can tell me what I am doing wrong I'd greatly appreciate it.
Thank you,probaly a mismatched quote ...
check this line
MailString.Append("<img src='http://www.sonar.bc.ca/BroadcastIMG/" +
i.Text + "'" + ">" +"<br>");
What part is exactly missing?
Gabriel Lozano-Morn

StringBuilder

can anyone tell me how to declare a stringbuilder using vb in visual studio, I am trying to use a stringbuilder in the following code, but visual studio states stringbuilder is not defined.

Imports System.Data
Imports System.Data.SqlClient
Imports System.Text.StringBuilder

Public Class datagrid2
Inherits System.Web.UI.Page

Public Sub UpdateCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

Dim sb1 As StringBuilder = New StringBuilder("")
sb1.Append("INSERT Employees (firstname, lastname, titleofcourtesy, title, country) VALUES(")
sb1.Append("@dotnet.itags.org.sFirstName, @dotnet.itags.org.sLastName, @dotnet.itags.org.sTitle, @dotnet.itags.org.sPosition, @dotnet.itags.org.sCountry)")
cmd.CommandText = sb1.ToString()Hi,

Dim sb1 As System.Text.StringBuilder = New System.Text.StringBuilder("")

HTH
Imports System.Text.StringBuilder <-- don't do this, StringBuilder is a class, not a namespace.

use:
Imports System.Text

now you can use "StringBuilder" in your code (instead of having to write the fully qualified version of it each time)
thanks guys

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 objMail

I am new to ASP.NET so please be gentle :-)
I am trying to build an text (not HTML) email. I am putting together the
string that will be the body of the email but the formatting keeps getting
messed up. See code below.

Thanks in advance for any help you can give!

I want it to look like this...

Thank you for ordering from mycompany.com!

Your order is being billed to:
John Smith

******** But it keeps coming out like **************

Thank you for ordering from mycompany.com!Your order is being billed to: "
John Smith

******* Here is my code ********
Dim sEmail As New System.Text.StringBuilder

sEmail.Append("Thank you for ordering from mycompany.com!" & Chr(13))
sEmail.Append("Your order is being billed to: " & Chr(34))
sEmail.Append(Chr(32) & rdrMbrs.Item("fullname"))

objMail.Body = sEmail.toString()

Quote:

Originally Posted by

******** But it keeps coming out like **************
>
Thank you for ordering from mycompany.com!Your order is being billed to: "
John Smith
>
>
******* Here is my code ********
sEmail.Append("Thank you for ordering from mycompany.com!" & Chr(13))
sEmail.Append("Your order is being billed to: " & Chr(34))
sEmail.Append(Chr(32) & rdrMbrs.Item("fullname"))


The newline in the internet world is not Chr(13) which is only
carriage-return.

The newline if CRLF:
Chr(13) & Chr(10)

I'm not sure but I think vbCrlf - constant - should be automatically
available to VB.Net programmers. It used to be there in VB6 and I think
should exist even now.

See this page for a good discussion:
http://en.wikipedia.org/wiki/Newline
HTH

--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujinionline.com
-------------
I agree with Gaurav. However, a better approach is to use
System.Environment.NewLine.

Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
>I agree with Gaurav. However, a better approach is to use

Quote:

Originally Posted by

System.Environment.NewLine.


Not sure if System.Environment.NewLine is a good approach since again, we
are going to OS specific newline which is CRLF on Windows, CR on Mac and LF
on Unix/Linux etc.

Ok... if we are working with Microsoft .Net Framework, we know that we are
on Windows and it will translate to CRLF.

But I would like to play safe. Although an impossible probability today, but
what if Microsoft plans to release it on other OS as well ;)

--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujinionline.com
-------------
Hi Gaurav,

Using System.Environment.NewLine is the preferred way to represent a
"NewLine"; although you're right that the internal implementation of this
read-only property currently is implemented as:

public static string NewLine
{
get
{
return "\r\n";
}
}

However, consider someday your code is going to run on other platform, your
code doesn't have to be modified since you're calling into the BCL (Base
Class Library). I believe the BCL on different platform should return the
new line constant accordingly.

#Brad Abrams : Pet Peeve #493: Console.WriteLine ("\n")
http://blogs.msdn.com/brada/archive.../08/211053.aspx
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Quote:

Originally Posted by

However, consider someday your code is going to run on other platform,
your
code doesn't have to be modified since you're calling into the BCL (Base
Class Library). I believe the BCL on different platform should return the
new line constant accordingly.


I agree. I use it as the way to write a new-line (mainly since I also work
with Mono at times).

But hey! Hold on... the original problem was in the mail-message being sent.
In the mail-message composed, Environment.NewLine is definitely a very bad
choice.
There cannot be any choice other than CRLF (="\r\n" or "Chr(13) & Chr(10)").

I still hold on to my point that Environment.NewLine should not be used to
indicate a new-line while composing a mail.

--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujinionline.com
-------------
This worked great!!! Chr(13) & Chr(10) Thanks everyone for all you help.
One more thing why does the tab also not work? Chr(32)

Thanks Again!

"Gaurav Vaish (MasterGaurav)" <gaurav.vaish.nospam@.nospam.gmail.comwrote
in message news:%2374qm4VQHHA.3444@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

>

Quote:

Originally Posted by

>However, consider someday your code is going to run on other platform,
>your
>code doesn't have to be modified since you're calling into the BCL (Base
>Class Library). I believe the BCL on different platform should return the
>new line constant accordingly.


>
I agree. I use it as the way to write a new-line (mainly since I also work
with Mono at times).
>
But hey! Hold on... the original problem was in the mail-message being
sent.
In the mail-message composed, Environment.NewLine is definitely a very bad
choice.
There cannot be any choice other than CRLF (="\r\n" or "Chr(13) &
Chr(10)").
>
I still hold on to my point that Environment.NewLine should not be used to
indicate a new-line while composing a mail.
>
>
>
--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujinionline.com
-------------
>
>


"Rick" <rick@.di-wave.comwrote in message
news:OuKqUIWQHHA.496@.TK2MSFTNGP06.phx.gbl...

Quote:

Originally Posted by

This worked great!!! Chr(13) & Chr(10) Thanks everyone for all you help.
One more thing why does the tab also not work? Chr(32)


Chr(32) is a <space>
Chr(9) is a <tab>
Thanks very much!!

"Mark Rae" <mark@.markNOSPAMrae.comwrote in message
news:e%23E1InWQHHA.5032@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

"Rick" <rick@.di-wave.comwrote in message
news:OuKqUIWQHHA.496@.TK2MSFTNGP06.phx.gbl...
>

Quote:

Originally Posted by

>This worked great!!! Chr(13) & Chr(10) Thanks everyone for all you help.
>One more thing why does the tab also not work? Chr(32)


>
Chr(32) is a <space>
Chr(9) is a <tab>
>


My apology for ignoring the requirement is to use the line breaks in email
message. According to RFC 2045 (http://www.ietf.org/rfc/rfc2045.txt), the
Line Break in a text body must use a CRLF sequence.

I hope I didn't cause too much confusion.

Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
My apology for ignoring the requirement is to use the line breaks in email

Quote:

Originally Posted by

message. According to RFC 2045 (http://www.ietf.org/rfc/rfc2045.txt), the
Line Break in a text body must use a CRLF sequence.


That's ok.
btw, that's not just an RFC-2045 requirement but also elsewhere like in HTTP
etc.
CRLF is the "NewLine" of the "Internet" and specifically, "the Web".

Quote:

Originally Posted by

I hope I didn't cause too much confusion.


I hope not. :)

--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-------------

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 Class

Could anyone show me the code that allows me reset a Stringbuilder back to
either null or nothing or a blank space?How about this?
sb.Length = 0
I hope this helps,
Steve C. Orr, MCSD, MVP
http://SteveOrr.net
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
> Could anyone show me the code that allows me reset a Stringbuilder back to
> either null or nothing or a blank space?
Yes, just tested but my comp. is incr. slow at home.
Dim sb As New StringBuilder
sb.Append("Hello")
MsgBox(sb.ToString)
sb.Length = 0
MsgBox(sb.ToString)
"Steve C. Orr [MVP, MCSD]" <Steve@.Orr.net> schreef in bericht
news:OUdAFyd9FHA.2640@.tk2msftngp13.phx.gbl...
> How about this?
> sb.Length = 0
>
> --
> I hope this helps,
> Steve C. Orr, MCSD, MVP
> http://SteveOrr.net
>
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
>
Hi Paul,
It looks like you can set the Length to zero or just use New again.
Here's a little demo:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs)
Dim sb As New StringBuilder
sb.Append("!", 50)
sb.Append(": Length is now " & sb.Length.ToString)
Label1.Text = sb.ToString
sb.Length = 0
Label2.Text = "After Length=0:" & sb.ToString
sb = New StringBuilder
End Sub
Ken
Microsoft MVP [ASP.NET]
"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
> Could anyone show me the code that allows me reset a Stringbuilder back to
> either null or nothing or a blank space?
Actually, I tried using New again and that did not seem to work.
Setting the length to 0 did work.
Thank you for your assistance.
"Ken Cox" wrote:

> Hi Paul,
> It looks like you can set the Length to zero or just use New again.
> Here's a little demo:
> Protected Sub Page_Load(ByVal sender As Object, ByVal e As
> System.EventArgs)
> Dim sb As New StringBuilder
> sb.Append("!", 50)
> sb.Append(": Length is now " & sb.Length.ToString)
> Label1.Text = sb.ToString
> sb.Length = 0
> Label2.Text = "After Length=0:" & sb.ToString
> sb = New StringBuilder
> End Sub
> Ken
> Microsoft MVP [ASP.NET]
>
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:972F577C-0629-4B47-98EA-E403F429BB84@.microsoft.com...
>
>

StringBuilder AppendLine dont print Line breaks in my emails!

Hello... I'm working with StringBuilder to create a message to send via text email.

My methos is:

StringBuilder retorno = new StringBuilder();

retorno.AppendLine ( "A lot of text 1" );
retorno.AppendLine ( "A lot of text 2" );

return retorno.ToString() ;

Well.. I this last line I return the text to the message, but the email arrives without line breaks.

What can i do? thanks!

if you email format is in HTML, then you can use tag "<BR>" to create a line break

StringBuilder sb = new StringBuilder();
sb.Append("A lot of text 1");
sb.Append("<br>");
sb.Append("A lot of text 2);
return retorno.ToString() ;

else

you may try using \r\n, sb.Append("XXX\\r\\nXXXX");


have you tried for this one ?? it shoud work as it worked for me..

 StringBuilder retorno =new StringBuilder(); retorno.AppendLine("A lot of text 1"); retorno.AppendLine("<br />"); //....append a <br /> Tag... retorno.AppendLine("A lot of text 2"); Response.Write(retorno.ToString());

hope it helps./.

StringBuilder AppendFormart cannot handle String!

Hello,

If I use AppendFormat with string as a parameter.
I get string cannot be converted to IFormatProvider.

This occurs in 2.0

Thanks.
JayIt might be the actual format that's invalid, not the parameter. Perhaps an
example of code that doesn't work would help...

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/

"Jay Balapa" <jbalapa@.hotmail.com> wrote in message
news:eZplPbsGGHA.1100@.TK2MSFTNGP10.phx.gbl...
> Hello,
> If I use AppendFormat with string as a parameter.
> I get string cannot be converted to IFormatProvider.
> This occurs in 2.0
> Thanks.
> Jay

StringBuilder AppendFormart cannot handle String!

Hello,
If I use AppendFormat with string as a parameter.
I get string cannot be converted to IFormatProvider.
This occurs in 2.0
Thanks.
JayIt might be the actual format that's invalid, not the parameter. Perhaps an
example of code that doesn't work would help...
Karl
MY ASP.Net tutorials
http://www.openmymind.net/
"Jay Balapa" <jbalapa@.hotmail.com> wrote in message
news:eZplPbsGGHA.1100@.TK2MSFTNGP10.phx.gbl...
> Hello,
> If I use AppendFormat with string as a parameter.
> I get string cannot be converted to IFormatProvider.
> This occurs in 2.0
> Thanks.
> Jay
>

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 help

Dim sbRegX As New StringBuilder(HttpUtility.HtmlEncode(txtComments.Text))
sbRegX.Replace("<a>", "<a>")
sbRegX.Replace("</a>", "")
How do I get the attributes of href and target to be encoded?"Aaron" <fromtheweb@.aaronminoo.com> schrieb:
>Dim sbRegX As New StringBuilder(HttpUtility.HtmlEncode(txtComments.Text))
>sbRegX.Replace("<a>", "<a>")
>sbRegX.Replace("</a>", "")
>How do I get the attributes of href and target to be encoded?
Encoded as what?
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>
Herfried,
I have a text box that could have <a href="http://links.10026.com/?link=yahoo.com"
target="_new">yahoo</a>
With just
sbRegX.Replace("<a>", "<a>")
sbRegX.Replace("</a>", ""</a> )
The output is
<a href="http://links.10026.com/?link=yahoo.com" target="_blank">Yahoo
and the data looks like this
<a href="yahoo.com"
target="_blank">Yahoo</a>,
I need it to look like http://www.yahoo.com with it in a new window.
TIA
Aaron
"Herfried K. Wagner [MVP]" <hirf-spam-me-here@.gmx.at> wrote in message
news:uEsaI%23CIGHA.3944@.tk2msftngp13.phx.gbl...
> "Aaron" <fromtheweb@.aaronminoo.com> schrieb:
> Encoded as what?
> --
> M S Herfried K. Wagner
> M V P <URL:http://dotnet.mvps.org/>
> V B <URL:http://classicvb.org/petition/>
Aaron,
You'll be looking for Server.HtmlEncode and Server.HtmlDecode. You may also
want to experiment (depending on all the uses of the input text) with
Sever.UrlEncode and Server.UrlDecode.
Sincerely,
S. Justin Gengo, MCP
Web Developer / Programmer
www.aboutfortunate.com
"Out of chaos comes order."
Nietzsche
"Aaron" <fromtheweb@.aaronminoo.com> wrote in message
news:eGhc$WDIGHA.3728@.tk2msftngp13.phx.gbl...
> Herfried,
> I have a text box that could have <a href="http://links.10026.com/?link=yahoo.com"
> target="_new">yahoo</a>
> With just
> sbRegX.Replace("<a>", "<a>")
> sbRegX.Replace("</a>", ""</a> )
> The output is
> <a href="http://links.10026.com/?link=yahoo.com" target="_blank">Yahoo
> and the data looks like this
> <a href="yahoo.com"
> target="_blank">Yahoo</a>,
>
> I need it to look like http://www.yahoo.com with it in a new window.
> TIA
> Aaron
> "Herfried K. Wagner [MVP]" <hirf-spam-me-here@.gmx.at> wrote in message
> news:uEsaI%23CIGHA.3944@.tk2msftngp13.phx.gbl...
>

Stringbuilder Parsing Text: Need to remove square character

Hi everyone,

I am attempting to parse data from a webpage and want to remove any unneccesary junk from the string. I start by removing any Tags from the text I have retrieved from the web page. Next, I split the text into an array. However, I end up with a string that contains a bunch of characters that look like ?, sometimes there are many in a row: ???? in each string. I would like to remove these characters.

These characters are the only things left separating me from the data I want, but I am not sure how to remove them... Does anyone have an idea? It is interesting that when I display my string in a textbox, or using a label, the squares are not visible (I think they display as spaces) but when I debug I see them.

Thanks,

zoop

Those chars probably are line feeds, tabs or some other control chars.

Try:

Dim junk asString ="bla bla bla....."

junk=junk.replace(ControlChars.Lf,"")

junk=junk.replace(ControlChars.NewLine,"")

junk=junk.replace(ControlChars.Tab,"")


etc, etc...


If I'm not mistaken you are seeing the hidden space place holder. You can use regular expressions to remove them. Try something like below to remove them.

using System.Text.RegularExpressions;

private string StripSpaces(string inputString)
{
return Regex.Replace(inputString, @."[^\s$]","");
}


Thanks for the input fellas. I have tried the suggestions above along with some variations and came up short. Replacing the ControlChars does not seem to make a difference on the format of the string. Running the stripSpaces function removes all of the data I am interested in and returns only the chars I am attempting to remove (blanks, or squares). Perhaps I lost something when I translated it into VB...

Anyway, since there is not much code to go over I thought perhaps it would help if I posted what I have here. I am going to omit the section where I replace any ControlChars for brevity, as it does not seem to make a difference.

1Private Sub btnSubmit_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles btnSubmit.Click2'// Store Page Source in DOC3Dim reqAs WebRequest = WebRequest.Create("http://world5.knightfight.co.uk/index.php?ac=highscore&vid=0")4Dim respAs WebResponse = req.GetResponse56Dim sAs Stream = resp.GetResponseStream7Dim srAs StreamReader =New StreamReader(s, Encoding.ASCII)8Dim docAs String = sr.ReadToEnd910'// Format text in DOC using StringBuilder Class11Dim sbAs StringBuilder =New StringBuilder(doc)12Dim endIndexAs Integer = sb.ToString.IndexOf("showuserid=")13Dim newString()As String14Dim strTestAs String1516'// Remove Unwanted Text17strTest = sb.Remove(0, endIndex).ToString1819'// Remove HTML Tags and Spaces20strTest = StripTags(strTest)21strTest = stripSpaces(strTest)2223'// TEMP - Display Preview in Multiline Textbox24txtbWebData.Text = strTest2526'// Split String into Array27newString = Split(strTest," ")28End Sub2930Public Function StripTags(ByVal HTMLAs String)As String31' Removes tags from passed HTML32Dim objRegExAs _33System.Text.RegularExpressions.Regex34Return objRegEx.Replace(HTML,"<[^>]*>","*")35End Function3637Public Function stripSpaces(ByVal inputStringAs String)As String38Dim objRegExAs _39System.Text.RegularExpressions.Regex40Return objRegEx.Replace(inputString,"[^\s$]","")41End Function42

I thought it would be an interesting exercise to try and capture some data from a highscores list on a website. The URL is in the code above, http://world5.knightfight.co.uk/index.php?ac=highscore&vid=0,so you could reproduce my results if you like. The end goal is to capture the data in the highscores list and format it in a way that makes sense. If you think there is a better approach please let me know :).

Thanks,

zoop


Sorry about that. Replace Return objRegEx.Replace(inputString, "[^\s$]", "") with Return objRegEx.Replace(inputString, "[^\S$]", ""). The \s matches any white space character and the \S matches any non-white space character.

Stringbuilder or table?

Hi

I am just wondering if i need dynamically create a html table, which way will be more efficient?

A. Use stringbuilder. For example, sb.append("<table border=0>""), for(i=0;i<10;i++){sb.append("<tr><td>abc</td></tr>")}, sb.append("</table>")

B. Use table control, t = new table, for(i=0;i<10;i++){tr=new tablerow, td=new tablecell, td.text="abc",tr.cells.add(td),t.rows.add(tr))

Thanks

~Mike


Hi

Honestly, i dont see it makes huge different

But I think B will quicker than A. because all table, row, cell are object. I think use object to create table will be faster than string built up.


Use the following code to test this:

private void RunTest(int count){ Stopwatch watch =new Stopwatch(); watch.Start();for (int i2 = 0; i2 < count; i2++) { Table table =new Table();for (int i = 0; i < 10; i++) { TableRow tr =new TableRow(); TableCell td =new TableCell(); td.Text ="abc"; tr.Cells.Add(td); table.Rows.Add(tr); } } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds); watch.Reset(); watch.Start();for (int i2 = 0; i2 < count; i2++) { StringBuilder sb =new StringBuilder(); sb.Append("<table border=0>");for (int i = 0; i < 10; i++) { sb.Append("<tr><td>abc</td></tr>"); } sb.Append("</table>"); } watch.Stop(); Debug.WriteLine(watch.ElapsedMilliseconds);} 

I did the test with a count of 1500 which should show a difference and let it run 4 times. The outputs are as follows:

22 // Table
4 // StringBuilder


29
5

22
4

26
4

But, as you won't to that 1,500 times, there won't be a lot of difference concerning the performance.


Hi all,

I think the best way is using Table, TableRow and TableCell objects. You can create a table with all cells and rows you want and navigate throw them using their structure. However, if you want to create a simple table that has only two cells or something similar, it's quicker to use StringBuilder object or a string variable.


If the table doesn't need to be a server control, then I think it would be a little more efficient to use a StringBuilder. I?haven't?done?any?tests,?but?writing?out raw?HTML?generally incurs?less?overhead?than?instantiang?controls?for?everything. Any performance difference between the two approaches is going to be negligable though, so personally i'd go for whatever you find the more readable.

A third, and possible better approach would be to put your information into a DataTable and bind it to a GridView, DataList or Repeater.
I'd say A is going to be slightly more efficient but as already pointed out it'll be negligible. I personally like the markup in my code to be neat when viewed so B would probably better achieve that, even if its only for me debugging its output when it goes skewey.

stringbuilder manipulation performance

can anyone tell me the performance difference between:
stringbuilder.append
stringbuilder.appendformat
stringbuilder.replace

As a general rule, StringBuilder has great performance over concatination using simple strings concatinations, specially when the data to be concatinated is unkown.

Regards


using the string builder itself has a big impact in string munipulation !!! each method menthioned above has a difference in the behaviour and can do different job as required but if you are aware of the performance what to use and which one .....i will not be really bothered as the stringbuilder methodology is great in terms of performance so you can choose what will do the job for you !!!

HTH