Friday, May 27, 2011

Image upload

how to upload image -button click code written applicable only in .cs file





first on .aspx page use fileupload control then on button click how to call it example given



protected void btnsub_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (Page.IsPostBack)
{
string hotel_image = "";
if (imageupload.HasFile)
{

hotel_image = imageupload.PostedFile.FileName;
imageupload.SaveAs(Server.MapPath("upload") + "//" + hotel_image);
}
string Content1 = txtcontent.Text.ToString().Trim();
string Title_of_hotel = txttitle.Text.ToString().Trim();
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ihotel"].ToString().Trim());
SqlCommand cmd = new SqlCommand("topfourhotel", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Content1", SqlDbType.VarChar).Value = Content1;
cmd.Parameters.Add("@Title_of_hotel", SqlDbType.VarChar).Value = Title_of_hotel;
cmd.Parameters.Add("@hotel_image", SqlDbType.VarChar).Value = hotel_image;
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();

if (i > 0)
{
Response.Write("Inserted Successfully . ");
}
else
{
Response.Write("Error Occured");
}
txtcontent.Text = "";
txttitle.Text = "";

}
}
}
}

FORM PAGE

protected void btnsubmit_Click(object sender, EventArgs e)
    {
        string name = TXTNNAME.Text.ToString().Trim();
        string gender = ddlgender.SelectedValue.ToString().Trim();
        string age = txtage.Text.ToString().Trim();
        string address = txtadd.Text.ToString().Trim();
        string phone = txtphone.Text.ToString().Trim();
        string password = txtpass.Text.ToString().Trim();
        string package="";
        if(chkpack.Checked==true)
        {
            package=chkpack.Text.ToString().Trim();
        }
        else
        {
            package = chkpack1.Text.ToString().Trim();
        }
        SqlConnection tcon= new SqlConnection(ConfigurationManager.AppSettings["templecon"].ToString().Trim());
        SqlCommand cmdlog=new SqlCommand("logininsert", tcon);
        cmdlog.CommandType = CommandType.StoredProcedure;
        cmdlog.Parameters.Add("@name", SqlDbType.VarChar).Value = TXTNNAME.Text.ToString().Trim();
        cmdlog.Parameters.Add("@gender", SqlDbType.VarChar).Value = ddlgender.SelectedValue.ToString().Trim();
        cmdlog.Parameters.Add("@age", SqlDbType.Int).Value = txtage.Text.ToString().Trim();
        cmdlog.Parameters.Add("@address", SqlDbType.VarChar).Value = txtadd.Text.ToString().Trim();
        cmdlog.Parameters.Add("@phone", SqlDbType.BigInt).Value = txtphone.Text.ToString().Trim();
        cmdlog.Parameters.Add("@password", SqlDbType.NVarChar).Value = txtpass.Text.ToString().Trim();


        cmdlog.Parameters.Add("@package", SqlDbType.VarChar).Value =package;
        tcon.Open();
        cmdlog.ExecuteNonQuery();
        tcon.Close();

      

    }

ENCRYPTION DECRYPTION

CREATE TABLE
THEN
%-- INSERTING THE VALUE--%
insert into testTable (firstcol,secondcol)values(1,'first')
 insert into testTable (firstcol,secondcol)values(2,'second')
 insert into testTable (firstcol,secondcol)values(3,'third')
 insert into testTable (firstcol,secondcol)values(4,'fourth')
 insert into testTable (firstcol,secondcol)values(5,'fifth')
 insert into testTable (firstcol,secondcol)values(6,'sixth')
 
select* from testtable
CREATING MASTER KEY AND CERTIFICATE
create master key encryption by password='SqlAuthority'
create CERTIFICATE encryptTestcert with subject='sqlAuthority'
create symmetric key testTableKey with algorithm =TRIPLE_DES
encryption by certificate encryptTestcert

ALTER TABLE TestTable add encryptsecondcol varbinary(256)
DECRYPTING KEY
open symmetric key testtablekey decryption by certificate encryptTestcert
update testtable set encryptsecondcol=encryptbykey(key_guid('testtablekey'),secondcol)

select * from testtable

OPEN symmetric key testtablekey decryption by certificate encryptTestcert
select convert(varchar(50),decryptbykey(encryptsecondcol)) as decryptseconcol from testtable

Rowdatabound and Rowcommand

&ltColumns&gt
&ltasp:TemplateField&gt
&ltItemTemplate&gt
&ltasp:Button ID="btnstatus" runat="server" CommandArgument='&lt%#DataBinder.Eval(Container.DataItem,"RegId") %&gt' CommandName="RStatus" /&gt
&ltasp:Button ID="btndelete" runat="server" Text="Delete" CommandArgument='&lt%#DataBinder.Eval(Container.DataItem,"RegId") %&gt' CommandName="del"/&gt
&lt/ItemTemplate&lt
&lt/asp:TemplateField&gt
&lt/Columns&gt


Event call on code behind page





protected void dtldetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "RStatus")
{
int i = Int32.Parse(e.CommandArgument.ToString().Trim());
string str = "update member_reg set status=1 where regid= " + i + " ";
SqlConnection con5 = new SqlConnection(ConfigurationManager.AppSettings["Forumcon"].ToString().Trim());
SqlCommand cmd = new SqlCommand(str, con5);
cmd.CommandType = CommandType.Text;
con5.Open();
cmd.ExecuteNonQuery();
con5.Close();
filldatalist();
}
else if (e.CommandName == "del")
{
int j = Int32.Parse(e.CommandArgument.ToString().Trim());
string str = "delete member_reg where regid= " + j + " ";
SqlConnection con3 = new SqlConnection(ConfigurationManager.AppSettings["Forumcon"].ToString().Trim());
SqlCommand cmd = new SqlCommand(str, con3);
cmd.CommandType = CommandType.Text;
con3.Open();
int i=cmd.ExecuteNonQuery();
con3.Close();
filldatalist();
}
}
protected void dtldetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label _RegID = (Label)e.Row.FindControl("lblregid");
Label _lblStatus = (Label)e.Row.FindControl("lblStatus");
Button _btnstatus = (Button)e.Row.FindControl("btnstatus");
if (_lblStatus.Text == "1")
{
_btnstatus.Text = "Approve";
}
else
{
_btnstatus.Text = "Unapprove";
}
}
}
}

use of dynamic hyperlink to gridview

&ltItemTemplate&gt
&lta href='QUESTIONANSWER.aspx?id=<%#DataBinder.Eval(Container.DataItem,"queryid") %&gt'&gt
&lt%#DataBinder.Eval(Container.DataItem,"question") %&gt&lt/a&gt
&lt/ItemTemplate&gt
public void grigfill()
{
try
{
SqlConnection con2 = new SqlConnection(ConfigurationManager.AppSettings["Forumcon"].ToString().Trim());
SqlDataAdapter da = new SqlDataAdapter("select Top 10 queryid,Name ,question from query", con2);
DataSet ds = new DataSet();
da.Fill(ds);
gridqueans.DataSource = ds;
gridqueans.DataBind();
}
catch (Exception Ex)
{
Response.Write("Error Occured");
}
}

Count Every Visitor on page through the use of Xml

    Create Xml File—Counter.Xml
  • &lt?xml version="1.0" standalone="yes"?&gt

  • &ltcounter&gt

  • &ltcount&gt

  • &lthits&gt0&lthits&gt

  • &ltcount&gt

  • &ltcounter&gt



On page load




this.countMe();

DataSet ds = new DataSet();

ds.ReadXml(Server.MapPath("counter.xml"));

lblcounter.Text = ds.Tables[0].Rows[0]["hits"].ToString().Trim();


Lblcounter is the id of the label which is defined in the .aspx Page.



&ltasp:Label ID="lblcounter" runat="server" Text="Label" BackColor="#CCFF99"
ondatabinding="Page_Load" BorderColor="Maroon"&gt&lt/asp:Label&gt

Thursday, May 26, 2011

Form Validation using jQuery

&lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt
<html&gt
<head&gt
<title>Simple Form Validation&lt/title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script&gt
&ltscript type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt&lt/script&gt

<script type="text/javascript"&gt
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required",// simple rule, converted to {required:true}
email: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
&lt/script&gt

<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
input[type=text], textarea { width: 250px; float: left; }
textarea { height: 50px; }
</style&gt
</head&gt

<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *&lt/span><input type="text" name="name" /&gt&lt/div>
<div class="form-row"&gt&ltspan class="label">E-Mail *&lt/span&gt&ltinput type="text" name="email" /></div>
<div class="form-row"&gt
<div class="form-row"&gt&ltinput class="submit" type="submit" value="Submit">
</form>
</body>
</html>

Jquery image crossslider

Here is a simple guide on how to put CrossSlide on a website:

Download the jQuery library and include it along with my plugin in the head section of your website:

&ltscript src="jquery.min.js"&gt&lt/script&gt
&ltscript src="jquery.cross-slide.min.js"&gt&lt/script&gt
Put a block element somewhere in your page and give it an id:

&ltdiv id="slideshow"&gt&lt/div&gt
Make sure the element has a fixed size, even when emptied of its contents, by setting its width and height in the CSS stylesheet:

#slideshow {
width: 600px;
height: 200px;
}
Open a script tag, define a "document ready handler" and activate my plugin on the div you created in step 2:

&ltscript&gt
$(function() {
$('#slideshow').crossSlide({
sleep: 2,
fade: 1
}, [
{ src: 'picture1.jpg' },
{ src: 'picture2.jpg' },
{ src: 'picture3.jpg' },
{ src: 'picture4.jpg' }
])
});
&lt/script&gt

Tuesday, May 24, 2011

Asp.net quiz

Try this to enjoy the Asp.net knowledge:
click here to play quiz

professional quiz

ASP.NET 3.5 Interview Questions & Answers

1. Explain the life cycle of an ASP .NET page.?
Following are the events occur during ASP.NET Page Life Cycle:

1)Page_PreInit
2)Page_Init
3)Page_InitComplete
4)Page_PreLoad
5)Page_Load
6)Control Events
7)Page_LoadComplete
8)Page_PreRender
9)SaveViewState
10)Page_Render
11)Page_Unload

Among above events Page_Render is the only event which is raised by page. So we can't write code for this event.

2. how does the cookies work in asp.net?
we know Http is an state-less protocol which is required for interaction between clinet and server .

so there is an need to remeber state of request raised by an web browser so that
web server can recognize you have already previously visited or not.

There are two types of state management techniques:
a) Client side state management
b) Server - side statemanagement

Using cookies comes under clinet side statemanagement .In HttpResponse we write
Cookie containing sessionId and other information within it.

when a browser made a request to the web server the same cookie is sent to the server where server recognize the session id and get other information stored to it previously.

3. What is Ispostback method in ASP.Net? Why do we use that??

Basically Post back is an action performed by a interactive Webpage. When it goes to the server side for a non-client Operation Server again posts it back to the client and hence the name.
Ex:

if(!IsPostBack)

will not allow the page to post back again n again bcoz it reduces the performance.

4. Can User Control be stored in library?.
I will say "NO"

there are 3 types of controls:
1) User Control
2) Custom Control
3) Web parts

you can reuse User control in the current project in which you have built it, but you can't move it to other project as unless you just copy paste the same file there and make the changes for that project ( which violets the concept of library).

but custom control can be shared between projects. and you can precompile them even as a dll, so this means you can use them in library of any type.

5. what is the difference between application state and caching?
Application Object and Cached Object both falls under Server side State Management.

Application object resides in InProc i.e. on the same server where we hosted our application.
Cache Object resides on server side/ DownStream/Client Side.

Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.

Only one user can access Application Object at a time hence we have to lock it every time we modify it.

6. what is boxing and unboxing?
Boxing is what happens when a value-type object is assigned to a reference-type variable.
Unboxing is what happens when a reference-type variable is assigned to a value-type variable।

7. What are the uses of Reflection??
Reflection is a concept using which we can

1) Load assemblies dynamically
2) Invoke methods at runtime
3) Retriving type information at runtime.

8. What is the use of AutoWireup in asp.net?
AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.
In the case where AutoEventWireup attribute is set to false (by default) event handlers are automatically required for Page_Load or Page_Init. However when we set the value of the AutoEventWireup attribute to true the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.

9. what events will occur when a page is loaded?
Below are the events occures during page load.

1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad

10. Where is the View state Data stored?
ViewState data is stored in the hidden field. When the page is submitted to the server the data is sent to the server in the form of hidden fields for each control. If th viewstate of the control is enable true the value is retained on the post back to the client when the page is post backed.

11. What is the difference between custom web user control and a custom web server control?
Web User Control:
1) Easy to Create.
2) It Can be used inside the same Application.(To use it in other application we need to add it to that project.)
3) It Can take advantage of Caching Technique.

Web Server Control:
1) Bit tuff to create as compare to User Control.
2) Easy to use.
3) Can be added to ToolBox.

12. Where do the Cookie State and Session State information be stored?
Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it.
Coming to Session State
As we know for every process some default space will be allocated by OS.
In case of InProc Session Info will be stored inside the process where our
application is running.
In case of StateServer Session Info will be stored using ASP.NET State Service.
In case of SQLServer Session info will be stored inside Database. Default DB
which will be created after running InstallSQLState Script is ASPState.
13. What is the difference between adding reference in solution Explorer and adding references by USING ?
Adding reference in solution explorer is used to add the DLL for that project for reference only. If you want to utilize that DLL methods/functions in our aspx.cs/.cs file etc you must write using that nameclass library name in file.

14. What are the different types of sessions in ASP.Net? Name them.?
Session Management can be achieved in two ways

1)InProc
2)OutProc

OutProc is again two types
1)State Server
2)SQL Server

InProcAdv.:
1) Faster as session resides in the same process as the application
2) No need to serialize the data
DisAdv.:
1) Will degrade the performance of the application if large chunk of data is stored
2) On restart of IIS all the Session info will be lost
State ServerAdv.:
1) Faster then SQL Server session management
2) Safer then InProc. As IIS restart
won't effect the session data
DisAdv.:
1) Data need to be serialized
2) On restart of ASP.NET State Service session info will be lost
3)Slower as compared to InProc
SQL ServerAdv.:
1) Reliable and Durable
2) IIS and ASP.NET State Service
restart won't effect the session data
3) Good place for storing large chunk of data
DisAdv.:
1) Data need to be serialized
2) Slower as compare to InProc and State Server
3)Need to purchase Licensed
version of SQL Serve
15. How do you design a website with multilingual support in ASP.NET?
Multilingual website can be created using Globalization and Localization.
Using Globalization we change the Currency Date Numbers etc to Language Specific Format.
To change the string which is there in the label button etc to language specific string we use Localization.
In Localization we have to create different Resource files for different languages.
During this process we use some classes present in System.Resources System.Globalization System.Threading namespaces.
16. What is caching? What are different ways of caching in ASP.NET?
Caching is a technique of persisting the data in memory for immediate access to requesting program calls. This is considered as the best way to enhance the performance of the application.

Caching is of 3 types:
Output Caching - Caches the whole page.
Fragment Caching - Caches a part of the page
Data Caching - Caches the data

17. What is meant by 3-tier architecture.
We generally split our application into 3-Layers
1)Presentation Layer ( Where we keep all web forms Master Pages and User Controls).
2)Business Layer (Where we keep business logic). e.g Code related to manipulating data Custom Exception classes Custom Control classes Login related code if any etc. etc.
3)Data Access Layer (Where we keep code used to interact with DB). e.g. We can have the methods which are using SQL Helper (Application Block).
18. Explain the basic functionality of garbage collector?
Garbage Collector in .Net Framework is used for Automatic Memory Management i.e. it is collect all unused memory area and give to application. system.gc.collect() is a method for release the memory. But remember one think it is only an request i.e. we can't explicitly release the memory by using system.gc.collect().
19. What is the difference between mechine.config and web.config?
machine.config is a system level configuration i.e it is applied on all application in o/s that the configuration is set where as in web.config it is applicable to only one application i.e each asp.net webapplication will contain atleast on web.config file.
20. How can exception be handled with out the use of try catch?
using Exception Management application block
or
Page_error
Application_error objects
21. What is the difference between Response.Redirect and Server.Transfer.
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server.Server.Transfer does not update the clients url history list or current url.
Response.Redirect is used toredirect the user's browser to another page or site. This performs a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.
22. Where the assembly is stored in asp.net?.
private are stored in application / bin directory and public are stored in GAC.
23. How we implement Web farm and Web Garden concept in ASP.NET?.
A web farm is a multi-server scenario. So we may have a server in each state of US. If the load on one server is in excess then the other servers step in to bear the brunt.
How they bear it is based on various models.
1. RoundRobin. (All servers share load equally)
2. NLB (economical)
3. HLB (expensive but can scale up to 8192 servers)
4. Hybrid (of 2 and 3).
5. CLB (Component load balancer).
A web garden is a multi-processor setup. i.e. a single server (not like the multi server above).
How to implement webfarms in .Net:
Go to web.config and
Here for mode you have 4 options.
a) Say mode inproc (non web farm but fast when you have very few customers).
b) Say mode StateServer (for webfarm)
c) Say mode SqlServer (for webfarm)
Whether to use option b or c depends on situation. StateServer is faster but SqlServer is more reliable and used for mission critical applications.
How to use webgardens in .Net:
Go to web.config and
Change the false to true. You have one more attribute that is related to webgarden in the same tag called cpuMask.
24. Is there any limit for query string? means what is the maximum size?..
Servers should be cautious about depending on URI lengths above 255 bytes because some older client or proxy implementations may not properly support these lengths.
Query string length depends on browser compatability

IE supports upto 255
Firefox supports upto 4000
25. What is the exact purpose of http handlers?
ASP.NET maps HTTP requests to HttpHandlers. Each HttpHandler enables processing of individual HTTP URLs or groups of URL extensions within an application. HttpHandlers have the same functionality as ISAPI extensions with a much simpler programming model
Ex
1.Default HttpHandler for all ASP.NET pages ->ASP.NET Page Handler (*.aspx)
2.Default HttpHandler for all ASP.NET service pages->ASP.NET Service Handler (*.asmx)
An HttpHandler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler usually launches a process that can be lengthy and returns before that process finishes
After writing and compiling the code to implement an HttpHandler you must register the handler using your application's Web.config file.

Thursday, May 19, 2011

onblur and onfocus-textbox

Onblur and Onfocus textchange
function myFocus(element) {
if (element.value == element.defaultValue) {
element.value = '';
}
}
function myBlur(element) {
if (element.value == '') {
element.value = element.defaultValue;
}
}

Define it like this
<asp:textbox id="txtname" runat="server" text="Enter Your Name" height="29px" onfocus="myFocus(this);" onblur="myBlur(this);">

Monday, May 16, 2011

Diffrence between windows authentication and sql server authentication


Wnidows Authentication 
1.Single User can only login
2.Not Integerated
3.Not Security

SQL Authentication
1.Multi user can login
2.Integerated
3.More security

Send mail in asp.net

just write the code in button click and then do some editting

protected void btnsubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string StrMailBody = "Name: " + txtname.Text.ToString().Trim() + ", Contact No.: " + txtcont.Text.ToString().Trim();
            SmtpClient client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            client.Host = "smtp.gmail.com";
            client.Port = 587;

            // setup Smtp authentication
            System.Net.NetworkCredential credentials =
                new System.Net.NetworkCredential("emailid", "pwd");
            client.UseDefaultCredentials = false;
            client.Credentials = credentials;

            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("emailid");
            msg.To.Add(new MailAddress("receiver emaid id "));
            //msg.CC.Add(new MailAddress("email"));
            msg.Bcc.Add(new MailAddress("sandeepchrs@yahoo.com"));

            msg.Subject = "SMWS - Contact Us";
            msg.IsBodyHtml = true;
            msg.Body = string.Format("<html><head></head><body><b>Name: </b>" + txtname.Text.ToString().Trim() + "<b>Contact us: </b>" + txtcont.Text.ToString().Trim() + "</body>");

            try
            {
                client.Send(msg);
                //lblMsg.Text = "Your message has been successfully sent.";
            }
            catch (Exception ex)
            {
                //lblMsg.ForeColor = Color.Red;
                //lblMsg.Text = "Error occured while sending your message." + ex.Message;
            }
        }
    }

Url rewritting work in IIS-7.0

1. Take the Web form


 <div>
        <a href="page1">Page 1</a><br />
        <a href="page2">Page 2</a><br />
        <a href="page3">Page 3</a>
</div>


2.pagge1 ===redirect to second page with id
3.in code behind page od second
 if (Request.QueryString["id"] != null)
        {
            string s = Request.QueryString["id"].ToString().Trim();
            switch(s)
            {
                case "1":
                    Response.Write("this is page 1");
                    break;
                case "2":
                    Response.Write("this is page 2");
                    break;
                case "3":
                    Response.Write("this is page 3");
                    break;
            }
}


4.in the web config file

 <urlMappings>
      <add url="~/page1" mappedUrl="~/jquery.aspx?id=1"/>
      <add url="~/page2" mappedUrl="~/jquery.aspx?id=2"/>
      <add url="~/page3" mappedUrl="~/jquery.aspx?id=3"/>
 </urlMappings>




  http://www.youtube.com/watch?v=FRhQhp3VKys



http://peterkellner.net/2008/08/24/urlrewrite-with-aspnet-urlrewriter-wildcard-mapping-iis6-iis7/------------------

Check username if it exist in database through stored procedure

THIS IS DONE THROUGH STORED PROCEDURE

CREATE PROCEDURE [dbo].[checkusername]
(
@name varchar (50),
@gender char ,
@dob nvarchar,
@deslogin nvarchar

)
AS
BEGIN

IF EXISTS(SELECT * FROM REGISTRATION WHERE [name] = @name)
BEGIN
print 10
END
ELSE
BEGIN
INSERT into REGISTRATION([name], gender,dob,deslogin) VALUES(@name,@gender,@dob,@deslogin )
END
END

Create title, meta tag dynamically

1.In aspx page define like this to access it in .cs page.

<title>
        <%= PageTitle %></title>
    <%= MetaKeywords %>
    <%= MetaDescription %>2.
Define it globally to access inside

  public static string HotelNameForHeading, City, PageTitle, MetaKeywords, MetaDescription ;

PageTitle="html contatic";
MetaKeywords ="html contatic";
MetaDescription  ="html contatic";


3. And you can define it as page.title="html";

String V/s Stringbulder


In Dot Net there will be many cases where in we need to operate on strings and first thing we remember is using system.String but there are certainly many points we need to remember and consider before we operate on strings.
1) Performance.
2)how many times we need to concatenate.
Lets take an example for concatenate five strings.
EX 1. Using System.String
System.String str =“My Name is sandeep chaurasia ”;
str += “and i am”; str += “working on “;
str += “Post of “;
str += “difference between string and string builder”;
Response.Write(str);
and the expected output well you probably guessed it right
“My Name is sandeep chaurasia and i amworking on Post of difference between string and string builder”
Now what has happed? yes the important question now how many times we have appended the str variable those number of times string was created in memory location and abandoned when a new string is created and later waiting for garbage collection.
This leads to memory wastage and degradation of performance because string are immutable(that means any change to string causes a runtime to create a new string and abandon old one).
Think about the situation where in u need to work on 100 or more strings????
Dot Net has answer for it in the form of System.Text.StringBuilder class
EX2. Same Example using StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append( “My Name is sandeep”);
sb.Append( “and i am”);
sb.Append( “working on “);
sb.Append( “Post of “);
sb.Append( “difference between string and string builder”);
and the output is same as previous
“My Name is sandeepand i amworking on Post of difference between string and string builder”
But this time there was only one string created in memory dynamically and modified as we append the new string, by this there is not much garbage collection and also helps improve performance. Append is taken only for example there are a lot of other functions which are just waiting for you to invoke.Happy coding.