1.string is immutable where is string builder is mutable
2.In stringBuilder, automatically increase and decrease size of string object whenever add elements and delete elements .Where in string , it is fixed size .
3.StringBuilder can perform a insert(),Delete(),Reverse(),Sort() operations etc and we can create multiple instances .Where as String , It can't perform.
4.StringBuilder takes enough memory for variable .Where as String can't perform.
we use strings for non-changing strings because every time when a string is changed a new instance of string is created using new memory locations. whereas in stringbuilder we can work on the same memory location.
so stringbuilder is efficient in terms of memory for changing strings.
Friday, January 22, 2010
Using Microsoft Application Block for interacting with Database
Example below shows how can we use Application Block for DAL layer.
//This method inserts values to DB by using a stored procedure
public void DBInsert(string[] points)
{
SqlParameter[] param = SqlHelperParameterCache.GetSpParameterSet(_connection, "sp_CIP_insert");
if (param == null)
{
param = new SqlParameter[7];
param[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
param[1] = new SqlParameter("@Realistic", SqlDbType.Int);
param[2] = new SqlParameter("@Investigative", SqlDbType.Int);
param[3] = new SqlParameter("@Artistic", SqlDbType.Int);
param[4] = new SqlParameter("@Social", SqlDbType.Int);
param[5] = new SqlParameter("@Enterprising", SqlDbType.Int);
param[6] = new SqlParameter("@Conventional", SqlDbType.Int);
SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_insert", param);
}
param[0].Value = points[0];
param[1].Value = points[1];
param[2].Value = points[2];
param[3].Value = points[3];
param[4].Value = points[4];
param[5].Value = points[5];
param[6].Value = points[6];
SqlHelper.ExecuteNonQuery(_connection, CommandType.StoredProcedure, "sp_CIP_insert",param);
}
//This method gets the values from DB, it uses ExecuteReader class
public int[] Uscores(string appcode)
{
int[] Uscr = new int[6];
SqlParameter[] spm = SqlHelperParameterCache.GetCachedParameterSet(_connection, "sp_CIP_getScore");
if (spm == null)
{
spm = new SqlParameter[1];
spm[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_getScore", spm);
}
spm[0].Value = appcode.Trim();
SqlDataReader dr = SqlHelper.ExecuteReader(_connection, CommandType.StoredProcedure, "sp_CIP_getScore",spm);
if (dr.Read())
{
Uscr[0] = Convert.ToInt32(dr["Realistic"].ToString());
Uscr[1] = Convert.ToInt32(dr["Investigative"].ToString());
Uscr[2] = Convert.ToInt32(dr["Artistic"].ToString());
Uscr[3] = Convert.ToInt32(dr["Social"].ToString());
Uscr[4] = Convert.ToInt32(dr["Enterprising"].ToString());
Uscr[5] = Convert.ToInt32(dr["Conventional"].ToString());
dr.Close();
}
return Uscr;
}
//This method inserts values to DB by using a stored procedure
public void DBInsert(string[] points)
{
SqlParameter[] param = SqlHelperParameterCache.GetSpParameterSet(_connection, "sp_CIP_insert");
if (param == null)
{
param = new SqlParameter[7];
param[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
param[1] = new SqlParameter("@Realistic", SqlDbType.Int);
param[2] = new SqlParameter("@Investigative", SqlDbType.Int);
param[3] = new SqlParameter("@Artistic", SqlDbType.Int);
param[4] = new SqlParameter("@Social", SqlDbType.Int);
param[5] = new SqlParameter("@Enterprising", SqlDbType.Int);
param[6] = new SqlParameter("@Conventional", SqlDbType.Int);
SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_insert", param);
}
param[0].Value = points[0];
param[1].Value = points[1];
param[2].Value = points[2];
param[3].Value = points[3];
param[4].Value = points[4];
param[5].Value = points[5];
param[6].Value = points[6];
SqlHelper.ExecuteNonQuery(_connection, CommandType.StoredProcedure, "sp_CIP_insert",param);
}
//This method gets the values from DB, it uses ExecuteReader class
public int[] Uscores(string appcode)
{
int[] Uscr = new int[6];
SqlParameter[] spm = SqlHelperParameterCache.GetCachedParameterSet(_connection, "sp_CIP_getScore");
if (spm == null)
{
spm = new SqlParameter[1];
spm[0] = new SqlParameter("@appcode", SqlDbType.VarChar);
SqlHelperParameterCache.CacheParameterSet(_connection, "sp_CIP_getScore", spm);
}
spm[0].Value = appcode.Trim();
SqlDataReader dr = SqlHelper.ExecuteReader(_connection, CommandType.StoredProcedure, "sp_CIP_getScore",spm);
if (dr.Read())
{
Uscr[0] = Convert.ToInt32(dr["Realistic"].ToString());
Uscr[1] = Convert.ToInt32(dr["Investigative"].ToString());
Uscr[2] = Convert.ToInt32(dr["Artistic"].ToString());
Uscr[3] = Convert.ToInt32(dr["Social"].ToString());
Uscr[4] = Convert.ToInt32(dr["Enterprising"].ToString());
Uscr[5] = Convert.ToInt32(dr["Conventional"].ToString());
dr.Close();
}
return Uscr;
}
Sending Email from asp.net with proper exception handling
Hi below is the code for sending email from asp.net application......
using System.Net;
using System.Net.Mail;
public MailGeneration()
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello "+"<br/>");
sb.Append("Please find the occupations report attached to this mail.");
sb.Append("<br/><br/>");
sb.Append("Warm Regards,");
string strBd = sb.ToString();
strBd = HttpContext.Current.Server.HtmlDecode(strBd);
MailMessage mail = new MailMessage("Hara@Testmail.com", "mail@testmail.com");//sends to candidate
mail.CC.Add("mail@ccmail.com");//sends as CC
mail.Subject = "Mail Subject";
mail.Body = "Mail Body";
mail.IsBodyHtml = true;
mail.Attachments.Add(new System.Net.Mail.Attachment("File to be attached"));
mail.Attachments[0].Name = "File Name to be Displayed";
string smtpClient = System.Configuration.ConfigurationManager.AppSettings["SMTPClientHost"].ToString().Trim();
SmtpClient objSmtpClient = new SmtpClient(smtpClient);
try
{
objSmtpClient.Send(mail); //Sending Mail
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
for (int recipient = 0; recipient < recExc.InnerExceptions.Length - 1; recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
//Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = recExc.InnerExceptions[recipient].StatusCode;
if ((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable))
{
//Log this to event log: recExc.InnerExceptions[recipient].FailedRecipient
System.Threading.Thread.Sleep(5000);
objSmtpClient.Send(mail);
}
else
{
//Log error to event log.
//recExc.InnerExceptions[recipient].StatusCode or use statusCode
}
}
}
//General SMTP execptions
catch (System.Net.Mail.SmtpException smtpExc)
{
//Log error to event log using StatusCode information in
//smtpExc.StatusCode
}
catch (Exception ex)
{
//Log error to event log.
}
finally
{
mail.Attachments.Dispose();
}
}
using System.Net;
using System.Net.Mail;
public MailGeneration()
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello "+"<br/>");
sb.Append("Please find the occupations report attached to this mail.");
sb.Append("<br/><br/>");
sb.Append("Warm Regards,");
string strBd = sb.ToString();
strBd = HttpContext.Current.Server.HtmlDecode(strBd);
MailMessage mail = new MailMessage("Hara@Testmail.com", "mail@testmail.com");//sends to candidate
mail.CC.Add("mail@ccmail.com");//sends as CC
mail.Subject = "Mail Subject";
mail.Body = "Mail Body";
mail.IsBodyHtml = true;
mail.Attachments.Add(new System.Net.Mail.Attachment("File to be attached"));
mail.Attachments[0].Name = "File Name to be Displayed";
string smtpClient = System.Configuration.ConfigurationManager.AppSettings["SMTPClientHost"].ToString().Trim();
SmtpClient objSmtpClient = new SmtpClient(smtpClient);
try
{
objSmtpClient.Send(mail); //Sending Mail
}
catch (System.Net.Mail.SmtpFailedRecipientsException recExc)
{
for (int recipient = 0; recipient < recExc.InnerExceptions.Length - 1; recipient++)
{
System.Net.Mail.SmtpStatusCode statusCode;
//Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = recExc.InnerExceptions[recipient].StatusCode;
if ((statusCode == System.Net.Mail.SmtpStatusCode.MailboxBusy) || (statusCode == System.Net.Mail.SmtpStatusCode.MailboxUnavailable))
{
//Log this to event log: recExc.InnerExceptions[recipient].FailedRecipient
System.Threading.Thread.Sleep(5000);
objSmtpClient.Send(mail);
}
else
{
//Log error to event log.
//recExc.InnerExceptions[recipient].StatusCode or use statusCode
}
}
}
//General SMTP execptions
catch (System.Net.Mail.SmtpException smtpExc)
{
//Log error to event log using StatusCode information in
//smtpExc.StatusCode
}
catch (Exception ex)
{
//Log error to event log.
}
finally
{
mail.Attachments.Dispose();
}
}
Friday, January 15, 2010
Getting values of another page into a diff page by using Context
We can get the values from a previous page(e.g. PageOne.aspx) into a new page(e.g. PageTwo.aspx) by using Context.
To make use of Context the old page i.e. PageOne.aspx should use Server.Transfer("PageTwo.aspx") to navigate to PageTwo.aspx.
Codes to retrive values of PageOne.aspx in PageTwo.aspx
PageTwo.aspx
public class PageTwo : Page
{
public PageOne RetriveVal;
private void Page_Load(object sender, EventArgs e)
{
this.RetriveVal= (PageOne) this.Context.Handler;
Label1.Text=RetriveVal.GetVal();////GetVal() returns a string which is defined in PageOne.aspx.cs
}
}
To make use of Context the old page i.e. PageOne.aspx should use Server.Transfer("PageTwo.aspx") to navigate to PageTwo.aspx.
Codes to retrive values of PageOne.aspx in PageTwo.aspx
PageTwo.aspx
public class PageTwo : Page
{
public PageOne RetriveVal;
private void Page_Load(object sender, EventArgs e)
{
this.RetriveVal= (PageOne) this.Context.Handler;
Label1.Text=RetriveVal.GetVal();////GetVal() returns a string which is defined in PageOne.aspx.cs
}
}
Editing the HTML of a aspx page or ascx page at runtime...
Using HtmlAgilityPack.dll we can do so...
Here is the code....
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HtmlDocument Hdoc = new HtmlDocument();
Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
foreach(HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
{
if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
{
txtHtmlEditor.Text = Hn.WriteTo();
break;
}
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
////txtHtmlEditor.Text is the TextBox contains the HTML
HtmlDocument Hdoc = new HtmlDocument();
Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
HtmlTextNode htxt = Hdoc.CreateTextNode(txtHtmlEditor.Text);
foreach (HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
{
if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
{
Hn.ParentNode.ReplaceChild(htxt, Hn);
Hdoc.Save(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
break;
}
}
txtHtmlEditor.Text = "";
lblSuccMsg.Text = "Successfully Saved the Html Contents";
}
Here is the code....
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HtmlDocument Hdoc = new HtmlDocument();
Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
foreach(HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
{
if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
{
txtHtmlEditor.Text = Hn.WriteTo();
break;
}
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
////txtHtmlEditor.Text is the TextBox contains the HTML
HtmlDocument Hdoc = new HtmlDocument();
Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
HtmlTextNode htxt = Hdoc.CreateTextNode(txtHtmlEditor.Text);
foreach (HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
{
if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
{
Hn.ParentNode.ReplaceChild(htxt, Hn);
Hdoc.Save(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
break;
}
}
txtHtmlEditor.Text = "";
lblSuccMsg.Text = "Successfully Saved the Html Contents";
}
Writing on an existing XML file
below your XML files named as someting.xml
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSlide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://MYDOMAINHERE.com/">
<Slide>
<ImagePath>/images/polperro/generic_1024.jpg</ImagePath>
<Name> images_15seconds</Name>
<Description />
</Slide>
<Slide>
<ImagePath>/Images/HeaderImages/header.jpg</ImagePath>
<Name>header.jpg</Name>
<Description />
</Slide>
</ArrayOfSlide>
Now this function will add contents in this XML file.
private void xmlUpdate(string filename)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
string ns = xDoc.DocumentElement.NamespaceURI;
XmlNode root = xDoc.DocumentElement;
XmlElement newElement = xDoc.CreateElement("Slide", ns);
XmlElement childElement1 = xDoc.CreateElement("ImagePath", ns);
childElement1.InnerText = @"/Images/HeaderImages/" + filename;
XmlElement childElement2 = xDoc.CreateElement("Name", ns);
childElement2.InnerText = filename;
XmlElement childElement3 = xDoc.CreateElement("Description", ns);
newElement.AppendChild(childElement1);
newElement.AppendChild(childElement2);
newElement.AppendChild(childElement3);
root.AppendChild(newElement);
xDoc.Save(Server.MapPath(@"~\XML\XMLImagePath.xml"));
lblSuccMsg.Text = "Successfully appended to the Xml file.";
}
Similarly deleting a Node from the XML file....
private void xmlDelete(string ImgPath)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
XmlNode root = xDoc.DocumentElement;
XmlNodeList xmlNdList = xDoc.GetElementsByTagName("Slide");
for (int i = 0; i < xmlNdList.Count; i++)
{
if (xmlNdList.Item(i).Name == "Slide")
{
if (xmlNdList.Item(i).ChildNodes.Item(0).InnerText.Trim() == ImgPath)
{
root.RemoveChild(xmlNdList.Item(i));
}
}
}
xDoc.Save(Server.MapPath(@"~\XML\XMLImagePath.xml"));
}
Similarly reading from that XML file......
private string[,] xmlData()
{
string[,] ImagePaths;
XmlDocument xDocm = new XmlDocument();
xDocm.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
XmlNodeList xmlNdList = xDocm.GetElementsByTagName("Slide");
ImagePaths = new string[xmlNdList.Count, 2];
for (int i = 0; i < xmlNdList.Count; i++)
{
if (xmlNdList.Item(i).Name == "Slide")
{
ImagePaths[i, 0] = xmlNdList.Item(i).ChildNodes.Item(0).InnerText;
ImagePaths[i, 1] = xmlNdList.Item(i).ChildNodes.Item(1).InnerText;
}
}
return ImagePaths;
}
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSlide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://MYDOMAINHERE.com/">
<Slide>
<ImagePath>/images/polperro/generic_1024.jpg</ImagePath>
<Name> images_15seconds</Name>
<Description />
</Slide>
<Slide>
<ImagePath>/Images/HeaderImages/header.jpg</ImagePath>
<Name>header.jpg</Name>
<Description />
</Slide>
</ArrayOfSlide>
Now this function will add contents in this XML file.
private void xmlUpdate(string filename)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
string ns = xDoc.DocumentElement.NamespaceURI;
XmlNode root = xDoc.DocumentElement;
XmlElement newElement = xDoc.CreateElement("Slide", ns);
XmlElement childElement1 = xDoc.CreateElement("ImagePath", ns);
childElement1.InnerText = @"/Images/HeaderImages/" + filename;
XmlElement childElement2 = xDoc.CreateElement("Name", ns);
childElement2.InnerText = filename;
XmlElement childElement3 = xDoc.CreateElement("Description", ns);
newElement.AppendChild(childElement1);
newElement.AppendChild(childElement2);
newElement.AppendChild(childElement3);
root.AppendChild(newElement);
xDoc.Save(Server.MapPath(@"~\XML\XMLImagePath.xml"));
lblSuccMsg.Text = "Successfully appended to the Xml file.";
}
Similarly deleting a Node from the XML file....
private void xmlDelete(string ImgPath)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
XmlNode root = xDoc.DocumentElement;
XmlNodeList xmlNdList = xDoc.GetElementsByTagName("Slide");
for (int i = 0; i < xmlNdList.Count; i++)
{
if (xmlNdList.Item(i).Name == "Slide")
{
if (xmlNdList.Item(i).ChildNodes.Item(0).InnerText.Trim() == ImgPath)
{
root.RemoveChild(xmlNdList.Item(i));
}
}
}
xDoc.Save(Server.MapPath(@"~\XML\XMLImagePath.xml"));
}
Similarly reading from that XML file......
private string[,] xmlData()
{
string[,] ImagePaths;
XmlDocument xDocm = new XmlDocument();
xDocm.Load(Server.MapPath(@"~\XML\XMLImagePath.xml"));
XmlNodeList xmlNdList = xDocm.GetElementsByTagName("Slide");
ImagePaths = new string[xmlNdList.Count, 2];
for (int i = 0; i < xmlNdList.Count; i++)
{
if (xmlNdList.Item(i).Name == "Slide")
{
ImagePaths[i, 0] = xmlNdList.Item(i).ChildNodes.Item(0).InnerText;
ImagePaths[i, 1] = xmlNdList.Item(i).ChildNodes.Item(1).InnerText;
}
}
return ImagePaths;
}
Subscribe to:
Posts (Atom)