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>