Monday, October 4, 2010

Disable right click on a web page

Add these script to your webpage, This blocks the user from using right click.

<HTML><HEAD>
<TITLE>ASP Web Pro</TITLE>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
<!--
var message="Sorry, the right-click function is disabled.";
function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}
if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
// -->
</SCRIPT>
</BODY>
</HTML>

Sunday, October 3, 2010

Application configuration files in .net


.NET gives an easy way to store configuration information in a ApplicationConfiguration File. In the simple implementation, you can store information as Key-Value pairs.

For example, consider a case where you have to use a DataSource in your application. If you hardcore the DataSource information in your code, you will have a bad time when you have to change this datasource. You have to change your source code and re-compile it. This won't work everytime you give your product to different customers or when you run your application in different machines!

In earlier days, programmers used to store this information in special files called ".ini" files or in system registry. The application can read the information from the .ini file or registry and no need to re-compile the code when the values are changed in .ini file or registry.

But this is a pain most of the time. It is not fun opening the registry, locate your entries and make appropriate changes. It is quite possible that you may mess up with some important entries in the registry and make your system not running any more. In fact, in secured systems, administrator may deny access to the registry and users will not have the choice to edit the registry at all.

.NET gives you a simple and easy solution for this problem - the ApplicationConfiguration File. Each application can have a configuration file, which is actually an XML file. You can use any text editor (including notepad) to open the configuration file and change the values. The application will load the values from this configuration file and you do not have to change your source code everytime you change your DataSource or any other information stored in configuration file.

app.config for Windows applications

Windows applications in VS.NET uses the name 'app.config' by default for the configuration file. This will not be automatically created when you create a Windows application. If you need a configuration file for your application, open your project in VS.NET, go to the 'Solution Explorer' and right click on the project name. Choose Add > Add new item from the menu and select 'Application Configuration file' from the list of choices. This will create an app.config file for you in the application root.

By default, the app.config file will have the following content:

?xml version="1.0" encoding="utf-8" ?
configuration

/configuration

To store values in configuration file, you can create xml elements in the format

add key="MyKey" value="MyValue" /

See the sample config entries below:

?xml version="1.0" encoding="utf-8" ?
configuration
appSettings
add key="DatabasePath" value="c:\\projects\database.mdb" /
/appSettings
/configuration

And to read from this config file, just use the following code in your application:


string dbPath = System.Configuration.ConfigurationSettings.AppSettings["DatabasePath"];

ConfigurationSettings is the class
used to access the contents of the configuration file. Since this class is part
of the namespace System.Configuration,
we have to use the fully qualified name System.Configuration.ConfigurationSettings.
As a shortcut, you can use the using directive
on top of the file like below:

using System.Configuration;

If you have the above directive on top of the file, then you can directly use
the class ConfigurationSettings.

string dbPath = ConfigurationSettings.AppSettings["DatabasePath"];

When you compile your application, VS.NET will automatically create a file called .exe.config in your bin\debug folder. The contents of the app.config will be automatically copied to this new config file when you compile the application. When you deliver the application to the end user, you have to deliver the exe and this new config file called .exe.config and NOT the app.config. Users can modify the data in .exe.config file and application will read the data from the config file, when restarted.

web.config for web applications

The web applications use the same concept, but they use a config file with the name 'web.config'. There are couple of things to note in this case.
*  web.config is created automatically by VS.NET when you create any web project.
*  When you compile the web application, web.config is NOT renamed or copied to the BIN folder.
*  web.config has several default entries in it to support web/IIS configuration & security.
*  You can add the section in the web.config and add your key/value pairs in that section.
*  You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default system will look for a web.config in the same folder as the page and if not found, then looks in the parent folder.




Saturday, October 2, 2010

Working with Cookies


Websites typically use session cookies to ensure that users are recognized when they move from page to page within one site and that any information you have entered is remembered. For example, if an e-commerce site which uses session cookies then items placed in a shopping cart would appear by the time you reach the checkout.
The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value.
When a browser makes a request to the server, it sends the cookies for that server along with the request. In this ASP.NET application, we can read the cookies using the HttpRequest object, which is available as the Request property of Page class.
We added one text box, two buttons and 1 label to the web page. The text box is used for inputting the information of cookie. By clicking Add button, the sample application will create a new cookie. By clicking View button, you will see the cookie created.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies["MyCookie"]["Data"] = TextBox1.Text;
Response.Cookies["MyCookie"]["Time"] = DateTime.Now.ToString("G");
Response.Cookies["MyCookie"].Expires=DateTime.Now.AddMonths(1);
Label1.Text = "Cookie created!
" + "Your cookie contains:" + Request.Cookies["MyCookie"]["Data"] + "
" + Request.Cookies["MyCookie"]["Time"] + "
";
Response.Cookie("MyCookie").Expires=DateTime.FromString("2006-10-1");
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Request.Cookies["MyCookie"] == null)
Label1.Text = "There is no cookie:";
else
Label1.Text = "Your cookie contains:" + "" + Request.Cookies["MyCookie"]["Data"] + "
" + Request.Cookies["MyCookie"]["Time"] + "
";
}

The front end Default.aspx page looks something like this:

asp:TextBox ID="TextBox1" runat="server"
asp:Button ID="Button1" runat="server" Text="Add" Width="70px" 
asp:Button ID="Button2" runat="server" Text="View" Width="84px"
asp:Label ID="Label1" runat="server" Text="" Width="138px"


The flow for the code behind page is as follows

using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{

protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies["MyCookie"]["Data"] = TextBox1.Text;
Response.Cookies["MyCookie"]["Time"] = DateTime.Now.ToString("G");
Response.Cookies["MyCookie"].Expires=DateTime.Now.AddMonths(1);
Label1.Text = "Cookie created!
" + "Your cookie contains:" + Request.Cookies["MyCookie"]["Data"] + "
" + Request.Cookies["MyCookie"]["Time"] + "
";
Response.Cookie("MyCookie").Expires=DateTime.FromString("2006-10-1");
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Request.Cookies["MyCookie"] == null)
Label1.Text = "There is no cookie:";
else
Label1.Text = "Your cookie contains:" + "" + Request.Cookies["MyCookie"]["Data"] + "
" + Request.Cookies["MyCookie"]["Time"] + "
";
}
}

Friday, October 1, 2010

Exception Handling

What is an 'Exception' ?

'Exception' is an error situation that a program may encounter during runtime. For example, your program may be trying to write into a file, but your hard disk may be full. Or, the program may be trying to update a record in database, but that record may be already deleted. Such errors may happen any time and unless you handle such situation properly, your application may have un predictable behavior.

What is 'Exception Handling'?

An exception can occur anytime during the execution of an application. Your application must be prepared to face such situations. An application will crash if an exception occurs and it is not handled. "An exception handler is a piece of code which will be called when an exception occurs."

.NET Framework provides several classes to work with exceptions. The keywords try, catch are used to handle exceptions in .NET. You have to put the code (that can cause an exception) in a try block. If an exception occurs at any line of code inside a try block, the control of execution will be transfered to the code inside the catch block.

Syntax :

try
{
//Code which can cause exception;
}
catch(Exception ex)
{
//Code to handle the exception;
}

'finally' block 

You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception.

try
{
//Statements;
}
catch(Exception ex)
{
//Statements;
}

finally
{
//Statements;
}

Why should we catch exceptions ?

If an exception is not 'handled' in code, the application will crash and user will see an ugly message. Instead, you can catch the exception, log the errors and show a friendly message to the user.


Thursday, September 30, 2010

ASP.net Page Life Cycle

ASP.NET determines that the page request by a user requires to be parsing and compiling or to render cached copy of the page to be send. Thus it comes very much before of the beginning of the page life cycle. After this, it is also checked that request is a normal request, postback, cross-page postback or callback. The page constructor creates a tree of controls as soon as the HTTP runtime instantiates the page class to perform the request.

Events

PreInit

This event is the beginning of the page life cycle. Every page controls are initialized and the properties are set according to aspx source code.

  • Possible to Change or set Master page, Themes
  • Creates or re-creates dynamic controls.
  • Reads or sets Profile property values.


Init

First, the Init event for the Page object occurs, then Init event occurs for each control on the Page. Viewstate information is not available at this stage.

  • Controls have been initialized zed
  • Theme skins applied if any.
  • Initialize control properties.


InitComplete


This event is used to processing tasks that require all initialization be complete.

PreLoad

This event is used before Perform any processing that should occur before Load. Use this event if you need to perform processing on your page or control before the Load event. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load

Set properties in controls and establish database connections

Control Events

These are control specific events such as – Button Click, DropDownIndexChanged etc.

Load Complete

This event is used for performing those tasks which require load has been completed.

PreRender

In this event page insures that all child controls are created. Page calls EnsureChildControls for all controls, including itself. Every controls whose datasource/databind property is set calls for its databind method.

SaveStateComplete

This event occurs after viewstate encoded and saved for the page and for all controls.

Render

Every ASP.NET control has render method and the page instance calls this method to output the control’s markup, after this event any changes to the page or controls are ignored.

Unload

Unload event used to do cleanup task like closing the database connections, closing of the open files, completing logging or other requested tasks. Unload events occurs for each control on page control tree first and after that page.

Wednesday, September 29, 2010

Working with SQL Database - part 2 [Stored Procedures]

Using Stored Procedures:

A Stored Procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time).


Syntax:

CREATE PROCEDURE [Procedure_Name]
(
[@Param1] [type],
[@Param2] [type]......
)
AS
BEGIN
[Your SQL Stataments]
END
GO

Example:

CREATE PROCEDURE setData
(
@Name VARCHAR(30),
@EMAIL VARCHAR(30),
@MOBILE VARCHAR(30)
)
AS
BEGIN
INSERT INTO testdata(name,email,mobile)
VALUES(@Name,@EMAIL,@MOBILE);
END

Implementation:

cmd = new SqlCommand("
setData
",con); //cmd- Command, con- Connection Variables.
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text;
cmd.Parameters.Add("@Email", SqlDbType.
VarChar
).Value = txtEmail.Text;
cmd.Parameters.Add("@Mobile", SqlDbType.BigInt).Value = txtMobile.Text;
cmd.ExecuteNonQuery();

The above statements when executed inserts the records in to the database table.

Tuesday, September 28, 2010

Working with SQL Database - part 1

1. Add a connection string in your application's web.config file.

In the connectionStrings tag, add a key and value for publishing the connection.

2.Include the following namespaces.

using System.Data.SqlClient;
using System.Data;
using System.Configuration;

3.Declare the basic variables for database interaction in your application.

SqlConnection con;
SqlCommand cmd;
SqlDataReader rd;

4.Establish connection with your database.

con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString.ToString());
con.Open();

5.After establishing connection. It is possible perform all the operations on the database. First we look into entering data into the database.

cmd = new SqlCommand("insert into [tablename] values(@arg1,@arg2,...)",con);
cmd.Parameters.Add("@rangeFrom", SqlDbType.Int).Value = [yourvalue];
cmd.Parameters.Add("@rangeTo", SqlDbType.VarChar).Value = [yourvalue];
cmd.ExecuteNonQuery(); // this executes the above query and the data is stored.

6.So we stored the data. Now let us focus on retrieving the data.

cmd = new SqlCommand("select * from [tablename]", con);
rd = cmd.ExecuteReader(); // used for select statements.
Grid.DataSource = rd; // Assigning the data to a GridView Control
Grid.DataBind();

7. Once you run your application, the data from the table will displayed in the Grid.

What is ASP?

Active Server Pages (ASP) is a server side scripting language that lets a webmaster transform the plain, static web site into a dazzling, dynamic solution. With Microsoft's server side scripting language you can gather data from your site's visitors, use sessions, cookies, application variables, and more.