Search content within the blog

Monday, December 29, 2008

Rounding of decimal values

decimal ShippingCharge = 0.0m;
ShippingCharge = decimal.Round(decimal.Parse(dr["TotalShippingcharge"].ToString()), 2);
//here 2 stands for number of decimal places
lblShipping.Text = ShippingCharge.ToString();

Friday, December 26, 2008

Publishing And Reading RSS Feeds In ASP.NET

What Is RSS?

RSS or Really Simple Syndication (version 2.0) is a method of publishing and displaying almost any type of data over the internet. The most well-known RSS feeds are news and weather related ones provided by publishers like BBC, Yahoo News, Telegraph India, etc. RSS publishing is not only related to news, anyone can publish data from a persistent database as he or she generates the output in the XML format supported and understood by RSS protocol.

These feeds are specially useful when people want to display information on their websites which are maintained and updated regularly by a third party agency. This saves time and effort in collecting and maintaining the same data all over again.

RSS feeds have their outputs as XML formats with specific tags like <channel/>, <title/>, <link/>, <description/>, etc. While reading the RSS feeds, the subscriber must be aware of the structure of the feed. A sample RSS feed is as follows which may be published over the internet for some subscriber to access.

<rss version="2.0">
<channel>
<title>Employee Details</title>
<link>http://localhost/RSSFeeds</link>
<description>Details of all Company Employees...</description>
<copyright>Copyright 2008 - 2010</copyright>
<item>
<title>John Doe</title>
<description>Main Street</description>
<link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=1</link>
<pubDate>9/22/2008 1:43:48 PM</pubDate>
</item>
<item>
<title>Jane Doe</title>
<description>First Street</description>
<link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=2</link>
<pubDate>9/22/2008 1:43:48 PM</pubDate>
</item>
<item>
<title>Andrew Doe</title>
<description>Downtown</description>
<link>http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpId=3</link>
<pubDate>9/22/2008 1:43:48 PM</pubDate>
</item>
</channel>
</rss>
Available RSS Readers

Instead of developing a custom RSS Reader, you can use a number of readers already available on the internet. Some of these are SharpReader, BitsCast, BlogBridge, NewsGator, NetNewsWire, Mozilla, FeedDemon, RssBandit, Shrook, Feedreader, etc.
RSS feed publishing

This sample application is about publishing SQL Server 2005 table data as a custom RSS feed over the internet.

SQL Server 2005 Database
To begin with, let us create a database in SQL Server 2005 with name RSSDB. In RSSDB, create a table with name tblEmployees, having the design as shown in Figure I.

Provide default as 0 to the Emp_IsDeleted column.

Image 1. Design of Employee table
Enter some data into the tblEmployees table as follows:
Image 2. Employee table filled with some data

Create a new SQL Server stored procedure called GetEmployees. To do this, open a SQL Server 2005 query window, then paste and execute the following:

CREATE PROCEDURE [dbo].[GetEmployees]
AS
BEGIN
SELECT * FROM tblEmployees
END

ASP.NET 2.0

1.

Open Microsoft Visual Studio 2005 and create a 'Web Site' with name RSSFeeds. After the project is created, right click on the project node and click on 'Add New Item'.
2.

In the 'Add New Item' dialog box, select 'Web Form' and enter the name EmployeeDetails.aspx in the 'Name' area and click on Add.
3.

Create a new web.config file and inside the <configuration></configuration> section enter the following:

<connectionStrings>
<add name="SQLEmployee" connectionString="Data Source={server name};DataBase=RSSDB;User Id=JavaUser; Password=*****;"/>
</connectionStrings>
4.

Open the 'Source' view of EmployeeDetails.aspx.
5.

After the first line of <%@ Page %> directive, add the following:

<%@ OutputCache Duration="120" %>

While creating a dynamic RSS feed, a problem may creep in while the user provides different parameter names like, EmpId to the RSS feed url. It may happen that when the user tries to view the output with a different EmpId, the output that is shown is the old one. It happens as the previous cached page is retrieved. To work around this problem, VaryByParam is used to tell the cache that the output varies based on this parameter value (EmpId) and a new cache needs to be created based on the EmpId value passed. In that case, instead of the previous statement, include the line as follows:

<%@ OutputCache Duration="120" VaryByParam="EmpId" %>

6.

Open the EmployeeDetails.aspx.cs page.
7.

Inside the Page_Load function, enter the following block:

if (!Page.IsPostBack)
{}

8.

Inside the Page.IsPostBack block, enter the following lines of code:

// Clear the response buffer contents
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter xmlRSSFeed = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

// Start writing the rss tags
xmlRSSFeed.WriteStartDocument();
xmlRSSFeed.WriteStartElement("rss");
xmlRSSFeed.WriteAttributeString("version", "2.0");
xmlRSSFeed.WriteStartElement("channel");
xmlRSSFeed.WriteElementString("title", "Employee Details");
xmlRSSFeed.WriteElementString("link", "http://localhost/RSSFeeds");
xmlRSSFeed.WriteElementString("description", "Details of all Company Employees...");
xmlRSSFeed.WriteElementString("copyright", "Copyright 2008 - 2010");

// Objects needed for connecting to the SQL database
SqlConnection sqlCon;
SqlCommand sqlCmd;
SqlDataReader sqlDr;

// Call SQL Server stored procedure
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLEmployee"].ToString());
sqlCmd = new SqlCommand("GetEmployees", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;

sqlCon.Open();

sqlDr = sqlCmd.ExecuteReader();

// Loop through the content of the database and add them to the RSS feed
while (sqlDr.Read())
{
xmlRSSFeed.WriteStartElement("item");
xmlRSSFeed.WriteElementString("title", sqlDr["Emp_FirstName"].ToString() + " " +
sqlDr["Emp_LastName"].ToString());
xmlRSSFeed.WriteElementString("description", sqlDr["Emp_Address"].ToString());
xmlRSSFeed.WriteElementString("link", "http://localhost/RSSFeeds/EmployeeDetails.aspx?EmpID=" +
sqlDr["Emp_Id"]);
xmlRSSFeed.WriteElementString("pubDate", DateTime.Now.ToString());
xmlRSSFeed.WriteEndElement();

}
sqlDr.Close();
sqlCon.Close();

// Close all tags
xmlRSSFeed.WriteEndElement();
xmlRSSFeed.WriteEndElement();
xmlRSSFeed.WriteEndDocument();
xmlRSSFeed.Flush();
xmlRSSFeed.Close();
Response.End();

9.

Right-click EmployeeDetails.aspx and click on 'Set as Start Page'.
10.

Run the project from inside Visual Studio 2005.

RSS feed reader

A custom RSS Feed Reader can be developed in ASP.NET 2.0 targeting the feed: http://localhost/RSSFeeds/EmployeeDetails.aspx

ASP.NET 2.0

1.

Open Microsoft Visual Studio 2005 and create a 'Web Site' with name RSSFeedReader. After the project is created, right click on the project node and click on 'Add New Item'.
2.

In the 'Add New Item' dialog box, select 'Web Form' and enter the name RSSRead.aspx in the 'Name' area and click on Add.
3. Open the 'Source' view of RSSRead.aspx.

4.

Inside the <form> tag of RSSRead.aspx document, include the following html:

<table cellpadding="0" cellspacing="0">
<tr>
<td>
<table class="NormalText" runat="server" id="tblNews" cellpadding="0" cellspacing="0">
</table>
</td>
</tr>
</table>

5.

Open RSSRead.aspx.cs.
6. Include the following using statements at the top of the file:

using System.Net;
using System.Xml;
using System.IO;
7.

Create a method as follows inside the document:

public void ProcessRSSItem(string rssURL)
{
// Read the RSS feed
WebRequest myRequest = WebRequest.Create(rssURL);
WebResponse myResponse = myRequest.GetResponse();

Stream rssStream = myResponse.GetResponseStream();

// Load a XML Document
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);

XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

string title = "";
string link = "";
string description = "";

// Loop through RSS Feed items
for (int i = 0; i < rssItems.Count; i++)
{
XmlNode rssDetail;

rssDetail = rssItems.Item(i).SelectSingleNode("title");
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = "";
}

rssDetail = rssItems.Item(i).SelectSingleNode("link");
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = "";
}

rssDetail = rssItems.Item(i).SelectSingleNode("description");
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = "";
}

// Populate the HTML table rows and cells
HtmlTableCell cell1 = new HtmlTableCell();
cell1.InnerHtml = "<b><a href='" + link + "' target='new'>" + title + "</a></b>";
HtmlTableRow tr1 = new HtmlTableRow();
tr1.Cells.Add(cell1);
tblNews.Rows.Add(tr1);
HtmlTableCell cell2 = new HtmlTableCell();
cell2.InnerHtml = "<p align='justify'>" + description + "</p>";
HtmlTableRow tr2 = new HtmlTableRow();
tr2.Cells.Add(cell2);
tblNews.Rows.Add(tr2);
}
}

8.

Inside the Page_Load method, write the following code to call the ProcessRSSItem method:

string rssURL = "http://localhost/RSSFeeds/EmployeeDetails.aspx".ToString();
try
{
ProcessRSSItem(rssURL);
}
catch (Exception ex)
{
}

9.

Right-click RSSRead.aspx and click on 'Set as Start Page'.
10.

Run the project from inside Visual Studio 2005 and enjoy new feature. Happy Programming!

Displaying RSS Feeds in Asp.Net

private void SetNews()
{
string[] strFeeds = ProcessRSSItem("http://www.loobalee.com/blog/feed/rss/", 1);
if(strFeeds.Length>1)
{
lblMessageXML.Text = "<b>" + strFeeds[0] + "</b><br/>" + strFeeds[1];
}
}

public static string[] ProcessRSSItem(string rssURL, int requiredItems)
{
WebRequest myRequest = WebRequest.Create(rssURL);
WebResponse myResponse = myRequest.GetResponse();

Stream rssStream = myResponse.GetResponseStream();
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);

XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

string title = "";
string link = "";
string description = "";

string[] toreturn;
if (requiredItems <= 0 || requiredItems > rssItems.Count)
{
requiredItems = rssItems.Count;
}

for (int i = 0; i < requiredItems; i++)
{
XmlNode rssDetail;

rssDetail = rssItems.Item(i).SelectSingleNode("title");
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = "";
}
rssDetail = rssItems.Item(i).SelectSingleNode("link");
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = "";
}
rssDetail = rssItems.Item(i).SelectSingleNode("description");
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = "";
}

//Response.Write("<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/>");
//Response.Write(description + "</p>");
}
return new string[] { title, description };
}

Refresh parent window on closing child window

function refreshParent() {
window.opener.location.href = window.opener.location.href;

if (window.opener.progressWindow)

{
window.opener.progressWindow.close()
}
window.close();
}

We can use this on any button click event in child window or on window unload event.

Wednesday, December 24, 2008

Checking if javascript is disabled in the browser

in your head section of the html page you will have some script written as folows,

<script type="text/javascript">
//just add the below line
document.write("");

function somefunction()
{
//
}
</script>

and before closing of the head tag add the following lines
<NOSCRIPT>
<meta http-equiv="REFRESH" content="0;URL=JavascriptDisabled.aspx"/> </NOSCRIPT>
here JavascriptDisabled.aspx is the page where the user will be redirected if the javascript is disabled

contents for JavascriptDisabled.aspx can be as follows
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JavascriptDisabled.aspx.cs" Inherits="JavascriptDisabled" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Loobalee-Javascript Disabled</title>
</head>
<body bgcolor="Lightblue">
<form id="form1" runat="server">
<div>
<table style="top:750px" align="center" width="50%" border="1">
<tr>
<td style="color:White">
Javascript is disabled in your browser .Enable javascript and try re-loading the page else <a href="Visitor/Login.aspx">Click Here</a>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Monday, December 22, 2008

DateTime Structure in C#

Below are common uses of the DateTime Structure in C#

DateTime.Now; 12/22/2008 5:29:25 AM
DateTime.Now.ToString(); 12/22/2008 5:29:25 AM
DateTime.Now.ToShortTimeString() 5:29 AM
DateTime.Now.ToShortDateString() 12/22/2008
DateTime.Now.ToLongTimeString() 5:29:25 AM
DateTime.Now.ToLongDateString() Monday, December 22, 2008




DateTime.Now.ToString("d") 12/22/2008
DateTime.Now.ToString("D") Monday, December 22, 2008
DateTime.Now.ToString("f") Monday, December 22, 2008 5:29 AM
DateTime.Now.ToString("F") Monday, December 22, 2008 5:29:25 AM
DateTime.Now.ToString("g") 12/22/2008 5:29 AM
DateTime.Now.ToString("G") 12/22/2008 5:29:25 AM
DateTime.Now.ToString("m") December 22
DateTime.Now.ToString("r") Mon, 22 Dec 2008 05:29:25 GMT
DateTime.Now.ToString("s") 2008-12-22T05:29:25
DateTime.Now.ToString("t") 5:29 AM
DateTime.Now.ToString("T") 5:29:25 AM
DateTime.Now.ToString("u") 2008-12-22 05:29:25Z
DateTime.Now.ToString("U") Monday, December 22, 2008 10:29:25 AM
DateTime.Now.ToString("y") December, 2008
DateTime.Now.ToString("dddd, MMMM dd yyyy") Monday, December 22 2008
DateTime.Now.ToString("ddd, MMM d "'"yy") Mon, Dec 22 '08
DateTime.Now.ToString("dddd, MMMM dd") Monday, December 22
DateTime.Now.ToString("M/yy") 12/08
DateTime.Now.ToString("dd-MM-yy") 22-12-08

Wednesday, December 17, 2008

Handle javascript error message

onerror = handleErrors

var msg = null

function handleErrors(errorMessage, url, line)
{
msg += "Error message: " + errorMessage + "\\n";
msg += "URL: " + url + "\\n";
msg += "Line #: " + line;
alert(msg);
return true
}

This would show the error as a message box.

If we want to completely hide the error from the end user and also not show the yellow colour information symbol in the browser, we can remove the line 'alert(msg)'; .

Tuesday, December 9, 2008

Searching data between two dates by ignoring time values

Here is a stored procedure that returns records between from date and to date by ignoring their time values. If the from date , to date are not supplied it returns all the values of the table.
CREATE Procedure [dbo].getAllRecordsIgnoringTimevalues         
(
@FromDate VARCHAR(25) =NULL,--indicates that the parameter it is optional
@ToDate VARCHAR(25) =NULL --indicates that the parameter it is optional
)
As
Begin


Select *
From
[dbo].tabletosearch

WHERE
AND (CAST(FLOOR(CAST( fromdate AS float)) AS datetime) >= convert(datetime,@FromDate)OR ISNULL(convert(datetime,@FromDate),'')='')
AND (CAST(FLOOR(CAST( todate AS float)) AS datetime) <= convert(datetime,@ToDate) OR ISNULL(convert(datetime,@ToDate),'')='')

END

Using regular expressionsan to search for string,substring among array of strings .

Below is an function which searches for a existence of a string,substring among array of strings.

//Declare the string to search and the content string

string[] words ={"This","is an attempt","to search","string contents","using","regular expressions." };
string strToSearch = "regular";

//call the function SearchAndDisplay which will search and display the result.


if (!SearchAndDisplay(strToSearch,words))
{
Response.Write("No matches found.");
}

/*
This function iterates through a given array and finds existence of a string among it.if found returns true and prints the string else returns false.
*/
private bool SearchAndDisplay(string strToSearch,string[]arrContentString)
{
bool isMatchFound = false;
foreach (string tempString in arrContentString)
{
if (System.Text.RegularExpressions.Regex.IsMatch(tempString, strToSearch, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
isMatchFound = true;
Response.Write("Match found in :" + tempString.Trim() + "
");
}

}
return isMatchFound;

}

Thursday, December 4, 2008

Sql Function that returns only datepart of SQL DateTime

create function DateOnly(@DateTime DateTime)
-- Returns @DateTime at midnight; i.e., it removes the time portion
--of a DateTime value.
returns datetime
as
begin
return dateadd(dd,0, datediff(dd,0,@DateTime))
end
go

Select dbo.DateOnly(getdate()) AS DateWithoutTime

Gridview basic operations

Store the connection string details in web.config file
<connectionStrings>
<remove name="somename"></remove>
<add name="somename" connectionString="Data Source=yourserver;Initial Catalog=databsename; User Id=sa;Password=sa" providerName="System.Data.SqlClient">

</add>

</connectionStrings>

ASPX Page contents
<div>
<asp:Label runat="server" ID="lblMsg">
</asp:Label>
<asp:GridView runat="server" ID="grdDetails" AutoGenerateColumns="false" AutoGenerateEditButton="true"
AutoGenerateSelectButton="true" AutoGenerateDeleteButton="true" OnRowCancelingEdit="GridViewOnCancel"
OnRowUpdating="GridViewOnUpdate" OnRowEditing="GridViewOnEdit" AllowPaging="true" PagerSettings-Mode="NumericFirstLast" PageSize="4"
OnSelectedIndexChanged="GridSelectedIndecChanged" SelectedIndex="-1" OnRowDeleting="GridViewDelete" OnPageIndexChanging="GridViewPageIndexChanged">
<SelectedRowStyle BackColor="LightBlue" Font-Italic="true" />
<PagerSettings Position="TopAndBottom" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Name
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField runat="server" ID="hdnLoginId" Value='<%# Eval("LoginId") %>' />
<%# Eval("LoginName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Details
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td style="width: 100%">
<table border="0" cellpadding="0" cellspacing="0" style="width: 99%">
<tr>
<td style="width: 25%">
Password: </td>
<td style="width: 75%">
<%#Eval("Password")%>
</td>
</tr>
<tr>
<td style="width: 25%">
LoginName: </td>
<td style="width: 75%">
<%#Eval("LoginName")%>
</td>
</tr>
<tr>
<td style="width: 25%">
Secret Answer: </td>
<td style="width: 75%">
<%#Eval("SecretAnswer")%>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Edit
</HeaderTemplate>
<ItemTemplate>
<%#Eval("RegisteredDate").ToString() == string.Empty ? DateTime.Now.ToString() : Eval("RegisteredDate")%>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField runat="server" ID="hdnRegisteredDate" Value='<%# Eval("RegisteredDate") %>' />
<asp:TextBox runat="server" ID="txtResponseDate" Text='<%#Eval("RegisteredDate")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
DisplayGrid();
}
private void DisplayGrid()
{
string connectionString = ReturnConnectionString("somename"); //somename is the connection name given in web.config file
if (connectionString != string.Empty)
{
DataSet objDataSet = new DataSet();
SqlConnection objConnection = new SqlConnection(connectionString);
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "dbo.[Loobi_Login_SelectAll]";
objCommand.Connection = objConnection;
// SqlParameter objParameter = new SqlParameter("@LoginId", SqlDbType.Int,4,ParameterDirection.Input,false,10,0,"",DataRowVersion.Proposed,7);
// objCommand.Parameters.Add(objParameter);
SqlDataAdapter objAdapTer = new SqlDataAdapter(objCommand);
objAdapTer.Fill(objDataSet);
if (objDataSet.Tables.Count > 0 && objDataSet.Tables[0].Rows.Count > 0)
{
grdDetails.DataSource = objDataSet.Tables[0].DefaultView;
grdDetails.DataBind();
}
else
{
lblMsg.Text = "No Records Found";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
protected void GridViewOnCancel(object Sender, GridViewCancelEditEventArgs e)
{
grdDetails.EditIndex = -1;
DisplayGrid();
}
protected void GridViewOnUpdate(object Sender, GridViewUpdateEventArgs e)
{
if (e.RowIndex >= 0)
{
if (grdDetails.Rows[e.RowIndex].FindControl("hdnLoginId") != null)
{
int loginid =int.Parse(((HiddenField)grdDetails.Rows[e.RowIndex].FindControl("hdnLoginId")).Value.Trim());
string NewDate = ((HiddenField)grdDetails.Rows[e.RowIndex].FindControl("hdnRegisteredDate")).Value.Trim();
grdDetails.EditIndex = -1;
}
DisplayGrid();
}

}
protected void GridViewOnEdit(object Sender, GridViewEditEventArgs e)
{
grdDetails.EditIndex = e.NewEditIndex;
DisplayGrid();
}
protected void GridViewOnDelete(object Sender, GridViewDeleteEventArgs e)
{
if (e.RowIndex > 0)
{
if (grdDetails.Rows[e.RowIndex].FindControl("hdnLoginId") != null)
{
//deleet code goes here
DisplayGrid();
}
}

}
protected void GridSelectedIndecChanged(object Sender, EventArgs e)
{
int index= grdDetails.SelectedIndex;
GridViewRow rw = grdDetails.Rows[index];
if (rw != null && rw.FindControl("hdnLoginId") != null)
{
int logind = int.Parse(((HiddenField)rw.FindControl("hdnLoginId")).Value.Trim());
Page.RegisterStartupScript("KeySelected", "<script language='javascript' type='text/javascript'>alert('" + logind.ToString() + "')</script>");

}
else
{
lblMsg.Text = "Row is null";
lblMsg.ForeColor = System.Drawing.Color.Red;
}

}
protected void GridViewDelete(object Sender, GridViewDeleteEventArgs e)
{
if (grdDetails.Rows[e.RowIndex].FindControl("hdnLoginId") != null)
{
string loginid = ((HiddenField)grdDetails.Rows[e.RowIndex].FindControl("hdnLoginId")).Value;
Page.RegisterStartupScript("KeySelected", "<script language='javascript' type='text/javascript'>alert('"+loginid+"')</script>");

}
}
protected void GridViewPageIndexChanged(object Sender, GridViewPageEventArgs e)
{
grdDetails.PageIndex = e.NewPageIndex;
DisplayGrid();
}

private string ReturnConnectionString(string connectionStringName)
{
System.Configuration.Configuration webConfig = null;
webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
if (webConfig != null)
{
System.Configuration.ConnectionStringSettings connString = null;
if (webConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = webConfig.ConnectionStrings.ConnectionStrings[connectionStringName];
if (connString != null && connString.ToString() != string.Empty)
{
return connString.ConnectionString;

}
else
{
lblMsg.Text = "The value of connection string in web.config file is null or empty";
lblMsg.ForeColor = System.Drawing.Color.Red;
return string.Empty;


}

}
else
{
lblMsg.Text = "No connection strings present in web.config file";
lblMsg.ForeColor = System.Drawing.Color.Red;
return string.Empty;

}
}
else
{
lblMsg.Text = "Configuration file missing";
lblMsg.ForeColor = System.Drawing.Color.Red;
return string.Empty;
}

}

Wednesday, December 3, 2008

CLR and Its Functions

Introduction
CLR is a Common Language Runtime . As the name suggests it's Common Runtime to all dotnet related languages like Vb,C#,VC++ ,J# etc.

When ever we compile any application in dotnet the corresponding langauge compiler will take care of it and convert into MSIL(Microsoft Intermediate Language) code , CLR will handle the code and convert into operating system native code with the help of JIT(Just In Time) compiler.There are many components in CLR which are used to do specific tasks or functions of CLR.

Functions of CLR
MemoryManagement
Scalability
Good toolsupport
LanguageIntegration
InterOperability
CodeManagement
ExceptionHandling
GarbageCollecter
JitCompiling
Components in CLR
The above functionalities achieved by all these componets .Each component is responsible for specific functionality.

1.Class Loader:
It is used to load all the classes at runtime

2.MSIL to native Compiler:
It is a JIT (Just In Time) compiler it will convert MSIL code to native code

3.Code manager:
It manages the cade during runtime

4.Garbage Collector:

It manages memory .It collects all the unused objects in the memory and deallocate them when the memory is less.

5.Security Engine:
It has all the security restrictions.

6.Type checker:

It enforces strict type checking.

7.Thread support:

It provides multithreading support to our application.

8.Exception manager:

It provides mechanisum to handle execptions at runtime.

9.Debug Engine:

Which allows you to debug applications.

10.Com Marshaler:

Which allows interoperability to our applications

11.Base class library support:

Which provides all types that application need at runtime

Advantages of CLR and MSIL Code

Platform Independency
Architecture Independency
Language Independency
Managing the memory using Garbage Collector

The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory leaks as well as some other common programming errors.

Following are some benefits of the runtime:

1.Performance improvements.
2.The ability to easily use components developed in other languages.
3.Extensible types provided by a class library.
4.New language features such as inheritance, interfaces, and overloading for object-oriented programming; support for explicit free threading that allows creation of multithreaded, scalable applications; support for structured exception handling and custom attributes.

Additional runtime features include:

1.Cross-language integration, especially cross-language inheritance.
2.Garbage collection, which manages object lifetime so that reference counting is unnecessary.
3.Self-describing objects, which make using Interface Definition Language (IDL) unnecessary.
4.The ability to compile once and run on any CPU and operating system that supports the
runtime.


Note:CLS and CTS are the specifications not components of CLR

Tuesday, December 2, 2008

Disabling back button in browsers(IE,Mozilla,Safari,Opera)

Just copy-paste the following code in the head section

<script type="text/javascript">
function noBack(){window.history.forward()}
noBack();
window.onload=noBack;
window.onpageshow=function(evt){if(evt.persisted)noBack()}
window.onunload=function(){void(0)}
</script>

Tuesday, November 25, 2008

Exporting Gridview contents to Excel

ASPX Page Code

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="GridviewExportToExcel.aspx.cs"
Inherits="Gridview_Export_To_Excel_GridviewExportToExcel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView AllowPaging="true" PageSize="2" ID="gvUsers" runat="server" OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
DisplayIDLink
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="MyLinkButton" runat="server" Text='<%#Eval("displayid")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DropDownData">
<ItemTemplate>
<asp:DropDownList ID="ddlNames" runat="server">
<asp:ListItem Text="Akshay" Value="Akshay" />
<asp:ListItem Text="Ashwin" Value="Ashwin" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Btn_Export" runat="server" Text="Export to Excel (Default)" OnClick="Btn_ExportClick" />
<asp:Button ID="Btn_ExportToExcelPaging" runat="server" Text="Export to Excel Paging"
OnClick="Btn_ExportExcelPaging" />
</div>
</form>
</body>
</html>

ASPX.CS
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class Gridview_Export_To_Excel_GridviewExportToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection("Data Source=server02;Initial Catalog=Trial;User ID=ashwin;Password=ashwin");//change here to ur connectionstring
SqlDataAdapter ad = new SqlDataAdapter("select top 2 orderid,displayid from loobi_order", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);

gvUsers.DataSource = ds;
gvUsers.DataBind();
}

protected void Btn_ExportClick(object sender, EventArgs e)
{
//ad this section to have those dropdowns,linkbuttons in excel file
string style = @"<style> .text { mso-number-format:\@; } </script> ";

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}

protected void Btn_ExportExcelPaging(object sender, EventArgs e)
{
//to convert link button, DropDownList etc date to simple text type
DisableControls(gvUsers);

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

private void DisableControls(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}

else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}


if (gv.Controls[i].HasControls())
{
DisableControls(gv.Controls[i]);
}
}

}

public override void VerifyRenderingInServerForm(Control control)
{
//this is required while exporting to excel
}

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}
}

Scrolling to top of the page using javascript

Just write the following line in your javascript function,
window.scrollTo(0,0);

Thursday, November 20, 2008

Highlighting the selected item in the menu

Note : This wont work if an update panel is present.

Master Pasge contents having menu

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MenuItemTest.master.cs"
Inherits="Master_Pages_MenuItemTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="NavigationMenu" StaticDisplayLevels="1" StaticSubMenuIndent="1" Orientation="horizontal"
Target="_blank" runat="server" OnMenuItemClick="NavigationMenu_MenuItemClick">
<StaticSelectedStyle BackColor="Black" Font-Italic="true" ForeColor="Black" BorderColor="Red" />
<Items>
<asp:MenuItem NavigateUrl="~/Menus/Menu2.aspx" Text="Menu2" Target="_Self"></asp:MenuItem>
<asp:MenuItem NavigateUrl="~/Menus/Menu1.aspx" Text="Menu1" Target="_Self"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

Add two pages namely menu1.aspx, menu2.aspx

Menu1.aspx
<%@ Page Language="C#" MasterPageFile="~/Master Pages/MenuItemTest.master" AutoEventWireup="true" CodeFile="Menu1.aspx.cs" Inherits="Menus_Menu1" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>

Menu1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Menu M = (Menu)this.Master.FindControl("NavigationMenu");
if (M != null)
{
M.Items[1].Selected = true;
}
}



Menu2.aspx
<%@ Page Language="C#" MasterPageFile="~/Master Pages/MenuItemTest.master" AutoEventWireup="true" CodeFile="Menu2.aspx.cs" Inherits="Menus_Menu2" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>



Menu2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Menu M = (Menu)this.Master.FindControl("NavigationMenu");
if (M != null)
{
M.Items[0].Selected = true;
}
}

Wednesday, November 19, 2008

Reading two Tables Data Using DataTableReader and NextResult

ASPX Page
<asp:GridView runat="server" ID="gvReaderData" AutoGenerateColumns="true"></asp:GridView>


protected void Page_Load(object sender, EventArgs e)
{

//fill first table
DataTable OrderDetails = new DataTable("OrderDetails");
String Sql = "Select top 5 email from Loobi_member";
SqlCommand cmd = new SqlCommand(Sql);
SqlConnection objConnection = new SqlConnection();
objConnection.ConnectionString = "Data Source=Loobi;Initial Catalog=Loobi;User ID=sa; Password=sa";
cmd.Connection = objConnection;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(OrderDetails);

//fill second table
DataTable LoginDetails = new DataTable("LoginDetails");
String Sql1 = "Select top 5 loginid from Loobi_Login";
SqlCommand cmd1 = new SqlCommand(Sql1);
SqlConnection objConnection1 = new SqlConnection();
objConnection1.ConnectionString = "Data Source=Loobi;Initial Catalog=Loobi;User ID=sa; Password=sa";
cmd1.Connection = objConnection1;
SqlDataAdapter adap1 = new SqlDataAdapter(cmd1);
adap1.Fill(LoginDetails);

DataTableReader objReader=new DataTableReader(new DataTable[]{OrderDetails,LoginDetails});
if (objReader.HasRows)
{
do
{
Response.Write("<br>");
Response.Write("Reading Table contents Started");
Response.Write("<br>");
while (objReader.Read())
{
Response.Write(objReader[0].ToString());
}
Response.Write("<br>");
Response.Write("Table contents completed");
Response.Write("<br>");
} while (objReader.NextResult());

}
else
{
Response.Write("No Data");
}

//Binding Data To Grid named gvReaderData
DataTableReader objEmailsReader = new DataTableReader(OrderDetails);
DataTable tblEmails = new DataTable();
tblEmails.Load(objEmailsReader);
gvReaderData.DataSource = tblEmails;
gvReaderData.DataBind();



}

Forms Authentication Without Role Based Security

Note:
Just copy paste the code to respective pages and try to access AuthenticatedPage.aspx page dirctly you will be re-directed to login page that is logon.aspx page

web.config settings
<system.web>
<authentication mode="Forms">
<forms name=".CookieAshwin" loginUrl="~/FormsAuthentication/logon.aspx"
protection="All" path="/" timeout="30" />
</authentication>
</system.web>




Logon.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="logon.aspx.cs" Inherits="FormsAuthentication_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>

<input id="txtUserName" type="text" runat="server" style="z-index: 103; left: 295px;
position: absolute; top: 128px" />

<asp:CheckBox ID="chkPersistCookie" runat="server" AutoPostBack="false" Style="z-index: 100;
left: 298px; position: absolute; top: 214px" />
<input id="txtUserPass" type="password" runat="server" style="z-index: 102; left: 297px;
position: absolute; top: 174px" />
<p>
</p>
<input type="submit" value="Logon" runat="server" id="cmdLogin" style="z-index: 104;
left: 382px; position: absolute; top: 254px" onserverclick="cmdLogin_ServerClick">
<asp:Label ID="lblMsg" ForeColor="Red" Font-Name="Verdana" Font-Size="10pt" runat="server"
Style="z-index: 105; left: 183px; position: absolute; top: 78px" Font-Names="Verdana"
Width="406px" />
</div>
</div>
</form>
</body>
</html>

Logon.aspx.cs code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class FormsAuthentication_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void cmdLogin_ServerClick(object sender, EventArgs e)
{
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "AuthenticatedPage.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}

private bool ValidateUser(string userName, string passWord)
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;


try
{
//change here to ur connection string
conn = new SqlConnection("Data Source=Server02;Initial Catalog=Loobi;User ID=sa;Password=sa");
conn.Open();

//change here to ur table name
cmd = new SqlCommand("Select password from loobi_login where loginname=@userName", conn);
cmd.Parameters.Add("@userName", SqlDbType.NVarChar, 65);
cmd.Parameters["@userName"].Value = txtUserName.Value;


lookupPassword = (string)cmd.ExecuteScalar();


cmd.Dispose();
conn.Dispose();
}
catch (Exception ex)
{

System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
}

// If no password found, return false.
if (null == lookupPassword)
{
// You could write failed login attempts here to event log for additional security.
return false;
}

// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return (0 == string.Compare(lookupPassword, passWord, false));


}
}



AuthenticatedPage.aspx Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AuthenticatedPage.aspx.cs" Inherits="FormsAuthentication_AuthenticatedPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Authenticated page
<asp:Button runat="server" ID="btnLogout" Text="LogOut" OnClick="btnLogout_Click" />
</div>
</form>
</body>
</html>


AuthenticatedPage.aspx.cs Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class FormsAuthentication_AuthenticatedPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLogout_Click(object Sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("logon.aspx");
}
}

WaterMark with Javascript

JavaScript
function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}

function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

ASPX
<asp:TextBox ID="txtWatermark" runat="server" />

C#
protected void Page_Load(object sender, EventArgs e)
{
string strWatermark = "Search Karamasoft.com";
txtWatermark.Text = strWatermark;
txtWatermark.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermark + "');");
txtWatermark.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermark + "');");
}

To Determine which version of .net are installed in clients system

Note : this works only in IE.

<script type="text/javascript" language="javascript">
function DetermineVersionsInstalled()
{
var a=navigator.userAgent.match(/\.NET CLR [0-9.]+/g);
if (a == null)
{
alert( ".NET Framework(s) is not installed" )
}
else
{
alert("The following versions of .NET Frameworks are installed:");
for(i = 0; i < a.length; ++i)
{
alert(a[i]);

}
}
return false;
}
</script>


<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnFindVersion" Text="Find Version" OnClientClick="Javascript:return DetermineVersionsInstalled();" />
</div>
</form>

Create XML from an Array

Passing arrays as arguments to stored procedures is not currently possible in SQL Server, but you can use XML to accomplish this. To do this, you need to create an XML string using your preferred language (C#, VB, etc.). You can use the following function to convert an array to an XML string (which you can then pass to the stored procedure). This example uses C#, but you can use the same logic with other languages:


protected void Page_Load(object sender, EventArgs e)
{
Object[] test = { 1, "item 2", 3, "item 4", 5, "item 6" };
Response.Write(ConvertToXML(test, "params", "param"));
}

protected string ConvertToXML(Object[] args, string rootName, string elemName)
{
string xmlStr = "<" + rootName + ">";

foreach (Object arg in args)
{
xmlStr += "<" + elemName + ">" + arg.ToString() +
"</" + elemName + ">";
}

xmlStr += "</" + rootName + ">";

return xmlStr;
}

Using the test case in the Page_Load method provided above as an example, the output XML would look like the following (but not as neatly formatted):


<params>
<param>1</param>
<param>item 2</param>
<param>3</param>
<param>item 4</param>
<param>5</param>
<param>item 6</param>
</params>

You can now pass that string to a SQL Server stored procedure or to other functions.

Tuesday, November 18, 2008

Adding sitemap provider details in web.config file

Web.config contents

Put this part of code under <system.web> section

<siteMap>
<providers>
<add name="Web1" type="System.Web.XmlSiteMapProvider" siteMapFile="~/SitemapFiles/Custom.sitemap"/>

</providers>

</siteMap>

Here the name can be any custom name and the siteMapFile"~/SitemapFiles/Custom.sitemap"
is the path of the sitemap file from the root.

type="System.Web.XmlSiteMapProvider" if it is XmlSiteMapProvider(change according to ur need)


ASPX Page OR Master Page
<asp:SiteMapPath ID="SiteMapPath1" runat="server" PathSeparator=">" PathDirection="RootToCurrent" CurrentNodeStyle-BackColor="AliceBlue" NodeStyle-BackColor="Beige" RootNodeStyle-BackColor="ActiveCaption" RenderCurrentNodeAsLink="false" ToolTip="Press on the link to go to the section" >
</asp:SiteMapPath>

Code-Behind
SiteMapPath1.Provider = SiteMap.Providers["Web1"];

Obtaining the list of triggers in your database alnog with the table names

select tbl = object_name(parent_obj), "trigger" = name
FROM sysobjects
where type = 'TR'
order by tbl

Enabling the Browser Back Button for GridView, ASP.NET AJAX History

One of the common navigation tools in a website is the back button of the browser. People use the back button quite frequently to go back to the page already visited. When there is a postback, the browser is updated with the information of the page visited and hence the back button gets enabled automatically. Assuming there is a GridView control that we are using in a page which fetches a lot of records, one of the common practices is to enable paging for the GridView such that the initial set of records loads quicker and people can page through the next set of records on a requirement basis.

When this GridView is in a normal ASP.NET Page, when users click on the paging buttons or links, the browser history gets updated and hence, if the users want to check the previous set of records, they can click on the back button and do the same.

However, in case of an ASP.NET AJAX enabled page, typically the GridView inside an Update Panel, it becomes impossible since the postback happens asynchronously and the browser history isn’t aware of the postback and hence the back button isn’t enabled.

To overcome this, ASP.NET 3.5 SP1 provides the History control that allows you to add history points to your AJAX Enabled page’s post backs and hence enable back button navigation for the users.

Let us examine this with a sample on Grid View. First, let us add a regular GridView control to an ASP.NET Page and configure it to use the NorthWind Database’s “Alphabetical list of products” table.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"
SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder"
SortExpression="UnitsOnOrder" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [CategoryName] FROM [Alphabetical list of products]">
</asp:SqlDataSource>

Note this sample assumes you have the Northwind Database installed and you have the connection string configured in the web.config to connect to the database. You can download the same from http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en for SQL Server 2000, 2005 etc.,

When you run this page, you will be able to page through the records and hit back button to go to the previous set of records.

Let us add Script Manager and Update Panel to this page and then move the contents into the Content Template of the Update Panel.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

>> The above GridView code snippet goes here


</ContentTemplate>
</asp:UpdatePanel>

Now when you run the page and click on the paging numbers i.e. 1,2,3..you will notice that the back button isn't enabled since this has been an asynchronous postback within the update panel.

To handle this, we need to do the following things

1. Set the EnableHistory=”true” for the ScriptManager (in this case, ScriptManager1). The updated ScriptManager declaration looks like this

<asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true">
</asp:ScriptManager>

2. Handle the OnPageIndexChanging event of the GridView with an event ex.- OnPageIndexChanging="GridView1_PageIndexChanging" needs to go in the GridView declaration above.

3. Add the handler code in the code behind as follows:-

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {

if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating) {
ScriptManager1.AddHistoryPoint("Index", GridView1.PageIndex.ToString());
}
}

Basically we are checking if the ScriptManager is in an asynchronous postback and the ScriptManager is not currently navigating. The AddHistoryPoint is the method that helps us to define history points and we provide the PageIndex to the method using the GridView’s pageindex property.

4. Handle the Script Manager’s Navigate event in the declaration as OnNavigate="ScriptManager1_Navigate"

5. Add the Handler code in the codebehind as follows:-

string indexString = e.State["index"];
if (string.IsNullOrEmpty(indexString)) {
GridView1.PageIndex = 0;

} else {
int Index = Convert.ToInt32(indexString);
GridView1.PageIndex = Index;
}

Once we do the above, when you run the page and navigate across the pages, you could see that the back button is enabled and we can navigate using the back button.

Note that, if there are multiple GridView controls within the updatepanel, we need to handle them separately as currently, we are only handing GridView1. However, if the GridView or any other control is outside the scope of Update Panel, then back button enablement is taken care automatically.

Also, Sorting needs to be handled as well. For a sample on Sorting check http://aspnet.4guysfromrolla.com/articles/100808-1.aspx

Monday, November 17, 2008

Use Of Literal to Display Alerts from code-behind

Literal ltAlertMsg = new Literal();
ltAlertMsg.Mode = LiteralMode.Transform;
this.Controls.Add(ltAlertMsg);
ltAlertMsg.Text =@"<script>alert(""Test Message ."");</script>";

Thursday, November 13, 2008

Obtaining the name of the page viewed or been coded from code-behind

string PageName = null;
if (Request.UrlReferrer != null)
{
Int32 lenStart = Request.UrlReferrer.AbsolutePath.LastIndexOf("/") + 1;
Int32 lenRequired = Request.UrlReferrer.AbsolutePath.Length - lenStart;
PageName = Request.UrlReferrer.AbsolutePath.Substring(lenStart, lenRequired);
Response.Write(PageName .trim());
}

Limiting a User for clicking a button only once while processing$

Control:

<asp:updatepanel id="upOnelick" runat="server">
<contenttemplate>
<asp:Button ID="Button1" runat="server" Text="One Click"
onclick="Button1_Click" />
</contenttemplate>
<triggers>
<asp:asyncpostbacktrigger controlid="Button1" eventname="Click">
</triggers>
</asp:UpdatePanel>
<asp:updatepanel id="upOnelick" runat="server"> <contenttemplate>
<asp:button id="Button1" runat="server" text="One Click" onclick="Button1_Click">
</asp:button>
<triggers>
<asp:asyncpostbacktrigger controlid="Button1" eventname="Click">
</asp:asyncpostbacktrigger>
</triggers>

Javasript:

function pageLoad()
{
var manager = Sys.WebForms.<div id=":g4" class="ArwC7c ckChnd"><$>PageRequestManager.<$>getInstance();
manager.add_initializeRequest(<$>OnInitializeRequest);
}

function OnInitializeRequest(sender, args)
{
var manager = Sys.WebForms.<$>PageRequestManager.<$>getInstance();
// Check if we're posting back because of Button1
if (manager.get_<$>isInAsyncPostBack() && args.get_postBackElement().id.<$>toLowerCase() == "button1")
{
$get("Label1").innerHTML = "Still working on previous request.Please, be patient ...";
args.set_cancel(true);
}
} </div></contenttemplate></asp:updatepanel>

Calling serverside code when closing browser

ASPX.CS Contents

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] == "FromJavascript")
{
MyFuntion();
}
}

public void MyFuntion()
{
Response.Write("test write from server");
}

ASPX Contents


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript">
function PerformServerTasks()
{
__doPostBack("FromJavascript","");
alert("Form Unloading. After you click ok to this message.Server Side code will work");
}
</script>
</head>
<body onunload="PerformServerTasks();">
<form id="form1" runat="server">
<div>
<h1>Test Page</h1>
<%-- <a href="#" onclick="PerformServerTasks();">s</a>--%>
<input id="Text1" type="text" runat="server" value="" />
<asp:TextBox ID="SDF" runat="server" AutoPostBack="True" Text="Dont worry about this textbox.But dont remove it"></asp:TextBox>
</div>
</form>
</body>
</html>

Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

Original Reference: http://aspnet.4guysfromrolla.com/articles/081804-1.aspx
prerequisite's:
  • Create a XML File called Items.XML And Paste the contents present in 'XMLFile Contents' Section.
  • Paste the Contents present in 'ASPX page content' Section into ASPX Page.
  • Paste the Contents present in 'ASPX.CS Content' Section into ASPX .CS Page.
XMLFile Contents

<?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item>
<ItemName>Item1</ItemName>
<ItemDescription>Item1 Description</ItemDescription>
<ItemPrice>1.50</ItemPrice>
<ItemInStock>Y</ItemInStock>
</Item>
<Item>
<ItemName>Item2</ItemName>
<ItemDescription>Item2 Description</ItemDescription>
<ItemPrice>2.50</ItemPrice>
<ItemInStock>Y</ItemInStock>
</Item>

</Item>
</Items>


ASPX page content

<h3>
paging Repeater content using PageDatasourse</h3>
<asp:Button runat="server" ID="btnXMLReader" Text="Fill Repeater" OnClick="btnXMLReader_Click" />
<table width="100%" border="0">
<tr>
<td>
Repeater control with Paging functionality</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label></td>
</tr>
<tr>
<td>
<asp:Button ID="cmdPrev" runat="server" Text=" << " OnClick="cmdPrev_Click"></asp:Button>
<asp:Button ID="cmdNext" runat="server" Text=" >> " OnClick="cmdNext_Click"></asp:Button></td>
</tr>
</table>
<table border="1">
<tr>
<td width="60%">
<asp:Repeater runat="server" ID="rptDataFromXML">
<HeaderTemplate >
<table width="100%">
<tr>
<td width="50%" align="center">Data From XML File With Paging Functionality.</td>
<td width="50%" align="center">Page Size=2</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td align="left" style="color:Blue" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemName")%></td>
<td align="left" style="color:Red" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemDescription")%></td>
<td align="left" style="color:Chocolate" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemInStock")%></td>
</tr>
</table>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td align="left" style="color:Chocolate" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemName")%></td>
<td align="left" style="color:Blue" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemDescription")%></td>
<td align="left" style="color:Red" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemInStock")%></td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
<h3>
End of paging Repeater content using PageDatasourse</h3>

ASPX.CS Content

protected void btnXMLReader_Click(object Sender, EventArgs e)
{

#region --Reading data into dataset--
DataSet dsXmlContent = new DataSet();
dsXmlContent.ReadXml(Server.MapPath("XMLFiles/Items.xml"), XmlReadMode.Auto);

#endregion

#region --Bind the data obtained--

objDataSource.PageSize = 2;
objDataSource.AllowPaging = true;
objDataSource.DataSource = dsXmlContent.Tables[0].DefaultView;
objDataSource.CurrentPageIndex = CurrentPage;
if (dsXmlContent.Tables[0].Rows.Count > 0)
{
rptDataFromXML.DataSource = objDataSource;
rptDataFromXML.DataBind();
cmdPrev.Enabled = !(objDataSource.IsFirstPage);
cmdNext.Enabled = !(objDataSource.IsLastPage);
}
else
{
lblCurrentPage.Text = "No Records avaliable";
lblCurrentPage.ForeColor = System.Drawing.Color.Red;
}
#endregion

}
public int CurrentPage
{
get
{
object objTemp = this.ViewState["_currentPage"];
if (objTemp == null)
{
return 0;
}
else
{
return((int)objTemp);
}
}
set
{
this.ViewState["_currentPage"] = value;
}
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
btnXMLReader_Click(sender, e);
}
protected void cmdNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
btnXMLReader_Click(sender, e);
}

Tuesday, November 11, 2008

Encrypting, Decrypting Web.Config Contents

Original Reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=185&AspxAutoDetectCookieSupport=1

prerequisite's:
  • Add a global.asax file to your application.
  • Import namespace: <%@ Import Namespace="System.Web.Configuration" %>
  • Configure Application_Start Event and Application_End Event for the application to automatically encrypt, decrypt web.config file contents.
  • For the decrypt part to work first stop the webserver (IIS or Development server) then close the browser.
There are various sections of typical web.config file that usually contain sensitive information:
  • - username and password used to connect to databases
  • - usernam and password needed for runtime impersonation of fixed identity
  • - your smtp server username and password
  • etc
By using the built-in Encryption methods we can protect those configuration sections, so even if someone somehow manages
to obtain our web.config files or just take a brief look at them , there will not be much for him to see there.

ASP.NET 2.0 comes with two encryption providers we can use to protect our configuration files:
  • DataProtectionConfigurationProvider
  • RSAProtectedConfigurationProvider
  • also you can implement your own Providers, because its a plugin based model
here is an example showing the encryption, decryption implemented in global.asax file.

void Application_Start(object sender, EventArgs e)

{
// Code that runs on application startup

#region --Encrypt web.config section contents region wise--
try
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection objConfigSection = objConfig.GetSection("appSettings");
if (objConfigSection != null)
{
if (!objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
objConfig.Save();
}
}
}
catch (Exception ex)
{

}
#endregion

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
#region --Decrypt the sections of web.config that were encrypted--
try
{
//Configuration confg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
//ConfigurationSection confStrSect = confg.GetSection("appSettings");
if (objConfigSection != null && objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.UnprotectSection();
objConfig.Save();
}

}
catch (Exception ex)
{

}
#endregion
}