Monday, July 27, 2009

Return XML File

Get the data from datatable/list, write it in a xml format.

using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Text;

protected void Page_Load(object sender, EventArgs e)
{
ReturnProductDetailsCollections();
}
void ReturnProductDetailsCollections()
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-60));
PGILib objPGLib = new PGILib();
try
{
int CollectionID;
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
if (Request.QueryString["ProductID"] != null && Request.QueryString["LanguageID"] != null)
{
CollectionID = Convert.ToInt32(Request.QueryString["ProductID"]);
int iLanguageID = Convert.ToInt32(Request.QueryString["LanguageID"]);

string Currentlang = "";
DataTable dtCurrentlang = new DataTable();
dtCurrentlang = objPGLib.Script_GetLanguageName(iLanguageID);
if (dtCurrentlang.Rows.Count > 0)
{
foreach (DataRow dr in dtCurrentlang.Rows)
{
Currentlang = dr["LanguageShortName"].ToString();
}
}

int CategoryID = objPGLib.getCollectionCategoryIDByMarket(iLanguageID);

writer.WriteStartElement("designgallery");
writer.WriteAttributeString("Result", "Success");
DataTable dtProductCollection = new DataTable();

dtProductCollection = objPGLib.Script_GetDesignerCollections(CollectionID,CategoryID);
if (dtProductCollection.Rows.Count > 0)
{
foreach (DataRow dr1 in dtProductCollection.Rows)
{
string strpPath = ConfigurationManager.AppSettings["UploadLocation"].ToString() + dr1["SmallThumbnailPath"].ToString();
writer.WriteStartElement("product");
writer.WriteAttributeString("productid", dr1["ProductID"].ToString());
writer.WriteAttributeString("smallthumbnail", strpPath);
writer.WriteAttributeString("name", dr1["ProductName"].ToString());
writer.WriteAttributeString("designer", dr1["FirstName"].ToString());
writer.WriteEndElement();
}
}
}
else
{
writer.WriteStartElement("designgallery");
writer.WriteAttributeString("Result", "Failure");

}



writer.WriteEndElement();
Response.ContentType = "text/xml";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(sw);
}
catch (Exception ex)
{
AppLogger.LogError("Designer Gallery Product ReturnProductDetailsCollections(based on designerid) " + ex.Message, AppLogger.Severity.Error);
}


}

Rss Feeds in asp.net

To write the Rss Contents from list/datatable.

steps to follow:

Get the all the item (ex: news in a list/datatable loop through the items bind in the rss feeds format)

refer the attached image.

image 1



image 2



C#Code:

protected void Page_Load(object sender, EventArgs e)
{
this.Context.Response.ContentType = "text/xml";
this.Context.Response.ContentEncoding = Encoding.UTF8;
ShowHeader(this.Context);
NewsManager newsManager = new Telerik.News.NewsManager("News");
IList listOfNewsItems = newsManager.Content.GetContent();
if (listOfNewsItems.Count > 0)
{
foreach (IContent ICntNews in listOfNewsItems)
{
DateTime strPDate = Convert.ToDateTime(ICntNews.GetMetaData("Publication_Date"));
if (strPDate < DateTime.Now)
{
ShowItem(this.Context, ICntNews);
}
}
}

ShowFooter(this.Context);
}

private void ShowItem(HttpContext context, Telerik.Cms.Engine.IContent content)
{
context.Response.Write("");
context.Response.Write(string.Format("{0}", content.GetMetaData("Title")));
DateTime dtPubdate = Convert.ToDateTime(content.GetMetaData("Publication_Date"));
context.Response.Write(string.Format("{0}", dtPubdate.ToString("ddd, dd MMM yyyy hh:mm:ss GMT")));
context.Response.Write(string.Format("{0}", content.GetMetaData("Summary")));
context.Response.Write(string.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, ConfigurationManager.AppSettings["NewsDetails"].ToString() + "?sNewsID=" + content.ID));
context.Response.Write(string.Format("{0}", content.ID));
context.Response.Write("
");
}

private void ShowHeader(HttpContext context)
{
context.Response.Write("");
context.Response.Write("");
context.Response.Write("");
context.Response.Write("QFC Authority news ");
context.Response.Write("News headlines ");
context.Response.Write("http://www.qfc.com.qa/ ");
context.Response.Write("http://backend.userland.com/rss ");
context.Response.Write(Environment.NewLine);
}

private void ShowFooter(HttpContext context)
{
context.Response.Write("
");
context.Response.Write("
");
}

Friday, July 10, 2009

Open outlook and add reciepient emailid

To send mail call the below method in .Net.
1)
using System.Web.Mail;
public Boolean SendMail(string pstrFrom, string pstrTo, string pstrSubject, string pstrBody)
{
Boolean Result = false;
try
{
MailMessage omsg = new MailMessage();
omsg.From = pstrFrom;
omsg.To = pstrTo;
omsg.Subject = pstrSubject;
omsg.Body = pstrBody;
omsg.Priority = MailPriority.High;
omsg.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer = "";
SmtpMail.Send(omsg);
Result = true;
}
catch (Exception ex)
{
Result = false;
AppLogger.LogError("SendMail(4 parameters): " + ex.Message, AppLogger.Severity.Error);

}
return Result;

}

2)To open a outlook.

Wednesday, July 8, 2009

DateFormat

Standard Formats:
The following table lists the standard format characters for internationally accepted standard patterns. The format characters are case-sensitive; for example, 'g' and 'G' represent slightly different patterns. Note that on the whole the format handling of the DateTimePicker is almost identical to that of the associated Culture.DateTimeFormatInfo instance, the main exception being that day names "dddd" are not used anywhere.

Custom Formats:

Friday, July 3, 2009

Passing Data/Parameter/Value/ from one page to another page (.aspx/.ascx)

Passing Data/Parameter/Value/ from one page to another page (.aspx/.ascx)
Passing parameters from one page to another page is a very common task in Web development. Especially when you develop a project & redirects or navigates from one ASP.NET Web page to another, you will frequently want to pass information from the source page to the target page . In this post, I will show you some ways of transferring data/parameters/values between one page to another page which is also termed as State Management. The pages I created to show you the example is really simple which consists of a text field and a button in the first page named as page1 and a blank second page named as page2.

According to the characteristics of aspx page lifecycle web form do not retain their value after a page is displayed. To solve this problem, ASP.NET provides the following ways to retain variables between pages:
Query Strings
Cookies
Session variables
Server.Transfer
Post Back URL


Using Query String:

The most common & easiest way of passing data is query string. Usually we pass value(s) through query string of the page and then this value is pulled from Request object in another page. One thing keep in mind that user can view query string value any time(from brwser address, View source, even on mouse over of a link etc.). So never pass information which is secure like password through query string. Drawback of Query string appear after a question mark of a URL.

Example:
Suppose you want to pass the txtName TextBox value from page1 to page2 on button click event:

protected void btn_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx?name=" + txtName.Text);
}

Now the question is how we can read/retrieve my name from page2.aspx page? The way is:

string name = Request.QueryString["name"];

Now more advance is if you want to transfer special charaters or a line with spaces then you must have to use Server.UrlEncode method before transfer & Server.UrlDecode method to read data from page2.aspx:

protected void btn_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx?name=" + Server.UrlEncode(txtName.Text));
}

and to read from page2:

string name = Server.UrlDecode(Request.QueryString["name"]);

Now i want to show you how you can transfer more data:

protected void cmdTransfer_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx?name="+Server.UrlEncode(txtName.Text)+"&age="+txtAge.Text);
}

Now read both name & age from page2 in the same way:

string name = Request.QueryString["name"];
string age = Request.QueryString["age"];

now you can check the both parameter (with null value then write it).

Cookies:
Developers use cookies to store small amounts of information on the client. Drawback if user set the browser status cookie not supported won’t help. It’s stored only client machine. From the server we can check the page load event.
Example:
Now we create a cookie from page1 & read from page2:
for page1 button click event:

protected void cmdTransfer_Click(object sender, EventArgs e)
{
if(Request.Browser.Cookies) // To check that the browser support cookies
{
HttpCookie cookie = new HttpCookie("myname");
cookie.Value = txtName.Text;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Response.Redirect("page2.aspx");
}
else
{
// You have to follow other option.
}
}

Now read from page2:
if(Request.Cookies["myname"] != null)
Response.Write(Request.Cookies["myname"].Value);

Using Session Variables:
By default, session variables are stored in the web server memory. Session variables are unique per each user. If you open same url in two browser then server will create two independent sessions for you. Keep in mind that each session has a expire time. You can configure session time from IIS. Also one another thing is, you can receive session value form any pages after assigning. Write the below code under page1 button:

protected void btn_Click(object sender, EventArgs e)
{
Session["name"] = txtName.Text;
Response.Redirect("page2.aspx");
}

Now read session variable value from page2:

string name ="";
if(Session["name"]!=null)
name=Session["name"].ToString();


Using Server.Transfer:
We will use Server. Transfer to send the control to a new page. Note that Server.Transfer only transfers the control to the new page and does not redirect the browser to it, which means you will see the address of the old page in your URL. If the user clicks Refresh on his browser, the browser prompt a message warning that the page can not be refreshed without resending information. Write the below code under page1 button click event:

protected void btn_Click(object sender, EventArgs e)
{
Server.Transfer("page2.aspx", true);
}

And write the below code in page2 load event:

if (Request.Form["txtEmail"])
Response.Write(Request.Form["txtNamel"]);

Now run the page1, enter your name & click. You will see your name in page2. Merits of using the above it won’t give any blank page or any warnings.

Using Post Back URL:
ASP.NET 2.0 has been introduced Cross page posting. By PreviousPage object you can search controls value from which page you are redirected here. To implement Cross page posting you have to define the PostBackUrl property of page1 button to page2. Like:

aspx/ascx design page btn propery called PostBackUrl="page2.aspx"

Now write the below code in page2 load event:

TextBox txtName = (TextBox)(PreviousPage.FindControl("txtName"));
string myname =txtName.Text;
Or
If you use usercontrol the previouspage// prpery won’t support.
TextBox txtName = (TextBox)Page.PreviousPage.FindControl("txtName"));
string myname =txtName.Text;

Copyright © 2009 Angel